利用映射实现两个结构相同javabean的赋值

来源:互联网 发布:基于大数据的用户画像 编辑:程序博客网 时间:2024/06/15 22:20
public static void test() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
// import java.lang.reflect.Field;
// import java.lang.reflect.InvocationTargetException;
Formbean form = new Formbean();
form.setName("tom");
form.setAge("dick");
Tobean to = new Tobean();
Field[] fields = form.getClass().getDeclaredFields();
for(int i = 0; i<fields.length;i++){
String name = fields[i].getName();
//System.out.println(name);
String tmp1 = name.substring(0, 1);
tmp1 = tmp1.toUpperCase();
String tmp2 = name.substring(1);
String methodName1 = "get"+tmp1+tmp2;
String methodName2 = "set"+tmp1+tmp2;
Class class1 = Formbean.class;
Class class2 = Tobean.class;
java.lang.reflect.Method method1 = class1.getMethod(methodName1, null);
java.lang.reflect.Method method2 = class2.getMethod(methodName2, new Class[]{String.class});
Object result = method1.invoke(form, null);
method2.invoke(to, new Object[]{result.toString()});

//System.out.println();
}
System.out.println(to.getClass().getName());
System.out.println(to.getName());
System.out.println(to.getAge());
}
public static void main(String[] args) throws Exception, NoSuchMethodException {
test();
}
原创粉丝点击