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 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.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

public class ReadBeanProperty {
    public static void main(String[] args) {
        Track track = new Track();
        track.setTitle("Till There Was You");

        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.example.commons.beanutils;

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 +
                '}';
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply