BeanUtils and ConvertUtils

Java BeanUtils – BeanUtils and ConvertUtils ”; Previous Next Description The BeanUtils is defined as a utility method for populating JavaBeans properties and ConvertUtils method converts string scalar values to objects, string arrays to arrays of the specified class. BeanUtils The BeanUtils accepts string values by using the setter methods and automatically converts them to suitable property types for Java primitives and uses the getter methods for reverse conversion. The populate() method accepts set of property values from java.util.HashMap and uses the suitable setters whenever bean contain the property with the same name. Example The below example shows usage of BeanUtils properties: import java.util.HashMap; import org.apache.commons.beanutils.BeanUtils; public class Test { @SuppressWarnings(“unchecked”) public static void main(String[] args){ @SuppressWarnings(“rawtypes”) HashMap map = new HashMap(); map.put(“username”,”admin”); map.put(“password”,”secret”); map.put(“age”,”52″); User bean = new User(); try{ BeanUtils.populate(bean,map); }catch(Exception e){ e.printStackTrace(); } System.out.println(“Username: “+bean.getUsername()); System.out.println(“Password: “+bean.getPassword()); System.out.println(“Age: “+bean.getAge()); } } Now we will create another class called User.java as shown below: public class User { private String username; private String password; private String age; public String getUsername(){ return username; } public void setUsername(String username){ this.username = username; } public String getPassword() { return password; } public void setPassword(String password){ this.password = password; } public String getAge() { return age; } public void setAge(String age){ this.age = age; } } Output Let”s carry out the following steps to see how above code works: Save the above first code as Test.java. Now execute the code using Run option or Ctrl+f11 and output as below gets displayed. ConvertUtils The Apache Commons BeanUtils is a library that comes with a number of converters to convert to and from different data types and also contain ConvertUtils utility class which makes use of these converters. Example The below example shows the conversion of string array to a double array using ConvertUtils utility: package com.javadb; import org.apache.commons.beanutils.ConvertUtils; public class ConvertStringArrayToDoubleArray { public static void main(String[] args) { String values[] = { “5”, “6”, “3” }; double[] doubleValues = (double[])ConvertUtils.convert(values, Double.TYPE); for (double d : doubleValues) { System.out.println(d); } } } Output Save the above first code as ConvertStringArrayToDoubleArray.java. Now execute the code using Run option or Ctrl+f11 and output as below gets displayed. Print Page Previous Next Advertisements ”;

RowSetDynaClass

Java BeanUtils – RowSetDynaClass ”; Previous Next Description The RowSetDynaClass copies the undisclosed data in the DynaBeans memory while creating an instance which displays the result and using this class, you can close the ResultSet data before proceeding the actual data that was returned. The drawback of this class is, you need to pay for the memory cost for copying the result data. It is more useful in the web application process. The main features of RowSetDynaClass are: It can be used to implement the java.io.Serializable (Serializable is an interface that does not contain any specific methods) to make classes serialized and deserialized. You can transfer the results of SQL query to remote Java based client application such as applet by using this class. The usage pattern of RowSetDynaClass will look like as shown below: Connection cn = …; // Obtain the connection Statement st = cn.createStatement(); ResultSet rs = st.executeQuery(“SELECT …”); RowSetDynaClass dc = new RowSetDynaClass(rs); rs.close(); st.close(); …; // Returns the connection List rows = dc.getRows(); …; // Processes the rows as desired Print Page Previous Next Advertisements ”;

Java BeanUtils – Home

Java BeanUtils Tutorial Job Search The Java BeanUtils are the components of the Apache Commons which are derived from JavaAPI and provides component architecture for the Java language. The Java BeanUtils design patterns uses utility classes that helps to get and set the property values on Java classes for retrieving and defining the bean properties. This tutorial covers most of the topics required for a basic understanding of Java BeanUtils and to get a feel of how it works. Audience This tutorial has been prepared for the beginners to help them understand the basic to advanced concepts related to Java BeanUtils. Prerequisites Before you start practicing various types of examples given in this reference, we assume that you are already aware about computer programs and computer programming languages. Print Page Previous Next Advertisements ”;

Operating On Collections

Java BeanUtils – Operating On Collections ”; Previous Next Description The Commons-Collections are build upon interfaces, implementations and utilities. It contains Closure interface in the code that can be applied on the arbitrary input object and code permits to apply Closures to contents of collection. There is Closure called BeanPropertyValueChangeClosure sets specified property to specified value. This value can be combined with commons-collections in which all the beans will have specified property to specified value in the collection. For instance, you can set the myCar property to TRUE for entire collection as shown below: //creating the closure BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure( “myCar”, Boolean.TRUE ); //updating the Collection CollectionUtils.forAllDo( myCollection, closure ); Print Page Previous Next Advertisements ”;

