Java中,复制一个对象,有什么好的方法

Python015

Java中,复制一个对象,有什么好的方法,第1张

使用Java的反射机制实现:为了能更好的区分,写成了两个类,可以运行下面的代码看看效果

import java.lang.reflect.Field

import java.lang.reflect.Method

import java.util.ArrayList

import java.util.HashMap

import java.util.List

import java.util.Map

public class Test {

public static void main(String[] args) throws Exception {

Customer1 c1 = new Customer1()

c1.setName("c1")

List<String>list = new ArrayList<String>()

list.add("1")

list.add("2")

c1.setList(list)

Map<String,String>map = new HashMap<String, String>()

map.put("map1", "map1")

map.put("map2", "map2")

c1.setMap(map)

Customer2 c2 = new Customer2()

//

Class c = c1.getClass()

Class class2 = c2.getClass()

Field fields[] = c.getDeclaredFields()

for (int i = 0i <fields.lengthi++) {

Field field = fields[i]

String fieldName = field.getName()

String firstLetter = fieldName.substring(0, 1).toUpperCase()

String getMethodName = "get" + firstLetter + fieldName.substring(1)

String setMethodName = "set" + firstLetter + fieldName.substring(1)

Method getMethod = c.getMethod(getMethodName, new Class[] {})

Method setMethod = class2.getMethod(setMethodName,

new Class[] { field.getType() })

Object value = getMethod.invoke(c1, new Object[] {})

setMethod.invoke(c2, new Object[] { value })

}

System.out.println(c2.getName())

System.out.println(c2.getList())

System.out.println(c2.getMap())

}

}

class Customer1 {

private String name

private List<String>list

private Map<String, String>map

public String getName() {

return name

}

public void setName(String name) {

this.name = name

}

public List<String>getList() {

return list

}

public void setList(List<String>list) {

this.list = list

}

public Map<String, String>getMap() {

return map

}

public void setMap(Map<String, String>map) {

this.map = map

}

}

class Customer2 {

private String name

private List<String>list

private Map<String, String>map

public String getName() {

return name

}

public void setName(String name) {

this.name = name

}

public List<String>getList() {

return list

}

public void setList(List<String>list) {

this.list = list

}

public Map<String, String>getMap() {

return map

}

public void setMap(Map<String, String>map) {

this.map = map

}

}

给你个小例子

class test implents Cloneable

{

test t1 = new test()

test t2 = null

try {

t2 = (test)t1.clone()

} catch (CloneNotSupportedException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

}

用clone()方法,不过在对象重载了Object的clone才能用。Object的clone方法是protected。