Get a value from a variable of a class, via reflection and then use methods of a value

mikeyusko :

I'm trying to get a value from a variable of a class via reflection way. For example, I have the Car class and it has engine property. Also, in the Engine class, I override the toString() method and defined one more hello() method.

And then when I try to get a value via

getDeclaredField() method, seems like I get a correct value of Engine instance, but for some reasons I can't call method hello() on it.

Car class

public class Car {
    final Engine engine = new Engine();
}

Engine class

public class Engine {

    public void hello() {
        System.out.println("hello");
    }

    @Override
    public String toString() {
        return "Engine";
    }
}

Main class

public class Main {
    public static void main(String[] args) {
        try {
            Field field = Car.class.getDeclaredField("engine");
            Object value = field.get(new Car());

            // It's print Engine as expected
            System.out.println(value);

            // But I can't call hello() method
            // value.hello()

        } catch (NoSuchFieldException | IllegalAccessException e) {
            System.out.println("Exception");
        }
    }
}

Elliott Frisch :

To call the hello() method, first verify that your value is an instance of Engine (using instanceof) and then cast value to an Engine. Like,

// Check type, cast instance and call hello() method
if (value instanceof Engine) {
    ((Engine) value).hello();
}

which you can also write like

if (value instanceof Engine) {
    Engine.class.cast(value).hello();
}

it's also common to save the Class reference and use it instead of hardcoding the particular Class you are working with; for example,

Class<? extends Engine> cls = Engine.class
// ...
if (cls.isAssignableFrom(value.getClass())) {
    cls.cast(value).hello();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150678&siteId=1