好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

全面剖析java中的注解(Annotation)

1.什么是 注解

 

用一个词就可以描述注解,那就是元数据,即一种描述数据的数据。所以,可以说注解就是源代码的元数据。比如,下面这段代码:

?

1

2

3

4

@override

public string tostring() {

  return "this is string representation of current object." ;

}

上面的代码中,我重写了tostring()方法并使用了@override注解。但是,即使我不使用@override注解标记代码,程序也能够正常执行。那么,该注解表示什么?这么写有什么好处吗?事实上,@override告诉编译器这个方法是一个重写方法(描述方法的元数据),如果父类中不存在该方法,编译器便会报错,提示该方法没有重写父类中的方法。如果我不小心拼写错误,例如将tostring()写成了tostrring(){double r},而且我也没有使用@override注解,那程序依然能编译运行。但运行结果会和我期望的大不相同。现在我们了解了什么是注解,并且使用注解有助于阅读程序。

annotation是一种应用于类、方法、参数、变量、构造器及包声明中的特殊修饰符。它是一种由jsr-175标准选择用来描述元数据的一种工具。

2.为什么要使用注解

 

使用annotation之前(甚至在使用之后),xml被广泛的应用于描述元数据。不知何时开始一些应用开发人员和架构师发现xml的维护越来越糟糕了。他们希望使用一些和代码紧耦合的东西,而不是像xml那样和代码是松耦合的(在某些情况下甚至是完全分离的)代码描述。

假如你想为应用设置很多的常量或参数,这种情况下,xml是一个很好的选择,因为它不会同特定的代码相连。如果你想把某个方法声明为服务,那么使用annotation会更好一些,因为这种情况下需要注解和方法紧密耦合起来,开发人员也必须认识到这点。

另一个很重要的因素是annotation定义了一种标准的描述元数据的方式。在这之前,开发人员通常使用他们自己的方式定义元数据。例如,使用标记interfaces,注释,transient关键字等等。每个程序员按照自己的方式定义元数据,而不像annotation这种标准的方式。

3.基本语法

 

编写annotation非常简单,可以将annotation的定义同接口的定义进行比较。我们来看两个例子:一个是标准的注解@override,另一个是用户自定义注解@todo。

?

1

2

3

4

@target (elementtype.method)

@retention (retentionpolicy.source)

public @interface override {

}

对于@override注释你可能有些疑问,它什么都没做,那它是如何检查在父类中有一个同名的函数呢。当然,不要惊讶,我是逗你玩的。@override注解的定义不仅仅只有这么一点代码。这部分内容很重要,我不得不再次重复:annotations仅仅是元数据,和业务逻辑无关。理解起来有点困难,但就是这样。如果annotations不包含业务逻辑,那么必须有人来实现这些逻辑。元数据的用户来做这个事情。annotations仅仅提供它定义的属性(类/方法/包/域)的信息。annotations的用户(同样是一些代码)来读取这些信息并实现必要的逻辑。

当我们使用java的标注annotations(例如@override)时,jvm就是一个用户,它在字节码层面工作。到这里,应用开发人员还不能控制也不能使用自定义的注解。因此,我们讲解一下如何编写自定义的annotations。

我们来逐个讲述编写自定义annotations的要点。上面的例子中,你看到一些注解应用在注解上。

3.1 四种基本元注解

j2se5.0版本在 java.lang.annotation提供了四种元注解,专门注解其他的注解:
@documented –注解是否将包含在javadoc中
@retention –什么时候使用该注解
@target? –注解用于什么地方
@inherited – 是否允许子类继承该注解

@documented–一个简单的annotations标记注解,表示是否将注解信息添加在java文档中。

@retention– 定义该注解的生命周期。
retentionpolicy.source – 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@override, @suppresswarnings都属于这类注解。
retentionpolicy.class – 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式。
retentionpolicy.runtime– 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

@target – 表示该注解用于什么地方。如果不明确指出,该注解可以放在任何地方。以下是一些可用的参数。需要说明的是:属性的注解是兼容的,如果你想给7个属性都添加注解,仅仅排除一个属性,那么你需要在定义target包含所有的属性。
elementtype.type:用于描述类、接口或enum声明
elementtype.field:用于描述实例变量
elementtype.method
elementtype.parameter
elementtype.constructor
elementtype.local_variable
elementtype.annotation_type 另一个注释
elementtype.package 用于记录java文件的package信息

