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 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();
			}

		}
	}

	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());

	}
}

 

你可能感兴趣的:(java)