简体   繁体   中英

How to access subclass method if given Class.class and object reference?

Given the code below:

Parent class:

public class Animal {
  //...
}

Subclasses:

public class Cat extends Animal {
    public void method2(){
        System.out.println("cat method2");
    }
}

public class Dog extends Animal{
    public void method2(){
        System.out.println("dog method2");
    }
}

Enum:

public enum Values {
    VALUE1("v1", Cat.class),
    VALUE2("v2", Dog.class);

    private String val;
    private Class<?> clazz;

    Values(String val, Class<?> clazz){
        this.val = val;
        this.clazz = clazz;
    }

    public String getVal() {
        return val;
    }

    public Class<?> getClazz() {
        return clazz;
    }

}

Main class:

public class Main {
    public static void main(String[] args) {
        Animal a = new Cat();
        method("VALUE1", a);
    }

    public static void method(String val, Animal a){
        Values value = Values.valueOf(val);

        value.getClazz().cast(a).method2();// this doesn't work. how to access method2?
    }
}

The code above won't work. How can I access method2 using Class.class reference? How can I cast The generic Animal class into a subclass given the parameters? If Class.class is not possible, what are the alternatives?

First option, and best option IMO, is to make Animal abstract and add an abstract method2() to Animal . Then you can implement it in Cat and Dog and invoke it without using Reflection. Second option, use reflection.

public static void method(String val, Animal a) {
    Values value = Values.valueOf(val);
    try {
        Method m = value.getClazz().getMethod("method2", null);
        m.invoke(a, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

or without Values , because that isn't doing much for you like

public static void method(Animal a) {
    try {
        Method m = a.getClass().getMethod("method2", null);
        m.invoke(a, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Both methods output

cat method2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM