java 反射工具类,有需要的朋友可以看一下,如果有帮到您请帮我点赞一下,如果有不同的观点和需求欢迎留言,大家一起讨论~~~
import com.google.common.collect.Lists;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* 作者:673164808@qq.com
* 功能:反射工具类
*/
public class ReflectionUtils {
/**
* 获取类以及父类的属性类型
* @param clazz
* @return
*/
public static ArrayList<Class> getAllFieldClazzs(Class<?> clazz){
ArrayList<Class> classs = Lists.newArrayList();
List<Class> tempClasss = null;
while (!clazz.equals(Object.class)){
tempClasss = Arrays.asList(clazz.getDeclaredFields()).stream().map(field -> field.getType()).collect(Collectors.toList());
classs.addAll(tempClasss);
clazz = clazz.getSuperclass();
}
return classs;
}
/**
* 获取类里面指定的属性类型,检测到list类型属性会自动获取其泛型
* @param clazz
* @param name
* @return
*/
public static Class getAllFieldClass(Class<?> clazz,String name){
Field field = null;
while (!clazz.equals(Object.class)){
try {
field = clazz.getDeclaredField(name);
break;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
}
return field.getType().equals(List.class)?getListGenericClass(field):field.getType();
}
/**
* 获取类里面指定的属性类型,检测到list类型属性会自动获取其泛型,并且可获取list泛型里面的指定属性
* @param clazz
* @param name
* @return
*/
public static Class getFieldClass(Class<?> clazz,String name){
List<String> nameList = Arrays.asList(name.split("\\."));
for (String tempName:nameList) {
clazz = getAllFieldClass(clazz,tempName);
}
return clazz;
}
/**
* 获取list的泛型类所有属性
* @param field
* @return
*/
public static Class getListGenericClass(Field field){
ParameterizedType listGenericType = (ParameterizedType)field.getGenericType();
Type[] listActualTypeArguments = listGenericType.getActualTypeArguments();
return (Class)listActualTypeArguments[0];
}
/**
* 获取list的泛型类指定属性
* @param clazz
* @param name
* @return
*/
public static Class getListGenericClass(Class<?> clazz,String name){
Field listField = null;
try {
listField = clazz.getDeclaredField(name);
} catch (Exception e) {
e.printStackTrace();
}
ParameterizedType listGenericType = (ParameterizedType)listField.getGenericType();
Type[] listActualTypeArguments = listGenericType.getActualTypeArguments();
return (Class)listActualTypeArguments[0];
}
public static void main(String[] args) {
ArrayList<Class> allFields = ReflectionUtils.getAllFieldClazzs(User.class);
allFields.stream().forEach(field -> {
System.out.println(field.getName());
});
System.out.println(ReflectionUtils.getFieldClass(User.class,"roles.id").getName());
System.out.println(getListGenericClass(User.class, "roles"));
}
}