Java BeanUtils – Background (Data Type Conversions) ”; Previous Next Description Data type conversion is a process of changing value from one data type to another. In the previous chapters, dynamically accessed properties of data types are recognized and to achieve the type conversions, we can use Java casts. The BeanUtils package gives various types of APIs and design patterns for performing the data type conversions. Print Page Previous Next Advertisements ”;
Category: java Beanutils
Background
Java BeanUtils – Background (DynaBeans) ”; Previous Next Description You can give dynamic property access on the existing JavaBean classes without altering with the help of PropertyUtils class. The dynamically calculated property values as JavaBean can also represented by using dynamic property access without writing a Java class to render these properties. This feature will not only save your time, but also allows dealing with cases where set of properties are specified dynamically. The DynaBean interface is produced by the BeanUtils package which implements the interface”s methods and DynaClass interface by defining set of properties which are supported by the group of DynaBeans. The java.lang.Class provides properties which are supported by JavaBean class instances. The below simple code snippet shows how to access the DynaBean properties: DynaBean car = …; // Details depend on which DynaBean implementation you use String companyName = (String) car.get(“companyName”); Model modelName = (Model) car.get(“model”); Object subordinate = car.get(“subordinate”, 2); The getter and setter methods of PropertyUtils property can be used to access the properties in DynaBeans. For instance, the PropertyUtils.getSimpleProperty() method is a DynaBean implementation which will convert to suitable DynaBean getter method clearly when you make the call. Therefore dynamic property access of an application is based on the PropertyUtils APIs and can be used to retrieve either JavaBeans or DynaBeans. Print Page Previous Next Advertisements ”;
Transforming Collections
Java BeanUtils – Transforming Collections ”; Previous Next Description The conversion from input object to output object is supported in commons-collections with the help of Transformer interface. The Transformers can be applied to get the output collection from input collection with the help of codes available in Commons-collections. BeanToPropertyTransformer is an example of Transformer that will convert a bean to its property value. This feature is able to extract a particular property from the input object and present it as output object. If you try to find out a particular car model from many car users in a collection. The syntax is shown below: // creating transformer BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( “person.company.carmodel” ); // transforming Collection Collection carModel = CollectionUtils.collect( peopleCollection, transformer ); Print Page Previous Next Advertisements ”;
WrapDynaBean
Java BeanUtils – WrapDynaBean ”; Previous Next Description As we have seen in the previous chapters, DynaBeans APIs provides get() and set() methods to access simple, indexed and mapped properties of DynaBeans dynamically. Instead of this, you can use the existing standard JavaBeans classes to access all beans by using the WrapDynaBean and WrapDynaClass. As the name itself indicates WrapDynaBean class is used to wrap the DynaBean APIs throughout the existing JavaBean class. To make use of the WrapDynaBean class, create the wrapper as shown in the below simple code: BeanDemo bean = …; DynaBean wrapper = new WrapDynaBean(bean); String yourName = wrapper.get(“yourName”); Print Page Previous Next Advertisements ”;
Customizing Introspection
Java BeanUtils – Customizing Introspection ”; Previous Next Description The introspection tool can be used to learn about the properties and operations provided by your class. BeanUtils package is depending on JavaBeans specification that determines the available properties for a particular bean class. The introspection mechanism can be customized from version 1.9.0 onwards and enables an application to alter or extend the default discovery of bean properties. You can achieve this by using the BeanIntrospector interface. By implementing this interface, we are able to process a specific target class and create its equivalent PropertyDescriptor objects. By default, DefaultBeanIntrospector objects are used by BeanUtils for detecting properties that are matching with the JavaBeans specification. You can extend the default discovery mechanism by using the PropertyUtils.addBeanIntrospector(BeanIntrospector) method of PropertyUtils. This custom BeanIntrospector can be called in the time of introspection of a class and adds the detected properties to the final result. Print Page Previous Next Advertisements ”;
Java BeanUtils – Overview
Java BeanUtils – Overview ”; Previous Next Description 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. The package org.apache.commons.beanutils contains tool called introspection that facilitates the use of getting and setting property values on Java classes and display them in a visual manner in the development tools. JavaBeans Characteristics The below listed are important characteristics of JavaBeans which are useful in the development structure: The class should be public and gives a public constructor with no arguments. It allows tools and applications to create new instances of the bean dynamically, without knowing what type of Java class name will be used as shown below: String className = …; Class beanClass = Class.forName(className); Object beanInstance = beanClass.newInstance(); The constructor which does not have arguments whose bean”s behavior can be configured separately from its instantiation. This can be achieved by using properties of the bean and also used to modify its behavior or data which are displayed by the bean. The bean property contains setter and getter methods which are used to access the property values. The design pattern for these properties can be specified by using the set or get prefix for the property names along with the first character capitalized by using the JavaBeans specification. For instance, you can use setter and getter methods for the properties first_name and last_name as shown below: public class Employee { public Employee(); // Zero-arguments constructor public String getFirstName(); public void setFirstName(String first_name); public String getLastName(); public void setLastName(String last_name); public String getFullName(); } If there are getter and setter methods for the property names, then the getter should match the setter datatype. In JavaBean specification, you can have more than one setter with same name, but with different property types. There is no need to define the getter and setter methods for each property. In the above code, there is no setter method for fullName property and it is only a read only property. You can create a JavaBean where there is no match for naming pattern by using the getter and setter methods. The JavaBean support classes in the Java language and BeanUtils package to specify the property method names in the BeanInfo class along with the bean class. The JavaBeans specification provides design patterns for event listeners, combines JavaBeans into component hierarchies and other helpful features of the BeanUtils package. External Dependencies You can use the following external dependencies for the commons-beanutils package: Logging Package Collections Package Print Page Previous Next Advertisements ”;
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 ”;
ResultSetDynaClass
Java BeanUtils – ResultSetDynaClass ”; Previous Next Description The ResultSet can be wrapped in the DynaBeans by using the ResultSetDynaClass which renders the results of SQL query as series of DynaBeans. The most commonly used collection is java.sql.ResultSet which is returned when JDBC driver uses SQL SELECT statement. The each row of result set can be made visible by using the Commons BeanUtils package. You can make use of the ResultSetDynaClass by using the DynaBean interface as shown in the below code snippet: Connection conn = …; Statement stmt = conn.createStatement(); ResultSet res_set = stmt.executeQuery(“select first_name, last_name from student”); Iterator rows = (new ResultSetDynaClass(res_set)).iterator(); while (rows.hasNext()) { DynaBean row = (DynaBean) rows.next(); System.out.println(“First Name is:” + row.get(“first_name”) + ” and Last Name is:” + row.get(“last_name”)); } rs.close(); stmt.close(); Print Page Previous Next Advertisements ”;
Background
Java BeanUtils – Background ”; Previous Next Description The standard JavaBeans of Java language can be used to access the property values of beans using the proper getter methods. The Java language supplies the java.beans.Introspector class to inspect a Java class at runtime. This indicates the property names of getter and setter methods along with the Reflection abilities to call such methods dynamically. You can make use of getting and setting bean properties dynamically by using the API”s in the BeanUtils package. The JavaBean property types are divided into three types (Some property types are supported by the JavaBeans specification and some are supported by the BeanUtils package): Simple: The simple properties contain single value which can be retrieved or altered. You can use property type like Java language primitive such as int, a simple object such as java.lang.String, or complex object which is specified either by using the Java language, an application, or a class library with the application. Indexed: An ordered collection of objects can be stored in the indexed property which can be accessed individually by using an integer-valued, non-negative index or subscript. The BeanUtils package includes datatype called java.util.List must be indexed in the JavaBeans specification. Mapped: The BeanUtils package contains datatype called java.util.Map which should be mapped in the standard JavaBeans APIs and the individual values can be set and accessed by using a String-valued key. You can get and set the property values for the datatypes by using the API methods specified in the PropertyUtils class. Consider the below code snippet of two bean classes defined with getter and setter methods: public class Employee { public FullName getFullName(); public void setFullName(String type, FullName fullname); public Employee getSubordinate(int index); public void setSubordinate(int index, Employee subordinate); public String getFirstName(); public void setFirstName(String first_name); public String getLastName(); public void setLastName(String last_name); } Print Page Previous Next Advertisements ”;