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

java中通过泛型和反射实现类拷贝

2014-07-02 00:00 344 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  泛型 反射