1. Three ways to obtain reflections
1.1 throughClass.class
To obtain
@Data
public class ModelA {
private String name;
private Integer age;
private LocalDateTime dateTime;
}
Copy the code
Class<ModelA> aClass = ModelA.class;
Copy the code
1.2 throughobj.getClass()
Way to obtain
ModelA modelA = new ModelA();
Class<? extends ModelA> aClass1 = modelA.getClass();
Copy the code
1.3 throughClass.forName()
Way to obtain
Class<? > aClass1 = Class.forName("com.demo.model.ModelA");
Copy the code
By Class. Class.forname () way to get reflection need to capture the Java lang. ClassNotFoundException
2. Obtain all properties of the object including the parent class through reflection
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;
}
Copy the code
3. Obtain object property information through reflection
public static void printFieldInfo(Field field) {
// Attribute name
String name = field.getName();
// Attribute type fully qualified class name (base type returns base type such as int)
String fieldTypeName = field.getGenericType().getTypeName();
// Get all the annotations decorated on the property
Annotation[] annotationArray = field.getDeclaredAnnotations();
// Get the @value annotation on the attribute
Value declaredAnnotation = field.getDeclaredAnnotation(Value.class);
}
Copy the code
4. Obtain method information through reflection
public static void printMethodInfo(Method method) {
for (Parameter parameter : method.getParameters()) {
// The name of the argument is arg0
String name = parameter.getName();
// Fully qualified class name (base type returns base type like int)
String parameterType = parameter.getParameterizedType().getTypeName();
// Get all the annotations decorated on the parameter
Annotation[] annotationArray = parameter.getDeclaredAnnotations();
// Get the @requestParam annotation on the parameter
RequestParam requestParam = parameter.getDeclaredAnnotation(RequestParam.class);
}
// The return type of the method
String methodReturnTypeName = method.getGenericReturnType().getTypeName();
// Get all the annotations decorated on the method
Annotation[] annotationArray = method.getDeclaredAnnotations();
// Get the @override annotation on the method
Override override = method.getDeclaredAnnotation(Override.class);
}
Copy the code