I have some classes and for some reason I need a procedure that create some variables of that class dinamically…
Let’s assume I have this code:
for (int i = 0 ; i < 5 ; i++)
{
....
POP tmp = new POP();
tmp = (POP) ast.convert(aso, POP.class);
}
I want that the POP class is set dinamically… I almost achieved what I want except for the casting from object to class, I do not know how to write it…
String className = "POP";
Class cl = Class.forName(className);
Class cl2 = POP.class;
cl = (??????) ast.convert(aso, cl2);
How can I solve it?
In your second code snippet, cl will actually be
Class<POP>but cl2 isClass<String>, which I guess is not what you expect. Assuming you are coding in Java 5 or newer, you should not use the raw types (Classinstead ofClass<?>), this will make your code safer and easier to read.Also note that you have to use the fully qualified class name, and not just the simple name of your classes. For example
When you have a Class instance you can use reflection to create new instances dynamically:
But maybe what you are trying to achieve could be done using the Abstract Factory pattern ? You provide an object that is able to create instances of the type that you want, and you can choose the factory to use based on the class name.
http://c2.com/cgi/wiki/wiki?AbstractFactoryPattern