危险!请马上替换代码中的BeanUtils!!!
全栈架构社区
共 4874字,需浏览 10分钟
·
2022-03-09 20:46
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 List ids;
}
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);
}
}
}
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 List integerListToStringList(List list) {
if ( list == null ) {
return null;
}
List list1 = new ArrayList( list.size() );
for ( Integer integer : list ) {
list1.add( String.valueOf( integer ) );
}
return list1;
}
}
@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. 结论
相关阅读:2T架构师学习资料干货分享
全栈架构社区交流群
「全栈架构社区」建立了读者架构师交流群,大家可以添加小编微信进行加群。欢迎有想法、乐于分享的朋友们一起交流学习。
看完本文有收获?请转发分享给更多人
往期资源:
评论