Java如何使用反射检查字段是初始化还是默认值? [英] Java how can I with reflection check if a field is initialized or is default value?

查看:1091
本文介绍了Java如何使用反射检查字段是初始化还是默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,应该是直截了当的问题。

So, should be straight forward question.

让我说我的课程有很多字段,如:

Lets say I have a class with a lot of fields like:

String thizz;
long that;
boolean bar;

我如何通过反思查看字段 thizz bar 是否已初始化或保留为默认值null,0和false?

How can I, with reflection, see if the fields thizz, that and bar have been initialized or left to their default values of null, 0 and false?

推荐答案

您只需要检查7种基本类型和一种引用类型。如果将所有数字类型组合在一起,则只需要检查四个值。

You have only 7 primitive types and one reference type to check. If you group all Number types together, you only have four values to check for.

Object o =
for (Field field : o.getClass().getDeclaredFields()) {
 Class t = field.getType();
 Object v = field.get(o);
 if(t == boolean.class && Boolean.FALSE.equals(v)) 
   // found default value
 else if(t == char.class && ((Character) v).charValue() == 0)
   // found default value
 else if(t.isPrimitive() && ((Number) v).doubleValue() == 0)
   // found default value
 else if(v == null)
   // found default value
}  

这篇关于Java如何使用反射检查字段是初始化还是默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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