数据加载中……
java Annotation初用

java的Annotation不是太熟悉,不过最近又要用,所以就找了相关的文档看了下,并写了一个Demo

基本的需求如下:

Server根据对方传递的类型码找到具体的某个类的具体方法并运行。个人觉得用Annotation去注释代码比较好,也减少配置文件,所以就体验了一把。

具体代码如下:

1、先定义一个自己的Annotation

@Retention(RetentionPolicy.RUNTIME)
public @interface CodeAnnotation {
    String code();
}

     这里一定要将自己的Annotation定义为运行时的,默认好像是编译时的,所以无法动态的根据server接收到的code去匹配函数
   2、
@Override定义父类basicHandler通过放射去获取执行子类的方法

    public Message execute(Message message) {
        String code 
= message.getCode();
        String className 
= this.getClass().getName();
        Message msg 
= null;
        
try {
            
for (Method m : Class.forName(className).getMethods()) {
                
if (m.getAnnotation(CodeAnnotation.class!= null) {
                    
if (code.equals(m.getAnnotation(CodeAnnotation.class).code())) {
                        
try {
                            msg 
= (Message)m.invoke(this, message);
                        } 
catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } 
catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } 
catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } 
catch (SecurityException e) {
            e.printStackTrace();
        } 
catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        
return msg;
    }
      这是基类中的方法,基类实现了接口中的execute方法,子类继承父类,并添加具体的业务方法和代码
   3、
一个具体的handler类示例
@CodeAnnotation(code = "10000001")
    
public Message method(Message message) {
        System.out.println(message.getUserId());
        
//TODO:
        return null;
    }
    
上面的代码,基本上手工的完成了命令码和方法的映射,个人对Spring还不是很精通,不知道Spring有没有完成现成的功能,不想重复早轮子。希望大侠们可以留言告之。

posted on 2012-01-21 01:19 潘潘.eagle 阅读(1669) 评论(1)  编辑  收藏 所属分类: JAVA

评论

# re: java Annotation初用 2012-01-23 23:12 tb

学习了
  回复  更多评论    

只有注册用户登录后才能发表评论。


网站导航: