[英]Copy all values from fields in one class to another through reflection
我有一个 class,它基本上是另一个 class 的副本。
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
我正在做的是在通过网络服务调用发送CopyA
之前,将 class A
中的值放入CopyA
中。 现在我想创建一个反射方法,基本上将所有相同的字段(按名称和类型)从 class A
复制到 class CopyA
。
我怎样才能做到这一点?
这是我到目前为止所拥有的,但它并不完全有效。 我认为这里的问题是我试图在我正在循环的字段上设置一个字段。
private <T extends Object, Y extends Object> void copyFields(T from, Y too) {
Class<? extends Object> fromClass = from.getClass();
Field[] fromFields = fromClass.getDeclaredFields();
Class<? extends Object> tooClass = too.getClass();
Field[] tooFields = tooClass.getDeclaredFields();
if (fromFields != null && tooFields != null) {
for (Field tooF : tooFields) {
logger.debug("toofield name #0 and type #1", tooF.getName(), tooF.getType().toString());
try {
// Check if that fields exists in the other method
Field fromF = fromClass.getDeclaredField(tooF.getName());
if (fromF.getType().equals(tooF.getType())) {
tooF.set(tooF, fromF);
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException 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();
}
}
}
我相信一定有人已经以某种方式做到了这一点
如果您不介意使用第三方库,Apache Commons 的BeanUtils将使用copyProperties(Object, Object)
轻松处理此问题。
为什么不使用 gson 库https://github.com/google/gson
您只需将 A 类转换为 json 字符串。 然后将 jsonString 转换为您的子类(CopyA)。使用以下代码:
Gson gson= new Gson();
String tmp = gson.toJson(a);
CopyA myObject = gson.fromJson(tmp,CopyA.class);
BeanUtils 只会复制公共字段,速度有点慢。 而是使用 getter 和 setter 方法。
public Object loadData (RideHotelsService object_a) throws Exception{
Method[] gettersAndSetters = object_a.getClass().getMethods();
for (int i = 0; i < gettersAndSetters.length; i++) {
String methodName = gettersAndSetters[i].getName();
try{
if(methodName.startsWith("get")){
this.getClass().getMethod(methodName.replaceFirst("get", "set") , gettersAndSetters[i].getReturnType() ).invoke(this, gettersAndSetters[i].invoke(object_a, null));
}else if(methodName.startsWith("is") ){
this.getClass().getMethod(methodName.replaceFirst("is", "set") , gettersAndSetters[i].getReturnType() ).invoke(this, gettersAndSetters[i].invoke(object_a, null));
}
}catch (NoSuchMethodException e) {
// TODO: handle exception
}catch (IllegalArgumentException e) {
// TODO: handle exception
}
}
return null;
}
这是一个有效且经过测试的解决方案。 您可以控制类层次结构中的映射深度。
public class FieldMapper {
public static void copy(Object from, Object to) throws Exception {
FieldMapper.copy(from, to, Object.class);
}
public static void copy(Object from, Object to, Class depth) throws Exception {
Class fromClass = from.getClass();
Class toClass = to.getClass();
List<Field> fromFields = collectFields(fromClass, depth);
List<Field> toFields = collectFields(toClass, depth);
Field target;
for (Field source : fromFields) {
if ((target = findAndRemove(source, toFields)) != null) {
target.set(to, source.get(from));
}
}
}
private static List<Field> collectFields(Class c, Class depth) {
List<Field> accessibleFields = new ArrayList<>();
do {
int modifiers;
for (Field field : c.getDeclaredFields()) {
modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
accessibleFields.add(field);
}
}
c = c.getSuperclass();
} while (c != null && c != depth);
return accessibleFields;
}
private static Field findAndRemove(Field field, List<Field> fields) {
Field actual;
for (Iterator<Field> i = fields.iterator(); i.hasNext();) {
actual = i.next();
if (field.getName().equals(actual.getName())
&& field.getType().equals(actual.getType())) {
i.remove();
return actual;
}
}
return null;
}
}
我的解决方案:
public static <T > void copyAllFields(T to, T from) {
Class<T> clazz = (Class<T>) from.getClass();
// OR:
// Class<T> clazz = (Class<T>) to.getClass();
List<Field> fields = getAllModelFields(clazz);
if (fields != null) {
for (Field field : fields) {
try {
field.setAccessible(true);
field.set(to,field.get(from));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
public static List<Field> getAllModelFields(Class aClass) {
List<Field> fields = new ArrayList<>();
do {
Collections.addAll(fields, aClass.getDeclaredFields());
aClass = aClass.getSuperclass();
} while (aClass != null);
return fields;
}
这是一个迟到的帖子,但对未来的人仍然有效。
Spring 提供了一个实用程序BeanUtils.copyProperties(srcObj, tarObj)
,当两个类的成员变量名称相BeanUtils.copyProperties(srcObj, tarObj)
值从源对象复制到目标对象。
如果有日期转换(例如,字符串到日期)'null' 将被复制到目标对象。 然后,我们可以根据需要明确设置日期的值。
当数据类型不匹配时, Apache Common
的 BeanUtils 会抛出错误(特别是与 Date 的转换)
希望这可以帮助!
2012 年 11 月 19 日更新:现在也有一个新的 ModelMapper 项目。
tooF.set()
的第一个参数应该是目标对象 ( too
),而不是字段,第二个参数应该是值,而不是值来自的字段。 (要获取该值,您需要调用fromF.get()
- 再次传入目标对象,在本例中为from
。)
大多数反射 API 都是这样工作的。 您可以从类中而不是从实例中获取Field
对象、 Method
对象等,因此要使用它们(静态除外),您通常需要向它们传递一个实例。
Spring 有一个内置的BeanUtils.copyProperties
方法。 但它不适用于没有 getter/setter 的类。 JSON 序列化/反序列化可以是复制字段的另一种选择。 Jackson 可以用于此目的。 如果您使用的是 Spring 在大多数情况下 Jackson 已经在您的依赖项列表中。
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Clazz copyObject = mapper.readValue(mapper.writeValueAsString(sourceObject), Clazz.class);
我想你可以试试 推土机。 它对 bean 到 bean 的转换有很好的支持。 它也很容易使用。 您可以将它注入到您的 spring 应用程序中,也可以将 jar 添加到类路径中并完成。
以您的情况为例:
DozerMapper mapper = new DozerMapper();
A a= new A();
CopyA copyA = new CopyA();
a.set... // set fields of a.
mapper.map(a,copyOfA); // will copy all fields from a to copyA
不使用 BeanUtils 或 Apache Commons
public static <T1 extends Object, T2 extends Object> void copy(T1 origEntity, T2 destEntity) throws IllegalAccessException, NoSuchFieldException { Field[] fields = origEntity.getClass().getDeclaredFields(); for (Field field : fields){ origFields.set(destEntity, field.get(origEntity)); } }
是的还是来自Apache Jakarta的BeanUtils。
Orika 是一个简单的快速 bean 映射框架,因为它通过字节码生成来完成。 它执行嵌套映射和具有不同名称的映射。 有关更多详细信息,请查看此处示例映射可能看起来很复杂,但对于复杂的场景,它会很简单。
MapperFactory factory = new DefaultMapperFactory.Builder().build();
mapperFactory.registerClassMap(mapperFactory.classMap(Book.class,BookDto.class).byDefault().toClassMap());
MapperFacade mapper = factory.getMapperFacade();
BookDto bookDto = mapperFacade.map(book, BookDto.class);
如果您在依赖项中有 spring,您还可以使用org.springframework.beans.BeanUtils 。
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/BeanUtils.html
我在 Kotlin 中解决了上述问题,这对我的 Android 应用程序开发来说很好用:
object FieldMapper {
fun <T:Any> copy(to: T, from: T) {
try {
val fromClass = from.javaClass
val fromFields = getAllFields(fromClass)
fromFields?.let {
for (field in fromFields) {
try {
field.isAccessible = true
field.set(to, field.get(from))
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun getAllFields(paramClass: Class<*>): List<Field> {
var theClass:Class<*>? = paramClass
val fields = ArrayList<Field>()
try {
while (theClass != null) {
Collections.addAll(fields, *theClass?.declaredFields)
theClass = theClass?.superclass
}
}catch (e:Exception){
e.printStackTrace()
}
return fields
}
}
这是我的解决方案,将涵盖子 class 案例:
/**
* This methods transfer the attributes from one class to another class if it
* has null values.
*
* @param fromClass from class
* @param toClass to class
*/
private void loadProperties(Object fromClass, Object toClass) {
if (Objects.isNull(fromClass) || Objects.isNull(toClass))
return;
Field[] fields = toClass.getClass().getDeclaredFields();
Field[] fieldsSuperClass = toClass.getClass().getSuperclass().getDeclaredFields();
Field[] fieldsFinal = new Field[fields.length + fieldsSuperClass.length];
Arrays.setAll(fieldsFinal, i -> (i < fields.length ? fields[i] : fieldsSuperClass[i - fields.length]));
for (Field field : fieldsFinal) {
field.setAccessible(true);
try {
String propertyKey = field.getName();
if (field.get(toClass) == null) {
Field defaultPropertyField = fromClass.getClass().getDeclaredField(propertyKey);
defaultPropertyField.setAccessible(true);
Object propertyValue = defaultPropertyField.get(fromClass);
if (propertyValue != null)
field.set(toClass, propertyValue);
}
} catch (IllegalAccessException e) {
logger.error(() -> "Error while loading properties from " + fromClass.getClass() +" and to " +toClass.getClass(), e);
} catch (NoSuchFieldException e) {
logger.error(() -> "Exception occurred while loading properties from " + fromClass.getClass()+" and to " +toClass.getClass(), e);
}
}
}
由于这个原因,我不想向另一个 JAR 文件添加依赖项,所以写了一些适合我需要的东西。 我遵循 fjorm https://code.google.com/p/fjorm/的约定,这意味着我通常可访问的字段是公开的,而且我不会费心编写 setter 和 getter。 (在我看来,代码实际上更易于管理且更具可读性)
所以我写了一些适合我需要的东西(实际上并不难)(假设该类具有没有 args 的公共构造函数)并且它可以被提取到实用程序类中
public Effect copyUsingReflection() {
Constructor constructorToUse = null;
for (Constructor constructor : this.getClass().getConstructors()) {
if (constructor.getParameterTypes().length == 0) {
constructorToUse = constructor;
constructorToUse.setAccessible(true);
}
}
if (constructorToUse != null) {
try {
Effect copyOfEffect = (Effect) constructorToUse.newInstance();
for (Field field : this.getClass().getFields()) {
try {
Object valueToCopy = field.get(this);
//if it has field of the same type (Effect in this case), call the method to copy it recursively
if (valueToCopy instanceof Effect) {
valueToCopy = ((Effect) valueToCopy).copyUsingReflection();
}
//TODO add here other special types of fields, like Maps, Lists, etc.
field.set(copyOfEffect, valueToCopy);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(Effect.class.getName()).log(Level.SEVERE, null, ex);
}
}
return copyOfEffect;
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Effect.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
Mladen 的基本想法奏效了(谢谢),但需要一些更改才能保持稳健,所以我在这里贡献了它们。
应该使用这种类型的解决方案的唯一地方是如果您想克隆对象,但不能,因为它是托管对象。 如果您有幸拥有所有字段都具有 100% 无副作用的 setter 的对象,那么您绝对应该改用 BeanUtils 选项。
在这里,我使用lang3的实用方法来简化代码,所以如果你粘贴它,你必须先导入Apache的lang3库。
复制代码
static public <X extends Object> X copy(X object, String... skipFields) {
Constructor constructorToUse = null;
for (Constructor constructor : object.getClass().getConstructors()) {
if (constructor.getParameterTypes().length == 0) {
constructorToUse = constructor;
constructorToUse.setAccessible(true);
break;
}
}
if (constructorToUse == null) {
throw new IllegalStateException(object + " must have a zero arg constructor in order to be copied");
}
X copy;
try {
copy = (X) constructorToUse.newInstance();
for (Field field : FieldUtils.getAllFields(object.getClass())) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
//Avoid the fields that you don't want to copy. Note, if you pass in "id", it will skip any field with "id" in it. So be careful.
if (StringUtils.containsAny(field.getName(), skipFields)) {
continue;
}
field.setAccessible(true);
Object valueToCopy = field.get(object);
//TODO add here other special types of fields, like Maps, Lists, etc.
field.set(copy, valueToCopy);
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new IllegalStateException("Could not copy " + object, e);
}
return copy;
}
public <T1 extends Object, T2 extends Object> void copy(T1 origEntity, T2 destEntity) {
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.map(origEntity,destEntity);
}
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.4.0</version>
</dependency>
public static <T> void copyAvalableFields(@NotNull T source, @NotNull T target) throws IllegalAccessException {
Field[] fields = source.getClass().getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())
&& !Modifier.isFinal(field.getModifiers())) {
field.set(target, field.get(source));
}
}
}
我们阅读了类的所有字段。 从结果中过滤非静态和非最终字段。 但是访问非公共字段可能会出错。 例如,如果这个函数在同一个类中,而被复制的类不包含公共字段,就会出现访问错误。 解决方案可能是将此函数放在同一个包中或将访问权限更改为 public 或在循环调用 field.setAccessible (true); 的此代码中; 什么将使字段可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.