原文地址:http://stackoverflow.com/questions/18189980/how-do-annotations-work-internally

The first main distinction between kinds of annotation is whether they're used at compile time and then discarded (like @Override) or placed in the compiled class file and available at runtime (like Spring's @Component). This is determined by the @Retention policy of the annotation. If you're writing your own annotation, you'd need to decide whether the annotation is helpful at runtime (for autoconfiguration, perhaps) or only at compile time (for checking or code generation).

When compiling code with annotations, the compiler sees the annotation just like it sees other modifiers on source elements, like access modifiers (public/private) or final. When it encounters an annotation, it runs an annotation processor, which is like a plug-in class that says it's interested a specific annotation. The annotation processor generally uses the Reflection API to inspect the elements being compiled and may simply run checks on them, modify them, or generate new code to be compiled. @Override is an example of the first; it uses the Reflection API to make sure it can find a match for the method signature in one of the superclasses and uses the Messagerto cause a compile error if it can't.

There are a number of tutorials available on writing annotation processors; here's a useful one. Look through the methods on the Processor interface for how the compiler invokes an annotation processor; the main operation takes place in the process method, which gets called every time the compiler sees an element that has a matching annotation.

附录:

Writing an Annotation Based Processor in Java

原文地址http://travisdazell.blogspot.hk/2012/10/writing-annotation-based-processor-in.html

The code for this tutorial is on GitHub: https://github.com/travisdazell/Annotation-Based-Processor

Annotations have been around since Java 5. They provide a way to mark (i.e. annotate) Java code in a clean and concise manner. With Java 6 and 7, we can do even more with annotations. The most exciting of which, in my opinion, is the ability to write our own annotations and even process our own annotations to detect code issues or even generate source code at compile time.

In this example, we'll create an annotation named @Metrics. We'll be able to mark Java classes with @Metrics and at compile-time, generate a report of all methods defined in the class. To create your own annotation and its corresponding processor, follow these steps.

  1. Define the annotation. This is done by defining the annotation with @interface.

public @interface Metrics {
     }
  
     2. We can now annotate any class in our project with our new annotation.

import net.travisdazell.annotations.Metrics;

@Metrics
     public class CustomerDaoImpl implements CustomerDao {
        public Customer getCustomer(int customerId) {
           // return Customer record
        }
     }

3. The next step is to write a processor that, at compile time, will report all of the methods defined in CustomerDaoImpl.java. Here's our processor in its entirety.

package net.travisdazell.annotations.processors;

import java.lang.reflect.Method;
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.TypeElement;
import javax.tools.Diagnostic;

import net.travisdazell.annotations.Metrics;

@SupportedAnnotationTypes("net.travisdazell.annotations.Metrics")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class MetricsProcessor extends AbstractProcessor {
    
    @Override
    public boolean process(Set<? extends TypeElement> arg0,
            RoundEnvironment roundEnv) {

StringBuilder message = new StringBuilder();

for (Element elem : roundEnv.getElementsAnnotatedWith(Metrics.class)) {
            Metrics implementation = elem.getAnnotation(Metrics.class);

message.append("Methods found in " + elem.getSimpleName().toString() + ":\n");

for (Method method : implementation.getClass().getMethods()) {
                message.append(method.getName() + "\n");
            }

processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message.toString());
        }

return false; // allow others to process this annotation type
    }
}

4. Next, we need to package our annotation processor and annotation in a JAR file. We must also include a META-INF\services directory in our JAR file. Within the services directory, include a file named javax.annotation.processing.Processor. In that file, type the fully qualified name of the annotation processor.

Here's what my JAR file looks like when exploded in Eclipse.

5. Next, to test our annotation processor, create a class and annotate it with @Metrics.

package net.travisdazell.projects.testproject.dao.impl;

import net.travisdazell.annotations.Metrics;

@Metrics
public class CustomerDaoImpl {
}

6.When we compile this class, we'll get a message displaying the list of methods in the class. As expected, we see what's been inherited from java.lang.Object.

