I have two classes:

  • class a ( Parent )
  • class b ( Child )

    b extend a

These classes only store data as a structure, nothing more.

I need to convert class b to class a .

I know that it is not necessary to do this at all, since he is already a successor of class a . But I use a library that saves objects according to their affiliation.

I get class a class b object in the class a constructor, and manually assign all the fields there. But this solution looks bad, especially since there are about 30 fields.

Is it possible to somehow do this through a cycle, or to automate this process altogether?

PS Java I use in Android development.

UPD :

These classes have no heteros and setters; all their fields that need to be filled are public, and I’m not manually assigning them to this point myself - the library does it somewhere inside.

    2 answers 2

    If both classes have setters to all copied fields, you can use Apache Commons BeanUtils, the copyProperties method.

     BeanUtils.copyProperties(a, b); 

    I have compiled a working example for you right on the githaba . If you have maven installed, you can start it with mvn clean install, mvn exec: java

    The essence can be illustrated with this example:

     public class App { public static void main(String[] args) { //Готовим исходные данные B b = new B(); b.setX("123"); A a = new A(); //Копируем поля между классами try { BeanUtils.copyProperties(a, b); } catch (Exception e) { e.printStackTrace(); } //Вот эта строчка должна вывести только плохое test(b); //А вот это уже хорошее! test(a); } public static void test(A a) { if (a.getClass().equals(A.class)) { System.out.println(String.format("Все просто замечательно, и значение = %s", a.getX())); } else { System.out.println("Ты пытаешься выполнить меня с неверным классом!"); } } } 

    Of course, in order for this to work, you need to have the BeanUtils themselves in the classpath, which is easiest to do by adding a new dependency to Maven:

     <dependencies> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> </dependency> </dependencies> 

    If for some reason this method is not suitable (for example, you do not use bins), describe the problem more thoroughly, I will try to figure out how to copy the fields completely manually using reflection.

    • This option unfortunately does not fit, since the fields may (most likely) not have heterosexuals and setters, these are just classes for storing information as a structure, nothing more, so you probably have to reflex methods, if it's not hard for you, you could not him? Now add information about the classes. - wpbloger

    You can make it even easier. Here is an example:

     public class Test{ public static void main(String[] args){ DerivedNode dn = new DerivedNode(); Derived d = new Derived(dn); d.bar( dn ); } } class Base{ protected BaseNode n; public Base(BaseNode _n){ this.n = _n; } public void foo(BaseNode x){ n.foo(x); } } class BaseNode{ public void foo(BaseNode x){ System.out.println( "BaseNode foo" ); } } class Derived extends Base{ public Derived(BaseNode n){ super(n); } public void bar(DerivedNode x){ if( n instanceof DerivedNode ){ // приведение типа ((DerivedNode)n).bar(x); } else { // кидаем ошибку throw new RuntimeException("Invalid Object Type"); } } } class DerivedNode extends BaseNode{ public void bar(BaseNode b){ System.out.println( "DerivedNode bar" ); } }