Java.Annotations

0. Annotation Tricks

http://developer.android.com/reference/java/lang/annotation/Annotation.html

0.1 Annotation 接口

"Defines the interface implemented by all annotations. Note that the interface itself is not an annotation,

and neither is an interface that simply extends this one. Only the compiler is able to create proper annotation types."

只有编译器可以创建合适的annotation类型。

0.2 AnnotatedElement 接口

java.lang.reflect.AnnotatedElement

since 1.5

"Represents an annotated element of the program currently running in this VM.

This interface allows annotations to be read reflectively. All annotations returned

by methods in this interface are immutable and serializable." Ref[8]

实现该接口的有:

Class<T> 实现了该接口。

该接口有方法:

abstract <T extends Annotation> T getAnnotation(Class<T> annotationType)

Q: 那么annotationType参数应该接受哪些参数呢?

A: 参考ACRA的ACRA.java中以下方法的实现,

    public static ACRAConfiguration getNewDefaultConfig(Application app) {
        if(app != null) {
            return new ACRAConfiguration(app.getClass().getAnnotation(ReportsCrashes.class));
        } else {
            return new ACRAConfiguration(null);
        }
    }

可以看出传给annotationType的值是KLAnnotation.class。

KLAnnotation的定义:

@interface KLAnnotation {}

0.3 关于.class和getClass()的区别,以及关于Class

参见 http://www.cnblogs.com/cwgk/p/4103391.html

0.4  @interface Vs. class Vs. interface

"Annotation type declaration cannot have explicit superinterfaces.

Annotation type declaration cannot have an explicit superclass." Ref[6]

以上说法是否正确? 以及@interface 和class interface是同一级的关键字(或 组件)吗?

1. Annotations 基础

Ref[1,2,3,4,5]

1.1 Annotation简介

"Java annotations are used to provide meta data for your Java code.

Java annotations were added to Java from Java 5. This text covers Java annotations as they look in Java 6.

As far as I know, Java annotations have not changed in Java 7, so this text should be valid for

Java 7 programmers too." Ref[2]

Java注解 用来为Java代码添加元数据。

Java注解典型的被用于:
编译器指令,构建时指令,运行时指令

"Java has 3 built-in annotations that you can use to give instructions to the Java compiler. " Ref[2]

"Java annotations can be be used at build-time, when you build your software project.

The build process includes generating source code, compiling the source, generating

XML files (e.g. deployment descriptors), packaging the compiled code and files into a JAR file etc." Ref[2]

"Normally, Java annotations are not present in your Java code after compilation.

It is possible, however, to define your own annotations that are available at runtime. " Ref[2]

一般情况下,Java注解在编译后不存在于Java代码中。但是可以通过定义自己的注解,这样可以在运行时使用。

1.2 Java注解的写法

1 @Entity

"@" 告诉编译器这是一个注解。跟在"@"之后的字符串是注解的名字。

Java注解可以有元素(Elements), 你可以给这些元素进行赋值。元素和属性类似。

1 @Entity(tableName = "vehicles")

上例中的注解有个元素tableName,并给该元素赋值为vehicles。如果注解没有元素,不需要括号。

1 @Entity(tableName = "vehicles", primaryKey = "id") 

注解可以有多个元素。

1 @InsertNew(value = "yes")

如果注解只有一个元素,通常该元素被命名为value。当注解只有一个元素并且该元素的名字为value时,可以简写为:

1 @InsertNew("yes")

1.3 注解可以应用的位置

Java注解可以放在classse, interfaces, methods, method parameters, fields and local variables.

1 @Entity
2 public class Vehicle {
3 }
 1 @Entity
 2 public class Vehicle {
 3
 4     @Persistent
 5     protected String vehicleName = null;
 6
 7
 8     @Getter
 9     public String getVehicleName() {
10         return this.vehicleName;
11     }
12
13     public void setVehicleName(@Optional vehicleName) {
14         this.vehicleName = vehicleName;
15     }
16
17     public List addVehicleNameToList(List names) {
18
19         @Optional
20         List localNames = names;
21
22         if(localNames == null) {
23             localNames = new ArrayList();
24         }
25         localNames.add(getVehicleName());
26
27         return localNames;
28     }
29
30 }

上例中,示例了注解的使用位置。

1.4 内建的Java注解

Java comes with three built-in annotations which are used to give the Java compiler instructions:

@Deprecated

@Override

@SuppressWarnings

1.4.1  @Deprecated

"The @Deprecated annotation is used to mark a class, method or field as deprecated, meaning it should no longer be used.

If your code uses deprecated classes, methods or fields, the compiler will give you a warning. Here is @Deprecated Java

annotation example:" Ref[2]

1 @Deprecated
2 public class MyComponent {
3
4 }

1.4.2 @Override

"The @Override Java annotation is used above methods that override methods in a superclass.

If the method does not match a method in the superclass, the compiler will give you an error." Ref[2]

1.4.3 @SuppressWarnings

"The @SuppressWarnings annotation makes the compiler suppress warnings for a given method.

For instance, if a method calls a deprecated method, or makes an insecure type cast, the compiler may

