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.
field.getType() returns the declared type.
If you want to know the instantiation type you have to first instantiate the field.
import java.lang.reflect.Field;
public class InstanceTypeInfo {
private Number num = new Integer(0);
public static void main(String[] args) throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
InstanceTypeInfo dI = new InstanceTypeInfo();
Field field = dI.getClass().getDeclaredField("num");
System.out.println("Instance Type :" + field.get(dI).getClass());
System.out.println("Decleration Type:" + field.getType());
}
}
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 :
public class SomeService {
private Number number = new Integer(0);
private void setNumber(Number number){
this.number = number;
}
}
What if you do this?
SomeService service = new SomeService();
service.setNumber(new Double(0));//or more vicious : service.setNumber(0.0)
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) use instanceof
.
For example, if you absolutely want to use reflection :
Field field = SomeService.class.getDeclaredField("number");
field.setAccessible(true);
Object value = field.get(service);
if(value instanceof Integer){
Integer intValue = (Integer)value;
}