Java如何读取bean的嵌套属性值?
在这个示例中,您将看到如何读取bean的嵌套属性,我们将使用 PropertyUtils.getNestedProperty()方法。为了进行测试,我们将为bean创建三个类:Track和 Artist,并将ReadNestedProperty作为主程序运行。
Track类将包含的属性Artist对象。使用PropertyUtils.getNestedProperty()方法,我们想要获得演唱曲目的歌手姓名。此方法将首先从track对象读取artist属性,然后读取artist对象的name属性。
使用PropertyUtils.getNestedProperty()它读取嵌套属性可以无限读取嵌套级别。
package org.nhooo.example.commons.beanutils; import org.apache.commons.beanutils.PropertyUtils; public class ReadNestedProperty { public static void main(String[] args) { Track track = new Track(); track.setId(1L); track.setTitle("All My Loving"); track.setArtist(new Artist(1L, "Beatles")); try { String artistName = (String) PropertyUtils.getNestedProperty(track, "artist.name"); System.out.println("Artist Name = " + artistName); } catch (Exception e) { e.printStackTrace(); } } }
package org.nhooo.example.commons.beanutils; public class Track { private Long id; private String title; private Integer duration; private Artist artist; 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; } public Artist getArtist() { return artist; } public void setArtist(Artist artist) { this.artist = artist; } @Override public String toString() { return "Track{" + "id=" + id + ", title='" + title + '\'' + ", duration=" + duration + '}'; } }
package org.nhooo.example.commons.beanutils; public class Artist { private Long id; private String name; public Artist() { } public Artist(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
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>