views:

92

answers:

3

Let's say we have 2 classes A and B

public class A{

    private int member1;

    A() {
        member1 = 10;
    }

    public getMember(){
        return member1;
    }

}

Class B is also on the same lines except that its member variable is named member2 and gets intitialized to say 20 inside the constructor.

My Requirement :

At runtime , I get a string which contains a className ( could be A or B). I want to dynamically create an object of this class along with invoking the constructor. How can I achieve this . I don't want to use interfaces for common functionality of above classes Morever, later on I set the properties of this raw object using Propery Builder Bean Util class based on a list of columns .

Class clazz = Class.forName("className");
Obj obj = clazz.newInstance();

How I can dynamically convert that obj to className object.

A: 

Class Class has a cast method which at first sight seems to be doing just what you want. So you could try

... = clazz.cast(obj);

but what would be the return type??? It should be either A or B, but you can't declare a variable dynamically...

So I see no other way than the ugly, but tried and true

if (obj instanceof A) {
  A a = (A) obj;
  ...
} else if (obj instanceof B) {
  B b = (B) obj;
  ...
}

Note that if with bean introspection, you can always see the actual dynamic type and internals of the object, so I see not much point trying to get a static reference of the right type to it.

Péter Török
+1  A: 

How can I achieve this . I don't want to use interfaces for common functionality of above classes

Then the answer is very simple and you won’t like it: you can’t. You want to modify the static type of the variables which is, by definition, determined at compile time. Changing it at runtime is not possible.

Konrad Rudolph
A: 

What do you mean with "dynamically convert"? It IS an object of type "className", stored in a variable of type Object. If you want to use it as an object of type A, you have to cast it, and for example store it in a variable of type A.

ShiDoiSi
I meant dynamically cast that object to object of Type T . Any pointers now ?
vaibhav bindroo