58 lines
1.8 KiB
Java
58 lines
1.8 KiB
Java
package com.ruoyi.common.utils;
|
|
|
|
import cn.hutool.core.util.StrUtil;
|
|
|
|
import java.lang.reflect.Field;
|
|
|
|
/**
|
|
* 反射工具类
|
|
*/
|
|
public class ObjectFieldUtils {
|
|
public static String getValue(Object obj,String fieldName){
|
|
if(obj==null || StrUtil.isEmpty(fieldName)){
|
|
return "";
|
|
}
|
|
Field field=null;
|
|
try{
|
|
field=obj.getClass().getDeclaredField(fieldName);
|
|
field.setAccessible(true);
|
|
return String.valueOf(field.get(obj)==null?"":field.get(obj));
|
|
}catch (Exception e){
|
|
if(obj.getClass().getSuperclass()!=Object.class){
|
|
try{
|
|
field=obj.getClass().getSuperclass().getDeclaredField(fieldName);
|
|
field.setAccessible(true);
|
|
return String.valueOf(field.get(obj)==null?"":field.get(obj));
|
|
}catch (Exception e1){
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
e.printStackTrace();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static void setValue(Object obj,String fieldName,Object value){
|
|
if(obj==null || StrUtil.isEmpty(fieldName)||value==null){
|
|
return;
|
|
}
|
|
Field field=null;
|
|
try{
|
|
field=obj.getClass().getDeclaredField(fieldName);
|
|
field.setAccessible(true);
|
|
field.set(obj,value);
|
|
}catch (Exception e){
|
|
if(obj.getClass().getSuperclass()!=Object.class){
|
|
try{
|
|
field=obj.getClass().getSuperclass().getDeclaredField(fieldName);
|
|
field.setAccessible(true);
|
|
field.set(obj,value);
|
|
}catch (Exception e1){
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|