Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Unable to convert child class to parent class?

SreramOct 16 2013 — edited Oct 17 2013

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.

        }

    }

}

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 14 2013
Added on Oct 16 2013
5 comments
1,823 views