该Commons BeanUtils组件提供了一个称为的类PropertyUtils,该类提供了用于操作Bean的方法,例如Track下面的类。对于本演示中,我们使用Track的是有一个叫物业类id,title和duration。
要设置bean的值,我们可以使用PropertyUtils.setProperty()方法。此方法要求设置其属性值的Bean实例,属性名称和值。
package org.nhooo.example.commons.beanutils;
import org.apache.commons.beanutils.PropertyUtils;
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.nhooo.example.commons.beanutils;
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;
}
}一些例外情况可以通过这种方法被抛出,所以我们需要处理的IllegalAccessException,InvocationAccessException和NoSuchMethodException。为了使代码简单,我们将其捕获为java.lang.Exception。
如果我们无权访问该属性,或者bean的访问器抛出异常,或者如果我们尝试操作的方法不存在,则可能发生这些异常。
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>