Java如何确定bean的属性类型?
使用PropertyUtils.getPropertyType()我们可以确定bean的属性类型。此方法返回Classbean属性类型的对象。
package org.nhooo.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.nhooo.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;
}
}上面的代码片段的输出:
type = java.lang.String value = Magical Mystery Tour
Maven依赖
<!-- 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>