我试图通过反射方式从类的变量中获取值。例如,我有 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");
}
}
}
最佳答案
要调用 hello()
方法,首先验证您的 value
是否是 Engine
的实例(使用 instanceof
),然后将值
转换为引擎
。就像,
// 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();
}
关于java - 通过反射从类的变量获取值,然后使用值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326649/