This sample show us how to use the ReflexionUtils class in order to charge properties from a Object to a Map and also from a Map to an Object.
Este ejemplo nos muestra cómo utilizar la clase ReflexionUtils para cargar propiedades desde un Object a un Map y en sentido inverso desde un Map a un Object.
:::java
package ar.com.scf.sample06;
public class Author {
private int birth_year;
private String name;
public Author(String name, int birth_year) {
setName(name);
setBirth_year(birth_year);
}
public int getBirth_year() {
return birth_year;
}
public String getName() {
return name;
}
public void setBirth_year(int birth_year) {
this.birth_year = birth_year;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return getName();
}
}
:::java
package ar.com.scf.sample06;
public class Book {
private Author author;
private String ISBN;
private float price;
private String title;
public Book(String title, Author author, float price, String ISBN) {
setTitle(title);
setAuthor(author);
setPrice(price);
setISBN(ISBN);
}
public Author getAuthor() {
return author;
}
public String getISBN() {
return ISBN;
}
public float getPrice() {
return price;
}
public String getTitle() {
return title;
}
public void setAuthor(Author author) {
this.author = author;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public void setPrice(float price) {
this.price = price;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return getTitle() + ", " + getAuthor() + " [" + getISBN() + "], $" + getPrice();
}
}
:::java
package ar.com.scf.sample06;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import ar.com.scf.utils.ReflexionUtils;
public class Sample {
public static void main(String[] args) throws Exception {
Author verne = new Author("Jules Gabriel Verne", 1828);
Book book = new Book("De la Tierra a la Luna", verne, 32.0f, "9788420731940");
ReflexionUtils util = new ReflexionUtils();
Map<String, Object> target = new HashMap<String, Object>();
util.charge(book, target);
for (Entry<String, Object> entry : target.entrySet())
System.out.println(entry.getKey() + ": " + entry.getValue());
System.out.println("---x---");
Map<String, Object> source = new HashMap<String, Object>(target);
source.put("Title", "20.000 leguas de viaje submarino");
source.put("ISBN", "9686769749");
Book book2 = new Book(null, null, 0, null);
util.charge(source, book2);
System.out.println(book2);
}
}
:::console
ISBN: 9788420731940
Price: 32.0
Author: Jules Gabriel Verne
Title: De la Tierra a la Luna
---x---
20.000 leguas de viaje submarino, Jules Gabriel Verne [9686769749], $32.0