How do I set mapped property value of a bean?

This example demonstrate how to use PropertyUtils.setMappedProperty() method to modify a Map typed property value of a bean. To set the property we need to pass bean instance, property name, map key and map value to PropertyUtils.setMappedProperty() method.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;
import org.kodejava.commons.beanutils.support.Record;

import java.util.HashMap;
import java.util.Map;

public class PropertySetMappedExample {

    public static void main(String[] args) {
        // Create an instance of Recording bean.
        Record record = new Record();
        record.setId(1L);
        record.setTitle("Introduction");

        // Create a map to hold record tracks.
        Map<String, Track> tracks = new HashMap<>();
        tracks.put("track-one", new Track());
        tracks.put("track-two", new Track());
        tracks.put("track-three", new Track());
        record.setMapTracks(tracks);

        try {
            // We add another tracks to the record track using
            // a PropertyUtils.setMappedProperty() method.
            PropertyUtils.setMappedProperty(record,
                    "mapTracks", "track-four", new Track());
            PropertyUtils.setMappedProperty(record,
                    "mapTracks", "track-five", new Track());
        } catch (Exception e) {
            e.printStackTrace();
        }

        tracks = record.getMapTracks();
        System.out.println("New Track Numbers: " + tracks.size());
        for (String key : tracks.keySet()) {
            System.out.println(key + " = " + tracks.get(key));
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I set indexed property value of a bean?

In this example we show how to set the value of an indexed property. In the code below we modified the value of an array type. We’ll change the second colors of MyBean‘s colors property.

We do it in the same way as we are using the PropertyUtils.setSimpleProperty method. For indexed property we use the PropertyUtils.setIndexedProperty method and passes four arguments, they are the instance of bean to be manipulated, the indexed property name, the index to be changes and finally the new value.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.MyBean;

import java.util.Arrays;

public class PropertySetIndexedExample {
    public static void main(String[] args) {
        String[] colors = new String[]{"red", "green", "blue"};

        MyBean myBean = new MyBean();
        myBean.setColors(colors);
        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));

        try {
            PropertyUtils.setIndexedProperty(myBean, "colors", 1, "orange");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));
    }
}
package org.kodejava.commons.beanutils.support;

public class MyBean {
    private String[] colors;

    public void setColors(String[] colors) {
        this.colors = colors;
    }

    public String[] getColors() {
        return colors;
    }
}

The output of this code is:

Colors = [red, green, blue]
Colors = [red, orange, blue]

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I set property value of a bean?

The Commons BeanUtils component provides a class called PropertyUtils that supplies method for manipulating a bean such as our Track class below. For this demo we use a Track class that have a property called id, title and duration.

To set the value of a bean we can use the PropertyUtils.setProperty() method. This method ask for the bean instance whose property value to be set, the property name and the value.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;

