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

Wayan

Leave a Reply

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