Copy only superclass content in java

2

Is there a way to copy only the contents of the superclass into another class of the same type through a subclass instance in Java, without accessing getters and setters one by one?

Example:

public class A {
    private Integer id;
    private String nome;
    //outros
}

public class B extends A {
   private String age;
}

I need to do something like:

B objB = new B();
objB.setId(10);
objB.setNome("Jonh Doe");
objB.setAge(21);

A objA = // AQUI COPIAR DE objB apenas o conteúdo da superclasse A
    
asked by anonymous 20.06.2018 / 14:40

1 answer

1

As far as I know, it's not possible to do this with pure object orientation.

However, you can use some libs that do this job. A good example is the ModelMapper . With it you can copy the values of the attributes of an instance of type X to an instance of Y that will be created by ModelMapper:

class A {
    private Integer id;
    private String nome;
    //getters & setters
}

class B extends A {
   private String age;
   //getters & setters
}


class Mapeamento {

    public A fromBToA(B b) {
        ModelMapper mapper = new ModelMapper();
        return mapper.map(b, A.class);
    }
}

ModelMapper allows more sophisticated settings if you need to (see documentation).

    
20.06.2018 / 20:00