Coder Social home page Coder Social logo

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

BeanCopySource多个来源

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

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

sourceBean 静态内部类问题

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

值为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() );
	}
}

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还是覆盖了

@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 都有值。

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

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

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

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

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

加了@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

不支持 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;
}

}

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 !

关于@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的

并发情况下出现异常。

使用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)

泛型继承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有什么解决方案嘛?

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();
	}
}

多个对象转同一个对象

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

使用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)

CopyCollection 不支持 CopyProperty

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

无法对应到
List BList;

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

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.