12

I want to copy superclass object getters to subclass object setters. But how can I do this easily. I'm looking for something like clone. Could you please me help me to find it?

A simple code:

Super class:

public class SuperClass1 {
   private String name;
   private String surname;

   public void setName(String name) {
     this.name = name;
   }


   public String getName() {
     return this.name;
   }

   public void setSurname(String surname) {
     this.surname = surname;
   }


   public String getSurname() {
     return this.surname;
   }
}

Subclass:

public class SubClass1 extends SuperClass1 {
    private float gpa;

    public void setGpa(float gpa) {
       this.gpa = gpa;
    }

    public float getGpa() {
       return gpa;
    }
}

And caller class:

public class CallerClass1 {
   public static void main(String[] args) {
       SuperClass1 super1 = new SuperClass1();
       SubClass1 subclass1 = new SubClass1();
       // How to subclass1 object values easily taken from super1
  }
}
Lii
  • 11,553
  • 8
  • 64
  • 88
olyanren
  • 1,448
  • 4
  • 24
  • 42

2 Answers2

8

If performance is not an issue here, you can copy all the properties from one class to the other making use of reflection.

Check this link to this other question that explains how to do it:

Copy all values from fields in one class to another through reflection

This other link will give you the code, without using BeanUtils:

http://blog.lexique-du-net.com/index.php?post/2010/04/08/Simple-properties-Mapper-by-reflection

I always make use of this kind of functions in my projects. Really usefull.

Community
  • 1
  • 1
Jonathan
  • 11,809
  • 5
  • 57
  • 91
1

Don't use your own code, when there are special libraries. I use modelMapper (http://modelmapper.org/).

public class AppsUtil {

    private static ModelMapper mapper = new ModelMapper();

    public static ModelMapper getMapper() {
        return mapper;
    }

    static {
        // full matching of names in classes
        mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    }

Then use AppsUtil in your constructor in child class:

@Getter
public class AppsEmailException extends AppsException {

    /**
     * email, на который не отправилось сообщение
     */
    private String email;

    public AppsEmailException(AppsException baseClass, String email) {
        AppsUtil.getMapper().map(baseClass, this);
        this.email = email;
    }
}
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51