public class PropertySetExample {
    public static void main(String[] args) {
        Track track = new Track();
        try {
            PropertyUtils.setProperty(track, "id", 10L);
            PropertyUtils.setProperty(track, "title", "Hey Jude");
            PropertyUtils.setProperty(track, "duration", 180);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Track = " + track);
    }
}
package org.kodejava.commons.beanutils.support;

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

Some exceptions could be thrown by this method, so we need to handle the IllegalAccessException, InvocationAccessException and NoSuchMethodException. To make the code simple we will just catch it as java.lang.Exception.

These exceptions could happen if we don’t have access to the property, or the bean’s accessor throws an exception or if the method we tried to manipulate doesn’t exist.

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I determine bean’s property type?

Using the PropertyUtils.getPropertyType() we can determine the bean property type. This method return a Class object of bean’s property type.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Record;

public class PropertyType {
    public static void main(String[] args) {
        Record record = new Record();
        record.setTitle("Magical Mystery Tour");

        try {
            /*
             * Using PropertyUtils.getPropertyType() to determine the type of
             * title property.
             */
            Class<?> type = PropertyUtils.getPropertyType(record, "title");
            System.out.println("type = " + type.getName());

            String value = (String) PropertyUtils.getProperty(record, "title");
            System.out.println("value = " + value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.commons.beanutils.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Record {
    private Long id;
    private String title;
    private List<Track> tracks = new ArrayList<>();
    private Map<String, Track> mapTracks = new HashMap<>();

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

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

    public void setMapTracks(Map<String, Track> mapTracks) {
        this.mapTracks = mapTracks;
    }

    public Map<String, Track> getMapTracks() {
        return mapTracks;
    }
}

The output of the code snippet above:

type = java.lang.String
value = Magical Mystery Tour

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I read mapped bean’s property value?

In this example you’ll see how to read mapped property value of a bean. We use PropertyUtils.getMappedProperty() method the read the mapped property of the Record object that consist of Track objects.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;
import org.kodejava.commons.beanutils.support.Record;

import java.util.HashMap;
import java.util.Map;

public class ReadMapProperty {
    public static void main(String[] args) {
        Record record = new Record();
        record.setTitle("Abbey Road");

        Track track1 = new Track();
        track1.setTitle("Come Together");

        Track track2 = new Track();
        track2.setTitle("Something");

        Map<String, Track> tracks = new HashMap<>();
        tracks.put("1", track1);
        tracks.put("2", track2);

        record.setMapTracks(tracks);

        try {
            Track track = (Track) PropertyUtils.getMappedProperty(record, "mapTracks(1)");
            System.out.println("track.getTitle() = " + track.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.commons.beanutils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Record {
    private Long id;
    private String title;
    private List<Track> tracks = new ArrayList<>();
    private Map<String, Track> mapTracks = new HashMap<>();

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

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

    public void setMapTracks(Map<String, Track> mapTracks) {
        this.mapTracks = mapTracks;
    }

    public Map<String, Track> getMapTracks() {
        return mapTracks;
    }
}

And here is the result of our program.

track.getTitle() = Come Together

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

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

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;
import org.kodejava.commons.beanutils.support.Record;

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

public class ReadIndexedProperty {
    public static void main(String[] args) {
        Record record = new Record();
        record.setId(1L);
        record.setTitle("Sgt. Pepper's Lonely Hearts Club Band");

        List<Track> tracks = new ArrayList<>();
        Track track1 = new Track();
        track1.setTitle("Sgt. Pepper's Lonely Hearts Club Band");

        Track track2 = new Track();
        track2.setTitle("With A Little Help From My Friends");

        Track track3 = new Track();
        track3.setTitle("Lucy In The Sky With Diamonds");

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

        record.setTracks(tracks);

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

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

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

public class Record {
    private Long id;
    private String title;
    private List<Track> 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<Track> getTracks() {
        return tracks;
    }

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

Our program results are:

trackOne.getTitle() = Sgt. Pepper's Lonely Hearts Club Band
trackThree.getTitle() = Lucy In The Sky With Diamonds

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I 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. To test we will create three classes, Track and Artist for our beans and ReadNestedProperty as a main program to run.

The Track class will contain a property of an Artist object. Using the PropertyUtils.getNestedProperty() method we want to get the artist name that sings the track. This method will first read the artist property from the track object and then read the name property of the artist object.

Reading nested property using PropertyUtils.getNestedProperty() it can read nested level in no limit.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Artist;
import org.kodejava.commons.beanutils.support.Track;

public class ReadNestedProperty {
    public static void main(String[] args) {
        Track track = new Track();
        track.setId(1L);
        track.setTitle("Lucy In The Sky With Diamonds");
        track.setArtist(new Artist(1L, "The Beatles"));

        try {
            String artistName = (String) PropertyUtils.getNestedProperty(track, "artist.name");
            System.out.println("Artist Name = " + artistName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.commons.beanutils.support;

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

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

    public Artist getArtist() {
        return artist;
    }

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

    @Override
    public String toString() {
        return "Track{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", duration=" + duration +
                '}';
    }
}
package org.kodejava.commons.beanutils.support;

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

    public Artist() {
    }

    public Artist(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

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

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;

public class ReadBeanProperty {
    public static void main(String[] args) {
        Track track = new Track();
        track.setTitle("Here Comes The Sun");

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

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

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central