java中如何进行对象属性复制呢?
下文笔者讲述java中对象属性复制的简介说明,如下所示
实现思路: 1.Apache提供的BeanUtil.copyProperties和PropertyUtil.copyProperties两种方式 2.Spring中BeanUtils.copyProperties("转换后的类", "要转换的类"); 3.cglib提供的copy方式 4.Spring提供的copy方式例:
//1.Apache方式 import org.apache.commons.beanutils.BeanUtils; import java.lang.reflect.InvocationTargetException; public class TestDemo { public static void main(String[] args) { TestFrom testFrom = new TestFrom(); testFrom.setName("java265.com"); TestTo testTo = new TestTo(); BeanUtils.copyProperties(testTo,testFrom); } } //2.spring提供的BeanUtil.copyProperties方式 import org.springframework.beans.BeanUtils; public class TestDemo { public static void main(String[] args) { TestFrom testFrom = new TestFrom(); testFrom.setName("java265.com"); TestTo testTo = new TestTo(); BeanUtils.copyProperties(testFrom,testTo);//没抛异常 } } //3.cglib提供的copy方式 import net.sf.cglib.beans.BeanCopier; public class TestDemo { public static void main(String[] args) { TestFrom testFrom = new TestFrom(); testFrom.setName("java265.com"); TestTo testTo = new TestTo(); BeanCopier copier = BeanCopier.create(TestFrom.class,TestTo.class,false); copier.copy(testFrom,testTo,null); } } //4.spring提供的copy方式 import org.springframework.cglib.beans.BeanCopier; public class TestDemo { public static void main(String[] args) { TestFrom testFrom = new TestFrom(); testFrom.setName("java265.com"); TestTo testTo = new TestTo(); BeanCopier copier = BeanCopier.create(TestFrom.class,TestTo.class,false); copier.copy(testFrom,testTo,null); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。