Dynamically create and throw objects at runtime

Suppose 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 called member2 and gets initialized to say 20 inside the constructor.

My requirements:

At runtime, I get a string that contains the class name (could be A or B). I want to dynamically create an object of this class along with a constructor call. How can I achieve this. I dont want to use interfaces for the general functionality of the above Morever classes, later I set the properties of this raw object using Selfy Builder Bean Util class based on column list.

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

      

How can I dynamically convert the obj object to className.

+2


a source to share


3 answers


How can I achieve this. I dont want to use interfaces for the general functionality of the above classes



Then the answer is very simple and you won't like it: you cannot . You want to change the static type of variables, which by definition is determined at compile time. It cannot be changed at runtime.

+1


a source


The class Class

has a method cast

that at first glance seems to do exactly what you want. So you can try

... = clazz.cast(obj);

      

but what will the return type be ??? It should be either A

or B

, but you cannot dynamically declare a variable ...



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 the bean introspection you can always see the actual dynamic type and inner objects of the object, so I don't see many points trying to get a static reference to the correct type.

+1


a source


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

+1


a source







All Articles