Java 注解

元信息

Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。

Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。

由于 jdk 和框架大量使用注解,我也简单介绍下注解为何物,若您发现文章中存在错误或不足的地方,希望您能指出!

Java 定义了一套注解,共有 7 个,3 个在 java.lang 中,剩下 4 个在 java.lang.annotation 中。

作用在代码的注解是

  • @Override - 检查该方法是否是重写方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
  • @Deprecated - 标记过时方法。如果使用该方法,会报编译警告。
  • @SuppressWarnings - 指示编译器去忽略注解中声明的警告。

作用在其他注解的注解 (或者说 元注解) 是:

  • @Retention - 标识这个注解怎么保存,是只在代码中,还是编入 class 文件中,或者是在运行时可以通过反射访问。
  • @Documented - 标记这些注解是否包含在用户文档中。
  • @Target - 标记这个注解应该是哪种 Java 成员。
  • @Inherited - 标记这个注解是继承于哪个注解类 (默认 注解并没有继承于任何子类)

从 Java 7 开始,额外添加了 3 个注解:

  • @SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
  • @FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
  • @Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。

 

Annotation 架构图如下:

Annotation 的每一个实现类,都 和 1 个 RetentionPolicy 关联, 和 1~n 个 ElementType 关联。

注意 RetentionPolicy 的三种策略,自定义注解需要设置策略

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
       注解将被编译器丢弃
     */
    SOURCE,
<span class="hljs-comment">/**
 * 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文件中可用,但会被VM丢弃
 */</span>
CLASS,

<span class="hljs-comment">/**
 * 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.
 *  VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
 * <span class="hljs-doctag">@see</span> java.lang.reflect.AnnotatedElement 
 */</span>
RUNTIME

}


注意 ElementType,自定义注解时特别关注,有多种类型

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration 
        类,接口 (包括注解类型) 或 enum 声明 */
    TYPE,
<span class="hljs-comment">/** Field declaration (includes enum constants) 
    域声明(包括 enum 实例)*/</span>
FIELD,

<span class="hljs-comment">/** Method declaration 方法声明*/</span>
METHOD,

<span class="hljs-comment">/** Formal parameter declaration 参数声明*/</span>
PARAMETER,

<span class="hljs-comment">/** Constructor declaration 构造器声明*/</span>
CONSTRUCTOR,

<span class="hljs-comment">/** Local variable declaration 局部变量声明*/</span>
LOCAL_VARIABLE,

<span class="hljs-comment">/** Annotation type declaration 注解类型声明*/</span>
ANNOTATION_TYPE,

<span class="hljs-comment">/** Package declaration 包声明*/</span>
PACKAGE,

<span class="hljs-comment">/**
 * Type parameter declaration
 *
 * <span class="hljs-doctag">@since</span> 1.8
 */</span>
TYPE_PARAMETER,

<span class="hljs-comment">/**
 * Use of a type
 *
 * <span class="hljs-doctag">@since</span> 1.8
 */</span>
TYPE_USE

}


下面是个小例子:

自定义注解:

@Documented
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
<span class="hljs-keyword">public</span> String <span class="hljs-title function_">name</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">""</span>;
<span class="hljs-keyword">public</span> String <span class="hljs-title function_">value</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">""</span>;

}


 在类中使用

/**
 * @author dgm
 * @describe ""
 */
@CustomAnnotation(name="Class Annotation",  value = "类上的注解")
public class SampleClass {
	@CustomAnnotation(name = "field Annotation", value = "字段上的注解")
	public String sampleField;
<span class="hljs-meta">@CustomAnnotation(name = "constructor  Annotation", value = "构造器上的注解")</span>
<span class="hljs-keyword">public</span> <span class="hljs-title function_">SampleClass</span><span class="hljs-params">(String sampleField)</span> {
	<span class="hljs-built_in">super</span>();
	<span class="hljs-built_in">this</span>.sampleField = sampleField;
}

<span class="hljs-meta">@CustomAnnotation(name = "Method Annotation getSampleField", value = "getSampleField无参方法上的注解")</span>
<span class="hljs-keyword">public</span> String <span class="hljs-title function_">getSampleField</span><span class="hljs-params">()</span> {
	System.out.println(<span class="hljs-string">"getSampleField"</span>);
	<span class="hljs-keyword">return</span> sampleField;
}

<span class="hljs-meta">@CustomAnnotation(name = "Method Annotation setSampleField", value = "setSampleField方法上的注解")</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setSampleField</span><span class="hljs-params">(String sampleField)</span> {
	System.out.println(<span class="hljs-string">"setSampleField="</span> + sampleField);
	<span class="hljs-built_in">this</span>.sampleField = sampleField;
}

<span class="hljs-meta">@CustomAnnotation(name = "Method Annotation getSampleField hava param", value = "getSampleField有参方法上的注解")</span>
<span class="hljs-keyword">private</span> String <span class="hljs-title function_">getSampleField</span><span class="hljs-params">(String sampleField)</span> {
	<span class="hljs-keyword">return</span> sampleField;
}

}


