java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to read bean's property value?

In this example we'll learn how to use PropertyUtils.getSimpleProperty() to read a value of bean property. We'll create a Track class and this will be our bean. The PropertyUtils.getSimpleProperty() reads our bean property by accessing the bean getter methods. In this example we'll read the track title.

package com.javacoderanch.example.commons.beanutils;

import java.lang.reflect.InvocationTargetException;
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("Title = " + title);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }    
}

package com.javacoderanch.example.commons.lang;

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

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

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