当前位置:网站首页>Supplement: Annotation
Supplement: Annotation
2022-04-23 04:27:00 【I have learned to be silent】
primary coverage :
- annotation (Annotation) summary
- common Annotation Example
- Customize Annotation
- JDK Meta annotations in
- Using reflection to get annotation information ( In the reflection part )
- JDK 8 New features of annotations in
Catalog
Example 1 : Generate documentation related annotations
Example 2 : Format check at compile time (JDK Built in three basic annotations )
Example 3 : Trace code dependencies , Implement alternative profile functions
jdk 8 New features of annotations in :
Common annotation examples
Use Annotation Add... In front of it @ Symbol , and hold Annotation As a modifier Use . Used to decorate the program elements it supports
Example 1 : Generate documentation related annotations
@author: Indicate the author who developed the module , Use... Between multiple authors , Division
@version: Indicate the version of the module
@see: Refer to steering , That is, related topics
@since: From which version to add
@param: Description of a parameter in the method , You can't write without parameters
@return Description of the return value of the method , If the return value type of the method is void Can't write
@exception: Describe the exceptions that may be thrown by the method , If the method doesn't work throws An exception thrown explicitly cannot be written in it
Be careful :
@param @return and @exception All three tags are method only .
@param The format of :@param Parameter name parameter type parameter description
@return The format of :@return Return value type return value description
@exception The format of :exception Exception type description
@param and @exception You can have more than one side by side
Example 2 : Format check at compile time (JDK Built in three basic annotations )
@Override: Qualify override parent method , This annotation can only be used for methods
@Deprecated: Used to represent the decorated element ( class , Such method ) Deprecated . It's usually because of the danger of the decorated structure or the existence of a better choice
@SuppressWarnings: Suppress compiler warnings
Example 3 : Trace code dependencies , Implement alternative profile functions
Servlet3.o Notes are provided (annotation), Make it no longer necessary to web.xml In file Servlet Deployment of .
Custom annotation :
reference @SupperWarning
- The annotation states that :@interface
- Internally defined members , Usually use value Express
- You can specify default values for members , Use default Definition
- If the custom annotation has no members , It's a sign .
Define a new Annotation Type used @interface keyword
Custom annotations automatically inherit java.lang.annotation.Annotation Interface
Annotation The member variable of is in Annotation To declare in the form of a parameterless method in a definition . Its method name and return value define the name and type of the member . We call it configuration parameters . Types can only be eight basic data types 、String type 、class type 、enum type 、Annotation type 、 All the above types of arrays .
You can define Annotation The initial value is specified for the member variable of , To specify the initial value of a member variable, you can use default keyword
If there is only one parameter member , It is recommended to use The parameter name is value
If the defined annotation contains configuration parameters , Then the parameter value must be specified when using , Unless it has a default value . The format is “ Parameter name = Parameter values ”, If there is only one parameter member , And the name is value, It can be omitted “value=”
No member defined Annotation be called Mark ; Containing member variables Annotation It's called metadata Annotation
Be careful : User defined annotation must be accompanied by annotation information processing flow to make sense .
Two meta annotations will be indicated by custom annotation : Retention( Life cycle ). Target( Scope )
Custom annotation examples
public @interface MyAnnotation {
String [] value();
}
Specify default
public @interface MyAnnotation {
String [] value() default "hello";
}
@Override There are no members
public @interface Override {
}
Yuan notes
Annotations that annotate existing annotations
JDK Yuan Annotation Used to embellish other things Annotation Definition
JDK5.0 Provides 4 A standard meta-annotation type , Namely :
- Retention: Specify the decorated Annotation Life cycle of :SOURCE\CLASS( Default behavior )\RUNTIME Only declared as RUNTIME Life cycle notes , Only by reflection can we get .
- Target: Used to specify decorated Annotation Which program elements can be used to decorate
- The following two are less used
- Documented: Indicates that the modified annotation is being javadoc When parsing , Keep it .
- Inherited: Decorated with it Annotation Will be inherited .
@Retention
Can only be used to decorate one Annotation Definition , Used to specify the Annotation Life cycle of , @Rentention Contains a RetentionPolicy A member variable of type , Use
@Rentention When you have to be value The member variable specifies the value :
- RetentionPolicy.SOURCE: Valid in source file ( That is, source file retention ), The compiler simply discards comments for this strategy
- RetentionPolicy.CLASS: stay class Valid in file ( namely class Retain ), When running Java The program ,JVM Comments will not be retained . This is the default
- RetentionPolicy.RUNTIME: Valid at run time ( That is, keep it at run time ), When running Java The program ,JVM The comments will be kept . The program can get this comment through reflection .
for example @SuppressWarnings() Source code
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
/**
* The set of warnings that are to be suppressed by the compiler in the
* annotated element. Duplicate names are permitted. The second and
* successive occurrences of a name are ignored. The presence of
* unrecognized warning names is <i>not</i> an error: Compilers must
* ignore any warning names they do not recognize. They are, however,
* free to emit a warning if an annotation contains an unrecognized
* warning name.
*
* <p> The string {@code "unchecked"} is used to suppress
* unchecked warnings. Compiler vendors should document the
* additional warning names they support in conjunction with this
* annotation type. They are encouraged to cooperate to ensure
* that the same names work across multiple compilers.
* @return the set of warnings to be suppressed
*/
String[] value();
}
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,
/**
* 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
}
@Target
Used to modify Annotation Definition , Used to specify decorated Annotation Which program elements can be used to decorate .@Target It also contains a name called value Member variables of .
Value | Value | ||
---|---|---|---|
CONSTRUCTOR | Used to describe a constructor | PACKAGE | Used to describe a package |
FLELD | Used to describe domain | PARAMETRE | Used to describe parameters |
LOCAL_VARIABLE | Used to describe local variables | TYPE | Used to describe a class 、 Interface ( Including annotation types ) or enum Statement |
METHOD | Used to describe a method |
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
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
}
@Documented
Used to specify the Annotation Embellished Annotation Class will be javadoc Tools to extract documents . By default ,javadoc It doesn't include comments .
Defined as Documented The annotation for must be set Retention The value is RUNTIME.
@Inherited
Decorated with it Annotation Will be inherited . If a class uses the @lnherited Embellished Annotation, The subclass will automatically have the annotation .
- such as : If you mark it with @Inherited Custom annotations for annotations are annotated at the class level , Subclasses can inherit annotations at the parent class level
- Practical application , Use less
jdk 8 New features of annotations in :
Repeatable notes
@MyAnnotation(value = "hello")
@MyAnnotation(value = "hi")
class Person {
private String name;
private int age;}
Writing this directly will report an error
terms of settlement :
stay jdk8 before
1. Declare the value in the annotation as an array of annotation types
public @interface MyAnnotations {
MyAnnotation[] value();
}
2. Put two comments in
@MyAnnotations({@MyAnnotation(value = "hello"),@MyAnnotation(value = "hi")})
class Person {
private String name;
private int age;}
stay jdk8 in the future
stay MyAnnotation Statement above @Repeatable, The member value is MyAnnotations.class
MyAnnotation Of @Target and @Retention@Inherited It has to be with MyAnnotations identical .
@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {
String [] value() default "hello";
}
public @interface MyAnnotations {
MyAnnotation[] value();
}
@MyAnnotation(value = "hello")
@MyAnnotation(value = "hi")
class Person {
private String name;
private int age;
}
Type notes
JDK1.8 after , About meta annotations @Target Parameter type ElementType Enumeration value is two more individual
- TYPE_PARAMETER
- TYPE_USE
stay Java 8 Before , Annotations can only be used where they are declared ,Java8 Start , Annotations can be applied anywhere .
- ElementType.TYPE_PARAMETER Indicates that the annotation can be written in the declaration statement of type variable ( Such as : Generic declaration )
- ElementType.TYPE_USE Indicates that the annotation can be used in any statement using the type .
版权声明
本文为[I have learned to be silent]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230426360531.html
边栏推荐
- 【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..
- [AI vision · quick review of NLP natural language processing papers today, issue 31] Fri, 15 APR 2022
- 1个需求的一生,团队协作在云效钉钉小程序上可以这么玩
- Bacterial infection and antibiotic use
- MYSQL50道基础练习题
- MySQL 2013 lost connection to MySQL server during query
- STM32单片机ADC规则组多通道转换-DMA模式
- 229. 求众数 II
- 顺序表的基本操作
- 使用大华设备开发行AI人流量统计出现时间不正确的原因分析
猜你喜欢
IDE Idea 自动编译 与 On Upate Action 、 On Frame Deactivation 的配置
Chlamydia infection -- causes, symptoms, treatment and Prevention
[BIM introduction practice] Revit building wall: detailed picture and text explanation of structure, envelope and lamination
Xiaomi, which has set the highest sales record of domestic mobile phones in overseas markets, paid renewed attention to the domestic market
Bacterial infection and antibiotic use
递归调用--排列的穷举
【BIM入门实战】Revit中的墙体层次以及常见问题解答
Why recommend you to study embedded
秒杀所有区间相关问题
【论文阅读】【3d目标检测】Improving 3D Object Detection with Channel-wise Transformer
随机推荐
Xiaomi, which has set the highest sales record of domestic mobile phones in overseas markets, paid renewed attention to the domestic market
为什么推荐你学嵌入式
【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..
Effects of antibiotics on microbiome and human health
STM32F4单片机ADC采样及ARM-DSP库的FFT
【Echart】echart 入門
小红书被曝整体裁员20%,大厂之间内卷也很严重
[Li Hongyi 2022 machine learning spring] hw6_ Gan (don't understand...)
PHP export excel table
thymeleaf th:value 为null时报错问题
阿里云IoT流转到postgresql数据库方案
Nel ASA: her ø Ya facility in Norway officially opened
记录一下盲注脚本
IDE Idea 自动编译 与 On Upate Action 、 On Frame Deactivation 的配置
The latest price trend chart and trading points of London Silver
Does China Mobile earn 285 million a day? In fact, 5g is difficult to bring more profits, so where is the money?
Who will answer the question?
Single chip microcomputer serial port data processing (1) -- serial port interrupt sending data
三十六计是什么
Network principle | connection management mechanism in TCP / IP important protocol and core mechanism