码迷,mamicode.com
首页 > 编程语言 > 详细

java 反射注解信息

时间:2019-09-10 22:07:43      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:oid   arch   属性表   name   exce   strong   etag   catch   retention   

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();
    }
}
}

java 反射注解信息

标签:oid   arch   属性表   name   exce   strong   etag   catch   retention   

原文地址:https://blog.51cto.com/14437184/2437244

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!