How do I read bean's nested property value?

Category: commons.beanutils, viewed: 3188 time(s).

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 org.kodejava.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 org.kodejava.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 org.kodejava.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;
    }        
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats