兩個很簡單的java反射應(yīng)用
1,是否對java Web中無處不在的Vo ,Dto比較無語呢?想要看看其中的數(shù)據(jù),就必需不厭其煩的調(diào)用getXXX();所以寫了個BaseVo 只要繼承它,然后直接調(diào)用它的toString()方法,即可將里面的值都打印出來






































2,2個同類型的Vo/Dto,需要將一個中的值填充到另外一個里去。正常方法需要set/get 如果字段一多,簡直是噩夢。而利用反射,可以輕易實現(xiàn)。
1
public static void parseVO(Object obj, Object target)
2
throws Exception, NoSuchMethodException {
3
for (Field field : obj.getClass().getDeclaredFields()) {
4
Method getMethod = obj.getClass().getMethod(
5
"get" + field.getName().substring(0, 1).toUpperCase()
6
+ field.getName().substring(1));
7
Object result = getMethod.invoke(obj);
8
if (result != null) {
9
Method setMethod = target.getClass().getMethod(
10
"set" + field.getName().substring(0, 1).toUpperCase()
11
+ field.getName().substring(1), result.getClass());
12
setMethod.invoke(target, result);
13
}
14
}
15
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

posted @ 2009-01-23 12:04 LinuxChan 閱讀(502) | 評論 (2) | 編輯 收藏