Sample not working :
Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();
Field f = c.getDeclaredField("myColor");
f.setAccessible(true);
String valueOfMyColor = (String) f.get(o);
The problem in this code is that you have to cast with the String class. What I’m looking for, is to be able to find the class of an attribute from its name.
For example :
class Brush {
Color myColor;
}
//Somewhere else, in a far far away galaxy
Class<?> c = getMyClassFromAttributeName("myColor");
// and c should be of type Color
I’ve tried
Field f = this.getClass().getDeclaredField(code);
Class<?> c1 = f.getClass(); //Gives Field
Class<?> c2 = f.getDeclaringClass(); //Gives Brush
Thanks !
PS:
Used sample code from In Java, how to get attribute given the string with its name?
Use
Field.getType();.Example: