java 反射注解信息

发布时间:2020-06-22 13:20:50 作者:wx5d21d5e6e5ab1
来源:网络 阅读:350

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();
    }
}
}
推荐阅读:
  1. java中不同注解的作用
  2. java基础反射Reflection是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java ava j

上一篇:Linux系统Oracle12.2 RAC集群实施维护_Oracle数据库12cR2(项目实战之五)

下一篇:LESS入门

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》