当前位置:网站首页>Custom annotation (I)
Custom annotation (I)
2022-07-26 21:12:00 【One Zen - little monk】
The note is JDK1.5 A feature introduced at the beginning of the release , Used to describe the code , You can check the bags , class , Interface , Field , Method parameter , Local variables, etc
There are three categories :
1.java Own standard notes , Such as @Override( Override a method ),@Deprecated( Indicates that a class or method is out of date ),@SuppressWarnings( Indicate warnings to ignore )
2. One is meta annotation , Meta annotations are used to define annotations , Include @Retention( Indicate the stage in which the annotation is retained ),@Target( Indicate the scope of use of annotations ),@Inherited( Indicate that annotations are inheritable ),@Documented( Indicate whether to generate javadoc file )
3. Custom annotation , You can define comments according to your own needs
effect :
1. Generating documentation , Generated by metadata identified in the code javadoc file
2. Compile check , The metadata identified in the code allows the compiler to , Conduct inspection and verification
3. Dynamic processing at compile time , During compilation, the metadata represented in the code is processed dynamically , For example, dynamically generate code
4. Run time dynamic processing , The runtime dynamically processes the metadata represented in the code , For example, use reflection injection example
android Custom comments for
Use meta annotations to define our custom annotations
| Yuan notes | explain |
|---|---|
| @Target | Indicate where our annotations can appear . It's a ElementType enumeration |
| @Retention | The lifetime of this annotation |
| @Document | Indicates that annotations can be javadoc Such tools are documented |
| @Inherited | Whether subclasses are allowed to inherit the annotation , The default is false |
@Target ElementType type explain :
ElementType.TYPE Interface 、 class 、 enumeration 、 annotation
ElementType.FIELD Field
ElementType.METHOD Method
ElementType.PARAMETER Method parameter
ElementType.CONSTRUCTOR Constructors
ElementType.LOCAL_VARIABLE local variable
ElementType.ANNOTATION_TYPE annotation
ElementType.PACKAGE package
@Retention RetentionPolicy type explain :
RetentionPolicy.SOURCE Annotations are only kept in the source file , When Java File compiled into class When you file , The note is abandoned
RetentionPolicy.CLASS The annotation is reserved until class file , but jvm load class The document was abandoned , This is the default lifecycle
RetentionPolicy.RUNTIME Annotations are not only saved to class In file ,jvm load class After the document , There is still
Declaration notes :
adopt @Retention Meta annotations determine when we use annotations , Above
adopt @Target Determine what our annotations are working on
Custom annotation categories :
** Runtime annotations ,** Find our customized annotations through the reflection mechanism during the code running , Then do the corresponding thing
** Compile time annotations ,** In the compilation process, use javac Annotation processor to scan our customized annotations , Process annotations to generate some files we need ( Usually java file )
Compile time annotations :
1. Declaration notes
2. Parsing annotations
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
int value();
}
Annotation parsing at compile time requires us to implement an annotation parsing processor . Pay attention to the work done by the processor , In the process of code compilation , Find the annotation that specifies us , Then add your own specific logic ( It usually generates java file )
Be careful : To achieve a module Must be java-library( because java library To inherit the processor AbstractProcessor)
goole To facilitate our registration of annotation processors , Provide a library for registering processors @AutoService(Processor.class) To register
Add dependency
dependencies {
implementation 'com.google.auto.service:auto-service:1.0-rc2'
}
@AutoService(Process.class)
public class BindViewProcessor extends AbstractProcessor {
private Elements elements;
private Messager messager;
private Filer filer;
private Types types;
/** * The core method of annotation processor , Here we deal with annotations , And generate Java Auxiliary class * * @param set * @param roundEnvironment * @return */
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
Set<? extends Element> annotationElements = roundEnvironment.getElementsAnnotatedWith(BindView.class);
for (Element element : annotationElements){
// Get field name
if (element instanceof TypeElement) {
// Annotations for classes
try {
TypeElement typeElement2 = (TypeElement) element;
System.out.println("typeElement2:" + typeElement2);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Annotations are used for fields
}
}
return false;
}
/** * During compilation ,init() It will be automatically called by the annotation processing tool , And pass in ProcessingEnvironment Parameters , * Many useful tool classes can be obtained through this parameter (Elements,Filer,Messager etc. ) */
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
elements = processingEnv.getElementUtils();
messager = processingEnv.getMessager();
filer = processingEnv.getFiler();
types = processingEnv.getTypeUtils();
}
/** * return processor Treatable annotations * * @return */
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> sets = new HashSet<>();
sets.add(BindView.class.getCanonicalName());
return sets;
}
/** * Used to specify your java edition , Generally return to :SourceVersion.latestSupported() */
@Override
public SourceVersion getSupportedSourceVersion() {
return super.getSupportedSourceVersion();
}
}
process() The core of the method is Element Elements ,Element Elements representing programs , During annotation processing , The compiler will scan all java Source file , And treat each part of the source code as a specific type Element
In addition to understanding the process of customizing the processor Element Class and other subclasses , It also needs to be 4 A help class :
| Annotation processor help class | explain |
|---|---|
| Elements | One is used to deal with Element Tool class of |
| Types | One is used to deal with TypeMirror Tool class of |
| Filer | Used to create files ( Such as creating java file ) |
| Messager | For output , similar print function |
These four help classes , It can be done by init() Function , adopt ProcessingEnvironment Get
After writing the annotation, the processor is app Module import
implementation project(": Module name ")
stay process Function , adopt RoundEnvironment You can return the element with the given annotation
Source code :
public interface RoundEnvironment {
// Returns the element annotated with the given type .
Set<? extends Element> getElementsAnnotatedWith(TypeElement var1);
// Returns the element annotated with the given type .
Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> var1);
}
边栏推荐
- 没有网络怎么配置传奇SF登陆器自动读取列表
- IT系统为什么需要可观测性?
- Tinui development history
- GOM登录器配置免费版生成图文教程
- [Oracle training] - deploy Ogg known as zero downtime migration
- PLSQL package
- LCP 11. Statistics of expected number
- AI technology, simplifying the complex world | teatalk online application practical series, issue 2
- Google's new programming language is called carbon
- "Enterprise management" sincere crm+ - integrated management of enterprise business processes
猜你喜欢