generate a warning. You can suppress these warnings by annotating the method containing the code with

the@SuppressWarnings annotation." Ref[2]

1.5 创建自己的注解

和interface,class类似,Java注解定义在自己的文件中。

1 @interface MyAnnotation {
2
3     String   value();
4
5     String   name();
6     int      age();
7     String[] newNames();
8
9 }

@interface: "This signals to the Java compiler that this is a Java annotation definition."

"Notice that each element is defined similarly to a method definition in an interface.

It has a data type and a name. You can use all primitive data types as element data types.

You can also use arrays as data type. You cannot use complex objects as data type." Ref[2]

可以在自己的代码中使用上面定义的注解:

 1 @MyAnnotation(
 2     value="123",
 3     name="Jakob",
 4     age=37,
 5     newNames={"Jenkov", "Peterson"}
 6 )
 7 public class MyClass {
 8
 9
10 }

1.5.1 元素的默认值

可以为元素指定默认值。"That way the element becomes optional and can be left out. "

1 @interface MyAnnotation {
2
3     String   value() default "";
4
5     String   name();
6     int      age();
7     String[] newNames();
8
9 }

"The value element can now be left out when using the annotation. If you leave it out,

it will be considered as if you had used the default value for the value element."

1 @MyAnnotation(
2     name="Jakob",
3     age=37,
4     newNames={"Jenkov", "Peterson"}
5 )
6 public class MyClass {
7
8
9 }

在上例中value元素没有被指明值,所以value元素采用默认值。

1.5.2 元注解

元注解:修饰注解的注解。有@Retention @Target @Inherited

1.5.2.1 @Retention

"You can specify for your custom annotation if it should be available at runtime,

for inspection via reflection. You do so by annotating your annotation definition

with the @Retention annotation."

 1 import java.lang.annotation.Retention;
 2 import java.lang.annotation.RetentionPolicy;
 3
 4 @Retention(RetentionPolicy.RUNTIME)
 5
 6 @interface MyAnnotation {
 7
 8     String   value() default "";
 9
10 }

"@Retention(RetentionPolicy.RUNTIME) This is what signals to the Java compiler and JVM that the annotation

should be available via reflection at runtime." Ref[2].

在运行时访问annotation可以参考 Ref[11].

另外:RetetionPolicy 类提供了另外的两个值:

RetentionPolicy.CLASS: "means that the annotation is stored in the .class file, but not available at runtime.

This is the default retention policy, if you do not specify any retention policy at all."

RetentionPolicy.SOURCE: "means that the annotation is only available in the source code, and not in the .class

files and not a runtime. If you create your own annotations for use with build tools that scan the code, you

can use this retention policy. That way the .class files are not polluted unnecessarily." Ref[2]

1.5.2.2 @Target

"You can specify which Java elements your custom annotation can be used to annotate. You do so by

annotating your annotation definition with the @Target annotation." Ref[2]

1 import java.lang.annotation.ElementType;
2 import java.lang.annotation.Target;
3
4 @Target({ElementType.METHOD})
5 public @interface MyAnnotation {
6
7     String   value();
8 }

ElementType包含一下的targets:

ElementType.ANNOTATION_TYPE

ElementType.CONSTRUCTOR

ElementType.FIELD

ElementType.LOCAL_VARIABLE

ElementType.METHOD

ElementType.PACKAGE

ElementType.PARAMETER

ElementType.TYPE

"The ANNOTATION_TYPE target means Java annotation definitions. Thus, the annotation can only be used to annotate other annotations. Like the @Target and @Retention annotations.

The TYPE target means any type. A type is either a class, interface, enum or annotation." Ref[2]

1.5.2.3 @Inherited

"The @Inherited annotation signals that a custom Java annotation used in a class should be

inherited by subclasses inheriting from that class." Ref[2]

 1 java.lang.annotation.Inherited
 2
 3 @Inherited
 4 public @interface MyAnnotation {
 5
 6 }
 7
 8 @MyAnnotation
 9 public class MySuperClass { ... }
10
11 public class MySubClass extends MySuperClass { ... }

"In this example the class MySubClass inherits the annotation @MyAnnotation

because MySubClassinherits from MySuperClass, and MySuperClass has a @MyAnnotation annotation." Ref[2]

1.5.2.4 @Documented

1 java.lang.annotation.Documented
2
3 @Documented
4 public @interface MyAnnotation {
5
6 }
7
8 @MyAnnotation
9 public class MySuperClass { ... }

"When generating JavaDoc for the MySuperClass class, the @MyAnnotation is now included in the JavaDoc." Ref[2]

2. Demo

Ref[9]

3. Annotations 的使用案例

3.1 ACRA的实现

3.2 PerferenceInjector的实现

Ref[9]



Items

Java Annotations : Java 注解

RetentionPolicy: 保留策略



Reference

1. Java Annotations and Java Reflection - Tutorial  (AAAA) [Read]

http://www.vogella.com/tutorials/JavaAnnotations/article.html

2. Java Annotations  (AAAAA) [Read]

http://tutorials.jenkov.com/java/annotations.html

3. Java Annotations By Example (AAAA) [ToRead]

