16 反射操作注解

package annotate;

import java.lang.annotation.*;
import java.lang.reflect.Field;

// 通过反射操作注解


public class Test16 {
    public static void main(String[] args) throws Exception {
        Class c1= Student2.class;
        // 通过反射获得注解
        for (Annotation annotation : c1.getAnnotations()) {
            System.out.println(annotation);
        }
        // 获得注解的value具体的值
        Table annotation = (Table) c1.getAnnotation(Table.class);
        System.out.println((String) annotation.value());
        // 获得指定的注解
        Field age=c1.getDeclaredField("age");
        for (Annotation ageAnnotation : age.getAnnotations()) {
            System.out.println(ageAnnotation);
        }

    }
}

@Table("db_Student")  // db:数据库
class Student2{
    @MYField(columnName = "db_age",type = "int",length = 3)
    private int age;
    @MYField(columnName = "db_id",type = "int",length = 10)
    private int id;
    @MYField(columnName = "db_name",type = "String",length = 5)
    private String name;

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

    public int getAge() {
        return age;
    }

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

    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;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "age=" + age +
                ", id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
    String value();
}

// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MYField{
    String columnName(); // 列名
    String type();       // 类型
    int length();        // 长度
}
posted @ 2023-09-14 01:08  被占用的小海海  阅读(2)  评论(0编辑  收藏  举报