Java/Apache Common/Bean Utils — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 07:23, 1 июня 2010

BeanUtil Array Utils Example

import org.apache.rumons.lang.ArrayUtils;
public class ArrayUtilsExampleV1 {
  public static void main(String args[]) {
    long[] longArray = new long[] {10000, 30, 99};
    String[] stringArray = new String[] {"abc", "def", "fgh"};
    long[] clonedArray = ArrayUtils.clone(longArray);
    System.err.println(
      ArrayUtils.toString((ArrayUtils.toObject(clonedArray))));
    System.err.println(ArrayUtils.indexOf(stringArray, "def"));
    ArrayUtils.reverse(stringArray);
    System.err.println(ArrayUtils.toString(stringArray));
  }
}





BeanUtils Collections 2

import org.apache.rumons.beanutils.BeanPredicate;
import org.apache.rumons.collections.PredicateUtils;
public class BeanUtilsCollectionsV2 {
  public static void main(String args[]) {
    BeanPredicate predicate =
      new BeanPredicate("title", PredicateUtils.uniquePredicate());
    Movie movie = new Movie();
    movie.setTitle("The Italian Job");
    Movie movie1 = new Movie();
    movie1.setTitle("The Italian Job");
    System.err.println(predicate.evaluate(movie)); // evaluates true
    System.err.println(predicate.evaluate(movie1)); // evaluates false
  }
}
--------------------------------------------------------

import java.util.Map;
import java.util.List;
import java.util.Date;
public class Movie {
  public Movie() {
  }
  public Date getDateOfRelease() { return this.dateOfRelease; }
  public void setDateOfRelease(Date dateOfRelease) {
    this.dateOfRelease = dateOfRelease;
  }
  public String getTitle() { return this.title; }
  public void setTitle(String title) {this.title = title; }
  public Person getDirector() { return this.director; }
  public void setDirector(Person director) { this.director = director; }
  public List getActors() { return this.actors; }
  public void setActors(List actors) { this.actors= actors; }
  public String[] getKeywords() { return this.keywords; }
  public void setKeyWords(String[] keywords) { this.keywords = keywords; }
  public Map getGenre() { return this.genre; }
  public void setGenre(Map genre) { this.genre = genre; }
  private Date dateOfRelease;
  private String title;
  private Person director;
  private List actors;
  private String[] keywords;
  private Map genre;
}
--------------------------------------------------------------------

import java.util.Map;
import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
public class Person {
  public Person() {
  }
  public String getName() {
    return this.name == null ? "NoName" : this.name; }
  public void setName(String name) { this.name = name; }
  public int getGender() { return this.gender; }
  public void setGender(int gender) {  // 0 - Indeterminate, 1 - Male, 2 - Female
    this.gender = (gender > 2 || gender < 0) ? 0 : gender; }
  public Map getContactNumber() { return this.contactNumber; }
  public void setContactNumber(Map contactNumber) {
    this.contactNumber = contactNumber;
  }
  /**public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    if(otherPerson.getName().equals(this.name) &&
       otherPerson.getGender() == this.gender) return true;
    return false;
  }*/
  public boolean equals(Object o) {
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    return new EqualsBuilder()
               .append(name, otherPerson.getName())
               .append(gender, otherPerson.getGender())
               .isEquals();
  }
  public int hashCode() {
    return new HashCodeBuilder(7, 51)
               .append(name)
               .append(gender)
               .append(contactNumber)
               .toHashCode();
  }
  public String toString() {
    return new ToStringBuilder(this)
               .append("Name", name)
               .append("Gender", gender)
               .append("Contact Details", contactNumber)
               .toString();
  }
  private String name;
  private int gender;
  private Map contactNumber;
}





BeanUtils Date Utils

import org.apache.rumons.lang.time.DateUtils;
import java.util.Date;
import java.util.Calendar;
import java.util.Iterator;
import java.util.GregorianCalendar;
public class DateUtilsV1 {
  public static void main(String args[]) {
    GregorianCalendar calendar = new GregorianCalendar(1974, 5, 25, 6, 30, 30);
    Date date = calendar.getTime();
    System.err.println("Original Date: " + date);
    System.err.println("Rounded Date: " + DateUtils.round(date, Calendar.HOUR));
    System.err.println("Truncated Date: " +  DateUtils.truncate(date, Calendar.MONTH));
    Iterator itr = DateUtils.iterator(date, DateUtils.RANGE_WEEK_MONDAY);
    while(itr.hasNext()) {
      System.err.println(((Calendar)itr.next()).getTime());
    }
  }
}
----------------------------------------------------------------------------

