luni, 1 iunie 2015

[OmniFaces utilities 2.0] Set a collection of properties of a given object to the values associated with those properties


[OmniFaces utilities] The setProperties() sets a collection of properties of a given object to the 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 This particular method assumes that there's a write method for each property in the map with the right type. No specific checking is done whether this is indeed the case.

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#setProperties():

import org.omnifaces.util.Reflection;
...
Map<String, Object> properties = new HashMap<>();
properties.put("name", "MyBook");
properties.put("isbn", 123456789L);
properties.put("price", 3.44f);

BookBean bookBean = new BookBean();
Reflection.setProperties(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