当前位置:网站首页>Reflection operation annotation

Reflection operation annotation

2022-06-22 06:17:00 Kuxiaoya

practice :ORM( Object relation mapping )

 Insert picture description here

The code is as follows :

/** *  Practice reflection operation notes  */
public class Demo12 {
    
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
    
        Class c1 = Class.forName("www.jin.Student2");

        // Provide reflection to get annotation 
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
    
            System.out.println(annotation);
        }

        // Get annotated value Value 
        TableJin tableJin = (TableJin) c1.getAnnotation(TableJin.class);
        String value = tableJin.value();
        System.out.println(value);

        // Get the annotation specified by the class 
        Field f = c1.getDeclaredField("id");
        FieldJin annotation = f.getAnnotation(FieldJin.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
    }
}
@TableJin("db_student")
class Student2{
    

    @FieldJin(columnName = "db_id",type = "int",length = 10)
    private int id;
    @FieldJin(columnName = "db_age",type = "int",length = 10)
    private int age;
    @FieldJin(columnName = "db_name",type = "varchar",length = 3)
    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;
    }

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

// Annotation of class name 
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableJin{
    
    String value();
}

// Comment for attribute 
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldJin{
    
    String columnName();
    String type();
    int length();
}

Running results :

 Insert picture description here

原网站

版权声明
本文为[Kuxiaoya]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220609551506.html