dimanche 24 mars 2019

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

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");
        }
    }
}






Aucun commentaire:

Enregistrer un commentaire