Utility Objects & Classes

Java BeanUtils – Utility Objects & Classes ”; Previous Next Description The utility classes such as BeanUtils, ConvertUtils and PropertyUtils can be accessed through utility objects and shares the same caches and registered converters. You can instantiate corresponding class with same functionality for each static utility class. Static utility classes are the classes having only static methods performing some operations on the objects that are passed as parameters. Typically such classes have no state. The following table shows the Static Utility Classes and Utility Objects: S.N. Static Utility Class Utility Object 1 BeanUtils BeanUtilsBean 2 ConvertUtils ConvertUtilsBean 3 PropertyUtils PropertyUtilsBean Print Page Previous Next Advertisements ”;

Locale Aware Conversions

Java BeanUtils – Locale Aware Conversions ”; Previous Next Description The regular classes available in org.apache.commons.beanutils are not assigned for any specific event. These classes provide a clear interface to make use of situations very easily where the locale is not main thing. You can use Locale-aware extensions of beanutils classes which helps localization, from the org.apache.commons.beanutils.locale package. Print Page Previous Next Advertisements ”;

Comparing Beans

Java BeanUtils – Comparing Beans ”; Previous Next Description In Apache Commons Beanutils, you can compare the JavaBean objects by using the BeanComparator class based on a specified shared property value. This can be done by using the org.apache.commons.beanutils.BeanComparator comparator. Example The below example shows how to compare the two different beans. We will be creating two objects and set the first object to “BMW” and the other object to “AUDI”. Then, we will compare the objects by using the BeanComparator by calling its compare() method. Note: For BeanComparator, commons-collection and commons-logging jar files need to be included. package com.javadb.apachecommons.beanutils; import org.apache.commons.beanutils.BeanComparator; public class BeanComparatorExample { public static void main(String[] args) { Car car1 = new Car(); car1.setBrand(“BMW”); Car car2 = new Car(); car2.setBrand(“AUDI”); BeanComparator comparator = new BeanComparator(“brand”); System.out.println(“The value after comparing two beans is: ” + comparator.compare(car1, car2)); } } Now we will create one more class with the below code and save it as Car.java. package com.javadb.apachecommons.beanutils; public class Car { private String brand; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } } Output Save the above first code as BeanComparatorExample.java. Now execute the code using Run option or Ctrl+f11 and output as below gets displayed. Print Page Previous Next Advertisements ”;

Basic DynaBeans

Java BeanUtils – Basic DynaBeans ”; Previous Next Description The implementation of BasicDynaBean and BasicDynaClass specifies the capacity of dynamic property to provide the set of properties dynamically. You can start with DynaClass to establish the set of properties. A newInstance() method will create a new DynaBean instances to DynaClass and occupy its initial values as shown in the below example. Example The below example shows usage of basic DynaBean implementation: package com.javadb.apachecommons; import org.apache.commons.beanutils.BasicDynaClass; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.DynaClass; import org.apache.commons.beanutils.DynaProperty; public class DynaBeanExample { private final String NR_OF_WHEELS = “numberOfWheels”; private void runExample() { DynaClass dynaClass = new BasicDynaClass(“Car”, null, new DynaProperty[] { new DynaProperty(NR_OF_WHEELS, Integer.TYPE) }); try { DynaBean car = dynaClass.newInstance(); car.set(NR_OF_WHEELS, 4); System.out.println(“Number of wheels: ” + car.get(NR_OF_WHEELS)); System.out.println(“DynaBean is instance of DynaClass: ” + car.getDynaClass().getName()); } catch (IllegalAccessException | InstantiationException ex) { System.err.println(ex.getMessage()); } } public static void main(String[] args) { DynaBeanExample ac = new DynaBeanExample(); ac.runExample(); } } Output Let”s carry out the following steps to see how above code works: Save the above first code as DynaBeanExample.java. Now execute the code using Run option or Ctrl+f11 and output as below gets displayed. Print Page Previous Next Advertisements ”;

Suppressing Properties

Java BeanUtils – Suppressing Properties ”; Previous Next Description You can suppress the specific properties by using the bean introspection mechanism. The specialized BeanIntrospector interface is implemented by the type called SuppressPropertiesBeanIntrospector which suppresses the special class properties of Java beans. The collection of property names need to be provided which are not accessible on the beans while creating an instance. If these properties are identified by the other BeanIntrospector, then they will be removed while bean class processing. You can use a special class property for suppressing the properties for all beans which is genearted from getClass() method and inherited from Object and uses naming pattern for property get methods. In most of situations, an instance of SuppressPropertiesBeanIntrospector can be used to suppress the specific properties and can be achieved by using the SUPPRESS_CLASS constant of SuppressPropertiesBeanIntrospector. Print Page Previous Next Advertisements ”;

