Giter Site home page Giter Site logo

beanutils's Introduction

BeanUtils

Maven Central

This BeanUtils library is a Java bean copy utility with powerful functionality and high performance.

Maven Usage

	<dependency>
		<groupId>com.github.yangtu222</groupId>
		<artifactId>BeanUtils</artifactId>
		<version>1.0.11</version>
	</dependency>

Features:

  • support copy with Java primitive type auto-convert to its Java type. e.g. int <=> Integer
  • support copy with array type. e.g. int[] <=> Integer[]
  • support copy with Java Collection type. e.g. List => List
  • support copy with property name mapping. e.g. int id => int userId
  • support copy with recursion copy.
  • support custom data convert when coping.
  • with performance as native copy.
  • easy usage, annotation way to define the property mapping.
  • support one copy feature (IGNORE_PRIMITIVE_NULL_SOURCE_VALUE) (v1.0.2, thanks maosi)
  • support copy with BeanA[] <==> List (version 1.0.2 )
  • easy debug by dump the property mappings, and can be disabled using BeanCopyConfig. (version 1.0.2 )
  • support copy with Java Enum <=> String (v1.0.4, thanks TuWei1992)
  • support copy from JavaBean to String (v1.0.4, thanks TuWei1992, using Object.toString() )
  • support one copy feature (IGNORE_ALL_NULL_SOURCE_VALUE) (v1.0.7, thanks sj853)

A full Sample:

From class and To class:

	                                           @BeanCopySource(source=FromBean.class)          
	public class FromBean {                    public class ToBean {                           
	                                                                                       
		private boolean beanBool;              private Boolean beanBool;                   
		private byte beanByte;                 private Byte beanByte;                      
		private char beanChar;                 private Character beanChar;                 
		private short beanShort;               private Short beanShort;                    
		private int beanInt;                   private Integer beanInt;                    
		private Long beanLong;                 private long beanLong;                      
		private Float beanFloat;               private float beanFloat;                    
		private Double beanDouble;             private double beanDouble;                  
		private String beanString;             private String beanString;                  
		                                                                                   
		                                       @CopyPropery                                
		private MyEnum myEnum;                 private String myEnum;
		                                                                                   
		                                       @CopyPropery                                
		private String myEnum2;                private MyEnum myEnum2;
		                                                                                   
		                                       @CopyProperty(convertor=DateConvertor.class)
		private Date beanDate;                 private String beanDate;                    
		                                                                                   
		private int[] beanIntArray;            private int[] beanIntArray;                 
		                                                                                   
		                                       @CopyProperty                               
		private FromBean2 bean2;               private ToBean2 bean2;                      
		                                                                                   
		                                       @CopyCollection(targetClass=ToBean3.class)  
		private List<FromBean3> bean3List;     private List<ToBean3> bean3List;            
		                                                                                   
		                                       @CopyProperty                               
		private FromBean4[] bean4Array;        private ToBean4[] bean4Array;               
		                                                                                   
		// getters and setters...              @CopyProperty(property="beanInt")           
	}                                              private int beanId;                         
	                                                                                       
	                                               @CopyProperty(property="bean2.beanString")  
	                                               private String bean2String;                 
	                                           
	                                               // getters and setters...
	                                           }

And one line code as:

ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class);

Performance:

Library 1 time 100 times 10000 times 1000000 times 10000000 times
org.apache.commons.beanutils.BeanUtil.copyProperties 1 12 128 9963 99879
org.apache.commons.beanutils.PropertyUtils.copyProperties 0 2 56 5564 55651
org.springframework.beans.BeanUtils.copyProperties 0 2 5 473 4700
net.sf.ezmorph.bean.BeanMorpher 1 4 67 6769 68051
org.springframework.cglib.beans.BeanCopier.create 1 1 2 2 87 843
org.springframework.cglib.beans.BeanCopier.create 2 0 0 0 10 98
com.tuyang.beanutils.BeanCopyUtils.copyBean 1 0 0 0 21 196
com.tuyang.beanutils.BeanCopyUtils.copyBean 2 0 0 0 11 97
native Copy 0 0 0 10 88
  • The data in upper table is millisecond.
  • The performance test is run on Win10, with intel i7 6700HQ, and Memory 24G.
  • The test code is also contained in source code.
  • 2 ways called in BeanCopier.create and BeanCopyUtils.copyBean also can be found in source code.
  • native copy: that means using get/set methods called manually.

