反射操作注解

ORM:什么是ORM

Object relationship Mapping - > 对象关系映射

反射获得注解

public class test12 {
    
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("dome_05_注解.Student2");
        //通过反射 获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        // 获得 注解 value 的值
        Tablekuang annotation = (Tablekuang) c1.getAnnotation(Tablekuang.class);
        System.out.println(annotation.value());

        // 获得类指定的注解
        Field name = c1.getDeclaredField("name");
        Fieldkuang annotation2 = name.getAnnotation(Fieldkuang.class);

        System.out.println(annotation2.Columname());
        System.out.println(annotation2.type());
        System.out.println(annotation2.length());

    }
}

使用下面的自定义注解 和 测试类

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

// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldkuang {
    String Columname();
    String type();
    int length();
}

class Student2 {
    private int id;
    private int age;
    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;    }
}

运行结果

原文地址:https://www.cnblogs.com/kutsu/p/14008693.html