I have a simple class
public class SomeService {
private Number number = new Integer(0);
}
Is it possible to find out by means of java reflection the field type before upcasting?
I can just obtain Number type instead of Integer:
Field field = MealService.class.getDeclaredField("number");
field.setAccessible(true);
System.out.println("impl:"+field.getType());
Please advise.
This is perfectly logical : the information you get from the field type is the declared type. If you want to get the actual type, you need to get the actual value of the field of the instance. Due to polymorphism you cannot determine in advance the actual type of a value.
In your example, you can't change
number
's value but it is rarely the case in real life. For example :What if you do this?
So, in order to get the type of the value, the most simple solution is to call
getClass
on the value or (especially if you want to upcast) useinstanceof
. For example, if you absolutely want to use reflection :If you want to know the instantiation type you have to first instantiate the field.