public <T> T CopyT(Class<T> t, T template)
{
T model = null;
try
{
model = t.newInstance();
Class<?> classType = template.getClass();
Field[] flds = classType.getFields();
for( Field fld : flds)
{
try
{
Object value = fld.get(template);
fld.set(model, value);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
catch (InstantiationException e1)
{
e1.printStackTrace();
}
catch (IllegalAccessException e1)
{
e1.printStackTrace();
}
return model;
}
//简单点的通过反射实现拷贝
public Object CopyObj(Object OldObj)
{
Object newObj = new Object();
Class<?> classType = OldObj.getClass();
Field[] flds = classType.getFields();
for( Field fld : flds)
{
try
{
Object value = fld.get(OldObj);
fld.set(newObj, value);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return newObj;
}
转载于:https://my.oschina.net/u/726439/blog/286516