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...

问题:

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


回答1:

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

回答2:

You also need to call

field.setAccessible(true);

before you try to access it.
Though that may be only for private fields, see @Elliott.Frisch reply

  • 发表于 2019-03-26 05:59
  • 阅读 ( 190 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除