org.apache.commons.beanutils.converters.ArrayConverter Example

0

In this article, I am going to show you multiple examples of ArrayConverter. Before we start with the examples, let me first brief you about Apache Commons BeanUtils that ArrayConverter belongs to and how ArrayConverter contributes to it.
Apache Commons BeanUtils offer low-level utility classes that assist in getting and setting property values on Java classes that follow the naming standards as per JavaBeans Specification. For example, to set employee’s name we call:

empBean.setName("Foo");

If you don’t have access to the empBean type, you will have to rely on low-level reflection package to deal with JavaBeans. Instead of that, we can use Jakarta Commons BeanUtils package as it is just a metadata wrapper that make it easy to work with JavaBeans.

For example, setting the employee name BeanUtils way would be:

BeanUtils.setProperty(empBean, "name", "Foo");

One of the important aspect of BeanUtils package is the use of Converters which manage the conversion of objects from one type to another and from a specified type to a String value.
ArrayConverter is one of the sub-class of Converter that handles conversion to and from array objects. It was introduced in Apache Commons BeanUtils 1.8. The current example is based on Apache Commons BeanUtils 1.9.

To compile and run the examples, you need to add the following jars to the classpath. You can download these jars from Apache Commons website.

  1. commons-beanutils.jar (contains ArrayConverter)
  2. commons-collections.jar (dependency)
  3. commons-logging.jar (dependency)

1. Convert string value into a string array

Below example converts string “Foo,Bar” to a string array. We pass three different combinations of Foo, Bar. The first one is comma separated “Foo,Bar”. The second one has curly braces around Foo,Bar. Note that the converter ignores the curly braces and the converts the string value. The third one has ‘_’ (underscore) between Foo and Bar. Underscore will be treated as delimiter so the converted values will again be “Foo” and “Bar”.  Suppose we want the converter to treat underscore as part of the word, we need to explicitly set the allowed chars. After setting, there will be only one converted value “Foo_Bar”.

StringArrayConverter:

package javarticles.arrayconverter;

import java.util.Arrays;

import org.apache.commons.beanutils.converters.ArrayConverter;
import org.apache.commons.beanutils.converters.StringConverter;

public class StringArrayConverter {
	public static void main(String[] args) {
		String valueString = "Foo,Bar";
		ArrayConverter arrayConverter = new ArrayConverter(String[].class, new StringConverter());
		String[] valueArray = arrayConverter.convert(String[].class, valueString);
		print(valueString, valueArray);
		
		valueString = "{Foo,Bar}";
		valueArray = arrayConverter.convert(String[].class, valueString);
		print(valueString, valueArray);
		
		valueString = "Foo_Bar";
		valueArray = arrayConverter.convert(String[].class, valueString);
		print(valueString, valueArray);
		
		arrayConverter.setAllowedChars(new char[]{'_'});
		valueArray = arrayConverter.convert(String[].class, valueString);
		print(valueString, valueArray);
	}
	
	private static void print(String valueString, String[] valueArray) {
		System.out.println("Converted " + valueString + " to array: " + Arrays.asList(valueArray));
	}
}

Output:

Converted Foo,Bar to array: [Foo, Bar]
Converted {Foo,Bar} to array: [Foo, Bar]
Converted Foo_Bar to array: [Foo, Bar]
Converted Foo_Bar to array: [Foo_Bar]

2. Convert string into an Integer array

Let’s now try to convert a comma separated integer string value “1,2” into an Integer array.

IntegerArrayConverter:

package javarticles.arrayconverter;

import java.util.Arrays;

import org.apache.commons.beanutils.converters.ArrayConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;

public class IntegerArrayConverter {
	public static void main(String[] args) {
		String valueString = "1,2";
		ArrayConverter arrayConverter = new ArrayConverter(Integer[].class, new IntegerConverter());
		Integer[] valueArray = arrayConverter.convert(Integer[].class, valueString);
		print(valueString, valueArray);
	}
	
	private static void print(String valueString, Integer[] valueArray) {
		System.out.println("Converted " + valueString + " to array: " + Arrays.asList(valueArray));
	}
}

Output:

Converted 1,2 to array: [1, 2]

3. Convert integer array to String

In this example, I am going to convert an integer array {1, 2} into string “1, 2”. By default, only the first element of integer array will be converted so if don’t configure our converted, th econverted value would be just “1”. If we want all the elements to be converted, joined by delimiter, we should explicitly configure our converter by calling

converter.setOnlyFirstToString(false)

.

package javarticles.arrayconverter;

import org.apache.commons.beanutils.converters.ArrayConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;

public class IntegerArrayToStringConverter {
	public static void main(String[] args) {
		int[] values = new int[]{1, 2};
		ArrayConverter arrayConverter = new ArrayConverter(Integer[].class, new IntegerConverter());
		String value = arrayConverter.convert(String.class, values);
		System.out.println("By default only the first element is converted. Converted value is " + value);
		
		arrayConverter.setOnlyFirstToString(false);
		value = arrayConverter.convert(String.class, values);
		System.out.println("setOnlyFirstToString is set to false. Converted value is " + value);
	}	
}

Output:

By default only the first element is converted. Converted value is 1
setOnlyFirstToString is set to false. Converted value is 1,2

4. Custom array converter

In this example, I will show you a custom converter which converts a comma separated employee names into an array of Employee beans.

Employee:

package javarticles.arrayconverter;

public class Employee {
	private String name;
	public Employee(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	
	public String toString() {
		return "Employee Bean: " + name;
	}	
}

Employee Converter that converts an employee name to an Employee bean.

EmployeeConverter:

package javarticles.arrayconverter;

import org.apache.commons.beanutils.converters.AbstractConverter;

public class EmployeeConverter extends AbstractConverter {

	@Override
	protected Class<?> getDefaultType() {
		return Employee.class;
	}

	@Override
	protected  T convertToType(Class type, Object value)
			throws Throwable {
		if (Employee.class.equals(type)) {
            return type.cast(new Employee(value.toString()));
        }

        throw conversionException(type, value);
	}
}

In the below class, I create an ArrayConverter object based on EmployeeConverter. It converts “Foo,Bar” into array of Employee beans. After conversion, we get two Employee beans. First employee’s name is ‘Foo’ and the second ones name is ‘Bar’.

EmployeeStringToArrayConverter:

package javarticles.arrayconverter;

import java.util.Arrays;

import org.apache.commons.beanutils.converters.ArrayConverter;

public class EmployeeStringToArrayConverter {
	public static void main(String[] args) {
		String valueString = "Foo,Bar";
		ArrayConverter arrayConverter = new ArrayConverter(String[].class, new EmployeeConverter());
		Employee[] valueArray = arrayConverter.convert(Employee[].class, valueString);
		print(valueString, valueArray);
	}
	
	private static void print(String valueString, Employee[] valueArray) {
		System.out.println("Converted " + valueString + " to array: " + Arrays.asList(valueArray));
	}	
}

Output:

Converted Foo,Bar to array: [Employee Bean: Foo, Employee Bean: Bar]

Download Source Code

In this article, I showed you examples of ArrayConverter. You can download the source code here: arrayconverter.zip

Share.

Leave A Reply