[OmniFaces utilities] The
setPropertiesWithCoercion()
sets a collection of properties of a given object to the (optionally coerced) values associated with those properties. In the map that represents these properties, each key represents the name of the property, with the value associated with that key being the value that is set for the property.
Note 1 In case
the value is a String, and the target type is not String, the
standard property editor mechanism will be used to attempt a conversion.
Note 2 This
method operates somewhat as the reverse of Reflection#setProperties(Object,Map).
Here only the available writable properties of the object are matched against
the map with properties to set. Properties in the map for which there isn't a
corresponding writable property on the object are ignored.
Note 3 Following
the above two notes, use this method when attempting to set properties on an
object in a lenient best effort basis.
Use Reflection#setProperties(Object,Map)
when all properties need to be set with the exact type as the value appears in
the map.
Method:
Usage:
Let's
suppose the following bean, BookBean:
package
book.beans;
import
java.io.Serializable;
public class
BookBean implements Serializable{
private static final long serialVersionUID =
1L;
private String name;
private long isbn;
private float price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getIsbn() {
return isbn;
}
public void setIsbn(long isbn) {
this.isbn = isbn;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
return "BookBean{" +
"name=" + name + ", isbn=" + isbn + ", price=" +
price + '}';
}
}
Now, let's
populate an instance of the BookBean with name=MyBook, isbn=123456789 and price=3.44 using Reflection#setPropertiesWithCoercion():
import
org.omnifaces.util.Reflection;
...
Map<String,
Object> properties = new HashMap<>();
properties.put("name",
"MyBook");
properties.put("isbn",
"123456789");
properties.put("price",
"3.44");
BookBean
bookBean = new BookBean();
Reflection.setPropertiesWithCoercion(bookBean,
properties);
Before
setting: BookBean{name=null,
isbn=0, price=0.0}
After
setting: BookBean{name=MyBook,
isbn=123456789, price=3.44}
Niciun comentariu :
Trimiteți un comentariu