API Usage:

	FromBean fromBean = ...;
	ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class);

or:

	List<FromBean> fromList = ...;
	List<ToBean> toList = BeanCopyUtils.copyList(fromList, ToBean.class);

or:

	BeanCopier copier = BeanCopyUtils.getBeanCopier(FromBean.class, ToBean.class);
	ToBean toBean = new ToBean();
	toBean = (ToBean)copier.copyBean(fromBean, toBean);

or with option class, when ToBean class cannot be modified. At this time ToBeanOption class acts as a configuration class of ToBean class, and annotations are configured in this class:

	FromBean fromBean = ...;
	ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class, ToBeanOption.class);
	
	@BeanCopySource(source=FromBean.class)
	public class ToBeanOption {
		
		@BeanCopy(property="beanInt")
		private int beanId;
		...
		

Annotation Detail

BeanCopySource:

	//use @BeanCopySource to specify the source class.
	@BeanCopySource(source=FromBean.class)
	public class ToBean {
		...
	}
	

source

Specify the source object class.

features

Specify the copy features. The features are:

  • IGNORE_PRIMITIVE_NULL_SOURCE_VALUE Ignore copying source null property to target primitive type property. e.g. Copy null (Integer type) to int. By default this feature is disabled, so we can debug where the pointer is null by thrown exception.

  • IGNORE_ALL_NULL_SOURCE_VALUE Ignore copying source null property to target property. By default this feature is disabled.

  • IGNORE_ENUM_CONVERT_EXCEPTION Ignore exceptions when converting from String to Enum when call Enum.valueOf(). This will happens when converting an invalid String value to Enum, and null will be set in this situation.

  • ENABLE_JAVA_BEAN_TO_STRING Support converting a JavaBean to String, if the property is annotated with CopyProperty/CopyCollection. The implementation is using JavaBean's toString() method as the result, and null if the JavaBean is null.

CopyProperty

default:

Used to specify the property should be copied to. e.g.

	@CopyProperty
	private ToBean2 bean2;

name mapping

Annotation CopyProperty's 'property' property is used for name mapping as following:

	@CopyProperty(property="beanInt")
	private Integer toInt;
	
	@CopyProperty(property="bean2.beanInt")
	private int bean2Int;

ignore

Annotation CopyProperty's 'ignored' property is used for ignoring the property when coping.

	@CopyProperty(ignored=true)
	private Integer beanInt;

convertor

Annotation CopyProperty's 'convertor' property is used for custom data converting.

	@CopyProperty(convertor=DateConvertor.class)
	private String beanDate;

The convertor class must be BeanCopyConvertor's implementation class and have a default constructor. Here is a sample:

public class GendorConvertor implements BeanCopyConvertor<Integer, String> {

	@Override
	public String convertTo(Integer object) {
		if( object == 1 ) 
			return "Male";
		if( object == 2) 
			return "Female";
		return "Unknown";
	}
}

optionClass

Annotation CopyProperty's 'optionClass' property is used for specifying the option class when do recursion copy.

	@CopyProperty(optionClass=ToBeanOption.class)
	private ToBean bean2;

CopyCollection

targetClass

Due to the limitation of Java, it is hard to get the class type of Collection's template parameter. So the targetClass should be specified as the Collection's template class.

	@CopyCollection(targetClass=ToBean2.class)
	private List<ToBean2> beanList;

name mapping/ignore/optionClass

name mapping/ignore/optionClass is the same to CopyProperty.

Advance

  • Disable Javassist library: if your project is not enable to use Javassist library, e.g. Android project, you can change BeanCopyConfig's beanCopyFactory to ReflactBeanCopyFactory.class, which is using Java reflect to archive the bean copy.

  • In collection copy, if the property is an abstract collection class, the default implementation class will be:

    • List: ArrayList
    • Set : HashSet
    • Deque: ArrayDeque
    • Queue: ArrayDeque

If you want to use other class as default implementation class, you can change BeanCopyConfig's related properties.

  • ClassLoader (1.0.6): You can specify a classLoader instance to BeanCopyConfig, otherwise BeanUtils will use toBean.getClass().getClassLoader() as the classLoader to avoid multi-classLoader issue.

License

Apache-2.0 License

Other

For Chinese user: http://www.jianshu.com/p/9a136ecd3838

beanutils's People

Contributors

yangtu222 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

beanutils's Issues

并发情况下出现异常。

使用option进行copy
BeanCopyUtils.copyBean(fromBean,ToBean.class,BeanOption.class);

异常信息:

Exception in thread "Thread-4" java.lang.NullPointerException
	at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:238)
	at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:199)
	at com.example.demo.beancopy.TestService.test(TestService.java:16)
	at com.example.demo.beancopy.TestYangtuBeanCopy.lambda$test2$0(TestYangtuBeanCopy.java:32)
	at java.lang.Thread.run(Thread.java:748)

