java通过反射操作注解

通过反射操作注解

package com.yuanyu.annandre;

import java.lang.annotation.*;
import java.lang.ref.SoftReference;

//通过反射操作注解
public class Test13 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("com.yuanyu.annandre.Student2");

        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation); //@com.yuanyu.annandre.Table(value=db_student)
        }

        //获得注解value的值
        Table table = (Table) c1.getAnnotation(Table.class); //获得指定注解
        System.out.println(table.value());

        //获得指定类的指定注解
        java.lang.reflect.Field f = c1.getDeclaredField("name");
        Field annotation = f.getAnnotation(Field.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.length());
        System.out.println(annotation.type());
    }
}

@Table("db_student")
class Student2{
    @Field(columnName = "db_name",length = 3,type = "varchar")
    String name;
    @Field(columnName = "db_id",length = 10,type = "int")
    int id;
    @Field(columnName = "db_age",length = 10,type = "int")
    int age;

    public Student2() {
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        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;
    }

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

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

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field{
    String columnName(); //字段名
    String type(); //字段类型
    int length(); //字段长度
}

程序运行结果:

@com.yuanyu.annandre.Table(value=db_student)
db_student
db_name
3
varchar

posted @ 2022-01-27 16:02  原语  阅读(257)  评论(0编辑  收藏  举报