1. 通过反射获取泛型信息
- 定义两个方法
- 一个方法有泛型形参,没有返回值
test01
- 一个方法没有形参,有泛型返回值
test02
public void test01(Map<String, User> map, List<User> list) {
System.out.println("test01");
}
public Map<String, User> test02() {
System.out.println("test02");
return null;
}
- 1、获取方法的泛型形参信息以及真实参数类型
通过反射先获取类class对象,然后获取类对象的指定方法,
Method method = 获取泛型信息.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("##" + genericParameterType);
if (genericParameterType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
- 输出结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5e94491fe274dc32206ce9d0e620089c.png)
- 2、获取方法的泛型返回值信息以及真实饭返回值参数信息
Method re = 获取泛型信息.class.getMethod("test02");
Type genericReturnType = re.getGenericReturnType();
System.out.println(genericReturnType);
if (genericReturnType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
- 输出结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/641413596d4bcdd725ad15b1dd300704.png)
2. 通过反射获取注解信息
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
@interface Table {
String value();
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
@interface FieldValue {
String columnName();
String type();
int length();
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.learn.reflection.Student");
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
Table table = (Table) c1.getAnnotation(Table.class);
String value = table.value();
System.out.println(value);
Field f = c1.getDeclaredField("name");
FieldValue annotation = f.getAnnotation(FieldValue.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}