package com.taiping.test; import java.lang.reflect.Field; import java.lang.reflect.Type; /** * <p> * Description: 判斷對象是否為空,進一步判斷對象中的屬性是否都為空 * * 對象為new,但對象中的屬性都為null * </p> * */ public class CheckObjectIsNullUtils { /** * 判斷對象是否為空,且對象的所有屬性都為空 * ps: boolean類型會有默認值false 判斷結果不會為null 會影響判斷結果 * 序列化的默認值也會影響判斷結果 * * @param object * @return */ @SuppressWarnings("rawtypes") public static boolean objCheckIsNull(Object object) { Class clazz = (Class) object.getClass(); // 得到類對象 Field fields[] = clazz.getDeclaredFields(); // 得到所有屬性 boolean flag = true; // 定義返回結果,默認為true for (Field field : fields) { field.setAccessible(true); Object fieldValue = null; try { fieldValue = field.get(object); // 得到屬性值 Type fieldType = field.getGenericType();// 得到屬性類型 String fieldName = field.getName(); // 得到屬性名 System.out.println("屬性類型:" + fieldType + ",屬性名:" + fieldName + ",屬性值:" + fieldValue); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (fieldValue != null) { // 只要有一個屬性值不為null 就返回false 表示對象不為null flag = false; break; } } return flag; } }