Tuesday, July 27, 2021

Java PropertyUtils Example - getting and setting properties by name

PropertyUtils class of Apache commons beanutils library is very useful and provides you the ability to modify properties of Java object at runtime. PropertyUtils enables you to write highly configurable code where you can provide the name of bean properties and their values from configuration rather than coding in Java program and Apache PropertyUtils can set those properties on Java object at runtime. One popular example of how powerful PropertyUtils can be is display tag which provides a rich tabular display for JSP pages, it uses PropertyUtils class to get values of an object at runtime and then display it.


You can set up properties as columns and only selected columns will be displayed. Even larger web framework like Struts and Spring also uses Apache commons beanutils library for getting and setting java properties by name.

PropertyUtils is based on Java reflection but provides a convenient method to operate on Java object at runtime. By using PropertyUtils you can get a map of all Object properties which enables you to change them at runtime by values coming from all the places like web request, database or configuration files. In this Java tutorial we will example of how to get and set properties of java object using PropertyUtils class at runtime.

This article is in continuation of my earlier post on open source library like How to limit number of user session in web application using Spring Security and How to perform LDAP authentication on windows Active directory using Spring Security. If you haven’t read them already you may find them useful and interesting.




Java Program to get object properties at runtime

How to change properties of object at runtime PropertyUtils Apache commons ExampleHere is a simple Java program which shows how to use PropertyUtils class to change object properties or to get Object and its properties at runtime. Remember we don’t know anything about Object at compile time. On runtime Object is provided to the program along with the name of the property to retrieve or modify:

import org.apache.commons.beanutils.PropertyUtils;

public class PropertyUtilsTest {

    public static void main(String args[]) {

        try{
        MobilePhone flexiColor = new MobilePhone();
        //here color and blue strings can come from variety or sources
        //e.g. configuration files, database, any upstream system or via HTTP Request
        PropertyUtils.setProperty(flexiColor, "color", "blue");
        String value = (String) PropertyUtils.getProperty(flexiColor, "color");
        System.out.println("PropertyUtils Example property value: " + value);
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static class MobilePhone {

        private String brand;
        private String color;

        public String getBrand() {
            return brand;
        }

        public void setBrand(String brand) {
            this.brand = brand;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }
}

Output:
PropertyUtils Example property value: blue


Benefits of using Apache commons PropertyUtils:

PropertyUtils provides lot of flexibility while writing program though that comes with the cost of reflection; here are some of the important benefits of using Apache commons PropertyUtils I can think of:

1) You can get any property value at runtime without having coded for it e.g. bean.getOrder() can be replaced by
PropertyUtils.getProperty(bean, order) where bean and order are runtime value and can change.

2) Similarly, you can set any object property at runtime e.g. bean.setOrder(order) can be replaced by

PropertyUtils.setProperty(bean, order, new Order())

3) Apache beanUtils enables you to write highly configurable code.

Errors and Exception while using PropertyUtils

If you try to set a property and getting "Exception in thread "main" java.lang.NoSuchMethodException: Property 'color' has no setter method" like below:

Exception in thread "main" java.lang.NoSuchMethodException: Property 'color' has no setter method at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1746) 
at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)


There could be different reasons for these exceptions e.g.

1) Bean class whose property you are setting is not public. Yes, you get this Exception even if the class is accessible like Inner class but not public rather it’s private, default or protected.

2) There is no setter method for that property.

3) The setter method for that property is private.

You will also get "java.lang.IllegalArgumentException: argument type mismatch" like below if you are passing incorrect type for argument or your argument type is not convertible on what method is expecting e.g. if a property is of type int and you are passing String.

java.lang.IllegalArgumentException: argument type mismatch
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)


Dependency:
commons-beanutils.jar
commons-logging.jar
commons-collections.jar

In order to use PropertyUtils class, you need to include commons-beanutils.jar in your Java Classpath. and since commons-beanutils.jar also has a dependency on commons-logging.jar you need to include that as well. If you are using Maven for building your project or maintaining dependency you can include the following dependency.

Maven dependency for apache commons beanutils


<dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.8.2</version>
</dependency>



That’s all on How to use PropertyUtils from Apache commons-beanutils.jar to get and set object properties at runtime.  Apart from PropertyUtils beanutils also contains several other utilities for dealing with beans in Java applications.


Other Java Programming tutorials you may like


Reference
http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/PropertyUtils.html

1 comment :

serid said...

Very nice article but I would also include a case for different class loaders - in that case it will throw a java.lang.IllegalArgumentException: argument type mismatch no matter whether the argument is of correct type or not .... wasted few hours on that as it becomes even more difficult to detect in case of web applications.

Adrian

Post a Comment