com.eworkcloud.excel.util.ClassUtils Maven / Gradle / Ivy
package com.eworkcloud.excel.util;
import lombok.SneakyThrows;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public abstract class ClassUtils {
private static boolean isPropertyName(String name) {
return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name));
}
/**
* 实例化对象类
*
* @param clazz 类
* @param 类型
* @return 实例
*/
@SneakyThrows
public static T newInstance(Class clazz) {
return clazz.newInstance();
}
/**
* 判断是不是集合
*
* @param clazz 类
* @return 集合
*/
public static boolean isCollection(Class> clazz) {
return Collection.class.isAssignableFrom(clazz);
}
/**
* 判断是不是集合
*
* @param field 字段
* @return 集合
*/
public static boolean isCollection(Field field) {
return isCollection(field.getType());
}
/**
* 获取class的字段(包括父类)
*
* @param clazz 类
* @return 字段数组
*/
public static Field[] getFields(Class> clazz) {
Map fieldMap = new LinkedHashMap<>();
do {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
if (isPropertyName(name) && !fieldMap.containsKey(name)) {
try {
field.setAccessible(true);
fieldMap.put(field.getName(), field);
} catch (SecurityException ignored) {
}
}
}
clazz = clazz.getSuperclass();
} while (clazz != Object.class && clazz != null);
return fieldMap.values().toArray(new Field[0]);
}
/**
* 获取字段的值
*
* @param field 字段
* @param obj 对象
* @return 值
*/
@SneakyThrows
public static Object getValue(Field field, Object obj) {
return field.get(obj);
}
/**
* 设置字段的值
*
* @param field 字段
* @param obj 对象
* @param value 值
*/
@SneakyThrows
public static void setValue(Field field, Object obj, Object value) {
field.setAccessible(true);
field.set(obj, value);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy