Marcx
Marcx

Reputation: 6826

Define a variable type another variable in Java

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?

Upvotes: 0

Views: 135

Answers (1)

ARRG
ARRG

Reputation: 2486

In your second code snippet, cl will actually be Class<POP> but cl2 is Class<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 (Class instead of Class<?>), 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

Class.forName("String"); // Won't work
Class.forName("java.lang.String"); // Is what you need.

When you have a Class instance you can use reflection to create new instances dynamically:

    Class<?> cl2 = ... ;        

    // If the class has a no-arg visible constructor
    Object foo = cl2.newInstance();

    // Or using an explicit constructor (here with an integer and a String as arguments)
    Constructor<Class<?>> cons = cl2.getConstructor(Integer.class, String.class);
    Object bar = cons.newInstance(1, "baz");

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

Upvotes: 1

Related Questions