Copy content only from the superclass in java

Asked

Viewed 80 times

2

There is a way to copy only superclass content in 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
  • 2

    Cloning maybe?

  • I used Clone @Articuno, but mysteriously the object came with the attributes of the subclass and the application launched an Exception because Hibernate did not recognize the entity...

  • 1

    You can put the use case on what you’re trying to do ?

  • 1

    The simplest way to do this is not to use inheritance but rather composition. That is to say, public class B { private A a; private String age; }.

1 answer

1


As far as I know, it’s not possible to do that with object-oriented "pure".

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 a type instance X to an instance of Y which 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 needed (see documentation).

  • 1

    From what I could observe, in fact, this is the most "attractive" solution currently.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.