java注解

一、java 自身的注解

  • @Deprecated 表明当前的元素已经不推荐使用
  • @Override 表明当前方法是覆盖了父类方法
  • @SuppressWarnings 关闭编译器警告信息

二、自定义注解

接口声明

1 @Target(ElementType.METHOD)
2 @Retention(RetentionPolicy.RUNTIME)
3 public @interface MyMethodAnnotation {
4 
5 }

使用自定义注解

 1 public class AnnotationDemo {
 2 
 3     @MyMethodAnnotation
 4     public void test() {
 5         
 6     }
 7     
 8     @MyMethodAnnotation
 9     public void test2() {
10         
11     }
12     
13     public void test3() {
14         
15     }
16 }

测试

 1 public class Client {
 2 
 3     public static void main(String[] args) {
 4         Method[] methods = AnnotationDemo.class.getMethods();
 5         for(Method m : methods) {
 6             if(m.isAnnotationPresent(MyMethodAnnotation.class)) {
 7                 System.out.println("----- " + m.getName() + " -------");
 8             }
 9         }
10     }
11 }

结果

----- test -------
----- test2 -------

三、元注解

作用负责注解其它注解

@Target
@Retention
@Documented
@Inherited

 1、@Target : 描述注解的使用范围

  取值(ElementType)有,

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE, // 用于描述类、接口(包括注解类型) 或enum声明

    /** Field declaration (includes enum constants) */
    FIELD, // 用于描述域

    /** Method declaration */
    METHOD, // 用于描述方法

    /** Parameter declaration */
    PARAMETER, // 用于描述参数

    /** Constructor declaration */
    CONSTRUCTOR, // 用于描述构造函数

    /** Local variable declaration */
    LOCAL_VARIABLE, // 用于描述局部变量

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE // 用于描述包
}

 2、@Retention : 描述注解的生命周期

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,  //在源文件有效 保留在源文件

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS, //在class文件有效 保留在class文件

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME //在运行时有效 运行时保留
}

3、@Documented : 用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化

4、@Inherited :阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

四、启示

想想,自定义注解还是有很多好处的。junit测试框架,方法上注解@Test,@Before, @After。没看过它的底层实现,不过仔细想想,无非也是通过运行期反射去拿到定义在方法的注解,

根据不同注解类型,来执行不同的操作。

原文地址:https://www.cnblogs.com/chenmo-xpw/p/5533239.html