• BeanUtils实现对象拷贝(三)


    package beanutil;
    
    import java.lang.reflect.InvocationTargetException;
    import java.util.Date;
    
    import org.apache.commons.beanutils.BeanUtils;
    
    import entity.Student;
    
    /**
     * 从一个javaBean对象到另一个javaBean对象;
     * 拷贝所有属性。
     * 
     * @author mzy
     * 
     */
    public class Demo03 {
    	public static void main(String[] args) {
    		Student s = new Student();
    		s.setId(1);
    		s.setName("mzy");
    		s.setScore(99.99);
    		s.setGender(true);
    		s.setBirth(new Date());
    		
    		try {
    			Object s2 = Class.forName("entity.Student").newInstance();
    			// 把值从后者拷贝到前者中去:
    			BeanUtils.copyProperties(s2, s);
    			
    			System.out.println(s2);
    			
    		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
    			e.printStackTrace();
    		}
    		
    	}
    }
    

    javaBean

    package entity;
    
    import java.util.Date;
    /**
     * 一个测试用:
     * 		student,javaBean
     * @author mzy
     *		一个标准的javaBean:
     *			1) 属性只要是private修饰的;
     *			2) 提供setter和getter方法;
     *			3) 提供无参构造。
     *		就行了;有参构造等不是必须的。
     */
    public class Student {
    	private int id;
    	private String name;
    	private double score;
    	private boolean gender;
    	private Date birth;
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public double getScore() {
    		return score;
    	}
    	public void setScore(double score) {
    		this.score = score;
    	}
    	public boolean isGender() {
    		return gender;
    	}
    	public void setGender(boolean gender) {
    		this.gender = gender;
    	}
    	public Date getBirth() {
    		return birth;
    	}
    	public void setBirth(Date birth) {
    		this.birth = birth;
    	}
    	
    	@Override
    	public String toString() {
    		return "Student [id=" + id + ", name=" + name + ", score=" + score + ", gender=" + gender + ", birth=" + birth
    				+ "]";
    	}
    }
    


  • 相关阅读:
    电影观后感
    自定义内存管理
    web.xml配置详解
    Annotation
    Centos中yum方式安装java
    linux下添加用户并赋予root权限
    Injector
    Container
    GlassFish的安装与使用(Windows)
    Version Control
  • 原文地址:https://www.cnblogs.com/mzywucai/p/11053468.html
Copyright © 2020-2023  润新知