CopyCollection 不支持 CopyProperty

您好,我测试了下在集合类copy 的时候不支持 @CopyProperty(property = "XXX")
如:
@CopyCollection(targetClass=B.class,optionClass =Aoption.class )
List AList;

无法对应到
List BList;

是否考虑在后续版本功能支持,谢谢。

sourceBean 静态内部类问题

sourceBean 包含静态内部类
targetClass property 注解自定义转换器
在使用BeanCopyUtils.copyList() 的时候报自定义转换器的property在sourceBean 未定义

Android Support

As it is, the library is not currently compatible with Android due to

Caused by: java.lang.ClassNotFoundException: Didn't find class "java.beans.Introspector" on path: DexPathList[[zip file "/data/app/app.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

Is it possible to add support?

Here is a thread - EsotericSoftware/yamlbeans#25

CopyFeature.IGNORE_PRIMITIVE_NULL_SOURCE_VALUE失效

CopyFeature.IGNORE_PRIMITIVE_NULL_SOURCE_VALUE 没有起到作用
我在 target的class中 设置 @BeanCopySource(source = Target.class, features = CopyFeature.IGNORE_PRIMITIVE_NULL_SOURCE_VALUE)

在进行copy的时候 null还是覆盖了

不支持 return this 的 setter 方法,导致 setter 进去为 null

class fromBean {
private int id;
private String name;

// setter getter

}

@BeanCopySource(source = fromBean.class)
class toBean {
private int id;
private String name;

/** 此处失效,凡是这种都失效  */
public toBean setName(String name) {
    this.name = name;
    return this;
}

}

BeanCopySource多个来源

@BeanCopySource(source={source1.class,sourc2.class})
public class clazz{
@CopyProperty(property={"source1.field1","source2.field2"})
private String field;
}

如果能支持这种是不是会更好?个人意见哈,肯定实现起来比较麻烦。

关于@CopyProperty中optionClass循环使用的问题

我有个一个类(比如region表达省市区县村等等)
里面相应的有 parent 和children
image
在做copy的时候 我希望 copy 父的父(排除父的子) 以及 子的子(排除子的父) 如下图
父中不要子 的option
image
子中不要父的option
image

目前子的子 循环都OK 的
但是父的父 copy死循环了 大概是 option中的 @CopyProperty 中的optionclass没起作用
image

现在我想了一个办法 我复制了一个 PlacePO2DTOWithoutChildren 命名为 PlacePO2DTOWithoutChildren2
image

