反射操作泛型
java
采用泛型擦除的机制来引入泛型,java
中的泛型仅仅是给编译器javac
使用的,确保数据的安全性和免去强制类型转换问题,但是,一旦编译完成,所有和泛型有关的类型全部擦除。
ParameterizedType
:表示一种参数化类型,比如CollectionGenericArrayType
:表示一种元素类型或者类型变量的数组结构TypeVariable
:是各种类型变量的公共父接口WildcardType
:代表一种通配符类型表达式
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class Test09 {
public void test(Map<String, User> map, List<User> list) {
}
public Map<String, User> Test01() {
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method test = Test09.class.getMethod("test", Map.class, List.class);
Type[] genericParameterTypes = test.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println(genericParameterType);
if(genericParameterType instanceof ParameterizedType){
Type[] types = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type type : types) {
System.out.println(type);
}
}
}
}
}
获取注解信息
package com.example.springboot;
import java.lang.annotation.*;
public class Test10 {
public static void main(String[] args) throws ClassNotFoundException {
Class aClass = Class.forName("com.example.springboot.Student");
System.out.println(aClass);
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation : annotations) {
//获取注解
System.out.println(annotation);
}
//获取注解的value
TableChen annotation = (TableChen) aClass.getAnnotation(TableChen.class);
System.out.println(annotation.value());
}
}
@TableChen("chen")
class Student {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableChen {
String value();
}
输出:
class com.example.springboot.Student
@com.example.springboot.TableChen(value=chen)
chen