java实体数据拷贝_JAVA实体类属性拷贝

本文介绍了四种在JAVA中实现实体类属性拷贝的方法:1) 利用反射进行属性复制,2) 使用Spring的BeanUtils.copyProperties,3) 使用BeanCopier.create,4) JSON对象互转。通过示例代码展示了每种方法的用法,并对比了它们的特性和适用场景。
摘要由CSDN通过智能技术生成

运行结果:

4587ec000e59e15e793fe142489b978e.pngimport java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.Date;

import org.springframework.beans.BeanUtils;

import org.springframework.cglib.beans.BeanCopier;

import com.alibaba.fastjson.JSON;

public class BeanOperationUtils {

public static void main(String[] args) {

try {

Parent parent = new Parent("LA", new Date());

System.out.println("这是原本的parent:" + parent);

Parent parentCopy = new Parent();

parentCopy = parent;

// 这种复制修改会造成parent对象的数据进行修改

parentCopy.setParentName("WA");

System.out.println("这是修改过的parent:" + parent);

System.out.println("这是parentCopy:" + parentCopy);

// 方法一:利用反射进行属性的复制

Child child1 = new Child();

copyReflex(parent, child1);

System.out.println("copyReflex:" + child1);

// 方法二: 使用BeanUtils.copyProperties方法进行属性复制

Child child2 = new Child();

copyProperties(parent, child2);

System.out.println("copyProperties:" + child2);

// 方法三: 使用BeanCopier.create方法进行属性复制

Child child3 = new Child();

copyBeanCopier(parent, child3);

System.out.println("copyBeanCopier:" + child3);

// 方法四:JSON互转

Child child4 = new Child();

child4 = (Child) copyJson(parent, child4);

System.out.println("copyJson:" + child4);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 反射(子类复制父类的属性值)

* @param parent 父类

* @param child  子类

* @throws Exception

*/

public static  void copyReflex(T parent, T child) throws Exception {

if (child.getClass().getSuperclass() != parent.getClass()) {

throw new Exception("child 不是 parent 的子类");

}

Class> parentClass = parent.getClass();

Field[] declaredFields = parentClass.getDeclaredFields();

for (int i = 0; i 

Field field = declaredFields[i];

Method method = parentClass.getDeclaredMethod("get" + upperHeadChar(field.getName()));

Object obj = method.invoke(parent);

field.setAccessible(true);

field.set(child, obj);

}

}

/**

* 对象属性拷贝

* 将源对象的属性拷贝到目标对象

* @param source 源对象

* @param target 目标对象

* @throws InvocationTargetException

* @throws IllegalAccessException

*/

public static void copyProperties(Object source, Object target)

throws IllegalAccessException, InvocationTargetException {

BeanUtils.copyProperties(source, target);

}

/**

* 使用BeanCopier.create方法进行属性复制 耗时最少,不使用转换器时,属性类型不同时无法复制,使用转换器后,耗时会相对变长。

* 可以用缓存解决性能瓶颈问颗(高并发的时候考虑)

* @param source 源对象

* @param target 目标对象

* @throws Exception

*/

public static void copyBeanCopier(Object source, Object target) throws Exception {

// 第三个参数表示是否使用转换器,false否,true是

BeanCopier beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);

beanCopier.copy(source, target, null);// 第三个参数是转换器,可自定义一个转换器,对属性不一致的对象属性进行转换

}

/**

* JSON互转

* @param source 源对象

* @param target 目标对象

* @return Object

* @throws Exception

*/

public static Object copyJson(Object source, Object target) throws Exception {

String parentJson = JSON.toJSONString(source);

target = JSON.parseObject(parentJson, target.getClass());

return target;

}

/** 首字母转大写 */

public static String upperHeadChar(String in) {

String head = in.substring(0, 1);

String out = head.toUpperCase() + in.substring(1, in.length());

return out;

}

}

/** 父类 */

class Parent {

private String parentName;

private Date date;

public Parent() {

}

public Parent(String parentName, Date date) {

super();

this.parentName = parentName;

this.date = date;

}

public String getParentName() {

return parentName;

}

public void setParentName(String parentName) {

this.parentName = parentName;

}

public Date getDate() {

return date;

}

public void setDate(Date date) {

this.date = date;

}

@Override

public String toString() {

String date = getDate() == null ? null : DateUtils.formatDateToString(getDate(), DateUtils.DATE_FULL_STR);

return "父类名字:" + this.parentName + ",时间:" + date;

}

}

/** 子类 */

class Child extends Parent {

private int id;

private String childName;

public Child() {

}

public Child(String childName, String date) {

super();

this.childName = childName;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getChildName() {

return childName;

}

public void setChildName(String name) {

this.childName = name;

}

@Override

public String toString() {

String date = getDate() == null ? null : DateUtils.formatDateToString(getDate(), DateUtils.DATE_FULL_STR);

return "\n\t父类名字:" + getParentName() + ",时间:" + date + ";   子类id:" + this.id + ",名字:" + this.childName;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设我们有一个实体类`Person`,它具有`name`和`age`两个属性。现在我们需要将一个类型为`Person`的实体拷贝为另一个类型为`User`的实体,并将其中的`age`属性从`int`类型转换为`String`类型。可以使用Java 8的Stream API轻松完成这个任务。 首先,我们需要使用一个工具类来实现实体类拷贝。这里使用了`BeanUtils`工具类,它可以将一个JavaBean的属性拷贝到另一个JavaBean中。需要注意的是,该工具类需要导入`commons-beanutils`库。 接下来,我们可以使用Stream API来完成实体类拷贝属性修改。具体实现代码如下: ```java import org.apache.commons.beanutils.BeanUtils; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { // 原始实体对象 Person person = new Person("张三", 18); // 使用BeanUtils工具类拷贝实体对象 User user = new User(); BeanUtils.copyProperties(user, person); // 修改属性类型 user.setAge(String.valueOf(person.getAge())); // 输出拷贝后的实体对象 System.out.println(user); } } // Person实体类 class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } // User实体类 class User { private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } ``` 在上述代码中,我们首先使用`BeanUtils.copyProperties()`方法将`person`对象的属性拷贝到`user`对象中。然后,我们使用`setAge()`方法将`user`对象中的`age`属性从`int`类型转换为`String`类型。最后,我们输出拷贝后的`user`对象。 需要注意的是,在使用`BeanUtils.copyProperties()`方法拷贝属性时,需要确保两个实体类中的属性名称和类型相同。在本示例中,`Person`和`User`类的`name`属性名称和类型均相同,因此可以直接拷贝。而`age`属性的类型不同,因此需要在拷贝后进行类型转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值