Java获取反射的三种方式及应用

愿天堂没有BUG

共 2295字,需浏览 5分钟

 ·

2021-06-28 02:40

  1. 获取反射的三种方式

1.1 通过Class.class获取

@Data
public class ModelA {

private String name;

private Integer age;

private LocalDateTime dateTime;

}
复制代码
 Class<ModelA> aClass = ModelA.class;
复制代码

1.2 通过obj.getClass()方式获取

 ModelA modelA = new ModelA();
Class<? extends ModelA> aClass1 = modelA.getClass();
复制代码

1.3 通过Class.forName()方式获取

 Class<?> aClass1 = Class.forName("com.demo.model.ModelA");
复制代码

通过Class.forName()方式获取反射需要捕获java.lang.ClassNotFoundException

2. 通过反射获取对象中的所有属性包括父类的

public List<Field> getAllField(Class<?> aClass) {
if (aClass == null) {
return new ArrayList<>();
}
List<Field> fieldList = new ArrayList<>();
while (aClass != null) {
fieldList.addAll(Arrays.asList(aClass.getDeclaredFields()));
aClass = aClass.getSuperclass();
}
return fieldList;
}
复制代码

3. 通过反射获取对象属性的信息

public static void printFieldInfo(Field field) {
// 属性名称
String name = field.getName();
// 属性类型 全限定类名(基本类型返回就是基本类型 如 int)
String fieldTypeName = field.getGenericType().getTypeName();
// 获取修饰在属性上的所有注解
Annotation[] annotationArray = field.getDeclaredAnnotations();
// 获取修饰在属性上的@Value注解
Value declaredAnnotation = field.getDeclaredAnnotation(Value.class);
}
复制代码

4. 通过反射获取方法的信息

public static void printMethodInfo(Method method) {
for (Parameter parameter : method.getParameters()) {
// 这里得到的参数name是arg0
String name = parameter.getName();
// 全限定类名(基本类型返回就是基本类型 如 int)
String parameterType = parameter.getParameterizedType().getTypeName();
// 获取修饰在参数上的所有注解
Annotation[] annotationArray = parameter.getDeclaredAnnotations();
// 获取修饰在参数上的@RequestParam注解
RequestParam requestParam = parameter.getDeclaredAnnotation(RequestParam.class);
}

// 方法的返回类型
String methodReturnTypeName = method.getGenericReturnType().getTypeName();
// 获取修饰在方法上的所有注解
Annotation[] annotationArray = method.getDeclaredAnnotations();
// 获取修饰在方法上的@Override注解
Override override = method.getDeclaredAnnotation(Override.class);
}


作者:闹了个笑话吧
链接:https://juejin.cn/post/6976995899494891550
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。



浏览 99
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报