Table Of Contents
- 1. Introduction
- 2. When to Use Annotation Processors
- 3. Annotation Processing Under the Hood
- 4. Writing Your Own Annotation Processor
- 5. Running Annotation Processors
- 6. What’s next
- 7. Download the source code
1. Introduction
In this part of the tutorial we are going to demystify the magic of annotation processing, which is often used to inspect, modify or generate source code, driven only by annotations. Essentially, annotation processors are some kind of plugins of the Java compiler. Annotation processors used wisely could significantly simplify the life of Java developers so that is why they are often bundled with many popular libraries and frameworks.
Being compiler plugins also means that annotation processors are a bit low-level and highly depend on the version of Java. However, the knowledge about annotations from the part 5 of the tutorial How and when to use Enums and Annotations and Java Compiler API from the part 13 of the tutorial, Java Compiler API, is going to be very handy in the understanding of intrinsic details of how the annotation processors work.
2. When to Use Annotation Processors
As we briefly mentioned, annotations processors are typically used to inspect the codebase against the presence of particular annotations and, depending on use case, to:
- generate a set of source or resource files
- mutate (modify) the existing source code
- analyze the exiting source code and generate diagnostic messages
The usefulness of annotation processors is hard to overestimate. They can significantly reduce the amount of code which developers have to write (by generating or modifying one), or, by doing static analysis, hint the developers if the assumptions expressed by a particular annotation are not being hold.
Being somewhat invisible to the developers, annotation processors are supported in full by all modern Java IDEs and popular building tools and generally do not require any particular intrusion. In the next section of the tutorial we are going to build own somewhat naïve annotation processors which nonetheless will show off the full power of this Java compiler feature.
3. Annotation Processing Under the Hood
Before diving into implementation of our own annotation processors, it is good to know the mechanics of that. Annotation processing happens in a sequence of rounds. On each round, an annotation processor might be asked to process a subset of the annotations which were found on the source and class files produced by a prior round.
Please notice that, if an annotation processor was asked to process on a given round, it will be asked to process on subsequent rounds, including the last round, even if there are no annotations for it to process.
In essence, any Java class could become a full-blow annotation processor just by implementing a single interface: javax.annotation.processing.Processor
. However, to become really usable, each implementation of the javax.annotation.processing.Processor
must provide a public no-argument constructor (for more details, please refer to the part 1 of the tutorial, How to create and destroy objects) which could be used to instantiate the processor. The processing infrastructure will follow a set of rules to interact with an annotation processor and the processor must respect this protocol:
- the instance of the annotation processor is created using the no-argument constructor of the processor class
- the
init
method is being called with an appropriatejavax.annotation.processing.ProcessingEnvironment
instance being passed
- the
getSupportedAnnotationTypes
, getSupportedOptions
, and getSupportedSourceVersion
methods are being called (these methods are only called once per run, not on each round)
- and lastly, as appropriate, the process method on the
javax.annotation.processing.Processor
is being called (please take into account that a new annotation processor instance is not going to be created for each round)
The Java documentation emphasizes that if annotation processor instance is created and used without the above protocol being followed then the processor’s behavior is not defined by this interface specification.
4. Writing Your Own Annotation Processor
We are going to develop several kinds of annotation processors, starting from the simplest one, immutability checker. Let us define a simple annotation Immutable
which we are going to use in order to annotate the class to ensure it does not allow to modify its state.
1 |
@Target ( ElementType.TYPE ) |
2 |
@Retention ( RetentionPolicy.CLASS ) |
3 |
public @interface Immutable { |
Following the retention policy, the annotation is going to be retained by Java compiler in the class file during the compilation phase however it will not be (and should not be) available at runtime.
As we already know from part 3 of the tutorial, How to design Classes and Interfaces, immutability is really hard in Java. To keep things simple, our annotation processor is going to verify that all fields of the class are declared as final. Luckily, the Java standard library provides an abstract annotation processor, javax.annotation.processing.AbstractProcessor
, which is designed to be a convenient superclass for most concrete annotation processors. Let us take a look on SimpleAnnotationProcessor annotation processor implementation.
01 |
@SupportedAnnotationTypes ( "com.javacodegeeks.advanced.processor.Immutable" ) |
02 |
@SupportedSourceVersion ( SourceVersion.RELEASE_7 ) |
03 |
public class SimpleAnnotationProcessor extends AbstractProcessor { |
05 |
public boolean process( final Set< ? extends TypeElement > annotations, |
06 |
final RoundEnvironment roundEnv) { |
08 |
for ( final Element element: roundEnv.getElementsAnnotatedWith( Immutable. class ) ) { |
09 |
if ( element instanceof TypeElement ) { |
10 |
final TypeElement typeElement = ( TypeElement )element; |
12 |
for ( final Element eclosedElement: typeElement.getEnclosedElements() ) { |
13 |
if ( eclosedElement instanceof VariableElement ) { |
14 |
final VariableElement variableElement = ( VariableElement )eclosedElement; |
16 |
if ( !variableElement.getModifiers().contains( Modifier.FINAL ) ) { |
17 |
processingEnv.getMessager().printMessage( Diagnostic.Kind.ERROR, |
18 |
String.format( "Class '%s' is annotated as @Immutable , |
19 |
but field '%s' is not declared as final ", |
20 |
typeElement.getSimpleName(), variableElement.getSimpleName() |
28 |
// Claiming that annotations have been processed by this processor |
The SupportedAnnotationTypes
annotation is probably the most important detail which defines what kind of annotations this annotation processor is interested in. It is possible to use * here to handle all available annotations.
Because of the provided scaffolding, our SimpleAnnotationProcessor
has to implement only a single method, process
. The implementation itself is pretty straightforward and basically just verifies if class being processed has any field declared without final
modifier. Let us take a look on an example of the class which violates this naïve immutability contract.
02 |
public class MutableClass { |
05 |
public MutableClass( final String name ) { |
09 |
public String getName() { |
Running the SimpleAnnotationProcessor
against this class is going to output the following error on the console:
1 |
Class 'MutableClass' is annotated as @Immutable, but field 'name' is not declared as final |
Thus confirming that the annotation processor successfully detected the misuse of Immutable
annotation on a mutable class.
By and large, performing some introspection (and code generation) is the area where annotation processors are being used most of the time. Let us complicate the task a little bit and apply some knowledge of Java Compiler API from the part 13 of the tutorial, Java Compiler API. The annotation processor we are going to write this time is going to mutate (or modify) the generated bytecode by adding the final
modifier directly to the class field declaration to make sure this field will not be reassigned anywhere else.
01 |
@SupportedAnnotationTypes ( "com.javacodegeeks.advanced.processor.Immutable" ) |
02 |
@SupportedSourceVersion ( SourceVersion.RELEASE_7 ) |
03 |
public class MutatingAnnotationProcessor extends AbstractProcessor { |
07 |
public void init (ProcessingEnvironment processingEnv) { |
08 |
super .init( processingEnv ); |
09 |
trees = Trees.instance( processingEnv ); |
13 |
public boolean process( final Set< ? extends TypeElement > annotations, |
14 |
final RoundEnvironment roundEnv) { |
16 |
final TreePathScanner< Object, CompilationUnitTree > scanner = |
17 |
new TreePathScanner< Object, CompilationUnitTree >() { |
19 |
public Trees visitClass( final ClassTree classTree, |
20 |
final CompilationUnitTree unitTree) { |
22 |
if (unitTree instanceof JCCompilationUnit) { |
23 |
final JCCompilationUnit compilationUnit = ( JCCompilationUnit )unitTree; |
25 |
// Only process on files which have been compiled from source |
26 |
if (compilationUnit.sourcefile.getKind() == JavaFileObject.Kind.SOURCE) { |
27 |
compilationUnit.accept( new TreeTranslator() { |
28 |
public void visitVarDef( final JCVariableDecl tree ) { |
29 |
super .visitVarDef( tree ); |
31 |
if ( ( tree.mods.flags & Flags.FINAL ) == 0 ) { |
32 |
tree.mods.flags |= Flags.FINAL; |
43 |
for ( final Element element: roundEnv.getElementsAnnotatedWith( Immutable. class ) ) { |
44 |
final TreePath path = trees.getPath( element ); |
45 |
scanner.scan( path, path.getCompilationUnit() ); |
48 |
// Claiming that annotations have been processed by this processor |
The implementation became more complex, however many classes (like TreePathScanner
,TreePath
) should be already familiar. Running the annotation processor against the sameMutableClass
class will generate following byte code (which could be verified by executing javap -p MutableClass.class
command):
1 |
public class com.javacodegeeks.advanced.processor.examples.MutableClass { |
2 |
private final java.lang.String name; |
3 |
public com.javacodegeeks.advanced.processor.examples.MutableClass(java.lang.String); |
4 |
public java.lang.String getName(); |
Indeed, the name
field has final
modifier present nonetheless it was omitted in the original Java source file. Our last example is going to show off the code generation capabilities of annotation processors (and conclude the discussion). Continuing in the same vein, let us implement an annotation processor which will generate new source file (and new class respectively) by appending Immutable
suffix to class name annotated with Immutable
annotation.
01 |
@SupportedAnnotationTypes ( "com.javacodegeeks.advanced.processor.Immutable" ) |
02 |
@SupportedSourceVersion ( SourceVersion.RELEASE_7 ) |
03 |
public class GeneratingAnnotationProcessor extends AbstractProcessor { |
05 |
public boolean process( final Set< ? extends TypeElement > annotations, |
06 |
final RoundEnvironment roundEnv) { |
08 |
for ( final Element element: roundEnv.getElementsAnnotatedWith( Immutable. class ) ) { |
09 |
if ( element instanceof TypeElement ) { |
10 |
final TypeElement typeElement = ( TypeElement )element; |
11 |
final PackageElement packageElement = |
12 |
( PackageElement )typeElement.getEnclosingElement(); |
15 |
final String className = typeElement.getSimpleName() + "Immutable" ; |
16 |
final JavaFileObject fileObject = processingEnv.getFiler().createSourceFile( |
17 |
packageElement.getQualifiedName() + "." + className); |
19 |
try ( Writer writter = fileObject.openWriter() ) { |
20 |
writter.append( "package " + packageElement.getQualifiedName() + ";" ); |
21 |
writter.append( "\\n\\n" ); |
22 |
writter.append( "public class " + className + " {" ); |
23 |
writter.append( "\\n" ); |
26 |
} catch ( final IOException ex ) { |
27 |
processingEnv.getMessager().printMessage(Kind.ERROR, ex.getMessage()); |
32 |
// Claiming that annotations have been processed by this processor |
As the result of injecting this annotation processor into compilation process of the MutableClass
class, the following file will be generated:
1 |
package com.javacodegeeks.advanced.processor.examples; |
3 |
public class MutableClassImmutable { |
Nevertheless the source file and its class have been generated using primitive string concatenations (and it fact, this class is really very useless) the goal was to demonstrate how the code generation performed by annotation processors works so more sophisticated generation techniques may be applied.
5. Running Annotation Processors
The Java compiler makes it easy to plug any number of annotation processors into the compilation process by supporting –processor command line argument. For example, here is one way of running MutatingAnnotationProcessor
by passing it as an argument of javac
tool during the compilation of MutableClass.java
source file:
1 |
javac - cp processors/target/advanced-java-part-14-java7.processors-0.0.1-SNAPSHOT.jar |
2 |
-processor com.javacodegeeks.advanced.processor.MutatingAnnotationProcessor |
3 |
-d examples/target/classes |
4 |
examples/src/main/java/com/javacodegeeks/advanced/processor/examples/MutableClass.java |
Compiling just one file does not look very complicated but real-life projects contain thousands of Java source files and using javac
tool from command line to compile those is just overkill. Likely, the community has developed a lot of great build tools (like Apache Maven, Gradle,sbt, Apache Ant, …), which take care of invoking Java compiler and doing a lot of other things, so nowadays most of Java project out there use at least one of them. Here, for example, is the way to invoke MutatingAnnotationProcessor
from Apache Maven build file (pom.xml):
02 |
< groupId >org.apache.maven.plugins</ groupId > |
03 |
< artifactId >maven-compiler-plugin</ artifactId > |
04 |
< version >3.1</ version > |
08 |
< annotationProcessors > |
09 |
< proc >com.javacodegeeks.advanced.processor.MutatingAnnotationProcessor</ proc > |
10 |
</ annotationProcessors > |
6. What’s next
In this part of the tutorial we have taken a deep look on annotation processors and the ways they help to inspect the source code, mutate (modify) resulting bytecode or generate new Java source files or resources. Annotation processors are very often used to free up Java developers from writing tons of boilerplate code by deriving it from annotations spread across codebase. In the next section of the tutorial we are going to take a look on Java agents and the way to manipulate how JVM interprets bytecode at runtime.
7. Download the source code
You can download the source code of this lesson here: advanced-java-part-14
- Java Annotation概述
@(Java)[Annotation|Java] Java Annotation概述 用途 编译器的相关信息,如用于检测错误和一些警告 编译时和部署时的处理,如一些软件用于自动生成代码之类的 运行时处 ...
- Java Annotation 注解
java_notation.html div.oembedall-githubrepos { border: 1px solid #DDD; list-style-type: none; margin ...
- paip.Java Annotation注解的作用and 使用
paip.Java Annotation注解的作用and 使用 作者Attilax 艾龙, EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog. ...
- Java Annotation认知(包括框架图、详细介绍、示例说明)
摘要 Java Annotation是JDK5.0引入的一种注释机制. 网上很多关于Java Annotation的文章,看得人眼花缭乱.Java Annotation本来很简单的,结果说的人没说清楚 ...
- Java Annotation原理分析(一)
转自:http://blog.csdn.net/blueheart20/article/details/18725801 小引: 在当下的Java语言层面上,Annotation已经被应用到了语言的各 ...
- Java Annotation 及几个常用开源项目注解原理简析
PDF 版: Java Annotation.pdf, PPT 版:Java Annotation.pptx, Keynote 版:Java Annotation.key 一.Annotation 示 ...
- Java Annotation 机制源码分析与使用
1 Annotation 1.1 Annotation 概念及作用 1. 概念 An annotation is a form of metadata, that can be added ...
- Java Annotation手册
Java Annotation手册 作者:cleverpig(作者的Blog:http://blog.matrix.org.cn/page/cleverpig) 原文:http://www.matri ...
- Java Annotation 必须掌握的特性
什么是Annotation? Annotation翻译为中文即为注解,意思就是提供除了程序本身逻辑外的额外的数据信息.Annotation对于标注的代码没有直接的影响,它不可以直接与标注的代码产生交互 ...
随机推荐
- debian修改ssh端口
vim /etc/ssh/sshd_config,修改port为你想要的端口 invoke-rc.d ssh restart 客户端连接: ssh 142.4.125.90 -l root -p875 ...
- emacs配置emacs-clang-complete-async
debian下需要安装apt安装下clang和llvm sudo apt-get install llvm-dev sudo apt-get install libclang-dev 网上抄来一个大神 ...
- 黄聪:Navicat for MySQL的1577错误解决
今天尝试使用了Windows下的可视化mysql数据库管理工具Navicat,界面清爽,易操作上手,感觉还不错. 不过当连接上mysql后,无论打开任何一个数据库,都会提示:1577 – Cannot ...
- Boost C++ 库 中文教程(全)
Boost C++ 库 目录 第 1 章 简介 第 2 章 智能指针 第 3 章 函数对象 第 4 章 事件处理 第 5 章 字符串处理 第 6 章 多线程 第 7 章 异步输入输出 第 8 章 进程 ...
- python 下载图片的方法
a='http://wx1.sinaimg.cn/mw600/006HOayNgy1fqjdi2nxohj32pw3o8x6s.jpg' #图片下载地址 ( 这里改成 文件txt地址)w='/U ...
- Bootstrap-Other:UI 编辑器
ylbtech-Bootstrap-Other:UI 编辑器 1.返回顶部 1. Bootstrap UI 编辑器 以下是 15 款最好的 Bootstrap 编辑器或者是在线编辑工具. 1. Boo ...
- gmake与make的区别
gnu make在linux下一般是叫make但是如果是在其他的unix系统下,因为有一个原生的makegnu make就改个名字叫gmake了.就这们简单 当port一个老的unix程序,如老的Su ...
- JQuery的筛选方法
前面咱们学习到了jquery的选择器的筛选用法,那么咱们接下来学习一下jquery的常用筛选方法,一张图搞定一切.
- 在WebBrowser中发送POST请求
我们要用到的也是WebBrowser的“Navigate”方法,其函数原型如下所示: Sub Navigate(URL As String, [Flags], [TargetFrameName], [ ...
- 【mysql数据库】一条语句添加多条数据
insert into persons (id_p, lastname , firstName, city ) values (200,'haha' , 'deng' , 'shenzhen'), ( ...