@inherited – 定义该注释和子类的关系

那么,注解的内部到底是如何定义的呢?annotations只支持基本类型、string及枚举类型。注释中所有的属性被定义成方法,并允许提供默认值。

?

1

2

3

4

5

6

7

8

9

@target (elementtype.method)

@retention (retentionpolicy.runtime)

@interface todo {

  public enum priority {low, medium, high}

  public enum status {started, not_started}

  string author() default "yash" ;

  priority priority() default priority.low;

  status status() default status.not_started;

}

下面的例子演示了如何使用上面的注解。

?

1

2

3

4

5

@todo (priority = todo.priority.medium, author = "yashwant" , status = todo.status.started)

public void incompletemethod1() {

//some business logic is written

//but it's not complete yet

}

如果注解中只有一个属性,可以直接命名为[value],使用时无需再标明属性名。

?

1

2

3

4

5

6

@interface author{

string value();

}

@author ( "yashwant" )

public void somemethod() {

}

3.2 重复注解

在java8以前,同一个程序元素前只能使用一个相同类型的annotation;如果需要在同一个元素前使用多个类型相同的annotation,则必须使用annotation[容器]。
下面先介绍这种[容器],
首先定义个mytag注解:

?

1

2

3

4

5

6

7

8

9

//指定注解保留到运行时

@retention (retentionpolicy.runtime)

//指定注解可以修饰类、接口、枚举

@target (elementtype.type)

@interface mytag

{

  string name() default "测试" ;

  int age() default 20 ;

}

然后再定义mytag注解的容器注解:

?

1

2

3

4

5

6

7

8

//指定注解保留到运行时

@retention (retentionpolicy.runtime)

//指定注解可以修饰类、接口、枚举

@target (elementtype.type)

@interface mytags

{

  mytag[] value();

}

然后就可以按照如下的方式来使用注解了

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@mytags ({

  @mytag (name= "测试1" ,age= 21 ),

  @mytag (name= "测试2" ,age= 22 )

})

public class test {

  public static void main(string[] args)

  {

  //通过反射解析注解

  class testclass= test. class ;

  //获得mytags注解

  mytags mytagsannotation= (mytags) testclass.getannotation(mytags. class );

  //获得添加到里面的mytag注解

  mytag[] mytags=mytagsannotation.value();

  for (mytag mytag : mytags)

  {

  system.out.println(string.format( "name:%1$s,age:%2$d" ,mytag.name(),mytag.age()));

  }

  }

}

打印:
name:测试1,age:21
name:测试2,age:22

java8为上面这种繁琐的语法提供了糖语法,在java8中新增加了@repeatable元注解,只需要在mytag注解上添加上元注解@repeatable(mytags.class)。
观察可以发现,@repeatable依然需要依赖容器注解,所以依然可以按照如下的方式来使用:

?

1

2

3

4

@mytags ({

  @mytag (name= "测试1" ,age= 21 ),

  @mytag (name= "测试2" ,age= 22 )

})

又因为mytag是重复注解,所以还可以像如下这样使用:

?

1

2

@mytag (name= "测试1" ,age= 21 )

@mytag (name= "测试2" ,age= 22 )

这里需要注意,重复注解只是一种简便写法,多个重复注解其实会被作为[容器]注解的value成员变量的数组元素。例如上面重复的mytag注解会被作为@mytags注解的value成员变量的数组元素处理。

4.使用注解

 

现在我们已经知道了可以通过使用@retention注解来指定注解的生存周期,注解的生存周期有三种,分别为:retentionpolicy.source,retentionpolicy.class,retentionpolicy.runtime,这三个值分别表示注解的生存周期为源代码,字节码,运行时中。

接下来介绍注解在不同阶段中的处理:

4.1 运行时处理的注解

其实在上面的案例中,已经展示了如何使用反射获取注解的数据。如果要在程序运行时处理注解,那么必须将注解的声明周期声明为: @retention(retentionpolicy.runtime) 。
由于注解本身是不包含任何业务逻辑的,在运行时中,我们就可以通过反射来实现具体的逻辑,
先定义一个debug注解:

