反射操作注解

反射操作注解

getAnnotations():获取全部注解

getAnnotation():获取单个注解

public class Demo10 {
    public static void main(String[] args) throws Exception {
        //通过反射获得注解
        Class c1 = Class.forName("com.saxon.reflection.Tcl");
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获得注解的value的值
        TableTcl tabletcl = (TableTcl) c1.getAnnotation(TableTcl.class);
        String value = tabletcl.value();
        System.out.println(value);
        //获得类指定的注解
        Field f = c1.getDeclaredField("name");
        FieldTcl annotation = f.getAnnotation(FieldTcl.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
    }
}
@TableTcl("db_tcl")
class Tcl{
    @FieldTcl(columnName = "db_id", type = "int", length = 10)
    private int id;
    @FieldTcl(columnName = "db_name", type = "varchar", length = 10)
    private String name;
    @FieldTcl(columnName = "db_age", type = "int", length = 10)
    private int age;

    public Tcl(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Tcl() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Tcl{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface  TableTcl{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldTcl{
    String columnName();
    String type();
    int length();
}
posted @ 2021-04-28 14:06  saxon宋  阅读(48)  评论(0)    收藏  举报