获取注解内容实例

@Table

package com.websocket.demo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {

    // 数据库表名
    String value();
}

 

@Field

package com.websocket.demo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {

    // 类型
    String type();

    // 列名
    String columnname();

    /// 长度
    int length();


}

 

 

实体类People.class

package com.websocket.demo.entity;

import com.websocket.demo.annotation.Field;
import com.websocket.demo.annotation.Table;

@Table("t_people")
public class People {

    @Field(type = "int", columnname = "id", length = 20)
    private int id;

    @Field(type = "varchar", columnname = "name", length = 20)
    private String name;

    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 People() {
    }

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

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

 

 

获取People类上的注解内容

    @Test
    public void annotationTest() throws Exception{
        Class cls = Class.forName("com.websocket.demo.entity.People");
        Annotation[] annotations = cls.getAnnotations();
        for(Annotation a: annotations){
            System.out.println("获取修饰类的注解" + a.toString());
        }
        Table t = (Table)cls.getDeclaredAnnotation(Table.class);
        System.out.println("获取指定类的注解" + t.toString() + " 注解参数vaule值" + t.value());

        Field[] fields = cls.getDeclaredFields();
        for(Field field : fields){
            com.websocket.demo.annotation.Field t_field = field.getDeclaredAnnotation(com.websocket.demo.annotation.Field.class);
            String type = t_field.type();
            String columnname = t_field.columnname();
            int length = t_field.length();
            System.out.println("type: " + type + ", columnname: " + columnname + ", length: " + length);
        }

    }

 

输出结果:

获取修饰类的注解@com.websocket.demo.annotation.Table(value=t_people)
获取指定类的注解@com.websocket.demo.annotation.Table(value=t_people) 注解参数vaule值t_people
type: int, columnname: id, length: 20
type: varchar, columnname: name, length: 20

 

posted @ 2021-02-19 11:47  ryelqy  阅读(274)  评论(0编辑  收藏  举报