开发工具使用的是IntelliJ IDEA
一. 神马是注解?
注解(也称为元数据),为我们的代码添加信息提供了一种形式化的方法,使我们在某些时刻可以方便的使用这些数据。
注解在一定程度上把数据与源码文件结合在一起,同时也是对来自
C#
之类的其它语言对java造成的语言特性压力所做出的一种回应。
注解是从Java SE5(JDK5,下文的JDK指的是>=JDK5)引入的特性,它可以帮助我们减轻编写“样板”代码的负担,通过注解,我们可以将这些元数据保存在Java源代码中,利用Annotation API为自己的注解构造处理工具;同时注解的有点还包括:更加干净易读的代码以及编译期类型检查等。虽然JDK5预先定义了一些元数据,但一般来说,主要还是需要我们自己添加新的注解,并且按自己的方式使用它们(嗯,就是这样!)
二. 注解的语法,了解一下?
注解的语法比较简单,除了@
符号的使用之外,它基本与Java固有的语法一致;JDK中内置了三种注解,定义在java.lang
包中
-
@Override,表示当前的方法覆盖基类中的方法,如果你不小心方法名写错了对不上基类中的方法,编译器会发出错误提示
-
@Deprecated,如果使用了这个注解,IDE会告诉我们这个方法过时了,不建议我们使用(一般文档中会告诉你那个API取代了它)。

- @SuppressWarnings,关闭编译器的警告信息,在JDK5以下,也可以使用该注解,不过会被忽略不会起作用。
另外Java还提供了另外四种注解,用于负责自定义注解,如下分类;
这里要注意的是,上面这三种注解我们称为
标准注解
接下来我们要说的这四种称为元注解
,元注解专门负责注解其它的注解。
-
@Target
,表示该注解可以用于什么地方,类型定义在ElementType
枚举中,可以参考图片:

-
@Retention
,表示需要在什么级别保存该注解信息,同样的,级别分类定义在RetentionPolicy枚举中,见图:

-
@Documented
,该注解包含在javadoc(注解 /** */)中. -
@Inherited
,允许子类集成父类中的注解.
注解元素可用的数据类型
- 所有的基本类型(int,float,boolean等)
- String
- Class
- enum
- Annotation
- 以上类型的数组
如果你使用了其他类型,那么编译器就会报错;
三. 接下来让我们来定义一个简单的注解吧!
我们以Runtime级别的注解举例,然后通过反射来获取注解的信息。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table
{
String tableName() default "";
}
上面Table注解是用于类、接口或枚举上,我们之定义一个tableName的参数;这边要注意的是默认值,因为编译器对元素的默认值有些挑剔。首先元素不能有不确定的值,也就是说元素必须要么具有默认值,要么在使用注解时提供元素的值;其次不能以null
最为默认值,为了绕开这个约束,我们可以自己定义一些特殊的值,例如空字符串或负数,以此表示某个元素不存在。
四. 如何使用?
1.首先我们定义一个UserTable类,加上注解
@Table(tableName = "tb_user")
public class UserTable{}
2.创建一个注解生成器
public class TableCreator
{
public void creator(Class<?> clazz) throws ClassNotFoundException
{
//获取被注解类的class对象
Class<?> tableClazz = Class.forName(clazz.getName());
//获取该类中使用的注解
Table table = tableClazz.getAnnotation(Table.class);
//获取注解的值
String tableName = table.tableName();
System.out.println(tableName);
}
}
3.获取注解信息
public class Main {
public static void main(String[] args) throws ClassNotFoundException
{
TableCreator tableCreator = new TableCreator();
tableCreator.creator(UserTable.class);
}
}
我们运行程序就能获取到如下结果:

