Re: Can you copy derived classes of the same superclass?
Eric,
Thanks again for writing. I figured out what I was doing wrong. The
inherited class had to have getters/setters like the derived classes
in order for the copyProperties() to work.
The following is a complete example using copyProperties():
The base class:
package test;
public class CommonClass {
private String sInherited;
//
public String getSInherited() {
return sInherited;
}
public void setSInherited(String inherited) {
sInherited = inherited;
}
}
Class A, which is one of 2 classes that extend CommonClass. It has
both unique and common property names:
package test;
public class A extends CommonClass {
private int iA; // a uniquely named attribute
private String sName; // a commonly named attribute
//
public A(){
}
//
public int getIA() {
return iA;
}
public void setIA(int ia) {
iA = ia;
}
public String getSName() {
return sName;
}
public void setSName(String name) {
sName = name;
}
}
Class B:
package test;
public class B extends CommonClass {
private int iB; // a uniquely named attribute
private String sName; // a commonly named attribute
//
public B(){
}
//
public int getIB() {
return iB;
}
public void setIB(int ib) {
iB = ib;
}
public String getSName() {
return sName;
}
public void setSName(String name) {
sName = name;
}
}
Now the test class that will load up A, then copy it to B:
package test;
import org.apache.commons.beanutils.*;
public class TestClass {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Begin...");
BeanUtilsBean bub = new BeanUtilsBean();
A a = new A();
B b = new B();
//
a.setIA(1);
a.setSName("Testing...");
a.setSInherited("inherited from A");
//
try {
bub.copyProperties(b, a); //(dest, orig)
System.out.println("-----");
System.out.println("a.getIA(): " + a.getIA());
System.out.println("a.getSName(): " + a.getSName());
System.out.println("a.getSInherited(): " + a.getSInherited());
System.out.println("b.getIB: " + b.getIB());
System.out.println("b.getSName(): " + b.getSName());
System.out.println("b.getSInherited(): " + b.getSInherited());
System.out.println("-----");
} catch (Exception ex){
System.out.println("Exception here: " + ex.toString());
}
System.out.println("End...");
}
}
Output:
Begin...
-----
a.getIA(): 1
a.getSName(): Testing...
a.getSInherited(): inherited from A
b.getIB: 0
b.getSName(): Testing...
b.getSInherited(): inherited from A
-----
End...
Since iB had no counterpart in class A, it was not copied, and assumed
the Java default for ints.
This is exactly the behavior I was hoping for. Thanks for the tip!
Bogus Exception