我试图通过反射方式从类的变量中获取一个值。例如,我有一个Car
类,它具有引擎属性。另外,在Engine
类中,我重写了toString()
方法并定义了另一个hello()
方法。
然后当我尝试通过获取值
getDeclaredField()
方法,似乎我得到了Engine
实例的正确值,但是由于某些原因,我无法在其上调用方法hello()
。
汽车课程
public class Car {
final Engine engine = new Engine();
}
引擎类
public class Engine {
public void hello() {
System.out.println("hello");
}
@Override
public String toString() {
return "Engine";
}
}
主要类
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");
}
}
}
答案 0 :(得分:2)
要调用hello()
方法,请首先验证您的value
是Engine
的实例(使用instanceof
),然后进行 cast value
到Engine
。喜欢,
// Check type, cast instance and call hello() method
if (value instanceof Engine) {
((Engine) value).hello();
}
您也可以这样写
if (value instanceof Engine) {
Engine.class.cast(value).hello();
}
保存Class
引用并使用它而不是对您正在使用的特定Class
进行硬编码也很常见;例如,
Class<? extends Engine> cls = Engine.class
// ...
if (cls.isAssignableFrom(value.getClass())) {
cls.cast(value).hello();
}
答案 1 :(得分:0)
您还需要致电
field.setAccessible(true);
在尝试访问它之前。
尽管那可能仅适用于私有字段,请参见@ Elliott.Frisch回复