Java獲取反射的三種方式及應(yīng)用
獲取反射的三種方式
1.1 通過Class.class獲取
@Data
public class ModelA {
private String name;
private Integer age;
private LocalDateTime dateTime;
}
復(fù)制代碼 Class<ModelA> aClass = ModelA.class;
復(fù)制代碼1.2 通過obj.getClass()方式獲取
ModelA modelA = new ModelA();
Class<? extends ModelA> aClass1 = modelA.getClass();
復(fù)制代碼1.3 通過Class.forName()方式獲取
Class<?> aClass1 = Class.forName("com.demo.model.ModelA");
復(fù)制代碼通過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;
}
復(fù)制代碼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);
}
復(fù)制代碼4. 通過反射獲取方法的信息
public static void printMethodInfo(Method method) {
for (Parameter parameter : method.getParameters()) {
// 這里得到的參數(shù)name是arg0
String name = parameter.getName();
// 全限定類名(基本類型返回就是基本類型 如 int)
String parameterType = parameter.getParameterizedType().getTypeName();
// 獲取修飾在參數(shù)上的所有注解
Annotation[] annotationArray = parameter.getDeclaredAnnotations();
// 獲取修飾在參數(shù)上的@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
來源:掘金
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
評論
圖片
表情
