Java 基础复习 Day 29
注解与反射 2
1.通过反射获取方法的参数和返回值的泛型类型
/通过反射获取泛型
public class Test11 {
public void test1(Map<String, User> map, List<User> users){
System.out.println("test01");
}
public Map<String, User> test(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method1 = Test11.class.getDeclaredMethod("test1", Map.class, List.class);
Type[] types = method1.getGenericParameterTypes();
for (Type type : types) {
System.out.println("###:" + type);
if (type instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();;
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("actual type: " + actualTypeArgument);
}
}
}
Method method2 = Test11.class.getDeclaredMethod("test", null);
Type returnType = method2.getGenericReturnType();
if(returnType instanceof ParameterizedType){
Type[] arguments = ((ParameterizedType) returnType).getActualTypeArguments();
for (Type type : arguments) {
System.out.println("actual type2" + type);
}
}
}
}
2.通过反射操作注解
public class Test12 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1= Class.forName("com.kou.reflection.Worker");
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("annotation: " + annotation);
}
TableW1 tableW1 = (TableW1)c1.getAnnotation(TableW1.class);
System.out.println(tableW1.value());
Field f1 = c1.getDeclaredField("name");
FieldW1 annotation = f1.getAnnotation(FieldW1.class);
System.out.println(annotation.columnName());
System.out.println(annotation.length());
System.out.println(annotation.type());
}
}
@TableW1(value = "tb_worker")
class Worker{
@FieldW1(columnName = "db_id",type = "int",length = 20)
private int id;
@FieldW1(columnName = "db_age",type = "int",length = 20)
private int age;
@FieldW1(columnName = "db_name",type = "varchar",length = 40)
private String name;
public Worker(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public Worker() {
}
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;
}
@Override
public String toString() {
return "Worker{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableW1{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldW1{
String columnName();
String type();
int length();
}