How do I read bean’s property value?

In this example we will learn how to use PropertyUtils.getSimpleProperty() method to read bean’s property value. To test this method we will create a simple class called Track for our bean. The Track class have some properties such as id, title and duration.

The PropertyUtils.getSimpleProperty() reads our bean property by accessing the bean’s getter method. The method takes two parameters. The first parameter is the bean and the second parameter is the bean’s property name. It returns a java.lang.Object as a result, that means we have to cast it to the desired type.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;

public class ReadBeanProperty {
    public static void main(String[] args) {
        Track track = new Track();
        track.setTitle("Here Comes The Sun");

        try {
            String title = (String) PropertyUtils.getSimpleProperty(track, "title");
            System.out.println("Track title = " + title);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And here is the Track class.

package org.kodejava.commons.beanutils.support;

public class Track {
    private Long id;
    private String title;
    private Integer duration;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getDuration() {
        return duration;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    @Override
    public String toString() {
        return "Track{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", duration=" + duration +
                '}';
    }
}

Maven Dependencies

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

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.