阐明:应用反射判断或者获取的对象中值或者字段
示例:
1. 获取带某注解的对象字段及属性名称
// 注解定义
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ModifyField {
/**
* 字段名称 * @return
*/
String name() default "";}
/**
* 获取对象中所有带 @ModifyField 注解的字段列表 map * @param
* @return
*/
public static Map<String, String> getAllFieldMap(Class<?> clazz) {Map<String, String> map = new HashMap<>();
if (clazz == null) {return map;}
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {ModifyField modifyField = field.getAnnotation(ModifyField.class);
if (modifyField != null) {map.put(field.getName(), modifyField.name());
}
}
return map;
}
2. 查看某对象属性是否全是空
/**
* 测验对象属性是否全是空 * @param object
* @return
*/
public static boolean checkAllFieldsIsNull(Object object) {if (null == object) {return true;}
try {for (Field f : object.getClass().getDeclaredFields()) {f.setAccessible(true);
if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {return false;}
}
} catch (Exception e) {log.error("checkAllFieldsIsNull err {}",e);
}
return true;
}
3. 获取某对象中的所有有值的字段及值内容
/**
* 获取对象中的所有有值的字段及值内容 * @param obj
* @return
*/
public static Map<String, Object> getAllFieldNotNull(Object obj) {Map<String, Object> map = new HashMap<>();
if (obj == null) {return map;}
try {Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {map.put(field.getName(), value);
}
}
} catch (IllegalAccessException e) {log.error("getAllFieldNotNull err {}",e);
}
return map;
}