vaibhav bindroo
vaibhav bindroo

Reputation: 149

Dynamically create and cast objects at runtime

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.

Upvotes: 2

Views: 6869

Answers (3)

Péter Török
Péter Török

Reputation: 116286

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.

Upvotes: 1

Volker Stolz
Volker Stolz

Reputation: 7402

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.

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545923

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.

Upvotes: 1

Related Questions