Reputation: 201
I have a class that is going to be passed into a function and it will be defined as follows:
class ayy{
String blah;
Class a;
Class b;
}
I want to be able to invoke the getSimpleName() method on the classes a and b. Currently I am doing it as follows:
Class c = (Class)argument; // Where argument is the "ayy" class
c.getField("a").getSimpleName();
But this gives me an error saying "getSimpleName()" is not defined for type field.
Upvotes: 0
Views: 249
Reputation: 178243
You cannot call a method directly on an object that results from reflection, such as you're doing with Field
, as if it were a reference variable of the desired type.
Instead, you'll need to call getDeclaredField
, because getField
only gets public
fields. Also, you'll need to get()
the value of the Field
, passing in an instance of the ayy
class, which will return the value of the Field
. Then you'll need to cast it to a Class
, because get()
returns an Object
. Then you can call getSimpleName()
.
Class<?> classOfA = (Class<?>) c.getDeclaredField("a").get(anAyy);
String simpleName = classOfA.getSimpleName();
You'll also need to catch the various reflection-related exceptions that may be thrown.
Upvotes: 2