How to copy superclass object values to subclass object values?

后端 未结 2 1827
攒了一身酷
攒了一身酷 2021-02-14 05:57

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?

相关标签:
2条回答
  • 2021-02-14 06:18

    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.

    0 讨论(0)
  • 2021-02-14 06:23

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题