Annotation

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注解的写法

 @Entity

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

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

 @Entity(tableName = "vehicles")

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

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

注解可以有多个元素。

 @InsertNew(value = "yes")

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

 @InsertNew("yes")

1.3 注解可以应用的位置

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

 @Entity
public class Vehicle {
}
 @Entity
public class Vehicle { @Persistent
protected String vehicleName = null; @Getter
public String getVehicleName() {
return this.vehicleName;
} public void setVehicleName(@Optional vehicleName) {
this.vehicleName = vehicleName;
} public List addVehicleNameToList(List names) { @Optional
List localNames = names; if(localNames == null) {
localNames = new ArrayList();
}
localNames.add(getVehicleName()); return localNames;
} }

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

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]

 @Deprecated
public class MyComponent { }

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注解定义在自己的文件中。

 @interface MyAnnotation {

     String   value();

     String   name();
int age();
String[] newNames(); }

@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]

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

 @MyAnnotation(
value="123",
name="Jakob",
age=37,
newNames={"Jenkov", "Peterson"}
)
public class MyClass { }

1.5.1 元素的默认值

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

 @interface MyAnnotation {

     String   value() default "";

     String   name();
int age();
String[] newNames(); }

"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."

 @MyAnnotation(
name="Jakob",
age=37,
newNames={"Jenkov", "Peterson"}
)
public class MyClass { }

在上例中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."

 import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { String value() default ""; }

"@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]

 import java.lang.annotation.ElementType;
import java.lang.annotation.Target; @Target({ElementType.METHOD})
public @interface MyAnnotation { String value();
}

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]

 java.lang.annotation.Inherited

 @Inherited
public @interface MyAnnotation { } @MyAnnotation
public class MySuperClass { ... } 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

 java.lang.annotation.Documented

 @Documented
public @interface MyAnnotation { } @MyAnnotation
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]

4. Annotation Processor

A:如何编写Annotation Processor? 以及调试Processor?

B: 如何没有和Annotation相对应的Processor,那么Annotation会有什么效果?


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

12. APT in Eclipse

http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_apt_getting_started.htm

13. Explore Annotations in Java 8 [To Read]

https://dzone.com/articles/explore-annotations-in-java-8

Java.Annotations的更多相关文章

  1. Java Annotations: Explored & Explained--转载

    原文地址:http://www.javacodegeeks.com/2012/08/java-annotations-explored-explained.html One of the many w ...

  2. Java Annotations, Java Reflection, and Java Test Runner

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

  3. Java custom annotations

    Custom annotation definition is similar as Interface, just with @ in front. Annotation interface its ...

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

    前言 译文链接:http://www.journaldev.com/2366/core-java-interview-questions-and-answers Java 8有哪些重要的特性 Java ...

  5. Java Annotation概述

    @(Java)[Annotation|Java] Java Annotation概述 用途 编译器的相关信息,如用于检测错误和一些警告 编译时和部署时的处理,如一些软件用于自动生成代码之类的 运行时处 ...

  6. java注释指导手册

    译文出处: Toien Liu   原文出处:Dani Buiza 编者的话:注解是java的一个主要特性且每个java开发者都应该知道如何使用它. 我们已经在Java Code Geeks提供了丰富 ...

  7. IREP_SOA Integration程序注释语法Annotations(概念)

    20150506 Created By BaoXinjian

  8. Java Annotation 机制源码分析与使用

    1 Annotation 1.1 Annotation 概念及作用      1.  概念 An annotation is a form of metadata, that can be added ...

  9. mybatis Java API

    既然你已经知道如何配置 MyBatis 和创建映射文件,你就已经准备好来提升技能了. MyBatis 的 Java API 就是你收获你所做的努力的地方.正如你即将看到的,和 JDBC 相比, MyB ...

随机推荐

  1. idea git 把本地项目上传到github上

    创建一个项目,在项目文件夹下执行以下命令 第二种方法: 先在idea上创建一个项目 注意以上只是在本地建立了本地仓库,代码都放在本地仓库. 现在上传到github上 到此才上传成功

  2. 学JS的心路历程 -函式(三)this

    this是什么,取决于被呼叫的呼叫地点. 昨天有提到说,呼叫函式时候会传递隐含参数:arguments和this并讲解了arguments,今天我们就来探讨this吧! 什么是this 我们都会呼叫函 ...

  3. python基础学习Day12 生成器、列表推导式、字典的表达式、字典键值对的互换、集合推导式

    一.生成器 1.1 生成器:就是(python)自己用代码写的迭代器,生成器的本质就是迭代器. 1.2 生成器函数 def func1(x): x += print() yield x print() ...

  4. https://www.oschina.net/project/zhlist/326/scripting 开源

    1https://www.oschina.net/project/zhlist/326/scripting

  5. 修改php.ini 的timezone

    php运行模式有apache 和 cli模式 这里讲cli 模式的php.ini设置 1.查找php.ini位置 php -i | grep php.ini 这样是表示 要改的文件 在/etc/php ...

  6. 游戏编程模式KeyNote

    [游戏编程模式KeyNote] 1.命令模式. 重做在游戏中并不常见,但重放常见.一种简单的重放实现是记录游戏每帧的状态,这样它可以回放,但那会消耗太多的内存.相反,很多游戏记录每个实体每帧运行的命令 ...

  7. 【Nodejs】Node.js(Express)の環境構築

    [Express]の環境 参考URL:http://expressjs.com/en/starter/generator.html ①Node.jsの準備 (参考URL:https://www.cnb ...

  8. 使用Python计算IP、TCP、UDP校验和

    IP数据报的校验: IP数据报只需要对数据头进行校验,步骤如下: 将接收到的数据的checksum字段设置为0 把需要校验的字段的所有位划分为16位(2字节)的字 把所有16位的字相加,如果遇到进位, ...

  9. monobehaviour生命周期完整版

  10. PHP序列及反序列化安全漏洞

      尽量阐述全PHP序列化的相关东西-.- 1.序列化和反序列化   序列化是将变量或对象转换成字符串的过程:反序列化是将字符串转换成变量或对象的过程.   序列化及反序列化常见函数:serializ ...