Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy fields between similar classes in java

Tags:

java

I have pairs of classes where the fields of one is a subset of the fields of another and the getters of the superset classes are all predictably named (getFoo()). Is there some way to efficiently copy all the common fields over from the superset class to the subset class, or at least auto-generate the code to do so.

I should note that:

  • For various reasons, I can't edit the superset classes, nor can I just use them throughout to avoid having to do the data copy.
  • I can potentially create new methods in the subset classes, but I can't change their fields.
  • We have dozens of these pairs, and some of the classes have many many fields so doing this by hand is unwieldy to say the least.
  • A colleague has come up with a method to create a generic copy method that uses java reflection to take any two classes, iterate through the fields as Strings, do string manipulation to determine the getter name, and then execute it to automatically set the field in the subset class. It's awful, but it appears to work. I'm really hoping there's a better way.

Edit: some simple code as requested

public class SuperClass {
  private int foo;
  private int bar;
  private float bat;
  public int getFoo() { return foo; }
  public int getBar() { return bar; }
  public float getBat() { return bat; }
}

public class SubClass {
  private int foo;
  private float bat;
}

//wanted
public static copySuperFieldsToSubMethod(Object super, Object sub) { ??? }

// also acceptable would be some way to autogenerate all the assignment 
// functions needed
like image 260
Dusty Avatar asked Dec 09 '10 04:12

Dusty


1 Answers

You could use the BeanUtils class in the Spring Framework to do this. It may not necessarily be any more efficient than your reflection-based technique, but it's certainly simple to code. I expect that all you would need to do is:

BeanUtils.copyProperties(source, target);

Javadoc for this method is available at http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/BeanUtils.html#copyProperties(java.lang.Object,%20java.lang.Object)

If that doesn't suit, you could also consider using BeanWrapper / BeanWrapperImpl in the Spring Framework to iterate through the properties of your classes. That would be simpler than using low-level reflection APIs.

like image 187
gutch Avatar answered Sep 28 '22 05:09

gutch