在这个例子中,我们将学习如何使用PropertyUtils.getSimpleProperty()方法读取bean的属性值。为了测试此方法,我们将为Trackbean创建一个简单的类。该Track班有一定的属性,如id,title和duration。
将PropertyUtils.getSimpleProperty()通过访问bean的getter方法读取我们的bean属性。该方法有两个参数。第一个参数是Bean,第二个参数是Bean的属性名称。java.lang.Object结果返回a ,这意味着我们必须将其强制转换为所需的类型。
package org.nhooo.example.commons.beanutils; import org.apache.commons.beanutils.PropertyUtils; public class ReadBeanProperty { public static void main(String[] args) { Track track = new Track(); track.setTitle("Till There Was You"); try { String title = (String) PropertyUtils.getSimpleProperty(track, "title"); System.out.println("Track title = " + title); } catch (Exception e) { e.printStackTrace(); } } }
这是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; } @Override public String toString() { return "Track{" + "id=" + id + ", title='" + title + '\'' + ", duration=" + duration + '}'; } }
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>