How to copy superclass object values to subclass object values?

后端 未结 2 1829
攒了一身酷
攒了一身酷 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: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;
        }
    }
    

提交回复
热议问题