cast or create obj1 from obj2 where obj1 and obj2 extends same abstract class

Estorsky :

For example I have:

public abstract class SomeAbstract {
  private int a;
  private int b;
  ..
  private int z;
}

public class A extends SomeAbstract {
  private String aField;
}

public class B extends SomeAbstract {
  private long bField;
}

(default constructors/setters/getters are omitted)

I have some instance of a class A and i wanna create instance of a class B from A(abstract fields).

Yes, I can use abstract class constructor or create constructor for class B like this :

public B(A a) {
  this.a = a.getA();
  this.b = a.getB();
  ..
  this.z = a.getZ(); 
}

But since I have many fields this does not look nice and convenient Is there another way?

Luiggi Mendoza :

You can create a constructor in the super class that receives another super class.

public abstract class SomeAbstract {
    /* attributes... */

    public SomeAbstract() {
    }

    protected SomeAbstract(SomeAbstract another) {
        this.a = another.a;
        /* and on... */
    }

}

And reuse this constructor in sub classes:

public class B extends SomeAbstract {

    public B(A a) {
        super(a);
        this.specificAttribute = a.somethingElse;
    }

}

If you have that many fields and don't want/need to create the whole code manually, you can use an external library that helps you with the mapping between classes. Some options are:

  • Dozer that maps data between objects. The configuration can be done through XML or annotations. This library works (AFAIK) using reflection, so it may have a direct impact on the performance of your application.
  • Orika that generates byte code at runtime to map data between objects. The configuration is done at design time. This library works (AFAIK) using reflection, so it may have a direct impact on the performance of your application, when I tested it, the execution time was faster than Dozer (about 7x faster).
  • MapStruct that will generate code to map the classes (using getters and setters, validating nulls and on) and this code will be available for at runtime. The configuration is done at design time through annotations. This library works (AFAIK) using Java code, so it's similar to the normal execution of the code (e.g. execute b.setValue(a.getValue())).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111777&siteId=1