Have a parent class. Have a child class which extends the parent abstract class. And i invoke the child class using reflection. When i convert the child class to parent class i get ClassCastException. Any ideas? Am i doing something wrong?
public abstract class A {
public void method1(.. args);
public void method2(.. args);
}
public class B extends A{
private static B b = null;
private B(){
}
public static B getInstance(){
if(b == null){
b = new B();
}
return b;
}
public void method1(.. args){
//implementation
}
public void method2(.. args){
//implementation
}
}
public class C{
private Map classmap = new HashMap();
public void loadmethods(){
Class thisClass;
try{
thisClass = Class.forName("B");
Method instanceMethod = thisClass.getDeclaredMethod("getInstance", (Class[])null);
Object instance = instanceMethod.invoke(null, (Object[])null);
classmap.put("B", instance);
} catch(Exception ex){
//log the error
}
}
public A getInstance(String classname){
return classmap .get(classname);
}
public static void main(String[] args){
C c = new C();
c.loadmethods();
A a = null;
try{
a = c.getInstance("B");//ClassCastException happening here
} catch(Exception ex){
//Can catch the exception here.
}
}
}