import java.util.Map;
import java.util.List;
import java.util.Date;
public class Movie {
  public Movie() {
  }
  public Date getDateOfRelease() { return this.dateOfRelease; }
  public void setDateOfRelease(Date dateOfRelease) {
    this.dateOfRelease = dateOfRelease;
  }
  public String getTitle() { return this.title; }
  public void setTitle(String title) {this.title = title; }
  public Person getDirector() { return this.director; }
  public void setDirector(Person director) { this.director = director; }
  public List getActors() { return this.actors; }
  public void setActors(List actors) { this.actors= actors; }
  public String[] getKeywords() { return this.keywords; }
  public void setKeyWords(String[] keywords) { this.keywords = keywords; }
  public Map getGenre() { return this.genre; }
  public void setGenre(Map genre) { this.genre = genre; }
  private Date dateOfRelease;
  private String title;
  private Person director;
  private List actors;
  private String[] keywords;
  private Map genre;
}
----------------------------------------------------------------------------

import java.util.Map;
import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
public class Person {
  public Person() {
  }
  public String getName() {
    return this.name == null ? "NoName" : this.name; }
  public void setName(String name) { this.name = name; }
  public int getGender() { return this.gender; }
  public void setGender(int gender) {  // 0 - Indeterminate, 1 - Male, 2 - Female
    this.gender = (gender > 2 || gender < 0) ? 0 : gender; }
  public Map getContactNumber() { return this.contactNumber; }
  public void setContactNumber(Map contactNumber) {
    this.contactNumber = contactNumber;
  }
  /**public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    if(otherPerson.getName().equals(this.name) &&
       otherPerson.getGender() == this.gender) return true;
    return false;
  }*/
  public boolean equals(Object o) {
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    return new EqualsBuilder()
               .append(name, otherPerson.getName())
               .append(gender, otherPerson.getGender())
               .isEquals();
  }
  public int hashCode() {
    return new HashCodeBuilder(7, 51)
               .append(name)
               .append(gender)
               .append(contactNumber)
               .toHashCode();
  }
  public String toString() {
    return new ToStringBuilder(this)
               .append("Name", name)
               .append("Gender", gender)
               .append("Contact Details", contactNumber)
               .toString();
  }
  private String name;
  private int gender;
  private Map contactNumber;
}
----------------------------------------------------------------------------

import java.util.List;
public class Actor extends Person {
  public Actor() {
  }
  public List getMovieCredits() { return this.movieCredits; }
  public void setMovieCredits(List movieCredits) {
    this.movieCredits = movieCredits;
  }
  public long getWorth() { return this.worth; }
  public void setWorth(long worth) { this.worth = worth; }
  private List movieCredits;
  private long worth;
}





Bean Utils: deal with collections

import org.apache.rumons.beanutils.BeanUtils;
import java.util.Map;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.GregorianCalendar;
public class BeanUtilsExampleV3 {
  public static void main(String args[]) throws Exception {
    BeanUtilsExampleV3 diff = new BeanUtilsExampleV3();
    Actor actor = diff.prepareData();
    Map describedData = BeanUtils.describe(actor);
    // check the map
    System.err.println(describedData.get("name"));
    // change this value
    describedData.put("name", "Robert Redford");
    // create a new Actor Bean
    Actor newActor = new Actor();
    BeanUtils.populate(newActor, describedData);
    System.err.println(BeanUtils.getProperty(newActor, "name"));
  }
  private Actor prepareData() {
    Actor actor = new Actor();
    actor.setName("Michael Caine");
    actor.setGender(1);
    actor.setWorth(10000000);
    return actor;
  }
}
----------------------------------------------------------------------------