虽然没有死循环了 但是 我有 至少 5个层级 现在只能拿到3个层级 再上级就不copy了 很奇怪
所以 我有尝试 PlacePO2DTOWithoutChildren 用PlacePO2DTOWithoutChildren 2
PlacePO2DTOWithoutChildren 2 用 PlacePO2DTOWithoutChildren 3 一直用到5
得到的结果还是 只有3个层级 copy源数据都是OK的

多个对象转同一个对象

假设 有AVO,BVO 都可能转CInfo,Cinfo内部有个字段D是枚举需要打CopyProperty注解,但是AVO有这个字段,BVO没有这个字段,能不能 转换的时候没有对应的属性,就直接转换结果为Null不要直接抛异常

@CopyProperty 需要多次注解,而且需要判断 source 来自的 class 来进行选择性 setter

有这样的需求,融合两个类 A 和 B 到一个类 C.


@BeanCopySource(source = P.class)
@BeanCopySource(source = A.class)
@BeanCopySource(source = B.class)
class C {
@CopyProperty(property = "id")
@CopyProperty(property = "id", class=A.class)
int aId;
@CopyProperty(property = "id")
@CopyProperty(property = "id", class=B.class)
int bId;
}

首先 @CopyProperty 是可以多次注解

如果 copyBean 只是是来自 A.class 则,只有 aId 有值。
如果 copyBean 只是是来自 B.class 则,只有 bId 有值。

如果 copyBean 只是是来自 H.class 则,只有 aId, bId 都有值。

开发模式下提供关闭缓存的选项

开发时修改了代码之后,有各种技术来重新加载变更后的代码而无需重启程序,能够大大的提升开发效率,但是BeanUtils会缓存映射关系,导致修改之后的代码无法生效,是否能够提供一个配置,在开发阶段关闭缓存?

会导致@ManyToOne @OneToMany的懒加载失效

我在Entity中使用@BeanCopySource注解后,会导致原本应该懒加载的属性变成了饥饿加载。
解决办法就是将Entity中的注解脱离出来,使用Option类的方式。
BeanCopyUtils.copyBean(inDTO, RecommendTheme.class, RecommendThemeOption.class);

泛型继承copy不好使

代码如下:

`
public class Parent {
private T id;

public T getId() {
    return id;
}

public void setId(T id) {
    this.id = id;
}

}
`

`public class Son extends Parent{
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

public class SonVo {

private Long id;
private String name;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

public class Test {

public static void main(String[] args) {
    Son son = new Son();
    son.setId(11L);
    son.setName("test");
    SonVo toBean = BeanCopyUtils.copyBean(son, SonVo.class);
    System.out.println("bean " + JSON.toJSONString(toBean));
}

}
然后在执行的时候就报属性不匹配:
Exception in thread "main" com.tuyang.beanutils.exception.BeanCopyException: Property parameter does not match: com.haixue.crm.chance.manager.service.Son[id(Object)] : com.haixue.crm.chance.manager.service.SonVo[id(Long)]
at com.tuyang.beanutils.internal.cache.BeanCopyCache.buildBeanCopyPropertyItem(BeanCopyCache.java:942)
at com.tuyang.beanutils.internal.cache.BeanCopyCache.getBeanCopy(BeanCopyCache.java:123)
at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:237)
at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:199)
at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:135)
at com.haixue.crm.chance.manager.service.Test.main(Test.java:12)
`
这个继承应该是执行的时候应该会拿到实际的参数类型,但是实际上好像没拿到。
通过源码发现在BeanCopyCache类中的
PropertyDescriptor sourcePd = PropertyUtils.getPropertyDescriptor(sourceClass, propertyName );获取到 Method readMethod = sourcePd.getReadMethod(); 的值是父类的值。现目前想到的方案有两种,第一种是在Target类的目标属性上添加convertor做转换 第二种是通过在子类上设置来自继承的属性的get,set方法。不知道还有没有更好的方法。

使用@CopyProperty拷贝Enum会抛出BeanCopyException

以下实体类

public enum Enum {
A,B,C;
}

@Data
public class Inside{
private String a;
private Enum b;
}