http://whyjavasucks.com/Blog/5/Java_By_Example/93/Java_Annotations

4. Complete Java Annotations Tutorial (AAAA) [ToRead]

http://howtodoinjava.com/2014/06/09/complete-java-annotations-tutorial/

5. Type Annotations in Java 8: Tools and Opportunities (AAA [ToRead]

http://www.infoq.com/articles/Type-Annotations-in-Java-8

6.

http://stackoverflow.com/questions/4722354/can-annotation-implement-interfaces

7. CODE GENERATION USING ANNOTATION PROCESSORS IN THE JAVA LANGUAGE  (AAAAA)

https://deors.wordpress.com/2011/09/26/annotation-types/

https://github.com/deors/deors.demos.annotations

8. Interface AnnotatedElement Java doc

http://docs.oracle.com/javase/7/docs/api/javax/annotation/processing/package-summary.html

9. Using Java 6 Processors in Eclipse

http://java.dzone.com/news/using-java-6-processors

10. Getting Started with the Annotation Processing Tool, apt

http://docs.oracle.com/javase/7/docs/technotes/guides/apt/GettingStarted.html

11. Java Reflection and Annotations tutorial

http://tutorials.jenkov.com/java-reflection/annotations.html

时间: 2024-09-30 20:40:58

Java.Annotations的相关文章

Java Annotations: Explored &amp; Explained--转载

原文地址:http://www.javacodegeeks.com/2012/08/java-annotations-explored-explained.html One of the many wonderful features of Java 5 SE is the introduction of the Annotations construct.Annotations are tags that we can insert into our program source code f

JournalDev 博客的 Java 教程集合(JournalDev Java Tutorials Collections)

Tutorials I have written a lot of posts here into many categories and as the number of post grows, keeping track of them becomes harder. So I have provided a summary post for most of the categories where you can read them in the order for better unde

MyBatis——Java API

Java API 既然你已经知道如何配置 MyBatis 和创建映射文件,你就已经准备好来提升技能了. MyBatis 的 Java API 就是你收获你所做的努力的地方.正如你即将看到的,和 JDBC 相比, MyBatis 很大程度简化了你的代码而且保持简洁,很容易理解和维护.MyBatis 3 已经引入 了很多重要的改进来使得 SQL 映射更加优秀. 应用目录结构 在我们深入 Java API 之前,理解关于目录结构的最佳实践是很重要的.MyBatis 非常灵 活, 你可以用你自己的文件来

Java注解介绍

原文链接: Java Annotations: An Introduction原文日期: 2005年10月14日翻译日期: 2014年07月20日翻译人员: 铁锚 翻译完后,感觉这篇文章是不是在http://www.developer.com被挖坟了? Java注解介绍 基于注解(Annotation-based)的Java开发无疑是最新的开发趋势.[译者注: 这是05年的文章,在2014年,毫无疑问,多人合作的开发,使用注解变成很好的合作方式,相互之间的影响和耦合可以很低]. 基于注解的开发将

android工具-annotations

在当下的java的使用中,annotations已经被广泛运用,来提升开发效率.在android中,主要是帮助开发者处理一些前后台任务.rest 服务.应用类.代码片段等,让开发者专注于真正重要的东西. (一)如何使用android annotations 具体使用方法请参看此文. (二)使用范例 /** * android annotations范例 * * @author peter_wang * @create-time 2014-9-13 下午7:40:56 */ // 设置Activi

【译】Core Java Questions and Answers【1-33】

前言 译文链接:http://www.journaldev.com/2366/core-java-interview-questions-and-answers Java 8有哪些重要的特性 Java 8发布于2014年3月,这块内容在Java面试中非常常见.如果你能清晰的回答这方面的问题,说明you are not out,喜欢学习最新的技术.Java 8是继Java 5的注解和泛型之后所做的最大的改动,主要的新特性如下: 1.接口支持静态方法和默认方法 2.函数式接口和Lambda表达式 3

Java中万恶的注解

本文由码农网 – 孙腾浩原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! 当Java 1.5引入注解,企业开发者对简化EJB和其他企业产品开发抱有很大期望.可以看一看同一时期的一篇文章用EJB 3.0简化企业Java开发. 然而从那时起,Java企业使用注解出现一些无法预料的后果和副作用,一些甚至到今天都没有被注意到.幸运的是,并非所有的副作用都没有被注意到,来看一些例子,在StackOverflow标题为“Why Java Annotations?”有很多有价值的评论,“Are

Java注解编程指南

Java注解编程指南 Java Annotation Tutorial +1概念 注解是JDK1.5开始引入的一个Java语言新特性.注解是与接口很相似,它与类.接口.枚举是在同一个层次,它 们都称作为java 的一个类型(TYPE). +1.1Java语言指南解释 注解(也被称做元数据),为我们提供了程序代码的描述信息,而这些描述信息并不属于程序本身.注解并不直接 影响其注释的代码的工作. +1.2Java编程思想解释 注解(也被称做元数据),为我们在代码中添加信息提供了一种形式化的方法,使我

Java Annotation 机制源码分析与使用

1 Annotation 1.1 Annotation 概念及作用      1.  概念 An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the