为什么不推荐使用BeanUtils属性转换工具
码农突围
共 4426字,需浏览 9分钟
·
2021-10-17 12:54
点击上方“码农突围”,马上关注
这里是码农充电第一站,回复“666”,获取一份专属大礼包 真爱,请设置“星标”或点个“在看
1 背景
2 示例
import lombok.Data;
import java.util.List;
@Data
public class A {
private String name;
private Listids;
}
@Data
public class B {
private String name;
private Listids;
}
import org.springframework.beans.BeanUtils;
import java.util.Arrays;
public class BeanUtilDemo {
public static void main(String[] args) {
A first = new A();
first.setName("demo");
first.setIds(Arrays.asList(1, 2, 3));
B second = new B();
BeanUtils.copyProperties(first, second);
for (String each : second.getIds()) {// 类型转换异常
System.out.println(each);
}
}
}
import org.easymock.cglib.beans.BeanCopier;
import java.util.Arrays;
public class BeanUtilDemo {
public static void main(String[] args) {
A first = new A();
first.setName("demo");
first.setIds(Arrays.asList(1, 2, 3));
B second = new B();
final BeanCopier beanCopier = BeanCopier.create(A.class, B.class, false);
beanCopier.copy(first,second,null);
for (String each : second.getIds()) {// 类型转换异常
System.out.println(each);
}
}
}
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface Converter {
Converter INSTANCE = Mappers.getMapper(Converter.class);
B aToB(A car);
}
import java.util.Arrays;
public class BeanUtilDemo {
public static void main(String[] args) {
A first = new A();
first.setName("demo");
first.setIds(Arrays.asList(1, 2, 3));
B second = Converter.INSTANCE.aToB(first);
for (String each : second.getIds()) {// 正常
System.out.println(each);
}
}
}
List
转为 B 中的 List
类型。import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import org.springframework.stereotype.Component;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
comments = "version: 1.3.1.Final, compiler: javac, environment: Java 1.8.0_202 (Oracle Corporation)"
)
@Component
public class ConverterImpl implements Converter {
@Override
public B aToB(A car) {
if ( car == null ) {
return null;
}
B b = new B();
b.setName( car.getName() );
b.setIds( integerListToStringList( car.getIds() ) );
return b;
}
protected ListintegerListToStringList(List {list)
if ( list == null ) {
return null;
}
Listlist1 = new ArrayList ( list.size() );
for ( Integer integer : list ) {
list1.add( String.valueOf( integer ) );
}
return list1;
}
}
.NumberFormatException
。@Override
public B aToB(A car) {
if ( car == null ) {
return null;
}
B b = new B();
b.setName( car.getName() );
if ( car.getNumber() != null ) { // 问题出在这里
b.setNumber( Long.parseLong( car.getNumber() ) );
}
b.setIds( integerListToStringList( car.getIds() ) );
return b;
}
public final class A2BConverter {
public static B from(A first) {
B b = new B();
b.setName(first.getName());
b.setIds(first.getIds());
return b;
}
}
3 结论
List
和 List
都是 List 类型,可以正常赋值。这就导致在使用很多属性映射工具时,编译时不容易明显的错误。- END - 最近热文
• 疯了!成千上万网友正自爆公司薪资待遇!!! • 985大学最美小姐姐,堪称今年最强博士后... • 0.2秒居然复制了100G文件? • 某科技公司领导称80后该退出IT行业,网友炸了!
评论