import java.util.Map;
import java.util.List;
import java.util.Date;
public class Movie {
  public Movie() {
  }
  public Date getDateOfRelease() { return this.dateOfRelease; }
  public void setDateOfRelease(Date dateOfRelease) {
    this.dateOfRelease = dateOfRelease;
  }
  public String getTitle() { return this.title; }
  public void setTitle(String title) {this.title = title; }
  public Person getDirector() { return this.director; }
  public void setDirector(Person director) { this.director = director; }
  public List getActors() { return this.actors; }
  public void setActors(List actors) { this.actors= actors; }
  public String[] getKeywords() { return this.keywords; }
  public void setKeyWords(String[] keywords) { this.keywords = keywords; }
  public Map getGenre() { return this.genre; }
  public void setGenre(Map genre) { this.genre = genre; }
  private Date dateOfRelease;
  private String title;
  private Person director;
  private List actors;
  private String[] keywords;
  private Map genre;
}
----------------------------------------------------------------------------

import java.util.Map;
import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
public class Person {
  public Person() {
  }
  public String getName() {
    return this.name == null ? "NoName" : this.name; }
  public void setName(String name) { this.name = name; }
  public int getGender() { return this.gender; }
  public void setGender(int gender) {  // 0 - Indeterminate, 1 - Male, 2 - Female
    this.gender = (gender > 2 || gender < 0) ? 0 : gender; }
  public Map getContactNumber() { return this.contactNumber; }
  public void setContactNumber(Map contactNumber) {
    this.contactNumber = contactNumber;
  }
  /**public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    if(otherPerson.getName().equals(this.name) &&
       otherPerson.getGender() == this.gender) return true;
    return false;
  }*/
  public boolean equals(Object o) {
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    return new EqualsBuilder()
               .append(name, otherPerson.getName())
               .append(gender, otherPerson.getGender())
               .isEquals();
  }
  public int hashCode() {
    return new HashCodeBuilder(7, 51)
               .append(name)
               .append(gender)
               .append(contactNumber)
               .toHashCode();
  }
  public String toString() {
    return new ToStringBuilder(this)
               .append("Name", name)
               .append("Gender", gender)
               .append("Contact Details", contactNumber)
               .toString();
  }
  private String name;
  private int gender;
  private Map contactNumber;
}
----------------------------------------------------------------------------

import java.util.List;
public class Actor extends Person {
  public Actor() {
  }
  public List getMovieCredits() { return this.movieCredits; }
  public void setMovieCredits(List movieCredits) {
    this.movieCredits = movieCredits;
  }
  public long getWorth() { return this.worth; }
  public void setWorth(long worth) { this.worth = worth; }
  private List movieCredits;
  private long worth;
}





BeanUtils get Property from Dynamic Beans

import org.apache.rumons.beanutils.DynaBean;
import org.apache.rumons.beanutils.DynaClass;
import org.apache.rumons.beanutils.BeanUtils;
import org.apache.rumons.beanutils.LazyDynaBean;
import org.apache.rumons.beanutils.DynaProperty;
import org.apache.rumons.beanutils.BasicDynaClass;
import java.util.Map;
import java.util.List;
import java.util.Date;
import java.util.HashMap;
import java.util.GregorianCalendar;
public class DynaBeansExampleV1 {
  public static void main(String args[]) throws Exception {
    Object movie = createMovieBean();
    System.err.println(BeanUtils.getProperty(movie, "title"));
    System.err.println(BeanUtils.getProperty(movie, "director.name"));
  }
  private static Object createMovieBean() throws Exception {
    // first create the properties
    DynaProperty properties[] = new DynaProperty[] {
      new DynaProperty("title", String.class),
      new DynaProperty("dateOfRelease", Date.class),
      new DynaProperty("keywords", String[].class),
      new DynaProperty("genre", Map.class),
      new DynaProperty("actors", List.class),
      new DynaProperty("director", DynaBean.class)
    };
    // next using the properties define the class
    DynaClass movieClass = new BasicDynaClass("movie", null, properties);
    // now, with the class, create a new instance
    DynaBean movieBean = movieClass.newInstance();
    // set its properties
    movieBean.set("title", "The Italian Job");
    movieBean.set("dateOfRelease",
      new GregorianCalendar(1969, 0, 1).getTime());
    movieBean.set("keywords", new String[] {"Italy", "Bank Robbery"});
    Map genre = new HashMap();
    genre.put("THR", "Thriller");
    movieBean.set("genre", genre);
    movieBean.set("genre", "ACT", "Action");
    DynaBean director = createPersonBean();
    director.set("name", "Peter Collinson");
    director.set("gender", new Integer(1));
    movieBean.set("director", director);
    return movieBean;
  }
  private static DynaBean createPersonBean() {
    DynaBean person = new LazyDynaBean();
    return person;
  }
}





