当前位置:网站首页>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
边栏推荐
- Leetcode->1 两数之和
- How to regulate intestinal flora? Introduction to common natural substances, probiotics and prebiotics
- 【Echart】echart 入門
- 小红书被曝整体裁员20%,大厂之间内卷也很严重
- Matlab minimalist configuration of vscode configuration
- The difference between lists, tuples, dictionaries and collections
- A new method for evaluating the quality of metagenome assembly - magista
- Express中间件①(中间件的使用)
- 【李宏毅2022 机器学习春】hw6_GAN(不懂..)
- 递归调用--排列的穷举
猜你喜欢

Xshell、Xftp连接新创建的Unbutu系统虚拟机全流程

Opencv -- yoact case segmentation model reasoning

Introduction to Cortex-M3 register set, assembly language and C language interface

MATLAB lit plusieurs diagrammes fig et les combine en un seul diagramme (sous forme de sous - Diagramme)

【NeurIPS 2019】Self-Supervised Deep Learning on Point Clouds by Reconstructing Space

秒杀所有区间相关问题

AWS EKS添加集群用户或IAM角色
![[AI vision · quick review of NLP natural language processing papers today, No. 32] wed, 20 APR 2022](/img/b2/269ae2e9be269c2bff73eb1da5b55d.png)
[AI vision · quick review of NLP natural language processing papers today, No. 32] wed, 20 APR 2022
![[mapping program design] coordinate inverse artifact v1 0 (with C / C / VB source program)](/img/12/de3b2c6ea98be57a8abe2790debfb5.png)
[mapping program design] coordinate inverse artifact v1 0 (with C / C / VB source program)

RC低通滤波器的逆系统
随机推荐
STM32 MCU ADC rule group multi-channel conversion DMA mode
[mapping program design] coordinate inverse artifact v1 0 (with C / C / VB source program)
LabVIEW 小端序和大端序区别
阿里十年技术专家联合打造“最新”Jetpack Compose项目实战演练(附Demo)
[AI vision · quick review of NLP natural language processing papers today, No. 32] wed, 20 APR 2022
指纹Key全国产化电子元件推荐方案
小红书被曝整体裁员20%,大厂之间内卷也很严重
C语言 字符常量
Alibaba cloud IOT transfer to PostgreSQL database scheme
QT program integration easyplayer RTSP streaming media player screen flicker what is the reason?
/etc/bash_completion.d目录作用(用户登录立刻执行该目录下脚本)
Go反射法则
Qtspim manual - Chinese Translation
A new method for evaluating the quality of metagenome assembly - magista
VHDL implementation of 32-bit binary to BCD code
[Li Hongyi 2022 machine learning spring] hw6_ Gan (don't understand...)
【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..
HMS Core Discovery第14期回顾长文|纵享丝滑剪辑,释放视频创作力
Qt程序集成EasyPlayer-RTSP流媒体播放器出现画面闪烁是什么原因?
现货黄金操作技巧_估波曲线