@Data
public class FromBean {
private String c;
private Inside inside;
}

@Data
@BeanCopySource(source=FromBean.class)
public class ToBean {

@CopyProperty(property = "inside.a")
private String a;

@CopyProperty(property = "inside.b")
private Enum b;

private String c;

}

使用copyBean
ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class);

会抛出如下异常
com.tuyang.beanutils.exception.BeanCopyException: beanCopy new instance

at com.tuyang.beanutils.internal.utils.InstanceUtils.newInstance(InstanceUtils.java:113)
at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:198)
at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:135)
at cn.com.business.BeanCopyTest.test(BeanCopyTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: java.lang.NoSuchMethodException: cn.com.business.BeanCopyTest$ToBean.()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at com.tuyang.beanutils.internal.utils.InstanceUtils.newInstance(InstanceUtils.java:108)
... 25 more

看异常的描述是枚举类没有构造方法,比较奇怪的是枚举类的拷贝不是应该是直接set的formBean.getInside().getB()的吗?为什么是还要new一个enum的。
然后对于CopyProperty拷贝enum有什么解决方案嘛?

值为null的包装类型转换为基本类型会引起空指针异常

  1. 如下代码所示,fromBean.setBeanLong(null);会导致空指针异常
  2. 能否增加转换特性如只转换原始对象的非空属性,代码类似于
    ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class, CopyFeature.IGNORE_NULL_SOURCE_VALUE)
public class Test02 {
	
	private FromBean getFromBean() {
		FromBean fromBean = new FromBean();
		
		fromBean.setBeanBool(true);
		fromBean.setBeanByte((byte)5);
		fromBean.setBeanChar((char)40);
		fromBean.setBeanShort((short)50);
		fromBean.setBeanInt(100);
		fromBean.setBeanFloat(100.50f);
		fromBean.setBeanLong(null);
		fromBean.setBeanDouble(2342332423.23432432523523);
		fromBean.setBeanString("Test test Test test.");
		return fromBean;
	}

	@Test
	public void testPrimitiveType() {
		FromBean fromBean = getFromBean();
		ToBean toBean = BeanCopyUtils.copyBean(fromBean, ToBean.class);
		assertEquals(fromBean.isBeanBool(), toBean.getBeanBool().booleanValue());
		assertEquals( fromBean.getBeanByte(), toBean.getBeanByte().byteValue() );
		assertEquals( fromBean.getBeanChar(), toBean.getBeanChar().charValue() );
		assertEquals( fromBean.getBeanShort(), toBean.getBeanShort().shortValue() );
		assertEquals( fromBean.getBeanInt(), toBean.getBeanInt().intValue() );
		assertEquals( fromBean.getBeanLong().longValue(), toBean.getBeanLong());
		assertEquals( fromBean.getBeanFloat().floatValue(), toBean.getBeanFloat(), 0);
		assertEquals( fromBean.getBeanDouble().doubleValue(), toBean.getBeanDouble(), 0 );
		assertEquals( fromBean.getBeanString(), toBean.getBeanString() );
	}
}

Problem with @CopyProperty(ignored=true) in n+1 object

Hi @yangtu222

I think i found a bug in this simple example :

public class User {
	public String name;	
	public Job job;
	
	@CopyProperty(ignored=true)
	public List<SomeThing> things1;
}

public class Job {
	public String name;	
	
	@CopyProperty(ignored=true)
	public List<SomeClass> things2;
}
// api call
User userCopy = BeanCopyUtils.copyBean(user, User.class);

I get the userCopy.things1 = null which is exactly what i want !

The problem is that userCopy.job.things2 is not null even if annotated with @CopyProperty(ignored=true).

So i think the annotations declared in N+1 are like not "parsed".

Thanks for your help !

使用option 类 并且没有忽略空的情况下会报错,异常如下

----测试代码如下

