The Commons BeanUtils
component provides a class called PropertyUtils
that supplies method for manipulating a bean such as our Track
class below. For this demo we use a Track
class that have a property called id
, title
and duration
.
To set the value of a bean we can use the PropertyUtils.setProperty()
method. This method ask for the bean instance whose property value to be set, the property name and the value.
package org.kodejava.commons.beanutils;
import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;
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.kodejava.commons.beanutils.support;
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 +
'}';
}
}
Some exceptions could be thrown by this method, so we need to handle the IllegalAccessException
, InvocationAccessException
and NoSuchMethodException
. To make the code simple we will just catch it as java.lang.Exception
.
These exceptions could happen if we don’t have access to the property, or the bean’s accessor throws an exception or if the method we tried to manipulate doesn’t exist.
Maven Dependencies
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023