JAVA - cast using class obtained by its name (string value)

casting, class, java, reflection

Solution

What you are trying to do is unnecessary because your list is declared as `List<Object>` so the cast is not needed.

-- Before Edit --

Not sure I understand what you need, but did you try to use:

Class.cast(object)

This is a method of the java.lang.Class

Problem

this is what my code looks if I use a predefined class: ``` List<MyClass> result = new ArrayList<MyClass>(); try { Query query = mgr.newQuery(MyClass.class); for(Object obj : (List<Object>) query.execute()) { result.add(((MyClass) obj)); } } .... return result; ``` now I need to be more generic: starting from a generic class name (as a string, ie "TheChosenOne") I need to do the same thing, but I can't figure out how the cast part should be done.. Just to make an example of what I'm trying to do: ``` String str = "TheChosenOne"; //this value may change Class cls; List<Object> result = new ArrayList<Object>(); try { if(str.equals("TheChosenOne")) cls = Class.forName("com.blabla.TheChosenOne"); else if(str.equals("Rabbit")) cls = Class.forName("com.blabla.Rabbit"); else if(str.equals("Batman")) cls = Class.forName("com.heroes.Batman"); else cls = null; if(cls != null){ Query query = mgr.newQuery(MyClass.class); for(Object obj : (List<Object>) query.execute()) { result.add(((???) obj)); //I need help here! } } } ... return result; ``` I took the "Class.forName()..." part here. Any suggestions? Thanks in advance, best regards

Original source

Related problems