LinuxChan的程序园地

前端后端Web开发技术

 

2009年1月23日

两个很简单的java反射应用

1,是否对java Web中无处不在的Vo ,Dto比较无语呢?想要看看其中的数据,就必需不厌其烦的调用getXXX();所以写了个BaseVo 只要继承它,
然后直接调用它的toString()方法,即可将里面的值都打印出来
    public String toString() {
        Field[] fields 
= this.getClass().getDeclaredFields();
        StringBuffer result 
= new StringBuffer();
        
for (Field field : fields) {
            
// System.out.prIntegerln(field.getName());
            String fieldName = field.getName();
            String methodName 
= "get" + fieldName.substring(01).toUpperCase()
                    
+ fieldName.substring(1);
            result.append(fieldName 
+ ":");
            Method method 
= null;
            Object obj 
= null;
            
try {
                method 
= UserVo.class.getMethod(methodName);
                obj 
= method.invoke(thisnull);
            }
 catch (SecurityException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }
 catch (NoSuchMethodException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }
 catch (IllegalArgumentException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }
 catch (IllegalAccessException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }
 catch (InvocationTargetException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

            
if (obj != null{
                result.append(obj);
            }
 else
                result.append(
"");
            result.append(
"\n");
        }

        
return result.toString();
    }


2,2个同类型的Vo/Dto,需要将一个中的值填充到另外一个里去。正常方法需要set/get 如果字段一多,简直是噩梦。而利用反射,可以轻易实现。
 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(01).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(01).toUpperCase()
11                                + field.getName().substring(1), result.getClass());
12                setMethod.invoke(target, result);
13            }

14        }

15    }

posted @ 2009-01-23 12:04 LinuxChan 阅读(480) | 评论 (2)编辑 收藏

开博了,今后会将自己的一些灵感收集其中

记录人生成长的方向。

posted @ 2009-01-23 11:57 LinuxChan 阅读(100) | 评论 (1)编辑 收藏

仅列出标题  

导航

统计

常用链接

留言簿(2)

随笔档案

友情链接

搜索

最新评论

阅读排行榜

评论排行榜