top.doudou.common.tool.utils.FieldUtils Maven / Gradle / Ivy
package top.doudou.common.tool.utils;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import top.doudou.base.exception.CustomException;
import top.doudou.base.util.StrUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author 傻男人<[email protected]>
* @Date: 2020/9/7 17:22
* @Version: 1.0
* @Description:
*/
@Slf4j
@Data
public class FieldUtils{
/**
* 获取private修饰的成员变量 获得某个类的所有声明的字段,即包括public、private和proteced也包括父类的申明字段。
* @param target
* @return
*/
public static List getAllFields(Class> target){
List superField = getSuperField(target);
Iterator iterator = superField.iterator();
while (iterator.hasNext()){
Field next = iterator.next();
if ("serialVersionUID".equals(next.getName())) {
iterator.remove();
}
}
return superField;
}
/**
* 获取所有非static修饰的字段
* @param target
* @return
*/
public static List getAllNoStaticFields(Class> target){
List superField = getSuperField(target);
Iterator iterator = superField.iterator();
while (iterator.hasNext()){
Field next = iterator.next();
if (Modifier.isStatic(next.getModifiers())) {
iterator.remove();
}
}
return superField;
}
private static List getSuperField(Class target){
if(target.equals(Object.class)){
return Lists.newArrayList();
}
List list = Lists.newArrayList();
Field[] declaredFields = target.getDeclaredFields();
list.addAll(Arrays.asList(declaredFields));
Class> superclass = target.getSuperclass();
list.addAll(getSuperField(superclass));
return list;
}
public static Object getFieldValue(Field field,Class> clazz,Object obj) {
String name = field.getName();
try {
Method method = clazz.getMethod("get" + StrUtils.firstToUpperCase(name));
return method.invoke(obj);
}catch (NoSuchMethodException e){
throw new CustomException("方法未找到:get"+ StrUtils.firstToUpperCase(name));
}catch (Exception e) {
throw new CustomException("未获取到的值方法:get"+StrUtils.firstToUpperCase(name));
}
}
public static Object getFieldValueNoException(Field field,Class> clazz,Object obj) {
try{
return getFieldValue(field,clazz,obj);
}catch (Exception e){
log.error(e.getMessage());
return null;
}
}
private static String acronymToUpper(String str) {
char[] chars = str.toCharArray();
if (chars[0] >= 'a' && chars[0] <= 'z') {
chars[0] = (char) (chars[0] - 32);
}
return new String(chars);
}
}