首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

反照妙用-判断对象各成员是否为null

2012-11-20 
反射妙用-判断对象各成员是否为null有时候大家会有判断新创建对象各成员是否为null的需求,通过反简单处理,

反射妙用-判断对象各成员是否为null
有时候大家会有判断新创建对象各成员是否为null的需求,通过反简单处理,可满足此需求:

import java.lang.reflect.Field;/** *  * @author elitesunry * @mail rysun@qq.com * @create 2011-5-10 7:21:30 */public abstract class ContentNullComparable {public boolean isEmpty(Object obj) {return isContentEmpty(this.getClass(), obj);}private boolean isContentEmpty(Class<?> clazz, Object obj) {Field[] fields = clazz.getDeclaredFields();int nullFiledCount = 0;for (Field field : fields) {Object fileldValue = null;try {// 这里不对复杂成员对象做嵌套判断fileldValue = field.get(obj);} catch (Exception e) {// ignore}if (fileldValue == null) {nullFiledCount++;if (nullFiledCount == fields.length) {return true;}}}return false;}}


继承此类即可:
/** * @author elitesunry * @mail rysun@qq.com * @create 2011-5-7 11:48:27 */public class EmptyClass {public static void main(String[] args) {A a1 = new A();System.out.println(a1.isEmpty(a1));A a2 = new A();a2.a = "value";System.out.println(a2.isEmpty(a2));A a3 = new A();a3.obj = new A();System.out.println(a3.isEmpty(a3));}}class A extends ContentNullComparable {String a;String b;A obj;}


由于java的单继承特性,这样的做法可能会导致你的类不能继承其他的类,你可以采用代理对象的方式解决此问题:
class DelegateContentNullComparable extends ContentNullComparable {...}class YourClass {...private DelegateContentNullComparable delegate;...delegate.isEmpty(...);...}

热点排行