Get Mapped Property

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.lang.reflect.Method;
import org.apache.rumons.collections.Bag;
import org.apache.rumons.collections.bag.HashBag;
import org.apache.rumons.beanutils.BeanUtils;
import org.apache.rumons.beanutils.PropertyUtils;
import org.apache.rumons.lang.StringUtils;
public class TasteOfThingsV1 {
  private static Map testMap;
  private static TestBean testBean;
  public static void main(String args[]) throws Exception {
    prepareData();
    HashBag myBag = new HashBag(testMap.values());
    System.err.println("How many Boxes? " + myBag.getCount("Boxes"));
    myBag.add("Boxes", 5);
    System.err.println("How many Boxes now? " + myBag.getCount("Boxes"));
    Method method =
      testBean.getClass().getDeclaredMethod("getTestMap", new Class[0]);
    HashMap reflectionMap =
      (HashMap)method.invoke(testBean, new Object[0]);
    System.err.println("The value of the "squ" key using reflection: " +
      reflectionMap.get("squ"));
    String squ = BeanUtils.getMappedProperty(testBean, "testMap", "squ");
    squ = StringUtils.capitalize(squ);
    PropertyUtils.setMappedProperty(testBean, "testMap", "squ", squ);
    System.err.println("The value of the "squ" key is: " +
      BeanUtils.getMappedProperty(testBean, "testMap", "squ"));
    String box = (String)testMap.get("box");
    String caps =
      Character.toTitleCase(box.charAt(0)) +
      box.substring(1, box.length());
    System.err.println("Capitalizing boxes by Java: " + caps);
  }
  private static void prepareData() {
    testMap = new HashMap();
    testMap.put("box", "boxes");
    testMap.put("squ", "squares");
    testMap.put("rect", "rectangles");
    testMap.put("cir", "circles");
    testBean = new TestBean();
    testBean.setTestMap(testMap);
  }
}
------------------------------------------------------------------
import java.util.Map;
import java.util.HashMap;
public class TestBean {
  private Map testMap;
  public Map getTestMap() {
    return this.testMap;
  }
  public void setTestMap(Map testMap) {
    this.testMap = testMap;
  }
}





Use Bean Utils to get property value from object

