Java Tutorial/Apache Common/toString builder — различия между версиями

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

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

Reflection to StringBuilder

/* 
 * ========================================================================
 * 
 * Copyright 2005 Tim O"Brien.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * ========================================================================
 */
import org.apache.rumons.lang.builder.rupareToBuilder;
import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ReflectionToStringBuilder;
class BuilderBean implements Comparable {
  private String prop1;
  private String prop2;
  public String getProp1() {
    return prop1;
  }
  public void setProp1(String pProp1) {
    prop1 = pProp1;
  }
  public String getProp2() {
    return prop2;
  }
  public void setProp2(String pProp2) {
    prop2 = pProp2;
  }
  public String toString() {
    return ReflectionToStringBuilder.toString(this);
  }
  public boolean equals(Object pObject) {
    return EqualsBuilder.reflectionEquals(this, pObject);
  }
  public int compareTo(Object pObject) {
    return CompareToBuilder.reflectionCompare(this, pObject);
  }
  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }
}
public class MainClass {
  public static void main(String[] pArgs) throws Exception {
    // Builder and Builder2 contain the same content
    BuilderBean builder = new BuilderBean();
    builder.setProp1("One");
    builder.setProp2("Two");
    BuilderBean builder2 = new BuilderBean();
    builder2.setProp1("One");
    builder2.setProp2("Two");
    BuilderBean builder3 = new BuilderBean();
    builder3.setProp1("Uno");
    builder3.setProp2("Dos");
    System.out.println("ToStringBuilder: " + builder.toString());
  }
}



ToStringBuilder: BuilderBean@743399[prop1=One,prop2=Two]



ToStringBuilder

