Dynamically create and cast objects at runtime
Posted
by vaibhav bindroo
on Stack Overflow
See other posts from Stack Overflow
or by vaibhav bindroo
Published on 2010-05-19T15:21:03Z
Indexed on
2010/05/19
15:30 UTC
Read the original article
Hit count: 256
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.
© Stack Overflow or respective owner