测试类

/**
 * 
 * @author dgm
 * @describe ""
 */
public class CustomAnnotationTest {
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
	<span class="hljs-type">Class</span> <span class="hljs-variable">c0</span> <span class="hljs-operator">=</span> SampleClass.class;
	<span class="hljs-type">Class</span> <span class="hljs-variable">c1</span> <span class="hljs-operator">=</span> Class.forName(<span class="hljs-string">"spring.annotation.SampleClass"</span>);
	<span class="hljs-type">Object</span> <span class="hljs-variable">o</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;
	<span class="hljs-keyword">try</span> {
		o = Class.forName(<span class="hljs-string">"spring.annotation.SampleClass"</span>).getConstructor(String.class).newInstance(<span class="hljs-string">"dongguangming"</span>);
	} <span class="hljs-keyword">catch</span> (NoSuchMethodException | SecurityException e) {
		<span class="hljs-comment">// TODO Auto-generated catch block</span>
		e.printStackTrace();
	}
	<span class="hljs-type">Class</span> <span class="hljs-variable">c2</span> <span class="hljs-operator">=</span> o.getClass();
	System.out.println(c0 == c1);
	System.out.println(c0 == c2);
	System.out.println(c1 == c2);

	<span class="hljs-comment">// 获取类的所有注解</span>
	Annotation[] classAnnotation = c0.getAnnotations();
	<span class="hljs-keyword">for</span> (Annotation ca : classAnnotation) {
		<span class="hljs-keyword">if</span> (ca <span class="hljs-keyword">instanceof</span> CustomAnnotation) {
			<span class="hljs-type">CustomAnnotation</span> <span class="hljs-variable">customAnnotation</span> <span class="hljs-operator">=</span> (CustomAnnotation) ca;
			System.out.println(<span class="hljs-string">"class name: "</span> + customAnnotation.name());
			System.out.println(<span class="hljs-string">"class value: "</span> + customAnnotation.value());
		}
	}

	<span class="hljs-comment">// 获取类的公有field</span>
	Field[] fields = c0.getFields();
	<span class="hljs-keyword">for</span> (Field field : fields) {
		Annotation[] fieldAnnotation = field.getAnnotations();
		<span class="hljs-keyword">for</span> (Annotation fa : fieldAnnotation) {
			<span class="hljs-keyword">if</span> (fa <span class="hljs-keyword">instanceof</span> CustomAnnotation) {
				<span class="hljs-type">CustomAnnotation</span> <span class="hljs-variable">customAnnotation</span> <span class="hljs-operator">=</span> (CustomAnnotation) fa;
				System.out
						.println(<span class="hljs-string">"field name: "</span> + customAnnotation.name());
				System.out.println(<span class="hljs-string">"field value: "</span>
						+ customAnnotation.value());

			}
		}
	}

	<span class="hljs-comment">// 获取构造器的所有注解</span>
	<span class="hljs-comment">// 获取类的构造器</span>
    Constructor&lt;?&gt;[] publicConstructors = c0.getConstructors();<span class="hljs-comment">//getDeclaredConstructors</span>

    <span class="hljs-keyword">for</span> (Constructor constructor : publicConstructors) {
		Annotation[] methodAnnotation = constructor.getAnnotations();
		<span class="hljs-keyword">for</span> (Annotation ma : methodAnnotation) {
			<span class="hljs-keyword">if</span> (ma <span class="hljs-keyword">instanceof</span> CustomAnnotation) {
				<span class="hljs-type">CustomAnnotation</span> <span class="hljs-variable">customAnnotation</span> <span class="hljs-operator">=</span> (CustomAnnotation) ma;
				System.out.println(<span class="hljs-string">"构造器 name: "</span>
						+ customAnnotation.name());
				System.out.println(<span class="hljs-string">"构造器 value: "</span>
						+ customAnnotation.value());

			}
		}
    }
    
