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

Java注解

时间:2021-01-26 12:44:39      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:method   ide   bool   coder   swa   retention   local   str   on()   

Java注解Annotation

元注解

@Retention

保留期,当@Retention应用到一个注解上,说明了这个注解的存活时间。

  • RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视
  • RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到JVM中
  • RetentionPolicy.RUNTIME注解可以保留到程序运行的时候,会被加载到JVM中,程序运行时可以获取
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
}
@Documented

作用:能够将注解中的元素包含到Javadoc中去

@Target

指定了注解运用的地方,被@Target注解的注解就被限定了运用的场景

  • ElementType.ANNOTATION_TYPE 可以给一个注解进行注解
  • ElementType.CONSTRUCTOR 可以给构造方法进行注解
  • ElementType.FIELD 可以给属性进行注解
  • ElementType.LOCAL_VARIABLE 可以给局部变量注解
  • ElementType.METHOD 方法
  • ElementType.PACKAGE 包
  • ElementType.PARAMETER 方法内的参数
  • ElementType.TYPE 类型 比如类、接口、枚举
@Inherited

继承,注解 Test 被 @Inherited 修饰,之后类 A 被 Test 注解,类 B 继承 A,类 B 也拥有 Test 这个注解。

@Repeatable

可重复,注解的值可以同时取多个

@interface Persons {
    Person[]  value();
}
@Repeatable(Persons.class)//@Repeatable后面括号中的类相当于一个容器注解,即用于存放其他注解的地方,本身也是注解
@interface Person{
    String role default "";
}
@Person(role="artist")
@Person(role="coder")
@Person(role="PM")
public class SuperMan{
}
//Persons 是一张总的标签,上面贴满了 Person 这种同类型但内容不一样的标签。把 Persons 给一个 SuperMan 贴上,相当于同时给他贴了程序员、产品经理、画家的标签。

注解的属性

AKA成员变量,注解只有成员变量,没有方法。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    int id();
    String msg();
}
//定义了TestAnnotation这个注解中两个属性
//赋值方式
@TestAnnotation(id=3,msg="hello annotation")
public class Test {
}
//如果一个注解没有任何属性
public @interface Perform{}
//在应用这个注解的时候,括号都可以省略
@Perform
Public void testMethod(){}

Java预置的注解

@Deprecated

标记过时的元素

@Override

提示子类要复写父类中被@Override修饰的方法

@SuppressWarnings

组织警告,之前说过调用被 @Deprecated 注解的方法后,编译器会警告提醒,而有时候开发者会忽略这种警告,他们可以在调用的地方通过 @SuppressWarnings 达到目的。

@FunctionalInterface

函数式接口注解,函数式接口就是一个具有一个方法的普通接口

@FunctionalInterface
public interface Runnable{
  public abstrct void run();
}

注解与反射

注解通过反射获取

@TestAnnotation()
public class Test {
    public static void main(String[] args) {
      //首先可以通过 Class 对象的 isAnnotationPresent() 方法判断它是否应用了某个注解
        boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
        if ( hasAnnotation ) {
          //然后通过 getAnnotation() 方法来获取 Annotation 对象。
            TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
            System.out.println("id:"+testAnnotation.id());//返回指定类型的注解
            System.out.println("msg:"+testAnnotation.msg());
        }
    }

总结

  • 注解相当于标签,标签为了解释事物,注解为了解释代码
  • 注解的基本语法,创建如同接口,但是多了@符号
  • 注解主要给编译器及工具类型的软件用的
  • 注解的提取需要借助于Java的反射技术,反射比较慢,所以使用注解时需要计较时间成本

Java注解

标签:method   ide   bool   coder   swa   retention   local   str   on()   

原文地址:https://www.cnblogs.com/GladysJiu/p/14325736.html

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