[英]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.例如,我有Car
类,它有引擎属性。 Also, in the Engine
class, I override the toString()
method and defined one more hello()
method.此外,在Engine
类中,我覆盖了toString()
方法并定义了另外一个hello()
方法。
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. getDeclaredField()
方法,似乎我得到了Engine
实例的正确值,但由于某些原因,我无法在其上调用方法hello()
。
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");
}
}
}
To call the hello()
method, first verify that your value
is an instance of Engine
(using instanceof
) and then cast value
to an Engine
.要调用hello()
方法,首先验证您的value
是Engine
的实例(使用instanceof
),然后将value
转换为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;保存Class
引用并使用它而不是对您正在使用的特定Class
进行硬编码也很常见; for example,例如,
Class<? extends Engine> cls = Engine.class
// ...
if (cls.isAssignableFrom(value.getClass())) {
cls.cast(value).hello();
}
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尽管这可能仅适用于私有字段,但请参阅 @Elliott.Frisch 回复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.