ToString Builder for Derived Class : toString builder « Apache Common « Java Tutorial






/* 
 * ========================================================================
 * 
 * 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.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.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.compareTo(candidate2));
    System.out.println("Two Jeffersons are still different (should be < 0): "
        + candidate2.compareTo(candidate));
    System.out.println("Two Martha Js are the same (should be zero): "
        + candidate2.compareTo(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.Comparable#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
  Download:  CommonLangToStringBuilderForDerivedClass.zip( 203 k)








37.2.toString builder
37.2.1.ToStringBuilder
37.2.2.ToString Builder for Derived Class
37.2.3.ToStringBuilder.reflectionToString
37.2.4.ToString Style.MULTI_LINE_STYLE
37.2.5.Reflection to StringBuilder