I have 2 java classes (Child1.java and Child2.java)
which extends from a common class (Parent.java)
. I have another common class (Common.java)
which can be called from both Child classes. I am getting the caller class name from the Thread.currentThread().getStackTrace()
and crate the Class instance through Java Reflection
. Then I am creating a new instance object from that class. Therefore the return type of the method is Object
Although I am returning an object at the moment, I need commonMethod()
to be written in a such a way where the called class new instance should be returned dynamically.
public class Child1 extends Parent {
public void method1()
{
new Common().commonMethod();
}
}
public class Child2 extends Parent {
public void method2()
{
new Common().commonMethod();
}
}
public Object commonMethod() throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
Class clazz = Class.forName(className);
return clazz.newInstance();
}
Any help would be appreciated
Aucun commentaire:
Enregistrer un commentaire