反射获取泛型,操作注解
通过反射获取泛型
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 ObtainGeneric {
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;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = ObtainGeneric.class.getMethod("test01",Map.class,List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for(Type genericParameterType:genericParameterTypes){
System.out.println("#"+genericParameterType);
//获取参数类型
Type[] actualTypeArguments = ((ParameterizedType)genericParameterType).getActualTypeArguments();
for(Type actualTypeArgument:actualTypeArguments){
System.out.println(actualTypeArgument);
}
}
}
}
反射操作注解
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test12 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("reflection.Student2");
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations){
System.out.println(annotation);
}
TableCheng tableCheng = (TableCheng)c1.getAnnotation(TableCheng.class);
String value = tableCheng.value();
System.out.println(value);
//获得指定类的注解
Field f = c1.getDeclaredField("name");
FieldCheng annotation = f.getAnnotation(FieldCheng.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.type());
}
}
@TableCheng("db_student")
class Student2 {
@FieldCheng(columnName = "db_id",type = "int", length = 10)
private int id;
@FieldCheng(columnName = "db_age",type = "int", length = 10)
private int age;
@FieldCheng(columnName = "db_name",type = "varchar", length = 30)
private String name;
public Student2() {
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableCheng{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldCheng{
String columnName();
String type();
int length();
}
result:
E:\JAVA\JDK\bin\java.exe "-javaagent:E:\IDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=55359:E:\IDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\IDEA\Annotation\out\production\Annotation reflection.Test12
@reflection.TableCheng("db_student")
db_student
db_name
varchar
varchar
@reflection.TableCheng("db_student")
db_student
db_name
varchar
varchar
Process finished with exit code 0
浙公网安备 33010602011771号