	<span class="hljs-comment">// 获取类的公有方法</span>
	Method[] methods = c0.getMethods();
	<span class="hljs-comment">// Annotation annotation =</span>
	<span class="hljs-comment">// methods[1].getAnnotation(CustomAnnotation.class);</span>
	<span class="hljs-keyword">for</span> (Method method : methods) {
		Annotation[] methodAnnotation = method.getAnnotations();
		<span class="hljs-keyword">for</span> (Annotation ma : methodAnnotation) {
			<span class="hljs-keyword">if</span> (ma <span class="hljs-keyword">instanceof</span> CustomAnnotation) {
				<span class="hljs-type">CustomAnnotation</span> <span class="hljs-variable">customAnnotation</span> <span class="hljs-operator">=</span> (CustomAnnotation) ma;
				System.out.println(<span class="hljs-string">"method name: "</span>
						+ customAnnotation.name());
				System.out.println(<span class="hljs-string">"method value: "</span>
						+ customAnnotation.value());

			}
		}

// 获取方法上的所有参数注解
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for(Annotation[] pa : parameterAnnotations){
for(Annotation a:pa){
if(a instanceof CustomAnnotation){
System.out.println("method param name:"
+ ((CustomAnnotation) a).name());
System.out.println("method param value:"
+ ((CustomAnnotation) a).value());
}
}
}

	}
   }

}


执行效果:

 看到了吧,一个类上可以多个注解,一个字段也可以有多个注解,构造器上也可以多个注解,方法上也可以有多个注解、参数上也可以有多个注解,而类是可以有多个字段、多个构造器(每个构造器都可能有多个参数)、多个方法(每个方法也都肯能有多个参数)),所以真正写框架时光逻辑性 if else 判断就折腾 了。。。举个例子类上有 A 注解执行什么代码,有 B 注解执行什么代码,以此类推字段、构造器、方法、参数的多个注解的处理过程。

 

实际开发中我们也会用到自定义注解,比如:

 

自定义注解是很强大的功能,广泛应用于框架(Struts,hibernate,Mybatis,Spring,  Spring boot,sping cloud,dubbo 等)和系统开发公共模块(比如上图中的登录拦截和取当前用户)中

 

参考:

0. Java 程序员必须掌握的 5 个注解! https://developer.51cto.com/art/201807/577539.htm

1. Lesson: Annotations

https://docs.oracle.com/javase/tutorial/java/annotations/

2. Java Annotations Tutorial https://www.javacodegeeks.com/2014/11/java-annotations-tutorial.html

3. How To Process Java Annotations

https://www.javacodegeeks.com/2015/01/how-to-process-java-annotations.html

4. An introductory guide to annotations and annotation processors 

https://blog.frankel.ch/introductory-guide-annotation-processor/

5. Java Annotation Processing and Creating a Builder
https://www.baeldung.com/java-annotation-processing-builder

6. How and when to use Enums and Annotations https://www.javacodegeeks.com/2015/09/how-and-when-to-use-enums-and-annotations.html

7. Common Annotations for the Java™ Platform™ https://download.oracle.com/otn-pub/jcp/common_annotations-1_3-mrel3-eval-spec/jsr-250.pdf?AuthParam=1590270326_b56b01b1aeacddec8562720c1b2f27b8

8. Java - Understanding @Inherited meta annotation

https://www.logicbig.com/tutorials/core-java-tutorial/annotations/inherited-meta-annotation.html

9. 深入理解 java 注解的实现原理 https://mp.weixin.qq.com/s?__biz=MzAxMjY1NTIxNA==&mid=2454441897&idx=1&sn=729688d470c94560c1e73e79f0c13adc&chksm=8c11e0a8bb6669be1cc4daee95b221ba437d536d598520d635fac4f18612dded58d6fddb0dce&scene=21#wechat_redirect

10.  Annotations in Java 5.0  https://javabeat.net/annotations-in-java-5-0/