Cast to concrete class and call method in Java

2019-04-28 20:48发布

Lets say we have a baseclass called A and some subclasses (B,C,D, etc.). Most subclasses have the method do() but the baseclass does not. Class AA provides a method called getObject(), which will create an object of type B, or C or D, etc., but returns the object as type A.

How do I cast the returned object to the concrete type and call its do() method, if this method is available?

EDIT: I'm not allowed to change the implementation of Class A, the subclasses or AA, since im using a closed Source API.. And yeah, it does have some design issues, as you can see.

8条回答
唯我独甜
2楼-- · 2019-04-28 21:52

If you are not allowed change A but you can change the subclasses then you can make an interface with the method do() and let all the subclass implement that interface.

public interface Doer {
    public void do();
}

public class B extends A implements Doer {
    //implement do method
}

//.. same for other subclass

Then you don't need a cast. Otherwise you will need some explicit downcasts.

查看更多
祖国的老花朵
3楼-- · 2019-04-28 21:52

Best way to do it have A class that method. But since you are not allowed to change any class. I would advice you to create a wrapper instance around all classes using reflections.

Static method in Below class is used just to show how to do it. You can have separate instance variable which can Wrap A in E.

public class E {

public static void doMethod(A a) {
    Class<?> class1 = a.getClass();
    Method method;
    try {
        method = class1.getDeclaredMethod("doMethod", null);// B, C, D has doMethod
        method.invoke(a, null);
        // I know to many exceptions
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}
}

Second option is instance of for which you will have to check for the type and then cast it.

查看更多
登录 后发表回答