Powered by Blogger.

How to Copy properties from one Bean OtherBean

>> Saturday, August 4, 2012

As we know the Bean class containing the variables with setters and getters methods. We can access through the getXxx and setXxx methods by different properties. To copy the properties form one bean to another they should have same datatypes.

To Run our program the requirements are:

As per shown in the below image you can create the files in Eclipse.



Person.java

package blog.javabynataraj;
//http://javabynataraj.blogspot.com
public class Person {

 private String name;
    private int age;
    
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

CopyPerson.java

package blog.javabynataraj;
//http://javabynataraj.blogspot.com
public class CopyPerson {

 private String name;
    private int age;
    
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }

}

The TestCopyProperties class will let us test copying properties from one bean to another. First, it creates a person object(fromBean) and a copyPerson(toBean) object. It outputs these objects to the console. Then, it call the BeanUtils.copyProperties() method with toBean as the first parameter and fromBean as the second parameter. Notice that the object that is copied to is the first parameter and the object that is copied from is the second parameter.

In the below program we are copying the properties from person object to copyPerson object using BeanUtils.copyProperties(targer,source) method.

TestCopyProperties.java

package blog.javabynataraj;
//http://javabynataraj.blogspot.com
import org.apache.commons.beanutils.BeanUtils;

public class TestCopyProperties {
 
 public static void main(String[] args) throws Exception{
  
  Person person = new Person();
  person.setName("Ramu");
  person.setAge(24);
  
  CopyPerson copyPerson = new CopyPerson();
  copyPerson.setName("Krishna");
  copyPerson.setAge(22);
  
  System.out.println("----Before copying the properties----");
  System.out.println("--Person Proerpties--");
  System.out.println(person.getName());
  System.out.println(person.getAge());
  System.out.println("--copyPerson Proerpties--");
  System.out.println(copyPerson.getName());
  System.out.println(copyPerson.getAge());
  
  //BeanUtils.copyProperties(destination,source);
  BeanUtils.copyProperties(copyPerson,person);
  
  System.out.println("----Person to CopyPerson----");
  //the Person bean properties copied to CopyProperties bean
  System.out.println(copyPerson.getName());
  System.out.println(copyPerson.getAge());
 }
}

Output:


Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.