您的位置:首页 > 编程语言 > Java开发

【Util】java copy bean 反射

2016-01-20 17:31 471 查看
@SuppressWarnings("unchecked")
public <S, T> T copySuperBean(Object source,  Class<T> target) throws InstantiationException, IllegalAccessException{
if (source == null) {
return null;
}
if (target == null) {
target = (Class<T>) source.getClass();
}
T newBean = target.newInstance();
Class<? extends Object> ss = source.getClass();
Class<?> ann = 	ss.getSuperclass();
if (ann.newInstance() instanceof BaseMsg && newBean instanceof WechatMessage) {
Field[] fields = ann.getDeclaredFields();
for (Field field : fields) {
Object value = null;
String name = field.getName();
String upperName = name.substring(0, 1).toUpperCase() + name.substring(1);
try {
String getName = String.format("get%s", upperName);
String setName = String.format("set%s", upperName);
Method getMethod = source.getClass().getMethod(getName,  new Class[] {});
Method setMethod = newBean.getClass().getMethod(setName,  new Class[] {field.getType()});
value = getMethod.invoke(source);
if (value == null) {
continue;
}
setMethod.invoke(newBean, value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return newBean;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: