All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
net.lulihu.ObjectKit.ReflectKit Maven / Gradle / Ivy
package net.lulihu.ObjectKit;
import lombok.extern.slf4j.Slf4j;
import net.lulihu.Assert0;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.lang.reflect.Field;
import java.util.List;
/**
* 反射工具类
*/
@Slf4j
public class ReflectKit {
/**
* 获取对象所有的属性
*
* @param cls 指定对象
* @return 所有的属性
*/
public static List getAllFieldsList(Class> cls) {
return FieldUtils.getAllFieldsList(cls);
}
/**
* 获取属性值
*
* @param obj 对象
* @param fieldName 对象属性名
* @return 对象属性值
*/
public static Object getFieldValue(Object obj, String fieldName) throws IllegalAccessException {
Assert0.toolBox()
.notNull(obj, "对象不可以为null")
.notNull(fieldName, "属性名称不可以为null");
Field targetField = getTargetField(obj.getClass(), fieldName);
return FieldUtils.readField(targetField, obj, true);
}
/**
* 获取属性值
*
* @param obj 对象
* @param targetField 对象属性
* @return 对象属性值
*/
public static Object getFieldValue(Object obj, Field targetField) throws IllegalAccessException {
Assert0.toolBox()
.notNull(obj, "对象不可以为null")
.notNull(targetField, "对象属性不可以为null");
return FieldUtils.readField(targetField, obj, true);
}
/**
* 获取目标属性
*
* @param targetClass 指定对象
* @param fieldName 属性名称
* @return 属性封装对象
*/
public static Field getTargetField(Class> targetClass, String fieldName) {
if (targetClass == null || Object.class.equals(targetClass)) return null;
Field field;
field = FieldUtils.getDeclaredField(targetClass, fieldName, true);
if (field == null) {
field = getTargetField(targetClass.getSuperclass(), fieldName);
}
return field;
}
/**
* 设置属性值
*
* @param obj 对象
* @param fieldName 属性名称
* @param value 设置的值
*/
public static void setFieldValue(Object obj, String fieldName, Object value) {
Assert0.toolBox()
.notNull(obj, "对象不可以为null")
.notNull(fieldName, "属性名称不可以为null")
.notNull(value, "属性值不可以为null");
Field targetField = getTargetField(obj.getClass(), fieldName);
try {
FieldUtils.writeField(targetField, obj, value);
} catch (IllegalAccessException e) {
LogKit.error(log, "给[{}]的属性[{}]设置值时发生例外", obj, fieldName, e);
}
}
/**
* 设置属性值
*
* @param obj 对象
* @param targetField 对象属性
* @param value 设置的值
*/
public static void setFieldValue(Object obj, Field targetField, Object value) {
Assert0.toolBox()
.notNull(obj, "对象不可以为null")
.notNull(targetField, "对象属性不可以为null")
.notNull(value, "属性值不可以为null");
try {
FieldUtils.writeField(targetField, obj, value);
} catch (IllegalAccessException e) {
LogKit.error(log, "给[{}]的属性[{}]设置值时发生例外", obj, targetField.getName(), e);
}
}
}