import org.apache.rumons.beanutils.BeanUtils;
import java.util.Map;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.GregorianCalendar;
public class BeanUtilsExampleV1 {
  public static void main(String args[]) throws Exception {
    BeanUtilsExampleV1 diff = new BeanUtilsExampleV1();
    Movie movieBean = diff.prepareData();
    System.err.println("Movie Title: " +
      BeanUtils.getProperty(movieBean, "title"));
    System.err.println("Movie Year: " +
      BeanUtils.getProperty(movieBean, "dateOfRelease"));
    System.err.println("Movie Director: " +
      BeanUtils.getProperty(movieBean, "director.name"));
    System.err.println("Movie Director Home Contact: " +
      BeanUtils.getProperty(movieBean, "director.contactNumber(Home)"));
    System.err.println("Movie Genre (Thriller): " +
      BeanUtils.getProperty(movieBean, "genre(THR)"));
    System.err.println("Movie Actor 1 name: " +
      BeanUtils.getProperty(movieBean, "actors[0].name"));
    System.err.println("Movie Actor 1 worth: " +
      BeanUtils.getProperty(movieBean, "actors[0].worth"));
    System.err.println("Movie Actor 1 other movie 1: " +
      BeanUtils.getProperty(movieBean, "actors[0].movieCredits[0].title"));
  }
  private Movie prepareData() {
    Movie movie = new Movie();
    movie.setTitle("The Italian Job");
    movie.setDateOfRelease(new GregorianCalendar(1969, 0, 1).getTime());
    // sets the genre
    Map genre_map = new HashMap();
    genre_map.put("THR", "Thriller");
    genre_map.put("ACT", "Action");
    movie.setGenre(genre_map);
    // creates the Director
    Person director = new Person();
    director.setName("Peter Collinson");
    director.setGender(1);
    Map director_contacts = new HashMap();
    director_contacts.put("Home", "99922233");
    director_contacts.put("Mobile", "0343343433");
    director.setContactNumber(director_contacts);
    movie.setDirector(director);
    // create the actors
    Actor actor1 = new Actor();
    actor1.setName("Michael Caine");
    actor1.setGender(1);
    actor1.setWorth(10000000);
    List actor1_movies = new ArrayList();
    Movie movie2 = new Movie();
    movie2.setTitle("The Fourth Protocol");
    Movie movie3 = new Movie();
    movie3.setTitle("Shiner");
    actor1_movies.add(movie2);
    actor1_movies.add(movie3);
    actor1.setMovieCredits(actor1_movies);
    Actor actor2 = new Actor();
    actor2.setName("Margaret Blye");
    actor2.setGender(2);
    actor2.setWorth(20000000);
    List actors = new ArrayList();
    actors.add(actor1);
    actors.add(actor2);
    movie.setActors(actors);
    return movie;
  }
}
-----------------------------------------------------------------------------

import java.util.List;
public class Actor extends Person {
  public Actor() {
  }
  public List getMovieCredits() { return this.movieCredits; }
  public void setMovieCredits(List movieCredits) {
    this.movieCredits = movieCredits;
  }
  public long getWorth() { return this.worth; }
  public void setWorth(long worth) { this.worth = worth; }
  private List movieCredits;
  private long worth;
}
-----------------------------------------------------------------------------

import java.util.Map;
import java.util.List;
import java.util.Date;
public class Movie {
  public Movie() {
  }
  public Date getDateOfRelease() { return this.dateOfRelease; }
  public void setDateOfRelease(Date dateOfRelease) {
    this.dateOfRelease = dateOfRelease;
  }
  public String getTitle() { return this.title; }
  public void setTitle(String title) {this.title = title; }
  public Person getDirector() { return this.director; }
  public void setDirector(Person director) { this.director = director; }
  public List getActors() { return this.actors; }
  public void setActors(List actors) { this.actors= actors; }
  public String[] getKeywords() { return this.keywords; }
  public void setKeyWords(String[] keywords) { this.keywords = keywords; }
  public Map getGenre() { return this.genre; }
  public void setGenre(Map genre) { this.genre = genre; }
  private Date dateOfRelease;
  private String title;
  private Person director;
  private List actors;
  private String[] keywords;
  private Map genre;
}
-----------------------------------------------------------------------------

import java.util.Map;
import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
public class Person {
  public Person() {
  }
  public String getName() {
    return this.name == null ? "NoName" : this.name; }
  public void setName(String name) { this.name = name; }
  public int getGender() { return this.gender; }
  public void setGender(int gender) {  // 0 - Indeterminate, 1 - Male, 2 - Female
    this.gender = (gender > 2 || gender < 0) ? 0 : gender; }
  public Map getContactNumber() { return this.contactNumber; }
  public void setContactNumber(Map contactNumber) {
    this.contactNumber = contactNumber;
  }
  /**public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    if(otherPerson.getName().equals(this.name) &&
       otherPerson.getGender() == this.gender) return true;
    return false;
  }*/
  public boolean equals(Object o) {
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    return new EqualsBuilder()
               .append(name, otherPerson.getName())
               .append(gender, otherPerson.getGender())
               .isEquals();
  }
  public int hashCode() {
    return new HashCodeBuilder(7, 51)
               .append(name)
               .append(gender)
               .append(contactNumber)
               .toHashCode();
  }
  public String toString() {
    return new ToStringBuilder(this)
               .append("Name", name)
               .append("Gender", gender)
               .append("Contact Details", contactNumber)
               .toString();
  }
  private String name;
  private int gender;
  private Map contactNumber;
}