java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to read bean's nested property value?

In this example you'll see how to read bean's nested property, we'll use PropertyUtils.getNestedProperty() method. Here we will create three classes, Track, Artist and ReadNestedProperty.

Here our Track class contains an Artist class. Using the mentioned method we want to get the artist name that sing the track. Where reading nested property using PropertyUtils.getNestedProperty() it can read nested level in no limit.

package com.javacoderanch.example.commons.beanutils;

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;

public class ReadNestedProperty {
    public static void main(String[] args) {
        Track track = new Track();
        track.setId(1);
        track.setTitle("All My Loving");
        
        Artist artist = new Artist();
        artist.setId(1);
        artist.setName("Beatles");
        
        track.setArtist(artist);
        
        try {
            String artistName = (String) PropertyUtils.getNestedProperty(track, "artist.name");
            System.out.println("Artist Name = " + artistName);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

package com.javacoderanch.example.commons.beanutils;

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

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

    public Artist getArtist() {
        return artist;
    }

    public void setArtist(Artist artist) {
        this.artist = artist;
    }    
}

package com.javacoderanch.example.commons.beanutils;

public class Artist {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }        
}