Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use BeanUtils.copyProperties

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to use BeanUtils.copyProperties", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use BeanUtils.copyProperties" this article.

1. Preface

In the process of development, the attributes and values of one object are assigned to another object, and get and set methods are widely used. It looks very bloated, so I am certainly not the only one who has this idea after thinking about it, so there must be a way to solve this problem technically, so I consulted some materials and found BeanUtils.copyProperties this method. Here are all the summaries and precautions when using them.

The org.springframework.beans.BeanUtils.copyProperties method is used to assign attributes between objects to avoid the assignment of attributes one by one through get and set methods.

two。 General use

BeanUtils is a common utility class in this package. The definition of this method is as follows:

Public static void copyProperties (java.lang.Object dest,java.lang.Object orig) throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException

If you have two JavaBean with many of the same properties, a common situation is the PO object (persistent object) in Struts and the corresponding ActionForm, such as Teacher and TeacherForm. We usually construct a PO object from ActionForm in Action. The traditional way is to assign values to attributes one by one using statements like the following:

/ 1 get TeacherFormTeacherForm teacherForm= (TeacherForm) form;//2 to construct Teacher object Teacher teacher=new Teacher (); / / 3 assign teacher.setName (teacherForm.getName ()); teacher.setAge (teacherForm.getAge ()); teacher.setGender (teacherForm.getGender ()); teacher.setMajor (teacherForm.getMajor ()); teacher.setDepartment (teacherForm.getDepartment ()); / / 4 persist Teacher objects to database HibernateDAO=;HibernateDAO.save (teacher)

With BeanUtils, the code has changed a lot, as follows:

/ 1 get TeacherFormTeacherForm teacherForm= (TeacherForm) form;//2 to construct Teacher object Teacher teacher=new Teacher (); / / 3 assign BeanUtils.copyProperties (teacher,teacherForm); / / 4 persist Teacher object to database HibernateDAO=;HibernateDAO.save (teacher)

If there are attributes with different names between Teacher and TeacherForm, BeanUtils does not process these attributes and requires the programmer to handle them manually.

For example, if Teacher contains a modifyDate attribute (which records the last modified date and does not need to be entered by the user in the interface), but TeacherForm does not have this attribute, add a sentence after copyProperties () in the above code:

Teacher.setModifyDate (new Date ()); 3. Ignore null values when copying attributes

One problem with using BeanUtils.copyProperties is that when the key value of the src object is Null

Will overwrite the corresponding key value of the target object to empty, which is obviously not what we want, the following method can solve the problem

/ * copy attributes and filter out attributes that are not copied * / public static void copyBeanProperties (final Object source,//1, the original object to be copied final Object target,//2, the copied result object / / 3, and get the attribute name final Collection excludes = new ArrayList () that you do not need to copy; final PropertyDescriptor [] propertyDescriptors = BeanUtils.getPropertyDescriptors (source.getClass () For (final PropertyDescriptor propertyDescriptor: propertyDescriptors) {String propName = propertyDescriptor.getName (); if (! includes.contains (propName)) {excludes.add (propName);}} / / 4, copy operation BeanUtils.copyProperties (source, target, excludes.toArray (new String [excludes.size ()]);}

Use case

Public static String [] getNullPropertyNames (Object source) {final BeanWrapper src = new BeanWrapperImpl (source); java.beans.PropertyDescriptor [] pds = src.getPropertyDescriptors (); Set emptyNames = new HashSet (); for (java.beans.PropertyDescriptor pd: pds) {Object srcValue = src.getPropertyValue (pd.getName ()); if (srcValue = = null) emptyNames.add (pd.getName ()) } String [] result = new String [emptyNames.size ()]; return emptyNames.toArray (result);} public static void copyPropertiesIgnoreNull (Object src, Object target) {BeanUtils.copyProperties (src, target, getNullPropertyNames (src));} 4. Notes for use (1)

Property.copyProperties () and BeanUtils.copyProperties ()

In addition to BeanUtils, there is a utility class called PropertyUtils, which also provides the copyProperties () method

1. Both org.springframework.beans and org.apache.commons.beanutils have performance problems compared to the get/set approach.

two。 Efficiency from high to low: get/set "PropertyUtils" BeanUtils.

Both the 3.PropertyUtils and BeanUtils utility classes deal with the existence of attributes with the same attribute name between the bean, regardless of the extra attributes in the source bean or the target bean.

4. Specifically: BeanUtils.copyProperties () can do type conversion within a certain range, but also note that when it cannot be converted, the default null value will be converted to 0Property.copyProperties () is a strict type conversion, which must be exactly the same as the property name. For null processing: PropertyUtils supports scenarios with null; BeanUtils does not support null for some attributes, as shown below:

A. the java.util.Date type is not supported, but its self-mining java.sql.Date is supported. Java.util.Date direct copy will report an exception.

B. not supported by Boolean,Integer,Long, etc., which will convert null to 0

C. Supported by String, it is still null after conversion.

5.BeanUtils 's advanced features, the org.apache.commons.beanutils.Converter interface, can customize type conversions and perform special handling on null values of some type data, such as ConvertUtils.register (new DateConverter (null), java.util.Date.class); but PropertyUtils does not.

In addition: it is worth noting that during testing, it is found that the BeanUtils class in the commons-beanutils-1.8.0.jar version supports the conversion from Byte to Integer or int. It shows that in the process of actual use, we still have to look more at the source code, do more testing, and pay attention to the minor changes brought about by the version number upgrade.

The conversion types supported by BeanUtils are as follows:

* java.lang.BigDecimal* java.lang.BigInteger* boolean and java.lang.Boolean* byte and java.lang.Byte* char and java.lang.Character* java.lang.Class* double and java.lang.Double* float and java.lang.Float* int and java.lang.Integer* long and java.lang.Long* short and java.lang.Short* java.lang.String* java.sql.Date* java.sql.Time* java.sql.Timestamp

Note here that java.util.Date is not supported, while its subclass java.sql.Date is supported. So be sure to use the java.sql.Date type if the object contains properties of a time type and you want to be converted. Otherwise, an argument mistype exception will be prompted during conversion.

5. Notes for use (2)

There are two sources of the method copyProperties () in Java.

BeanUtils is org.springframework.beans.BeanUtils.

BeanUtils is org.apache.commons.beanutils.BeanUtils.

Let's talk about their usage and differences in detail. This method is under different packages, and the parameter assignments passed in the copyProperties () methods of the two classes are opposite.

For example: BeanUtils.copyProperties b is the object (ABI b)

BeanUtils is org.springframework.beans.BeanUtils//a copied to b//a1 source file, b1 destination file public static void copyProperties (Object A1, Object b1) throws BeansException {copyProperties (A1, b1, null, (String []) null);}

BeanUtils is org.apache.commons.beanutils.BeanUtils.

/ b copy to a//a2 destination file, b2 original, source file public static void copyProperties (Object a2, Object b2) throws IllegalAccessException, InvocationTargetException {BeanUtilsBean.getInstance () .copyProperties (a2, b2);}

If the source of the reference package is different, the meaning is different. When you use it, you must see which package is under it.

6. Notes for use (3)

Is the method convenient and comfortable to use? But . Get/set code is easy to write comes at a price, that is, the running cost of using BeanUtils is also astonishing! BeanUtils takes longer than the sum of time to fetch data, copy it to the corresponding value object (by manually calling the get and set methods), and serialize it back to the remote client. So be careful with this power! Where there is loss, there is gain, and vice versa.

The above is all the contents of this article "how to use BeanUtils.copyProperties". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report