java反射实例

[color=indigo][color=indigo][color=indigo]public class Student{
private Integer sex ;
private String typeName ="good";
private Date sysdate ;
...
}

public class TestcopyBean{

public static Student getMap() {[color=indigo][/color]
Student map = new Student();
map.setSex(new Integer(1));
map.setTypeName( "hao");
map.setSysdate(new Date());
return map;
}

public static void merge(Student map)
throws SecurityException, NoSuchFieldException,
NoSuchMethodException, IllegalArgumentException,
InvocationTargetException, ClassNotFoundException, InstantiationException, IllegalAccessException {

Class c=map.getClass();
Field[] fields = c.getDeclaredFields();//得到此类所有的字段
//根据传入对象的类型,构造一个新的对象
Object o = c.newInstance();


Method setmethod = null;
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
String setMethod = "set" + fieldName.substring(0, 1).toUpperCase() +
fieldName.substring(1);//根据字段名拼凑其set方法名
String getMethod = "get"+ fieldName.substring(0, 1).toUpperCase() +
fieldName.substring(1);
//根据方法的名字,取得Method对象,下面两行语句分别取得了get和set方法对象
setmethod = c.getDeclaredMethod(setMethod,new Class[]{fields[i].getType()});
Method getMothod=c.getMethod(getMethod, new Class[]{});

Object value=getMothod.invoke(map, new Object[]{});
setmethod.invoke(o, new Object[]{value});

}
Student beano = (Student)o;
System.out.println(beano.getSex()+" "+beano.getTypeName()+" "+beano.getSysdate());


}

public static void main(String[] args) throws DocumentException, SecurityException, IllegalArgumentException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException, InstantiationException, IllegalAccessException{

merge(getMap());
}[/color][/color][/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值