五. 使用编译时注解,通过APT(Annotation Processing Tool),可以在代码编译期解析注解插件,生成源文件或者class文件
接下来写一个简单的例子,通过在对象中使用@DBTable和@PrimaryKey在编译的时候生成创建表结构语句
首先我们先来定义这两个注解,DBTable用于类上面,声明要生成的表名;PrimaryKey用于域变量上,声明表主键。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
public @interface DBTable
{
String tableName() default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.CLASS)
public @interface PrimaryKey
{
}
接下来我们新建一个UserTable
类,使用我们刚才新建的两个注解:
@DBTable(tableName = "tb_user")
public class UserTable
{
@PrimaryKey
private int id;
}
然后是最关键的,定义注解处理器,一般我们继承AbstractProcessor
这个类,我们先简单的定义一下
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("annotation.*")
public class TableProcessor extends AbstractProcessor{}
-
@SupportedSourceVersion
,指定注解处理器支持的最新JDK版本 -
@SupportedAnnotationTypes
,指定注解处理器要处理的注解,它的参数是数组,你可以传递多个注解或者是指定某个包下;上面指定的是annotation
包下的所有注解处理器在编译的时候都会进行扫描处理。
关于AbstractProcessor
AbstractProcessor是一个抽象类,实现了Processor接口,提供了四个方法。
-
void init(ProcessingEnvironment processingEnv);
- 会被注解处理工具调用,
ProcessingEnvironment
提供了一些实用的工具类 Elements, Types 和 Filer.
- 会被注解处理工具调用,
-
boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv);
- 相当于
main
函数, 是注解处理器的入口. 输入参数RoundEnviroment
可以查询出包含特定注解的被注解元素.
- 相当于
-
SourceVersion getSupportedSourceVersion();
- 指定
Java
版本.
- 指定
-
Set<String> getSupportedAnnotationTypes();
- 指定这个注解处理器是注册给哪个注解的, 这里需要用注解的全称, 比如
annotation.DBTable
;或者是指定某个包下
- 指定这个注解处理器是注册给哪个注解的, 这里需要用注解的全称, 比如
-
最后两个方法可以使用上面注解的方式来实现,我们代码中就是这样做的
下面是Processor的完整代码,都有注释很好理解。不得不说的是注解的API实在有点多,这里只是用到一点点(主要是这里只是个小例子,举一反三;问题不大)。
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("annotation.*")
public class TableProcessor extends AbstractProcessor
{
public static final String SUFFIX_NAME = "Helper";
/*
用于生成java文件
*/
private Filer filer;
private ProcessingEnvironment processingEnv;
@Override
public synchronized void init(ProcessingEnvironment processingEnv)
{
super.init(processingEnv);
this.processingEnv = processingEnv;
filer = processingEnv.getFiler();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)
{
Writer w = null;
//获取使用了@DBTable注解的类
Set<? extends Element> tableElementsSet = roundEnv.getElementsAnnotatedWith(DBTable.class);
for (Element element : tableElementsSet)
{
TypeElement typeElement = (TypeElement) element;
DBTable table = typeElement.getAnnotation(DBTable.class);
//声明主键的类型和字段名
String primaryKeyType = null;
String primaryKeyName = null;
//获取类的所有成员
List<? extends Element> allMembers = processingEnv.getElementUtils().getAllMembers(typeElement);
for (Element member : allMembers)
{
//获取成员上是否使用了@PrimaryKey注解
PrimaryKey primaryKeyAnnotation = member.getAnnotation(PrimaryKey.class);
//获取变量上使用了PrimaryKey的注解
if (primaryKeyAnnotation != null)
{
primaryKeyType = member.asType().toString();
primaryKeyName = member.getSimpleName().toString();
break;
}
}
//如果没有使用@PrimaryKey,抛异常
if (primaryKeyName == null)
throw new RuntimeException(typeElement.getQualifiedName() + " not defined @PrimaryKey");
try
{
//拼接类名
String className = typeElement.getSimpleName() + SUFFIX_NAME;
//创建java源文件,当然也有提供创建class文件的,具体看api
JavaFileObject a = filer.createSourceFile(typeElement.getQualifiedName() + SUFFIX_NAME);
w = a.openWriter();
w.write("//\n");
w.write("// Source code recreated from a .class file by IntelliJ IDEA\n");
w.write("// (powered by Fernflower decompiler)\n");
w.write("//\n");
//声明package
w.write("package " + getPackageName(typeElement) + ";\n");
//声明class name
w.write("public class " + className + "{ \n");
//写入构造
w.write("\tpublic " + className + "() { \n\n");
//在构造中生成建表语句
w.write("\t\tSystem.out.println(\"create table " + table.tableName() + " "
+ primaryKeyName + " " + primaryKeyType + " primary key auto_increment" + "\");\n");
w.write("\t}\n");
w.write("}");
} catch (Exception e)
{
e.printStackTrace();
} finally
{
IOUtils.close(w);
}
}
return true;
}
/**
* 获取包名
*
* @param element
* @return
*/
private String getPackageName(Element element)
{
return processingEnv.getElementUtils().getPackageOf(element.getEnclosingElement()).toString();
}
}
关于Element
程序的元素, 例如包, 类或者方法. 每个Element代表一个静态的, 语言级别的构件. 可以参考下面的代码理解
package com.example; // PackageElement
public class Foo { // TypeElement
private int a; // VariableElement
private Foo other; // VariableElement
public Foo () {} // ExecuteableElement
public void setA ( // ExecuteableElement
int newA // TypeElement
) {}
}
由此可见roundEnv.getElementsAnnotatedWith(*.class);
方法返回的不一定是类,可能是方法或者是变量,只不过我们上面的@DBTable
修饰的是类;
5.1 运行processor,生成文件;
1)执行Build -> Build Project生成class文件。
2)在终端输入一下命令(这里根据自己项目的实际路径来指定)
javac -encoding UTF-8 -cp out/production/Annotation -processor processor.TableProcessor -d out/production/Annotation -s src/ src/*/*.java
3)生成的文件如下:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package table;
public class UserTableHelper{
public UserTableHelper() {
System.out.println("create table tb_user id int primary key auto_increment");
}
}
参考资料
【Thinking in Java】
https://segmentfault.com/a/1190000009756015
网友评论