深度克隆测试代码

 深度克隆

测试代码:


package com.dyh.clonetest;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;

import lombok.Data;

@Data
class Hobby implements Cloneable{
	/**
	 * 
	 */
	private String hobbyName;
	
	@Override
	public Object clone() throws CloneNotSupportedException{
		 return super.clone();
	}
}

@Data
class User implements Cloneable{
	private String name;
	private String age;
	private Hobby hobby;
	private List hobbyList;
	private List hobbyList2;
	
	@Override
	public Object clone() throws CloneNotSupportedException{
		 return super.clone();
	}
}
/**
 * @author Administrator
 *
 */
public class Test {
	public static void main(String[] args) {
		JSONObject jo = new JSONObject();
		User u = new User();
		u.setAge("28");
		u.setName("xiaopengyou");
		Hobby h = new Hobby();
		h.setHobbyName("sayHi");
		Hobby h2 = new Hobby();
		h2.setHobbyName("sayHi2");
		Hobby h3 = new Hobby();
		h3.setHobbyName("sayHi3");
		
		List hl = new ArrayList<>();
		hl.add(h2);
		hl.add(h3);
		u.setHobby(h);
		u.setHobbyList(hl);
		List hl2 = new ArrayList<>();
		try {
			hl2.add((Hobby) h2.clone());
			hl2.add((Hobby) h3.clone());
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		u.setHobbyList2(hl2);
		
		jo.fluentPut("user", u);
		
		System.out.println(jo.toJSONString());
		User u2 = JSONObject.parseObject(jo.getJSONObject("user").toJSONString(),User.class);
		System.out.println(u2.getHobby().getHobbyName());
		System.out.println(u2.getHobbyList().get(1).getHobbyName());
		System.out.println(u2.getHobbyList2().get(1).getHobbyName());
		
	}
}

运行结果:

{"user":{"age":"28","hobby":{"hobbyName":"sayHi"},"hobbyList":[{"hobbyName":"sayHi2"},{"hobbyName":"sayHi3"}],"hobbyList2":[{"hobbyName":"sayHi2"},{"hobbyName":"sayHi3"}],"name":"xiaopengyou"}}
sayHi
sayHi3
sayHi3

你可能感兴趣的:(深度克隆,java)