Java 对象拷贝方式

(1)BeanUtils.cloneBean()使用:

http://www.cnblogs.com/fervour/archive/2009/12/18/1627868.html

package com.test;

import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

public class CloneTest3 {
    @Test
    public void testClone() throws Exception {
        Teacher sir = new Teacher("sir1");
        Student3 c = new Student3(1, sir);

        Student3 c2 = (Student3) BeanUtils.cloneBean(c);

        System.out.println(c.getSir() == c2.getSir());
        System.out.println(c == c2);

        c.getSir().setName("xx");
        System.out.println("clone is not deep");
        System.out.println(c.getSir().getName() + "," + c2.getSir().getName());
        System.out.println("------------------------testclone---end");
    }

    @Test
    public void testClone2() throws Exception {
        Teacher sir = new Teacher("sir1");
        Student3 c = new Student3(1, sir);

        Teacher sir2 = (Teacher) BeanUtils.cloneBean(c.getSir());
        Student3 c2 = new Student3();
        BeanUtils.copyProperties(c2, c);
        c2.setSir(sir2);

        System.out.println(c == c2);
        System.out.println(c.getSir() == c2.getSir());
        c.getSir().setName("xx");
        System.out.println(c2.getSir().getName() + "," + c.getSir().getName());
        System.out.println("clone is deep");
        System.out.println("------------------------testclone2---end");
    }
}
package com.test;

public class Student3 {
    private int num;
    private Teacher sir;

    public Student3(int num, Teacher sir) {
        super();
        this.num = num;
        this.sir = sir;
    }

    public Student3() {
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public Teacher getSir() {
        return sir;
    }

    public void setSir(Teacher sir) {
        this.sir = sir;
    }
}
package com.test;

public class Teacher {
    private String name;

    public Teacher(String name) {
        super();
        this.name = name;
    }

    public Teacher() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

下载相关jar包

 

(2)深拷贝和浅拷贝:

http://www.cnblogs.com/mengdd/archive/2013/02/20/2917971.html

 

(3)反序列化漏洞,针对类实现Serializable接口并定义方法readObject

http://sec.chinabyte.com/435/13618435.shtml

posted @ 2015-12-04 17:04  浪荡云流  阅读(606)  评论(0编辑  收藏  举报