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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024