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

oly*_*ren 10 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;
   }

}
Run Code Online (Sandbox Code Playgroud)

子类

public class SubClass1 extends SuperClass1{
    private float gpa;

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

    public float getGpa(){
       return gpa;
    }


}
Run Code Online (Sandbox Code Playgroud)

和来电班:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

}

Jon*_*han 8

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

查看此链接以解释如何执行此操作的其他问题:

通过反射将所有值从一个类中的字段复制到另一个类

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

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

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