Basic usage of Bean Utils, ConvertUtils, Property Utils and Collection Utils of apache-commons

Keywords: Java Apache Oracle Attribute

The BeanUtils toolkit, developed by Apache, is designed to facilitate programmers to easily manipulate Bean classes.


BeanUtils has four packages:

      org.apache.commons.beanutils

      org.apache.commons.beanutils.converters

      org.apache.commons.beanutils.locale

      org.apache.commons.beanutils.locale.converters


Of particular concern to us is the org.apache.commons.beanutils package, which is complementary to other packages. The above two are not localized for any processing, high execution efficiency. The next two require localization.


Class BeanUtils

It mainly provides various operations for JavaBean s, such as object, attribute replication and so on.


When BeanUtils sets the attribute value, if the attribute is the basic data type, BeanUtils will automatically help us to convert the data type, and BeanUtils also relies on the bottom getter and setter methods when setting the attribute. If the set attribute value is another reference data type, then a type converter must be registered to achieve automatic conversion (see ConvertUtils below).


Common methods:

cloneBean(Object bean)

Cloning of Objects

copyProperties(Object dest, Object orig)

Copies of objects

copyProperty(Object bean, String name, Object value)

Copy the specified property value to the specified bean

setProperty(Object bean, String name, Object value)

Sets the value of the specified property

populate(Object bean, Map<String,? extends Object> properties)

Copy map data to JavaBean (the key of map should be the same as the attribute name of javabean)


Note: copyProperty and setProperty Recommendation for daily use copyProperty . If we need to customize the populate() method, we can override it setProperty() method.

Example:

// JavaBean
public class Animal {
	private String name;
	private int age;
	private String color;
	private String sex;

	public Animal() {
	}
      getXxx and setXxx Omit...

}

/**
 * BeanUtils
 */
@Test
public void test1() throws Exception {
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("name", "tuantuan");
	map.put("age", 3);
	map.put("color", "black");
	map.put("sex", "female");

	// Copy map data into javabean
	Animal a1 = new Animal();
	BeanUtils.populate(a1, map);
	System.out.println(a1); // Animal [name=tuantuan, age=3, color=black, sex=female]

	// Copies of objects
	Animal a2 = new Animal();
	BeanUtils.copyProperties(a2, a1);
	System.out.println(a2);// Animal [name=tuantuan, age=3, color=black, sex=female]

	// Copy the specified properties
	Animal a3 = new Animal();
	BeanUtils.copyProperty(a3, "name", "yuanyuan");
	System.out.println(a3); // Animal [name=yuanyuan, age=0, color=null, sex=null]

	// Set the specified properties
	BeanUtils.setProperty(a3, "sex", "male");
	System.out.println(a3); // Animal [name=yuanyuan, age=0, color=null, sex=male]

	// Clone object
	Object object = BeanUtils.cloneBean(a3);
	System.out.println(object); // Animal [name=yuanyuan, age=0, color=null, sex=male]
}


ConvertUtils

The function of this tool class is to convert between a string and an instance of a specified type. In fact, BeanUtils is dependent ConvertUtils To complete the type conversion, but sometimes we may need a custom converter to complete the type conversion for special needs;

Main methods:

convert(Object value, Class<?> targetType)

Converts a given value to a specified Class type

// Converting integers to strings
Object object = ConvertUtils.convert(123, String.class);
String typeName = object.getClass().getTypeName();
System.out.println(typeName);

// Converting a date to a string
Object object2 = ConvertUtils.convert(new Date(), String.class);
String typeName2 = object2.getClass().getTypeName();
System.out.println(typeName2);

// Converting strings to Double
Object object3 = ConvertUtils.convert("123", Double.class);
String typeName3 = object3.getClass().getTypeName();
System.out.println(typeName3);


Custom type conversion:

Customize Converter, Realize Converter Interface, Rewrite Converter Method

class MyConverter implements Converter {
	private static SimpleDateFormat format;

	public MyConverter(String pattern) {
		format = new SimpleDateFormat(pattern);
	}

	@Override
	public Object convert(Class type, Object value) {
		if (value == null) {
			return null;
		}

		if (value instanceof String) {
			String tmp = (String) value;
			if (tmp.trim().length() == 0) {
				return null;
			} else {
				try {
					return format.parse(tmp);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		} else {
			throw new ConversionException("not String");
		}
		return value;
	}
}

Use:

MyConverter converter = new MyConverter("yyyy-MM-dd HH:mm:ss");
// Register the converter
ConvertUtils.register(converter, Date.class);
Object object3 = ConvertUtils.convert("2017-11-29 14:04:00", Date.class);
System.out.println(object3.getClass().getTypeName());
System.out.println(object3);

// When BeanUtils sets properties, type conversion is automatically performed
MyConverter converter = new MyConverter("yyyy-MM-dd HH:mm:ss");
// Register the converter
ConvertUtils.register(converter, Date.class);
Animal a5 = new Animal();
BeanUtils.copyProperty(a5, "birth", "2017-11-29 14:04:00");
System.out.println(a5);// Animal [name=null, age=0, color=null, sex=null, birth=Wed Nov 29 14:04:00 CST 2017]

PropertyUtils

BeanUtils and Property Utils have almost the same functions, the only difference is that BeanUtils assigns beans by type conversion.

For example, in copyProperty, BeanUtils can copy as long as the attribute name is the same, even if the type is different, and Property Beans may report errors!! Of course, the type of the same-name attribute between two beans must be convertible, otherwise the same error will be reported with BeanUtils. If the org.apache.commons.beanutils.Converter interface is implemented, the transformation between types can be customized. Because there is no type conversion, the speed of using Property Utils will be greatly improved!


CollectionUtils

Using this tool class, we modify, query, filter and so on.

Collection Utils belongs to the commons-collections package

String[] arrA = new String[] { "1", "2", "3" };
String[] arrB = new String[] { "1", "a", "b" };
List<String> listA = Arrays.asList(arrA);
List<String> listB = Arrays.asList(arrB);

// Judging whether a set is empty
System.out.println(CollectionUtils.isEmpty(listA));// false
System.out.println(CollectionUtils.isEmpty(listB));// false

// Judging whether a set is not empty
System.out.println(CollectionUtils.isNotEmpty(listA));// true
System.out.println(CollectionUtils.isNotEmpty(listB));// true

// Comparison of Two Sets
System.out.println(CollectionUtils.isEqualCollection(listA, listB));// false

// Operations of collections
// Union and collection
System.out.println(CollectionUtils.union(listA, listB));// [1, a, 2, b, 3]
// intersect
System.out.println(CollectionUtils.intersection(listA, listB));// [1]
// Complement Set of Intersection
System.out.println(CollectionUtils.disjunction(listA, listB));// [a, 2, b, 3]
// Subtract from a set
System.out.println(CollectionUtils.subtract(listA, listB));// [2, 3]
System.out.println(CollectionUtils.subtract(listB, listA));// [a, b]

List<String> listC = new ArrayList<>();
listC.add("1");
listC.add("2");
listC.add("3");
String[] arrC = { "4", "5", "6" };
// Adding values to collections
CollectionUtils.addAll(listC, arrC);
System.out.println(listC);// [1, 2, 3, 4, 5, 6]

Remarks:

Imperfect collation, to be improved later

Posted by m00p4h on Sun, 16 Dec 2018 01:54:04 -0800