物件屬性複製的三種方法:
1.Apache提供的BeanUtil.copyProperties和PropertyUtil.copyProperties兩種方式
BeanUtils.copyProperties("轉換後的類別 BeanUtils.copyProperties("轉換後的類別",
"要轉換的類別"); //多一步型別轉換,比PropertyUtils效率還差PropertyUtils.copyProperties(# "轉換後的類別", "要轉換的類別");
# 口訣:後付錢(後付前:後面的複製給前面)會拋異常
2.spring提供的BeanUtil.copyProperties方式 BeanUtils.copyProperties("要轉換的類別",
"轉換後的類別");# 和Apache參數順序相反
3. cglib提供的copy方式 BeanCopier copy=BeanCopier.create("要轉換的類別", "轉換後的類別", false);
# copy.copy(from, to,
null);
4.spring提供的copy方式# BeanCopier copy=BeanCopier. create("要轉換的類別", "轉換後的類別", false);
copy.copy(from, to ,
null);
1 /**2 * Created by hunt on 2017/6/28.3 */4 @Data5 public class TestFrom {6 private String name;7 }
View Code
1 import lombok.Data;2 3 /**4 * Created by hunt on 2017/6/28.5 */6 @Data7 public class TestTo {8 private String name;9 }
View Code
1 import org.apache.commons.beanutils.BeanUtils; 2 3 import java.lang.reflect.InvocationTargetException; 4 5 /** 6 * Created by hunt on 2017/6/28. 7 */ 8 public class TestDemo { 9 public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {10 TestFrom testFrom = new TestFrom();11 testFrom.setName("hunt");12 TestTo testTo = new TestTo();13 long begin = System.currentTimeMillis();14 for (int i = 0; i
View Code
1 import org.apache.commons.beanutils.PropertyUtils; 2 3 import java.lang.reflect.InvocationTargetException; 4 5 /** 6 * Created by hunt on 2017/6/28. 7 */ 8 public class TestDemo { 9 public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {10 TestFrom testFrom = new TestFrom();11 testFrom.setName("hunt");12 TestTo testTo = new TestTo();13 long begin = System.currentTimeMillis();14 for (int i = 0; i
View Code
1 import org.springframework.beans.BeanUtils; 2 3 /** 4 * Created by hunt on 2017/6/28. 5 */ 6 public class TestDemo { 7 public static void main(String[] args) { 8 TestFrom testFrom = new TestFrom(); 9 testFrom.setName("hunt");10 TestTo testTo = new TestTo();11 long begin = System.currentTimeMillis();12 for (int i = 0; i
第三种方式cglib的copy效率测试
1 import net.sf.cglib.beans.BeanCopier; 2 3 /** 4 * Created by hunt on 2017/6/28. 5 */ 6 public class TestDemo { 7 public static void main(String[] args) { 8 TestFrom testFrom = new TestFrom(); 9 testFrom.setName("hunt");10 TestTo testTo = new TestTo();11 long begin = System.currentTimeMillis();12 for (int i = 0; i
第四种方式Spring的copy效率测试
1 import org.springframework.cglib.beans.BeanCopier; 2 3 /** 4 * Created by hunt on 2017/6/28. 5 */ 6 public class TestDemo { 7 public static void main(String[] args) { 8 TestFrom testFrom = new TestFrom(); 9 testFrom.setName("hunt");10 TestTo testTo = new TestTo();11 long begin = System.currentTimeMillis();12 for (int i = 0; i
总结:这四种方式的效率是由低到高。(注意Apache的PropertyUtils不能进行类型转换的问题)
以上是詳解物件屬性複製的三種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!