I don't want to get the field
from the class
of my object like this:
myObject.getClass().getField(...);
But from the instance directly (something like: myObject.getField(...)
)! Why? Because its class
doesn't contain exact information about the field in this special case:
public void main() throws NoSuchFieldException {
final GenericClass<String> theInstance = new GenericClass<>();
theInstance.theField = new String();
// Directly, but without Reflection:
System.out.println(theInstance.theField.getClass().getName());
// By Reflection, but indirectly (via getClass()):
System.out.println(theInstance.getClass().getField("theField").getType().getName());
}
static class GenericClass<T> {
public T theField;
}
Output:
java.lang.String
java.lang.Object
The second output is correct but isn't exact. I know the reason, but don't want the reason. I want to access the field directly from theInstance
(through reflection).
NOTE: I will have access to theField
by its name (as a String
at run-time), so MUST use reflection (or something like that)!
Aucun commentaire:
Enregistrer un commentaire