首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

java.lang.refect反照UserForm

2012-11-05 
java.lang.refect反射UserFormimport java.lang.reflect.Fieldimport java.lang.reflect.InvocationTarge

java.lang.refect反射UserForm

import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import com.chai.form.UserForm;import comm.chai.vo.UserVo;public class test {public static void Copyreflect(Object obj1, Object obj2) {Class classobj1 = obj1.getClass();Class classobj2 = obj2.getClass();Field[] fields = classobj1.getDeclaredFields();for (int i = 0; i < fields.length; i++) {Field field = fields[i];String setMethodname = "set"+ field.getName().substring(0, 1).toUpperCase()+ field.getName().substring(1);String getMethodname = "get"+ field.getName().substring(0, 1).toUpperCase()+ field.getName().substring(1);try {if (field.getType() == String.class) {Method getmethod = classobj1.getDeclaredMethod(getMethodname, new Class[] {});Method setmethod = classobj2.getDeclaredMethod(setMethodname, new Class[] { String.class });setmethod.invoke(obj2, new Object[] { getmethod.invoke(obj1, new Object[] {}) });}else if (field.getType() == int.class) {Method getmethod = classobj1.getDeclaredMethod(getMethodname, new Class[] {});Method setmethod = classobj2.getDeclaredMethod(setMethodname, new Class[] { int.class });setmethod.invoke(obj2, new Object[] { getmethod.invoke(obj1, new Object[] {}) });}} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void main(String[] args) {UserForm form = new UserForm();form.setUsername("chai");form.setId(1000);UserVo vo = new UserVo();Copyreflect(form, vo);System.out.println(vo.getUsername()+"=="+vo.getId());}}

?

热点排行