Reputation: 897
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");
}
}
}
Upvotes: 2
Views: 61
Reputation: 490
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
Upvotes: 0
Reputation: 201447
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();
}
Upvotes: 2