1、首先我們了解一下如何自定義一個注解。
@Target(),下面是@Target的描述
* The constants of this enumerated type provide a simple classification of the * syntactic locations where annotations may appear in a Java program. These * constants are used in {@link Target java.lang.annotation.Target} * meta-annotations to specify where it is legal to write annotations of a * given type.
可以看到它主要用來表面注解用在哪里,我們常常可以看到有的注解用於類上,有的用於方法上等等,這個就是來表面注解用的位置的。
它的參數有下面幾個類型:
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Formal parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE, /** * Type parameter declaration * * @since 1.8 */ TYPE_PARAMETER, /** * Use of a type * * @since 1.8 */ TYPE_USE }
然后再看看@Retention,同樣可以用上面的方法,可以看到它主要用來表面注解保留到什么時候的。
主要參數有:
RetentionPolicy.RUNTIME : 在.class文件中仍保留,在虛擬機運行時也保留着。
RetentionPolicy.CLASS : 保留在.class文件中,但是在虛擬機運行時將會刪除,默認這個。
RetentionPolicy.SOURCE: 在編譯器生成.class文件過程中就會丟棄。
下面自定義一個注解Log,在使用時就可以@Log(value="");默認為空,Log也可以加其他的方法。
package com.springboot.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Log { String value() default ""; }