//引入的包
import org.springframework.cglib.beans.BeanCopier;
Team tt = new Team();
tt.setId(Identities.hexUuid2());
tt.setName("我的小组");
tt.setDescription("我最喜欢的小组");
TeamEditParam tp = new TeamEditParam();
BeanCopier copier = BeanCopier.create(Team.class, TeamEditParam.class, false);
copier.copy(tt, tp, null);
String id = tp.getId();
String name = tp.getNewTeamName();
String des = tp.getDescription();
package com.thingsmatrix.api;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AppleDTO {
private String name;
private int price;
private String address;
private String weight;
private String createDate;
}
package com.thingsmatrix.api;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FoodDTO {
private int price;
private String code;
private Integer weight;
private String name;
private Date createDate;
}
package com.thingsmatrix.api;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;
import org.springframework.test.context.junit4.SpringRunner;
import static junit.framework.TestCase.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = IotApiApplication.class)
public class IotApiApplicationTest {
@Test
public void test(){
// 动态生成用于复制的类,并使用Converter类
BeanCopier copier = BeanCopier.create(AppleDTO.class, FoodDTO.class, true);
AppleDTO source = new AppleDTO();
source.setPrice(new Integer(42));
FoodDTO target = new FoodDTO();
// 执行source到target的属性复制
copier.copy(source, target, new Converter() {
/**
* @param sourceValue source对象属性值
* @param targetClass target对象对应类
* @param methodName targetClass里属性对应set方法名,eg.setId
* @return
*/
public Object convert(Object sourceValue, Class targetClass, Object methodName) {
if (sourceValue.equals(Integer.TYPE)) {
return new Integer(((Number)sourceValue).intValue() + 1);
}
return sourceValue;
}
});
//assertTrue(target.getPrice() == 43);
if(target.getPrice()==43){
System.out.println("wwwwwwwwwwwwweeeeeeeeeeee");
}
}
}
网友评论