How do I read indexed bean’s property value?

In this example you’ll see how to read an indexed property of an object such as List or array. Using the PropertyUtils.getIndexedProperty() method we can do it easily. This method take the bean and the name of indexed property including the element to be read. Let’s see the example below for more details.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

import java.util.ArrayList;
import java.util.List;

public class ReadIndexedProperty {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("With The Beatles");

        List tracks = new ArrayList<>();
        Track track1 = new Track();
        track1.setTitle("It Won't Be Long");

        Track track2 = new Track();
        track2.setTitle("All I've Got To Do");

        Track track3 = new Track();
        track3.setTitle("All My Loving");

        tracks.add(track1);
        tracks.add(track2);
        tracks.add(track3);

        recording.setTracks(tracks);

        try {
            Track trackOne = (Track) PropertyUtils.getIndexedProperty(recording, "tracks[0]");
            Track trackThree = (Track) PropertyUtils.getIndexedProperty(recording, "tracks[2]");

            System.out.println("trackOne.getTitle() = " + trackOne.getTitle());
            System.out.println("trackThree.getTitle() = " + trackThree.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.example.commons.beanutils;

import java.util.ArrayList;
import java.util.List;

public class Recording {
    private Long id;
    private String title;
    private List tracks = new ArrayList<>();

    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 List getTracks() {
        return tracks;
    }

    public void setTracks(List tracks) {
        this.tracks = tracks;
    }
}

Our program results are:

trackOne.getTitle() = It Won't Be Long
trackThree.getTitle() = All My Loving

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia 🇮🇩. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply