在向上转换之前的java反射字段类型 [英] java reflection field type before upcasting

查看:305
本文介绍了在向上转换之前的java反射字段类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类

public class SomeService {

    private Number number = new Integer(0);
}

是否有可能通过java反射找出上传之前的字段类型?

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

请告知。

推荐答案

这是完全符合逻辑的:您从字段类型获得的信息是 声明的类型 。如果要获取实际类型,则需要获取实例字段的实际值。由于多态性,您无法事先确定值的实际类型。

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

如果你这样做怎么办?

SomeService service = new SomeService();
service.setNumber(new Double(0));//or more vicious : service.setNumber(0.0) 

因此,为了获得值的类型,最简单的解决方案是在值上调用 getClass 或(特别是如果你想要转发) )使用 instanceof
例如,如果你绝对想要使用反射:

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

这篇关于在向上转换之前的java反射字段类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