Detailed explanation of Apache's object replication example tutorial
BeanUtils.copyProperties and PropertyUtils.copyProperties
Both tool classes process properties with the same name that previously existed in two beans, whether it is the source bean or the target bean. None of the attributes are processed.
The principle is to use the JDK's own reflection mechanism to dynamically get and set, thereby converting our classes.
But we should pay attention to the data types they support. Another thing is that if a class is written inside a class, which is generally called an inner class, conversion of such a class will not be successful.
The biggest difference between the two is:
1.BeanUtils.copyProperties will perform type conversion, but PropertyUtils.copyProperties will not.
Since type conversion is performed, BeanUtils.copyProperties is not as fast as PropertyUtils.copyProperties.
Therefore, the scope of application of PropertyUtils.copyProperties is slightly narrower. It only copies properties with the same name and type. If the name is the same but the type is different, it will report an error.
2. Handling of null: PropertyUtils supports null scenarios; BeanUtils does not support null scenarios for some properties, specifically as follows:
1), date type is not supported ;
2), Boolean, Ineger, Long, Short, Float, Double, etc. are not supported: Convert to false, 0;
3), string: supported, keep null;
There are several things to note when using BeanUtils:
1. For attributes of type Boolean/Short/Integer/Float/Double, it will be converted to false, 0:
1 public class User { 2 3 private Integer intVal; 4 5 private Double doubleVal; 6 7 private Short shortVal; 8 9 private Long longVal; 10 11 private Float floatVal; 12 13 private Byte byteVal; 14 15 private Boolean booleanVal; 16 } 17 18 User src = new User(); 19 User dest = new User(); 20 BeanUtils.copyProperties(dest, src); 21 System.out.println(src); 22 System.out.println(dest); 23 24 //输出结果: 25 User [intVal=null, doubleVal=null, shortVal=null, longVal=null, floatVal=null, byteVal=null, booleanVal=null] 26 User [intVal=0, doubleVal=0.0, shortVal=0, longVal=0, floatVal=0.0, byteVal=0, booleanVal=false]
The explanation is that these types have corresponding basic types. When performing type conversion, it is possible When encountering a conversion similar to Integer -> int, it is obvious that the attribute of type int cannot be assigned a value of null, so it is uniformly converted to 0.
How to prevent it from turning to 0? It can be like this:


1 import org.apache.commons.beanutils.converters.IntegerConverter; 2 3 IntegerConverter converter = new IntegerConverter(null); //默认为null,而不是0 4 BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); 5 beanUtilsBean.getConvertUtils().register(converter, Integer.class);
2. For java.util.Date/BigDecimal/java.sql For the .Date/java.sql.Timestamp/java.sql.Time classes, if the value is null, an exception will be thrown during copying, and the corresponding Conveter needs to be used:
1 public class User2 { 2 3 private java.util.Date javaUtilDateVal; 4 5 private java.sql.Date javaSqlDateVal; 6 7 private java.sql.Timestamp javaSqlTimeStampVal; 8 9 private BigDecimal bigDecimalVal; 10 11 private java.sql.Time javaSqlTime; 12 13 } 14 15 User2 src = new User2(); 16 User2 dest = new User2(); 17 18 BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); 19 20 //如果没有下面几行,则在转换null时会抛异常,例如:org.apache.commons.beanutils.ConversionException: No value specified for 'BigDecimal' 21 //在org.apache.commons.beanutils.converters这个包下面有很多的Converter,可以按需要使用 22 beanUtilsBean.getConvertUtils().register(new BigDecimalConverter(null), BigDecimal.class); 23 beanUtilsBean.getConvertUtils().register(new DateConverter(null), java.util.Date.class); 24 25 beanUtilsBean.getConvertUtils().register(new SqlTimestampConverter(null), java.sql.Timestamp.class); 26 beanUtilsBean.getConvertUtils().register(new SqlDateConverter(null), java.sql.Date.class); 27 beanUtilsBean.getConvertUtils().register(new SqlTimeConverter(null), java.sql.Time.class); 28 29 beanUtilsBean.copyProperties(dest, src); 30 System.out.println(src); 31 System.out.println(dest);
Assume it is copied from A to B:
Requirement 1: If a field in B has a value (not null), then the field is not copied; that is, When the field in B has no value, it will be copied, which is suitable for supplementing the value of B.


1 import org.apache.commons.beanutils.BeanUtilsBean; 2 import org.apache.commons.beanutils.PropertyUtils; 3 4 public class CopyWhenNullBeanUtilsBean extends BeanUtilsBean{ 5 6 @Override 7 public void copyProperty(Object bean, String name, Object value) 8 throws IllegalAccessException, InvocationTargetException { 9 try { 10 Object destValue = PropertyUtils.getSimpleProperty(bean, name); 11 if (destValue == null) { 12 super.copyProperty(bean, name, value); 13 } 14 } catch (NoSuchMethodException e) { 15 throw new RuntimeException(e); 16 } 17 } 18 19 }
Requirement 2: If a field in A has no value (is null), then the field will not be copied, that is, do not copy null is copied to B.
1 import org.apache.commons.beanutils.BeanUtilsBean; 2 3 public class CopyFromNotNullBeanUtilsBean extends BeanUtilsBean { 4 5 @Override 6 public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { 7 if (value == null) { 8 return; 9 } 10 super.copyProperty(bean, name, value); 11 } 12 }
The above is the detailed content of Detailed explanation of Apache's object replication example tutorial. For more information, please follow other related articles on the PHP Chinese website!

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
