运行时注解解析

 

当注解的@RetentionRUNTIME时,此注解为运行时注解。

如果一个元素上面使用了运行时注解,我们可以在运行时使用反射,读取元素上的注解进行解析处理。

 

比如说对于如下的实体类Student,我们想根据他的成员变量生成插入数据库时的SQL语句

public class Student {

 

       @ColumnAnnotation(columnName = "id", length = 10, type = "int")

       private int id;

 

       @ColumnAnnotation(columnName = "sname", length = 10, type = "varchar")

       private String name;

 

       @ColumnAnnotation(columnName = "age", length = 10, type = "int")

       private int age;

 

       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 int getAge() {

              return age;

       }

 

       public void setAge(int age) {

              this.age = age;

       }

 

}

则可以创建如下的注解ColumnAnnotation,在Student类上使用注解,在运行时通过解析注解来生成语句

@Target(value={ElementType.FIELD})

@Retention(value = RetentionPolicy.RUNTIME)

public @interface ColumnAnnotation {

      

       String columnName();

       String type();

       int length();

}

 

public static void main(String[] args) {

       try {

              //获得类

              Class<?> clazz = Class.forName("com.bjsxt.annotation.Student");

             

              //获得类的注解

              Annotation[] annotations = clazz.getAnnotations();

              for (Annotation annotation : annotations) {

                     System.out.println(annotation);

              }

             

              //获得类的成员变量name

              Field field = clazz.getDeclaredField("name");

             

              //获得成员变量上的注解

              ColumnAnnotation sf = field.getAnnotation(ColumnAnnotation.class);

              System.out.println(sf.columnName());

              System.out.println(sf.type());

              System.out.println(sf.length());

             

       } catch (ClassNotFoundException e) {

              e.printStackTrace();

       } catch (NoSuchFieldException e) {

              e.printStackTrace();

       } catch (SecurityException e) {

              e.printStackTrace();

       }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值