?

1

2

3

4

5

6

7

8

//指定注解保留到运行时

@retention (retentionpolicy.runtime)

//指定该注解只能用于方法

@target (elementtype.method)

@interface debug

{

  boolean value() default false ;

}

接下来将该注解和具体的业务逻辑关联起来:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

public class debugtest {

  public static void main(string[] args) {

  class debugtestclass = debugtest. class ;

  //获得所有的方法

  method[] methods = debugtestclass.getmethods();

  for (method method : methods) {

  method.setaccessible( true ); //禁用安全机制

  if (method.isannotationpresent(debug. class )) { //检查是否使用了debug注解

  debug debug = method.getannotation(debug. class ); //获得注解实例

  string name = method.getname(); //获得方法名称

  if (debug.value()) {

   system.out.println( "method:" + name + " should debug" );

  } else {

   system.out.println( "method:" + name + " should't debug" );

  }

  }

  }

  }

  @debug ( false )

  public void testmethod1() {

  }

  @debug ( true )

  public void testmethod2() {

  }

  @debug ( true )

  public void testmethod3() {

  }

  @debug ( false )

  public void testmethod4() {

  }

  @debug ( true )

  public void testmethod5() {

  }

}

4.2 编译时处理的注解

若是编译时需要处理的注解,那么可以把注解的声明周期声明为: @retention(retentionpolicy.source) 。

在这里需要先介绍一下apt,api(annotation processing tool)是一种注解处理工具,他对源代码进行检测,并找出源代码所包含的annotation信息,然后针对annotation信息进行额外的处理。使用apt工具处理annotation时可以根据源文件中的annotation生成额外的源文件和其他的文件(文件的具体内容由annotation处理器的编写者决定),apt还会将编译生成的源代码文件和原来的源文件一起生成class文件。

使用apt的主要目的是为了简化开发者的工作量,因为apt可以在编译程序源代码的同时生成一些附属文件(比如源文件、类文件、程序发布描述文件等),这些附属文件的内容也都与源代码相关。换句话说,使用apt可以代替传统的对代码信息和附属文件的维护工具。

java提供的javac.exe工具有一个-processor选项,该选项可指定一个annotation处理器,如果在编译java源文件时指定了该annotation处理器,那么这个annotation处理器将会在编译时提取并处理java源文件中的annotaion.
每一个annoataion处理器都需要实现javax.annotataion.processor包下的processor接口,不过实现该接口必须实现该接口下的所有的方法,因此通常会采用继承abstractprocessor的方式来实现annotation的处理器。一个annotation处理器可以处理一个或多个annotaion注解。

在hibernate中,如果使用非注解的方式,那么每写一个java bean类文件,还必须额外地维护一个hibernate映射文件(名为*.hbm.xml的文件),下面将使用apt来简化这步操作。

为了示范使用apt根据源文件中的注解来生成额外的文件,下面定义3种注解。
标识持久化类的@persistent 注解:

?

1

2

3

4

5

6

7

8

9

//指定该注解可以修饰类,接口,枚举

@target (elementtype.type)

//指定该注解保留到编译时

@retention (retentionpolicy.source)

//指定该注解可以被显示在文档中(通过javadoc生成文档,便可以在被该注解修饰的元素上看到该注解信息)

@documented

public @interface persistent {

  string table();

}

标识属性的@id 注解:

?

1

2

3

4

5

6

7

8

9

10

11

//指定该注解只能修饰字段

@target (elementtype.field)

//指定该注解保留到编译时

@retention (retentionpolicy.source)

//指定该注解可以被显示在文档中(通过javadoc生成文档,便可以在被该注解修饰的元素上看到该注解信息)

@documented

public @interface id {

  string column();

  string type();

  string generator();

}

标识属性的@property 注解

?

1

2

3

4

5

6

7

8

9

10

//指定该注解只能修饰字段

@target (elementtype.field)

//指定该注解保留到编译时

@retention (retentionpolicy.source)

//指定该注解可以被显示在文档中(通过javadoc生成文档,便可以在被该注解修饰的元素上看到该注解信息)

@documented

public @interface property {

  string column();

  string type();

}

