如何将超类对象值复制到子类对象值?

时间:2011-12-12 08:33:03

标签: java

我想将超类对象getter复制到子类对象setter。但是我怎么能这么做呢。我正在寻找像克隆这样的东西。你能帮我找到它吗?

非常感谢。

一个简单的代码:

超级班:

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;
   }

}

子类

public class SubClass1 extends SuperClass1{
    private float gpa;

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

    public float getGpa(){
       return gpa;
    }


}

和来电者班:

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
  }
}

}

2 个答案:

答案 0 :(得分:6)

如果此处的性能不是问题,您可以使用反射将所有属性从一个类复制到另一个类。

检查此链接以解释如何执行此问题:

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

这个其他链接将为您提供代码,而不使用BeanUtils:

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

我总是在我的项目中使用这种功能。真有用。

答案 1 :(得分:0)

如果有特殊的库,请不要使用自己的代码。我使用modelMapperhttp://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);
    }

然后在子类的构造函数中使用AppsUtil

@Getter
public class AppsEmailException extends AppsException {

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

    public AppsEmailException(AppsException baseClass, String email) {
        AppsUtil.getMapper().map(baseClass, this);
        this.email = email;
    }
}
相关问题