8
java | 反射操作注解
source link: https://benpaodewoniu.github.io/2022/12/11/java76/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
java | 反射操作注解
反射操作注解。
package com.redisc;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.List;
import java.util.Map;
// 类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
String value();
}
// 属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TableField {
String columnName();
String type();
int length();
}
@Table("student")
class Student {
@TableField(columnName = "id", type = "int", length = 10)
public int id;
@TableField(columnName = "name", type = "varchar", length = 255)
public String name;
}
public class Test {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class c1 = Class.forName("com.redisc.Student");
// 通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
// 获得注解的值
Table annotation = (Table) c1.getAnnotation(Table.class);
System.out.println(annotation.value());
// 获得类指定的注解
Field f = c1.getDeclaredField("name");
TableField tableField = f.getAnnotation(TableField.class);
System.out.println(tableField.columnName());
System.out.println(tableField.type());
}
}
@com.redisc.Table("student")
student
name
varchar
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK