注解Annotation

注解 Annotation

作用:

  1. 不是程序本身,可以对程序做出解释
  2. 可以被其他程序读取(编译器等)

格式:

  1. @注释名 使用方式 @Override
  2. 还可以添加参数值 @SuppressWarnings(value = “unchecked”)

使用位置:

  1. package
  2. class
  3. method
  4. field

内置注解:

  • @Override
    • 重写
  • @Deprecated
    • 修饰方法/属性/类,表示不推荐使用
  • @SuppressWarnings
    • 抑制编译时的警告信息

自定义注解:

使用 @interface 自定义注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
    String column();
    String type();
    int length() default 5;
}

元注解:

负责注解其他注解,Java定义了4个标准 meta-annotation 类型

  • @Target
    • 取枚举的值 ElementType
      • PACKAGE:包
      • TYPE:类/接口/枚举/Annotation类型
      • CONSTRUCTOR:构造器
      • FIELD:域
      • METHOD:方法
      • LOCAL_VARIABLE:局部变量
      • PARAMETER:方法参数
  • @Retention
    • 取枚举值 RetentionPolicy
      • SOURCE:在源文件中有效
      • CLASS:在class文件中有效
      • RUNTIME:在运行时有效,可以被反射机制读取,常用
  • @Documented
  • @Inherited

注解信息读取:

/**
 * 表注解
 * */
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}

/**
 * 字段注解
 * */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
    String column();
    String type();
    int length() default 5;
}

/**
 * 注解使用
 * */
@Table("t_student")
public class Student {
    @Field(column = "id", type = "varchar2", length = 10)
    private Integer id;
    @Field(column = "nameeeee", type = "varchar2", length = 20)
    private String name;
    //getset
}

/**
 * 读取注解信息
 * */
@Test
public void test1() throws Exception {
    Class<?> clazz = Class.forName("annotation.Student");
    /* 获得类的所有有效注解 */
    Annotation[] annotations = clazz.getAnnotations();
    for (Annotation a : annotations) {
        System.out.println(a); // - @annotation.Table(value=t_student)
    }
    
    /* 获得类的指定注解 */
    Table table = clazz.getAnnotation(Table.class);
    System.out.println(table.value()); // - t_student
    
    /* 获得类的属性注解 */
    Field name = clazz.getDeclaredField("name");
    annotation.Field field = name.getAnnotation(annotation.Field.class);
    System.out.println(field); // - @annotation.Field(length=20, column=nameeeee, type=varchar2)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值