Reputation: 7653
Is there a way to determine in which class a field is declared from such code:
Class myObjClass = myObj.myField.getWhereDeclaredClass ();
Edit: Maybe i didn't express my self properly. Consider myObj class as following:
class MyObj {
MySecondObj myField = new MySecondObj ();
}
myField IS NOT of type java.lang.reflect.Field
, and i don't want to use hard coded string literlas with getField (String)
. The syntax must be:
myObj.myField.getWhereDeclaredClass ()
is there a way to do this?
Upvotes: 0
Views: 246
Reputation: 18633
Field.getDeclaringClass()
might work.
Example:
class A{
public int f;
}
class B extends A{
public int g;
}
class C extends B{
public int h;
}
class Test{
public static void main(String[]args) throws Exception{
Class<C> c = C.class;
System.out.println(c.getField("f").getDeclaringClass());
System.out.println(c.getField("g").getDeclaringClass());
System.out.println(c.getField("h").getDeclaringClass());
}
}
Prints:
class A
class B
class C
Edit:
I personally don't know of any way to do it without reflection. Then again, to be writing ".myField
" implies that you know the object to have that field, so in a sense it's still hardcoded, and it also implies that there's basically no chance of your reflective code actually throwing an Exception.
Is there any particular reason not to be using reflection? If it's performance, you could do it once with reflection and then hardcode the value you got.
Upvotes: 4