在有了三个annotation后,我们定义一个简单的java bean类person.java.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@persistent (table= "personinfo" )

public class person {

  @id (column= "person_id" ,type= "integer" ,generator= "identity" )

  private int id;

  @property (column= "person_name" ,type= "string" )

  private string name;

  @property (column= "person_age" ,type= "integer" )

  private int age;

 

  public person(){}

 

  public person( int id,string name, int age)

  {

  this .id=id;

  this .name=name;

  this .age=age;

  }

  //所有属性的setter和getter.....

}

接下来写一个api工具,该api工具是根据java类中的注解来生成一个hibernate 映射文件。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

import java.io.file;

import java.io.fileoutputstream;

import java.io.printstream;

import java.util.set;

 

import javax.annotation.processing.abstractprocessor;

import javax.annotation.processing.roundenvironment;

import javax.annotation.processing.supportedannotationtypes;

import javax.annotation.processing.supportedsourceversion;

import javax.lang.model.sourceversion;

import javax.lang.model.element.element;

import javax.lang.model.element.elementkind;

import javax.lang.model.element.name;

import javax.lang.model.element.typeelement;

 

//指定该注解支持java平台的最新版本为6.0

@supportedsourceversion (sourceversion.release_6)

//指定可以处理persistent,id,property注解

@supportedannotationtypes ({ "persistent" , "id" , "property" })

public class hibernateannotationprocessor extends abstractprocessor{

  @override

  public boolean process(set<? extends typeelement> annotations,

  roundenvironment roundenv) {

  //定义文件输出流,用于生成额外的文件

  printstream ps= null ;

  try {

  for (element t:roundenv.getelementsannotatedwith(persistent. class )){

  //获取正在处理的类名称

  name classname=t.getsimplename();

  //获得类定义前的@persistent annotation

  persistent per= t.getannotation(persistent. class );

  //创建文件输出流

  ps= new printstream( new fileoutputstream( new file(classname+ ".hbm.xml" )));

  //执行输出

  ps.println( "<?xml version=\"1.0\"?>" );

  ps.println( "<!doctype hibernate-mapping public \"-//hibernate/hibernate mapping dtd 3.0//en\"" );

  ps.println( "\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">" );

  ps.println( "<hibernate-mapping>" );

  ps.println( "<class name=\"" +classname+ "\" table=\"" +per.table()+ "\" >" );

  for (element f:t.getenclosedelements())

  {

   //只处理成员变量上的annotation

   if (f.getkind()==elementkind.field)

   {

   //获取成员变量定义前的@id annotation

   id id=f.getannotation(id. class );

   //但@id注解存在时,输出<id >元素

   if (id!= null )

   {

   ps.println( "<id name=\"" +f.getsimplename()+ "\" " +

    "column=\"" +id.column()+ "\" " +

    "type=\"" +id.type()+ "\">" );

   ps.println( "<generator class=\"" +id.generator()+ "\" />" );

   ps.println( "</id>" );

   continue ;

   }

   //获取成员变量前的@property annotation

   property p=f.getannotation(property. class );

   if (p!= null )

   {

   ps.println( "<property name=\"" +f.getsimplename()+ "\" " +

    "column=\"" +p.column()+ "\" " +

    "type=\"" +p.type()+ "\" />" );

   continue ;

   }

   }

  }

  ps.println( "</class>" );

  ps.println( "</hibernate-mapping>" );

  }

  } catch (exception e)

  {

  e.printstacktrace();

  } finally {

  if (ps!= null )

  ps.close();

  }

  return true ;

  }

}

在编译完hibernateannotationprocessor.java后执行如下的命令:

?

1

javac -processor hibernateannotationprocessor person.java

就可以看到在该路径下多了一个person.cfg.xml文件

?

1

2

3

4

5

6

7

8

9

10

11

12

<?xml version= "1.0" ?>

<!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 3.0//en"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

< class name= "person" table= "personinfo" >

<id name= "id" column= "person_id" type= "integer" >

<generator class = "identity" />

</id>

<property name= "name" column= "person_name" type= "string" />

<property name= "age" column= "person_age" type= "integer" />

</ class >

</hibernate-mapping>

 

查看更多关于全面剖析java中的注解(Annotation)的详细内容...

  阅读:11次