Lazy DynaBeans

Java BeanUtils – Lazy DynaBeans ”; Previous Next Description Lazy DynaBeans is an implementation of DynaBean, which gives the characteristics of Lazy List and Lazy Map this connects the properties of DynaClass. There are four types of Lazy DynaBeans: LazyDynaBean: It specifies lazy DynaBean that provides dynamically modified properties of names and data types. LazyDynaMap: It gives light weight implementation of DynaBean to map by using lazy map or list system. LazyDynaList: It provides list for DynaBean, Map”s or POJOS (Plain Old Java Object that specifies the normal java class). LazyDynaClass: It implements the MutableDynaClass interface. The following are the features of Lazy DynaBeans: Lazy property addition: It is used by the Lazy beans to add property to DynaClass automatically when set method is called and it has capability to add or remove the DynaClass”s properties. Lazy List/Array growth: The Lazy list or array will grow automatically when an indexed property is not able to accommodate the index being set. Lazy List/Array instantiation: The indexed property getter and setter methods of DynaBean”s results in lazy list or array instantiation, if there is no existence of an indexed property. If an indexed property is not defined, then it will be added automatically to DynaClass and default List implementation instantiated. Lazy Map instantiation: The mapped property getter and setter methods of DynaBean”s results in lazy map instantiation, if there is no existence of mapped property. If mapped property is not defined, then it will be added automatically to DynaClass and default Map implementation instantiated. Lazy Bean instantiation: The LazyDynaBean will instantiates the bean using a default empty constructor, if DynaClass property is defined as DynaBean or regular bean and does not exist in the DynaBean. LazyDynaBean It is implementation of standard lazy bean which specifies the lazy DynaBean that provides dynamically modified properties of names and data types. It implements the MutableDynaClass interface by associating with the LazyDynaClass. The below simple code shows usage of LazyDynaBean by using getters or setters: DynaBean dynaBean = new LazyDynaBean(); dynaBean.set(“company”, “Model”); // simple dynaBean.set(“customer”, “fname”, “Steve”); // mapped dynaBean.set(“customer”, “lname”, “Smith”); // mapped dynaBean.set(“address”, 0, addressLine1); // indexed dynaBean.set(“address”, 1, addressLine2); // indexed LazyDynaMap It gives light weight implementation of DynaBean to map by using lazy map or list system and it does not associates with properties of DynaClass. It itself implements the DynaClass interface and obtain the information of DynaClass from the map contents. LazyDynaMap creates its own Map by instantiating it or can be generated around an existing Map. The below code shows creation of new map: DynaBean dynaBean = new LazyDynaBean(); DynaBean dynaBean = new LazyDynaMap(); // create DynaBean dynaBean.set(“company”, “Model”); // simple dynaBean.set(“customer”, “fname”, “Steve”); // mapped dynaBean.set(“address”, 0, addressLine1); // indexed Map demoMap = dynaBean.getMap() // retrieve the Map The below code shows use of existing Map in DynaBean: Map demoMap = …. // exisitng Map DynaBean dynaBean = new LazyDynaMap(demoMap); // wrap Map in DynaBean dynaBean.set(“ford”, “raptor”); // set properties LazyDynaList It provides list for DynaBean, Map”s or POJOS (Plain Old Java Object that specifies the normal java class). There are two main points of this class: It automatically grows and occupies the list with DynaBean, java.util.Map or POJOS to specify the Lazy List behavior. It provides easy way to put a Collection or Array into Lazy list and easy way to come out from the Lazy List. LazyDynaClass It implements the MutableDynaClass interface and extends the BasicDynaClass. It can be used as default DynaClass by LazyDynaBean and with other DynaBean implementations. There is nothing to with the DynaClass when you are using the LazyDynaBean. The below code creates the LazyDynaClass: MutableDynaClass dynaClass = new LazyDynaClass(); // create DynaClass dynaClass.add(“price”, java.lang.Integer.class); // add property dynaClass.add(“orders”, OrderBean[].class); // add indexed property dynaClass.add(“orders”, java.util.TreeMapp.class); // add mapped property DynaBean dynaBean = new LazyDynaBean(dynaClass); // Create DynaBean with associated DynaClass The below code creates the LazyDynaBean and get the DynaClass: DynaBean dynaBean = new LazyDynaBean(); // Create LazyDynaBean MutableDynaClass dynaClass = (MutableDynaClass)dynaBean.getDynaClass(); // get DynaClass dynaClass.add(“price”, java.lang.Integer.class); // add property dynaClass.add(“exBeans”, myPackage.MyBean[].class); // add ”array” indexed property dynaClass.add(“exMap”, java.util.TreeMapp.class); // add mapped property Print Page Previous Next Advertisements ”;