🎉 add new method of EntityUtil

This commit is contained in:
fuhouyin 2023-10-09 11:48:23 +08:00
parent 0185f12088
commit 7e666897e8

View File

@ -1,7 +1,9 @@
package utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EntityUtil {
@ -19,4 +21,34 @@ public class EntityUtil {
}
return result;
}
/**
* 获取实体类中所有不为空的字段名
*/
public static List<String> findNotNullFields(Object obj) {
List<String> notNullFields = new ArrayList<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
try {
Object value = field.get(obj);
if (value!= null) {
notNullFields.add(field.getName());
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return notNullFields;
}
/**
* 根据字段名获取值
*/
public static Object getFieldValue(String fieldName, Object obj) throws Exception {
Class<?> clazz = obj.getClass();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
}
}