苹果官网罕见打折,iPhone13全系优惠600元;国际象棋机器人弄伤对弈儿童手指;国内Go语言爱好者发起新编程语言|极客头条

2022开放原子全球开源峰会议程速递 | 7 月 27 日分论坛议程一览

微服务化解决文库下载业务问题实践

Beginner experience of safety testing

APaaS低代码平台(一) | 把复杂留给自己,把简单留给用户

DevSecOps,让速度和安全兼顾

Interceptors

How to implement Devops with automation tools | including low code and Devops application practice

How to configure the legendary SF lander to automatically read the list without a network

How to block the legendary GEE engine version? Close player account tutorial through script + engine
随机推荐
BTC和ETH不确定性增强 因加息逼近?美国经济将面临更多痛苦
详细图解b树及C语言实现
关于:获取当前客户端登录的域控
[Oracle training] - deploy Ogg known as zero downtime migration
884. Uncommon words in two sentences - hash table
【MySQL系列】-索引知多少
微服务化解决文库下载业务问题实践
和月薪3W的字节程序员聊过后,才知道自己一直在打杂...
What is the role of cache in the storage system of data blocks?
[OBS] solve the problem of OBS pushing two RTMP streams + timestamp
拦截器、、
Explain the 190 secondary compiler (decoding table) module of SMR laminated hard disk of Western data in detail
Tinui development history
Apaas low code platform (I) | leave complexity to yourself and simplicity to users
Shell comprehensive application cases, archive files
flask 源码梗概
Shell function, system function, basename [string / pathname] [suffix] can be understood as taking the file name in the path, dirname file absolute path, and user-defined function
GOM跟GEE登陆器列表文件加密教程
How to block the legendary GEE engine version? Close player account tutorial through script + engine
SPI配置