java reflection field type before upcasting

£可爱£侵袭症+ 提交于 2020-01-11 10:43:20

问题


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.


回答1:


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());
    }
 }



回答2:


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;
}


来源:https://stackoverflow.com/questions/38618105/java-reflection-field-type-before-upcasting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!