不去覆蓋clone方法,不去調(diào)用clone方法,除非真的有必要。
2.java中clone兩個概念淺克隆 copy的是引用深克隆 copy的是實例,開辟新的堆空間java中的clone方法實現(xiàn)的是淺克隆,一個類可被淺克隆需實現(xiàn)Cloneable(此接口只是說明此類允許clone,它改變的是超類中受保護的clone方法的行為),如effective java中的第11條所說這是接口的一種極端非典型的用法,不值得效仿。3.淺克隆淺克隆看上去只要實現(xiàn)了Cloneable接口 且@Override clone方法為public后就可以了,但是實際應(yīng)用了,確定你要的是淺clone么?若是一個對象沒有實現(xiàn)Cloneable接口,也可以很簡單的使用反射實現(xiàn)對象的淺復(fù)制:非嚴(yán)謹(jǐn)?shù)腸ode如下:public static <T> T simpleClone(T obj) throws IllegalaccessException, InstantiationException { Class<T> c = (Class<T>) obj.getClass(); T cloneC = c.newInstance(); Field[] fields = c.getDeclaredFields(); if (fields != null && fields.length > 0) { for (Field field : fields) { field.setAccessible(true); Object value = field.get(obj); field.set(cloneC, value); } } return cloneC; }
當(dāng)然有很多工具類了:比如,sPRing的BeanUtils.copyProperties, apache的BeanUtils.copyProperties,cglib或者spring-cglib的BeanCopier
4.深克隆既然實際應(yīng)用中更希望使用的是深克隆,那么如何實現(xiàn)呢public class TestCloneBean implements Cloneable { private List<Integer> integers; public List<Integer> getIntegers() { return integers; } public void setIntegers(List<Integer> integers) { this.integers = integers; } @Override public TestCloneBean clone() { try { TestCloneBean t = (TestCloneBean) super.clone(); t.setIntegers(Lists.<Integer> newArrayList()); if (CollectionUtils.isNotEmpty(integers)) { for (Integer i : integers) { t.getIntegers().add(i); } } return t; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } @Override public String toString() { return ToStringBuilder.reflectionToString(this); }}public class JsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true); objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(Inclusion.NON_NULL); } public static ObjectMapper getObjectMapperInstance() { return objectMapper; } } testCode如下:TestCloneBean b = new TestCloneBean(); b.setIntegers(Lists.newArrayList(1)); String s = JsonUtils.getObjectMapperInstance().writeValueAsString(b); TestCloneBean a = JsonUtils.getObjectMapperInstance().readValue(s, TestCloneBean.class);
新聞熱點
疑難解答