Java Annotation

来源:互联网 发布:苏州矩阵光电 编辑:程序博客网 时间:2024/04/30 20:02

从JDK5开始,Java增加了Annotation(注解),Annotation是代码里的特殊标记,这些标记可以在编译、类加载、运行时被读取,并执行相应的处理。通过使用Annotation,开发人员可以在不改变原有逻辑的情况下,在源文件中嵌入一些补充的信息。代码分析工具、开发工具和部署工具可以通过这些补充信息进行验证、处理或者进行部署。 

Annotation提供了一种为程序元素(包、类、构造器、方法、成员变量、参数、局域变量)设置元数据的方法。Annotation不能运行,它只有成员变量,没有方法。Annotation跟public、final等修饰符的地位一样,都是程序元素的一部分,Annotation不能作为一个程序元素使用。
定义Annotation
自行去这个网址看吧
http://www.open-open.com/lib/view/open1423558996951.html

2 提取Annotation信息(反射)
当开发者使用了Annotation修饰了类、方法、Field等成员之后,这些Annotation不会自己生效,必须由开发者提供相应的代码来提取并处理Annotation信息。这些处理提取和处理Annotation的代码统称为APT(Annotation Processing Tool)

简单的提取Annotation信息程序
// Annotation的声明import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    String value();}

import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class AnnotationTest {    @MyAnnotation("Just a Test.")    public static void main(String[] args) throws Exception {          Method[] methods = Class.forName("AnnotationTest").getMethods();          for (Method m : methods) {                if (m.isAnnotationPresent(MyAnnotation.class)) {                      MyAnnotation annotation = m.getAnnotation(MyAnnotation.class);                      System.out.println("方法" + m.getName() + "的MyAnnotation注解内容为:"                                          + annotation.value());                }          }    }    @MyAnnotation(value="Hello NUMEN.")    public static void sayHello() {          System.out.println("Say Hello");    }}
输出结果
方法main的MyAnnotation注解内容为:Just a Test.方法sayHello的MyAnnotation注解内容为:Hello NUMEN.

3.利用反射实现简单的RPC调用
关键的MyAnnotationHelper类实现 Annotation信息和特定方法绑定

import java.io.IOException;import java.net.Socket;import java.util.HashMap;import java.util.Map;import java.util.StringTokenizer;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class MyAnnotationHelper {    /*     * 1. get到具体的请求     * 2. 匹配选中的请求     * 3. invoke     */    private static MyAnnotationHelper instance = null;    private final static String CRLF = System.getProperty("line.separator");    private StreamSocket streamSocket;    private Method[] methods;    private Map<String, Method> map;    private MyAnnotationHelper() throws Exception {        streamSocket = null;        init();    }    private void init() throws Exception {        if (map == null) map = new HashMap<String, Method>();        methods = Class.forName("SimpleHTTPServerHelper").getMethods();        for (Method m : methods) {            if (m.isAnnotationPresent(Mypath.class)) {                Mypath annotation = m.getAnnotation(Mypath.class);                System.out.println("方法" + m.getName() + "的MyAnnotation注解内容为:"                                    + annotation.value());                map.put(annotation.value(), m);            }        }    }    public static MyAnnotationHelper getInstance() throws Exception {        if (instance == null) instance = new MyAnnotationHelper();        return instance;    }    public void setSocket(Socket socket) throws IOException {        this.streamSocket = new StreamSocket(socket);    }    public void processRequest() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {        while (true) {            // 读取并显示 HTTP客户端提交的请求信息            String headerLine = streamSocket.receiveMessage();            if (headerLine.trim().equals(".")) {                System.out.println("会话结束!");                break;            } else {                if (headerLine.length() != 0)                    System.out.println("客户端的请求时:" + headerLine);                StringTokenizer s = new StringTokenizer(headerLine);                if ((s.countTokens() >= 2) && s.nextToken().equals("GET")) {                    String filename = s.nextToken();                    if (filename.startsWith("/"))                        filename = filename.substring(1);                    if (filename.endsWith("/"))                        filename += "index.html";                    if (filename.equals(""))                        filename += "index.html";                    String statusLine = null;                    String entityBody = null;                    if (map.containsKey(filename)) {                        statusLine = "HTTP/1.0 200 OK" + CRLF;                        SimpleHTTPServerHelper simpleHTTPServerHelper = new SimpleHTTPServerHelper();                        System.out.println("filename: "+ filename);                        Object invoke = map.get(filename).invoke(simpleHTTPServerHelper, null);                        entityBody = (String) invoke;                    } else {                        statusLine = "HTTP/1.0 404 Not Found" + CRLF;                        entityBody = "<HTML>" + "<HEAD>" + CRLF                                + "<TITLE>404 Not Found</TITLE>" + CRLF                                + "</HEAD><BODY>" + CRLF + "<h1>Not Found</h1>"                                + CRLF + "<p>The request URI " + filename                                + " was not found on this server.</p>" + CRLF                                + "</BODY></HTML>" + CRLF;                        System.out.println("该URL不存在");                    }                    streamSocket.sendMessage(statusLine);                    streamSocket.sendMessage(CRLF);                    streamSocket.sendMessage(entityBody);                    streamSocket.sendMessage(CRLF);                }            }        }    }}
代码下载地址:https://github.com/zhzdeng/SimpleHTTPServerForAnnotation.git

参考文章 http://www.open-open.com/lib/view/open1423558996951.html
0 0
原创粉丝点击