Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all values from fields in one class to another through reflection

I have a class which is basically a copy of another class.

public class A {   int a;   String b; }  public class CopyA {   int a;   String b; } 

What I am doing is putting values from class A into CopyA before sending CopyA through a webservice call. Now I would like to create a reflection-method that basically copies all fields that are identical (by name and type) from class A to class CopyA.

How can I do this?

This is what I have so far, but it doesn't quite work. I think the problem here is that I am trying to set a field on the field I am looping through.

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();             }          }     } 

I am sure there must be someone that has already done this somehow

like image 778
Shervin Asgari Avatar asked Nov 03 '09 14:11

Shervin Asgari


People also ask

How do I copy a class from one class to another in C#?

This way you can do: MyClass objA = new MyClass(<some parameters>); ... MyClass objB = new MyClass(objA);

How do you reflect a class in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");


1 Answers

If you don't mind using a third party library, BeanUtils from Apache Commons will handle this quite easily, using copyProperties(Object, Object).

like image 169
Greg Case Avatar answered Oct 14 '22 21:10

Greg Case