更新時(shí)間:2022-09-28 15:52:36 來源:動(dòng)力節(jié)點(diǎn) 瀏覽2257次
本文章向大家介紹Java反射取值賦值,主要包括Java反射取值賦值使用實(shí)例、應(yīng)用技巧、基本知識(shí)點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價(jià)值,需要的朋友可以參考一下。
項(xiàng)目需求:需要對獲取的數(shù)據(jù)每個(gè)字段值校驗(yàn)合法性,故想到用反射實(shí)現(xiàn)
/**
* 字段值校驗(yàn)
*
* @param r 需要校驗(yàn)的實(shí)體類
* @param properties 自定義需要校驗(yàn)的屬性
* @return
*/
private boolean verifyFields(RelatedRelation r, String[] properties) {
boolean flag = true;
Field[] fields = r.getClass().getDeclaredFields();
try {
// 去空格后,重新賦值
for (Field field : fields) {
field.setAccessible(true);
Object value = field.get(r);
String typeName = field.getType().getName();
if (StringUtils.equals(typeName, String.class.getTypeName()) && ObjectUtils.isNotEmpty(value)) {
String name = field.getName();
String v = ((String) value).trim();
Field f = r.getClass().getDeclaredField(name);
f.setAccessible(true);
f.set(r, v);
}
}
// 判斷屬性是否為空或null
for (String property : properties) {
Field field = r.getClass().getDeclaredField(property);
field.setAccessible(true);
Object value = field.get(r);
if (ObjectUtils.isEmpty(value)) {
field.set(r, "不能為空");
flag = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743