對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有沒有完成現成的功能,不想重復早輪子。希望大俠們可以留言告之。