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

import org.apache.commons.beanutils.PropertyUtils;

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

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

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

import java.util.Map;

public class Recording {
    private Long id;
    private String title;
    private Map<String, Track> mapTracks;

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

    public long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    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

<!-- https://search.maven.org/remotecontent?filepath=commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.