java 反射注解信息

Table,用类表示数据库的表

@Target(value= {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table{
    String value();

}

类中的属性,每个属性表示一个字段

    @Target(value= ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Fields {
        String columnName();
        String type();
        int length();
    }

类:

@Table("tb_student")
public class Student {

@Fields(columnName="id",type="int",length=10)
private int id;

@Fields(columnName="studentName",type="varchar",length=10)
private String studentName;

@Fields(columnName="age",type="int",length=3)
private int age;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getStudentName() {
    return studentName;
}
public void setStudentName(String studentName) {
    this.studentName = studentName;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

}

解析器:

public class Deam {

public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException {
    try {
        Class c=Class.forName("cn.sxt.in.Student");
        Annotation[] annotation= c.getAnnotations();  //获得类的所有注解,只是类的,不包括方法等

        for(Annotation a:annotation)
        {
            System.out.println(a);
        }
        //获得指定类的注解
        Table tb=(Table) c.getAnnotation(Table.class);
        System.out.println(tb.value());

        //获得属性的注解
        Field f=c.getDeclaredField("studentName"); //通过内容返回属性
        Fields f2=f.getAnnotation(Fields.class); //通过属性返回注解
        System.out.println(f2.columnName()+"-->"+f2.type()+"-->"+f2.length());

    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    }
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值