java Annotation初用
對(duì)java的Annotation不是太熟悉,不過(guò)最近又要用,所以就找了相關(guān)的文檔看了下,并寫(xiě)了一個(gè)Demo
基本的需求如下:
Server根據(jù)對(duì)方傳遞的類(lèi)型碼找到具體的某個(gè)類(lèi)的具體方法并運(yùn)行。個(gè)人覺(jué)得用Annotation去注釋代碼比較好,也減少配置文件,所以就體驗(yàn)了一把。
具體代碼如下:
1、先定義一個(gè)自己的Annotation
public @interface CodeAnnotation {
String code();
}
String code();
}
這里一定要將自己的Annotation定義為運(yùn)行時(shí)的,默認(rèn)好像是編譯時(shí)的,所以無(wú)法動(dòng)態(tài)的根據(jù)server接收到的code去匹配函數(shù)
2、@Override定義父類(lèi)basicHandler通過(guò)放射去獲取執(zhí)行子類(lèi)的方法
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;
}
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;
}
3、一個(gè)具體的handler類(lèi)示例
@CodeAnnotation(code = "10000001")
public Message method(Message message) {
System.out.println(message.getUserId());
//TODO:
return null;
}
上面的代碼,基本上手工的完成了命令碼和方法的映射,個(gè)人對(duì)Spring還不是很精通,不知道Spring有沒(méi)有完成現(xiàn)成的功能,不想重復(fù)早輪子。希望大俠們可以留言告之。public Message method(Message message) {
System.out.println(message.getUserId());
//TODO:
return null;
}
posted on 2012-01-21 01:19 潘潘.eagle 閱讀(1716) 評(píng)論(1) 編輯 收藏 所屬分類(lèi): JAVA