/* 
 * ========================================================================
 * 
 * Copyright 2005 Tim O"Brien.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * ========================================================================
 */
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.math.BigDecimal;
import org.apache.rumons.lang.builder.rupareToBuilder;
import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
class TaxReturn {
  private String ssn;
  private int year;
  private String lastName;
  private BigDecimal taxableIncome;
  public TaxReturn() {
  }
  public TaxReturn(String pSsn, int pYear, String pLastName, BigDecimal pTaxableIncome) {
    setSsn(pSsn);
    setYear(pYear);
    setLastName(pLastName);
    setTaxableIncome(pTaxableIncome);
  }
  public String getSsn() {
    return ssn;
  }
  public void setSsn(String pSsn) {
    ssn = pSsn;
  }
  public int getYear() {
    return year;
  }
  public void setYear(int pYear) {
    year = pYear;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String pLastName) {
    lastName = pLastName;
  }
  public BigDecimal getTaxableIncome() {
    return taxableIncome;
  }
  public void setTaxableIncome(BigDecimal pTaxableIncome) {
    taxableIncome = pTaxableIncome;
  }
  public String toString() {
    return new ToStringBuilder(this).append("ssn", ssn).append("year", year).append("lastName",
        lastName).toString();
  }
  public int hashCode() {
    return new HashCodeBuilder(3, 7).append(ssn).append(year).toHashCode();
  }
  public boolean equals(Object pObject) {
    boolean equals = false;
    if (pObject instanceof TaxReturn) {
      TaxReturn bean = (TaxReturn) pObject;
      equals = (new EqualsBuilder().append(ssn, bean.ssn).append(year, bean.year)).isEquals();
    }
    return equals;
  }
  public int compareTo(Object pObject) {
    return CompareToBuilder.reflectionCompare(this, pObject);
  }
}
public class MainClass {
  public static void main(String[] pArgs) throws Exception {
     TaxReturn return1 = new TaxReturn("012-68-3242", 1998, "O"Brien", new BigDecimal(43000.00));
     TaxReturn return2 = new TaxReturn("012-68-3242", 1999, "O"Brien", new BigDecimal(45000.00));
     TaxReturn return3 = new TaxReturn("012-68-3242", 1999, "O"Brien", new BigDecimal(53222.00));
     System.out.println("ToStringBuilder: " + return1.toString());
  }
}



ToStringBuilder: TaxReturn@1503a3[ssn=012-68-3242,year=1998,lastName=O"Brien]



ToString Builder for Derived Class

/* 
 * ========================================================================
 * 
 * Copyright 2005 Tim O"Brien.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * ========================================================================
 */
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.rumons.lang.builder.rupareToBuilder;
import org.apache.rumons.lang.builder.ReflectionToStringBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
import org.apache.rumons.lang.builder.ToStringStyle;
public class MainClass {
  public static void main(String[] pArgs) throws Exception {
    // Create a State
    State va = new State("VA", "Virginia");
    // Create a Birth Date
    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, 1743);
    calendar.set(Calendar.MONTH, Calendar.APRIL);
    calendar.set(Calendar.DAY_OF_MONTH, 13);
    Date dob = calendar.getTime();
    BigDecimal moneyRaised = new BigDecimal(293829292.93);
    // Create a Political Candidate
    PoliticalCandidate candidate = new PoliticalCandidate("Jefferson", "Thomas", dob, moneyRaised,
        va);
    System.out.println(candidate);
    // Create a Political Candidate
    PoliticalCandidate candidate2 = new PoliticalCandidate("Jefferson", "Martha", null, null, null);
    // Create a Political Candidate
    PoliticalCandidate candidate3 = new PoliticalCandidate("Jefferson", "Martha", dob, null, va);
    System.out.println("Two Jeffersons are still different (should be > 0): "
        + candidate.rupareTo(candidate2));
    System.out.println("Two Jeffersons are still different (should be < 0): "
        + candidate2.rupareTo(candidate));
    System.out.println("Two Martha Js are the same (should be zero): "
        + candidate2.rupareTo(candidate3));
  }
}
class State {
  private String abbreviation;
  private String name;
  public State() {
  }
  public State(String abbreviation, String name) {
    this.abbreviation = abbreviation;
    this.name = name;
  }
  public String getAbbreviation() {
    return abbreviation;
  }
  public void setAbbreviation(String abbreviation) {
    this.abbreviation = abbreviation;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String toString() {
    return ReflectionToStringBuilder.reflectionToString(this);
  }
}
/*
 * ========================================================================
 * 
 * Copyright 2005 Tim O"Brien.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * ========================================================================
 */
class PoliticalCandidate implements Comparable {
  private String lastName;
  private String firstName;
  private Date dateOfBirth;
  private BigDecimal moneyRaised;
  private State state;
  public PoliticalCandidate() {
  }
  public PoliticalCandidate(String lastName, String firstName, Date dateOfBirth,
      BigDecimal moneyRaised, State state) {
    this.lastName = lastName;
    this.firstName = firstName;
    this.dateOfBirth = dateOfBirth;
    this.moneyRaised = moneyRaised;
    this.state = state;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public Date getDateOfBirth() {
    return dateOfBirth;
  }
  public void setDateOfBirth(Date dateOfBirth) {
    this.dateOfBirth = dateOfBirth;
  }
  public BigDecimal getMoneyRaised() {
    return moneyRaised;
  }
  public void setMoneyRaised(BigDecimal moneyRaised) {
    this.moneyRaised = moneyRaised;
  }
  public State getState() {
    return state;
  }
  public void setState(State state) {
    this.state = state;
  }
  /*
   * public String toString() { return
   * ReflectionToStringBuilder.reflectionToString(this); }
   */
  /*
   * // get/set methods are omitted for brevity... public String toString() {
   * return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append(
   * "lastName", lastName ) .append( "firstName", firstName ) .toString(); }
   */
  /*
   * // get/set methods are omitted for brevity... public String toString() {
   * return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE) .append(
   * "lastName", lastName ) .append( "firstName", firstName ) .toString(); }
   */
  /*
   * // get/set methods are omitted for brevity... public String toString() {
   * return new ToStringBuilder(this, ToStringStyle.NO_FIELD_NAMES_STYLE)
   * .append( "lastName", lastName ) .append( "firstName", firstName )
   * .toString(); }
   */
  // get/set methods are omitted for brevity...
  public String toString() {
    return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).append("lastName", lastName)
        .append("firstName", firstName).toString();
  }
  /*
   * (non-Javadoc)
   * 
   * @see java.lang.ruparable#compareTo(java.lang.Object)
   */
  // A compare to which mimics the behavior of equals()
  public int compareTo(Object o) {
    int compare = -1; // By default return less-than
    if (o != null && PoliticalCandidate.class.isAssignableFrom(o.getClass())) {
      PoliticalCandidate pc = (PoliticalCandidate) o;
      compare = (new CompareToBuilder().append(firstName, pc.firstName).append(lastName,
          pc.lastName)).toComparison();
    }
    return compare;
  }
}



Jefferson,Thomas
Two Jeffersons are still different (should be > 0): 7
Two Jeffersons are still different (should be < 0): -7
Two Martha Js are the same (should be zero): 0



ToStringBuilder.reflectionToString

import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
import org.apache.rumons.lang.builder.ToStringStyle;
public class MainClass {
    public static void main(String[] args) {
        MyClass one = new MyClass("Becker", 35);
        MyClass two = new MyClass("Becker", 35);
        MyClass three = new MyClass("Agassi", 33);
        System.out.println("One>>>" + one);
        System.out.println("Two>>>" + two);
        System.out.println("Three>>>" + three);
        System.out.println("one equals two? " + one.equals(two));
        System.out.println("one equals three? " + one.equals(three));
        System.out.println("One HashCode>>> " + one.hashCode());
        System.out.println("Two HashCode>>> " + two.hashCode());
        System.out.println("Three HashCode>>> " + three.hashCode());
    }
}
class MyClass {
    private String name = null;
    private int age = 0;
    public MyClass(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
    public String toString() {
        return ToStringBuilder.reflectionToString(this,
            ToStringStyle.MULTI_LINE_STYLE);
    }
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}



One>>>MyClass@743399[
  name=Becker
  age=35
]
Two>>>MyClass@1d8957f[
  name=Becker
  age=35
]
Three>>>MyClass@3ee284[
  name=Agassi
  age=33
]
one equals two? true
one equals three? false
One HashCode>>> 462213092
Two HashCode>>> 462213092
Three HashCode>>> -530629296



ToString Style.MULTI_LINE_STYLE

import org.apache.rumons.lang.builder.EqualsBuilder;
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.ToStringBuilder;
import org.apache.rumons.lang.builder.ToStringStyle;

public class MainClass {
  public static void main(String[] args) {
    //Create new BuilderTrial instances
    BuilderTrial one = new BuilderTrial("Becker", 35);
    BuilderTrial two = new BuilderTrial("Becker", 35);
    BuilderTrial three = new BuilderTrial("Agassi", 33);
    //one and two hold the same data in different objects
    //three holds different data
    System.out.println("One>>>" + one);
    System.out.println("Two>>>" + two);
    System.out.println("Three>>>" + three);
    System.out.println("one equals two? " + one.equals(two));
    System.out.println("one equals three? " + one.equals(three));
    //As one and two hold the same data, the same hashcode is returned.
    System.out.println("One HashCode>>> " + one.hashCode());
    System.out.println("Two HashCode>>> " + two.hashCode());
    System.out.println("Three HashCode>>> " + three.hashCode());
  }
}
class BuilderTrial {
  private String name;
  private int age;
  public BuilderTrial(String name, int age) {
      this.name = name;
      this.age = age;
  }
  public static void main(String[] args) {
  }
  public boolean equals(Object objCompared) {
      if (!(objCompared instanceof BuilderTrial)) {
          return false;
      }
      BuilderTrial rhs = (BuilderTrial) objCompared;
      return new EqualsBuilder().append(name, rhs.name).append(age, rhs.age)
                                .isEquals();
  }
  public String toString() {
      return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("Name",
          name).append("Age", age).toString();
  }
  public int hashCode() {
      return new HashCodeBuilder(15, 19).append(name).append(age).toHashCode();
  }
}



One>>>BuilderTrial@a981ca[
  Name=Becker
  Age=35
]
Two>>>BuilderTrial@e7b241[
  Name=Becker
  Age=35
]
Three>>>BuilderTrial@167d940[
  Name=Agassi
  Age=33
]
one equals two? true
one equals three? false
One HashCode>>> -923455822
Two HashCode>>> -923455822
Three HashCode>>> -1433293806