java 两个类复制_反射机制实现两个类的复制

废话不多说 简单的实现 直接上代码 我怕话多审核不过

实现的类

public class Copy {

@SneakyThrows

public static void objectClone(Object newObject, Object oldObject) {

//获取目标对象的所有属性

Field[] oldFiled = oldObject.getClass().getDeclaredFields();

//新建待办对象

Field newField;

//遍历目标对象的所有属性

for (Field oldField : oldFiled) {

//判断权限是否是PUBLIC

if (!oldField.isAccessible())

//不是则修改权限

oldField.setAccessible(true);

try {

//目标对象属性复制给待办对象

newField = newObject.getClass().getDeclaredField(oldField.getName());

//判断类型是否相等

if (oldField.getType() != newField.getType()){

continue;

}

//判断访问权限

if (!newField.isAccessible())

//修改访问权限

newField.setAccessible(true);

//把待办对象set方法赋值

newField.set(newObject, oldField.get(oldObject));

}catch (Exception e){

continue;

}

}

return;

}

}

调用方法

//通过反射机制 把UserOne复制给UserTwo

@Test

public void copy() {

UserOne userOne = new UserOne();

userOne.setId(3);

userOne.setName("小伙子");

userOne.setIsnot(true);

userOne.setSex("塑料袋积分");

userOne.setAge("我今年19岁");

UserTwo userTwo = new UserTwo();

Copy.objectClone(userTwo, userOne);

System.out.println(userTwo.getId() + "," + userTwo.getName()+","+userTwo.getSex()+"."+userTwo.getAge());

}

实体类 1

@Getter

@Setter

@Entity

@AllArgsConstructor

@NoArgsConstructor

@Table(name = "userone")

public class UserOne implements Serializable {

@Id

@ApiModelProperty(value = "用户id", name = "id")

private Integer id;

@Column(name = "name")

@ApiModelProperty(value = "用户姓名", name = "name")

protected String name;

public boolean isnot;

private String sex;

实体类2

@Data

@Entity

@Table(name = "usertwo")

public class UserTwo implements Serializable {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

//@Column(name = "age")

private String name;

private Integer sex;

private String age;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值