1. 程式人生 > >Java中通過反射判斷私有屬性是否為空的工具類

Java中通過反射判斷私有屬性是否為空的工具類

class ObjectIsEmptyUtil {
		public static boolean isEmpty(Object obj, String objProperty) throws Exception, IllegalAccessException {
		// 獲取類物件
		Class<?> clazz = obj.getClass();
		// 得到屬性集合
		Field[] fs = clazz.getDeclaredFields();
		// 遍歷屬性
		for (Field field : fs) {
			field.setAccessible(true
); // 找到需要判斷的屬性名稱 if (field.getName().equalsIgnoreCase(objProperty)) { // 判斷該物件是否為空 if ((field.get(obj) == null || field.get(obj) == "" || "null".equalsIgnoreCase(field.get(obj).toString()))) { return true; } } } return false; } }