yangtu222 / beanutils Goto Github PK
View Code? Open in Web Editor NEWBeanUtils library is a Java bean copy utility with powerful functionality and high performance.
License: Apache License 2.0
BeanUtils library is a Java bean copy utility with powerful functionality and high performance.
License: Apache License 2.0
你好,我想将beanList通过convertor转换为output改如何做?
class sourceBean{ List<Bean2> beanList; } class targetBean{ String output; }
----测试代码如下
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
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)
某些场景下目标类是自动生成的代码,无法添加注解。
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 没有起到作用
我在 target的class中 设置 @BeanCopySource(source = Target.class, features = CopyFeature.IGNORE_PRIMITIVE_NULL_SOURCE_VALUE)
在进行copy的时候 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;
}
}
features可以增加功能作用到单个属性上吗。
希望某个属性,对null值不拷贝,但另外的对象null值拷贝,这个需求可以考虑吗?
1.0.5 的实现总是使用 CtClass.toClass()
. 建议提供接口允许用户设置需要的 ClassLoader
, 并在相应的地方调用 CtClass.toClass(ClassLoader loader)
方法.
开发时修改了代码之后,有各种技术来重新加载变更后的代码而无需重启程序,能够大大的提升开发效率,但是BeanUtils会缓存映射关系,导致修改之后的代码无法生效,是否能够提供一个配置,在开发阶段关闭缓存?
代码如下:
`
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方法。不知道还有没有更好的方法。
您好,可以提供一个全局忽略大小写的copy 方法吗
比如
public class ClassA {
private String aa;
}
public class ClassA {
private String aA;
}
aa 和 AA ,Aa,aA可以互相赋值
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 !
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();
}
}
测试了一下好像不能直接转换, 可不可以支持直接从String -> Enum ?
@BeanCopySource(source={source1.class,sourc2.class})
public class clazz{
@CopyProperty(property={"source1.field1","source2.field2"})
private String field;
}
如果能支持这种是不是会更好?个人意见哈,肯定实现起来比较麻烦。
假设 有AVO,BVO 都可能转CInfo,Cinfo内部有个字段D是枚举需要打CopyProperty注解,但是AVO有这个字段,BVO没有这个字段,能不能 转换的时候没有对应的属性,就直接转换结果为Null不要直接抛异常
有这样的需求,融合两个类 A 和 B 到一个类 C.
首先 @CopyProperty 是可以多次注解
如果 copyBean 只是是来自 A.class 则,只有 aId 有值。
如果 copyBean 只是是来自 B.class 则,只有 bId 有值。
如果 copyBean 只是是来自 H.class 则,只有 aId, bId 都有值。
你好, BeanCopyUtils.copyBean() 时sourceObject对象为CGLIB生成的, 无法获取它的属性值.获取到的值为null.
和cglib的copier一样,无法在加了@accessors(chain=true)的两个实体类实现转换,但是Spring的BeanUtils可以,而且简单测试10次循环的copy,性能较其他二者较低,不知道是不是打印了一大串log的原因,可以在哪里关闭log吗?
fromBean.setBeanLong(null);
会导致空指针异常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() );
}
}
有些对象的值来自多个对象 mapper,需要注解多个 @BeanCopySource ,指定不同的 source
我在Entity中使用@BeanCopySource注解后,会导致原本应该懒加载的属性变成了饥饿加载。
解决办法就是将Entity中的注解脱离出来,使用Option类的方式。
BeanCopyUtils.copyBean(inDTO, RecommendTheme.class, RecommendThemeOption.class);
使用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)
你好,
出现一个影响比较大的一个问题,希望帮忙解决,谢谢!
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
场景是,从多个source 对象拷贝不同的属性到target Object
如果target Object中存在CopyColletion配置,而OptionClass中不存在这个字段,则会报错,提示缺少对应的字段异常
sourceBean 包含静态内部类
targetClass property 注解自定义转换器
在使用BeanCopyUtils.copyList() 的时候报自定义转换器的property在sourceBean 未定义
以下实体类
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有什么解决方案嘛?
我有个一个类(比如region表达省市区县村等等)
里面相应的有 parent 和children
在做copy的时候 我希望 copy 父的父(排除父的子) 以及 子的子(排除子的父) 如下图
父中不要子 的option
子中不要父的option
目前子的子 循环都OK 的
但是父的父 copy死循环了 大概是 option中的 @CopyProperty 中的optionclass没起作用
现在我想了一个办法 我复制了一个 PlacePO2DTOWithoutChildren 命名为 PlacePO2DTOWithoutChildren2
虽然没有死循环了 但是 我有 至少 5个层级 现在只能拿到3个层级 再上级就不copy了 很奇怪
所以 我有尝试 PlacePO2DTOWithoutChildren 用PlacePO2DTOWithoutChildren 2
PlacePO2DTOWithoutChildren 2 用 PlacePO2DTOWithoutChildren 3 一直用到5
得到的结果还是 只有3个层级 copy源数据都是OK的
您好,我测试了下在集合类copy 的时候不支持 @CopyProperty(property = "XXX")
如:
@CopyCollection(targetClass=B.class,optionClass =Aoption.class )
List AList;
无法对应到
List BList;
是否考虑在后续版本功能支持,谢谢。
非编译期间生成 copy 实现的,该项目表现得非常出色👏。
github地址:https://github.com/lets-mica/mica-jmh
项目中,copy源对象,很有可能会修改字段名字,这边是以字符串的方式匹配上的,如果忘记全局查找修改的话,感觉很容易就忘记了
如果每次操作对象的一次copy都会打印info级别的log有点伤io性能,这些对于开发者来讲大多时候不是必须的
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.