How do annotations work internally--转的更多相关文章

  1. How those spring enable annotations work--转

    原文地址:http://blog.fawnanddoug.com/2012/08/how-those-spring-enable-annotations-work.html Spring's Java ...

  2. Android注解使用之使用Support Annotations注解优化代码

    前言: 前面学习总结了Java注解的使用,博客地址详见Java学习之注解Annotation实现原理,从本质上了解到什么注解,以及注解怎么使用?不要看见使用注解就想到反射会影响性能之类,今天我们就来学 ...

  3. Scala Macros - scalamela 1.x,inline-meta annotations

    在上期讨论中我们介绍了Scala Macros,它可以说是工具库编程人员不可或缺的编程手段,可以实现编译器在编译源代码时对源代码进行的修改.扩展和替换,如此可以对用户屏蔽工具库复杂的内部细节,使他们可 ...

  4. [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...

  5. EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射

    I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...

  6. Multiple annotations found at this line

    Multiple annotations found at this line 在使用MyEclipse的时候,通过MVN导入项目时候,webapp下面的JSP页面报了如下的错误: 这种情况通常的原因 ...

  7. How Do Annotations Work in Java?--转

    原文地址:https://dzone.com/articles/how-annotations-work-java Annotations have been a very important par ...

  8. 使用Android Annotations开发

    使用Android Annotations框架gradle配置1.修改Module下的build.gradle apply plugin: 'com.android.application' appl ...

  9. Entity Framework Code First (三)Data Annotations

    Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...

随机推荐

  1. Selenium中的几种等待方式,需特别注意implicitlyWait的用法

    摘:http://blog.csdn.net/pf20050904/article/details/20052485 最近在项目过程中使用selenium 判断元素是否存在的时候 遇到一个很坑爹的问题 ...

  2. js基础知识:变量

    一.什么是变量? 在JavaScript中,变量用来存放值的,存放任何数据类型的值都可以,它就是值的容器. 二.变量怎么用? (一)用var声明1个变量 在使用变量之前,需要var关键字来声明变量,变 ...

  3. Mac OS X 安装Win7双系统

    Mac10安装双系统 为了有一个纯净的开发环境,就在mac电脑中安装windows虚拟机.刚开始使用还很顺利,两个系统的交互很方便,mac用来下载.搜索和写笔记:windows纯开发.时间长了以后关机 ...

  4. Zookeeper会话

    Zookeeper会话的状态可以分为以下四种:CONNECTING,CONNECTED,CLOSED和NOT_CONNECTED.下图展示了会话的状态和状态之间的转移过程: 会话的初始状态为NOT_C ...

  5. centos7.2 默认启动内核修改

    总所周知,修改centos6的内核启动顺序,只需要修改/etc/grub.conf 里的default项配置即可.那么centos7系统该如何修改呢? 下面就centos7系统修改内核,做如下记录: ...

  6. unity渲染层级关系小结(转存)

    最近连续遇到了几个绘制图像之间相互遮挡关系不正确的问题,网上查找的信息比较凌乱,所以这里就把自己解决问题中总结的经验记录下来. Unity中的渲染顺序自上而下大致分为三层. 最高层为Camera层,可 ...

  7. 实现Ogre的脚本分离 - 天龙八部的源码分析(一)

    目的 在研究天龙八部游戏的源码之时, 发现 Ogre 材质的模板部分被单独放在一个 material 文件之内, 继承模板的其他材质则位于另外的文件, 当我使用Ogre 官方源码, 加载脚本时其不会查 ...

  8. go程序注册为windows服务

    cmd下运行:nssm install 服务名 go打包好的exe文件 nssm下载地址:http://nssm.cc/,将下载好nssm.exe放到/windows/system32文件夹下

  9. 【转】Eclipse打JAR包,插件FatJar安装与使用

    原文地址:http://blog.csdn.net/jikeyzhang/article/details/4731968 下载RUL: 下载fatJar插件,解压缩后是一个.../plugins/(n ...

  10. 深入理解Ember-Data特性(下)

    写在前面 最近比较忙,换了新工作还要学习很多全新的技术栈,并给自己找了很多借口来不去坚持写博客.常常具有讽刺意味的是,更多剩下的时间并没有利用而更多的是白白浪费,也许这就是青春吧,挥霍吧,这不是我想要 ...