public static void main(String[] args) {
AdjustDto adjustDto = new AdjustDto();
adjustDto.setFlag(null);
adjustDto.setSerialNo(null);
PrpCadjustEntity prpCadjustEntity = new PrpCadjustEntity();
System.out.println(BeanUtilExt.copyBean(adjustDto, prpCadjustEntity,AdjustEntityOpt.class));
}
-----log below

Dump Bean Copy Property Mapping:

From: [AdjustDto] To: [PrpCadjustEntity] Option: [AdjustEntityOpt]

CopyFeature: (NONE)

                    String getAdjustCode()|String setAdjustCode()
                          String getFlag()|String setFlag()
                String getRiskAdjustCode()|String setRiskAdjustCode()
           BigDecimal getRiskAdjustValue()|BigDecimal setRiskAdjustValue()
                        Long getSerialNo()|long setSerialNo()
                                 (ignored)|String setConveyanceFlag()
                                 (ignored)|Long setItemkindNo()
                                 (ignored)|String setPolicyNo()
                                 (ignored)|String setPrecisionFlag()
                                 (ignored)|String setRemark()
                                 (ignored)|String setRiskCode()

Exception in thread "main" java.lang.NullPointerException
at com.tuyang.beanutils.internal.javassist.impl.BeanCopier$$javassist0.copyBean(BeanCopier$$javassist0.java)
at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:238)
at cn.com.libertymutual.xuanbird.util.BeanUtilExt.copyBean(BeanUtilExt.java:116)
at cn.com.libertymutual.xuanbird.prpall.nonmotor.service.impl.EndorseGenerateServiceImpl.main(EndorseGenerateServiceImpl.java:230)

加了@Accessors(chain=true)无法copy属性

和cglib的copier一样,无法在加了@accessors(chain=true)的两个实体类实现转换,但是Spring的BeanUtils可以,而且简单测试10次循环的copy,性能较其他二者较低,不知道是不是打印了一大串log的原因,可以在哪里关闭log吗?

相同的的类名copy时报NullPointerException

你好,
出现一个影响比较大的一个问题,希望帮忙解决,谢谢!
1.第一种情况 :
如下的例子,两个相同的类名在不同的包下,开发时没有问题,上线则报空指针(可以确定target 和source 都不为null,用了lombok 插件),线上环境是 spring boot + docker
cn.com.**.health.dto.sdbao.request.policyfree.OrderInfo policyFree_orderInfo = policyFreeRequestBody.getOrderInfo();
UserInfo policyFree_applyUser = policyFreeRequestBody.getApplyUser();
List policyFree_insuredUsers = policyFreeRequestBody.getInsuredUsers();
OrderInfo proposalOrder_orderInfo = BeanUtilExt.copyBean(policyFree_orderInfo, OrderInfo.class);

2.第二种情况
不同的模块下(module)相同的包路径,不同的类 开发时没有问题,上线则报空指针。

------------附错误日志
java.lang.NullPointerException at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:238) at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:199) at com.tuyang.beanutils.BeanCopyUtils.copyBean(BeanCopyUtils.java:135) at

Logger must use log4J

com.tuyang.beanutils.internal.logger.Logger

springboot recommends logback, but the jar must use the log4j, Otherwise, it will directly system.out.println. it does not make sense,

public static Logger getLogger(Class<?> clazz) {
	 try {
		Class<?> loggerClass = Logger.class.getClassLoader().loadClass("org.apache.log4j.Logger");
		Method method = loggerClass.getMethod("getLogger", Class.class);
		Object logger = method.invoke(null, clazz);
		return new Logger(logger);
	}catch (Exception e) {
			
	}
	return new Logger(null);
}


public void info(Object message, Throwable t) {
	if( logger != null ) {
		try {
			Method method = logger.getClass().getMethod("info", Object.class, Throwable.class);
			method.invoke(logger, message, t);
		} catch (Exception e) {
			e.printStackTrace();
		}
	} else {
		if( BeanCopyConfig.instance().getLogLevel() < LogLevelInfo )
			return;
		
		System.out.println(message.toString());
		t.printStackTrace();
	}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.