java print object's properties and values ToStringBuilder.reflectionToString

1. Introduction and introduction
1. ToStringBuilder, HashCodeBuilder, EqualsBuilder, ToStringStyle, ReflectionToStringBuilder, CompareToBuilder and other classes are located under commons-lang.jar, so to use these classes, you must import commons-lang.jar.
   2. Why use ToStringBuilder?
     In the system, the log is generally printed, because the toString() method of all entities uses a simple "+", because each "+" will create a new String object, so if the system memory is small, it will burst the memory ( There are many premise system entities). Using ToStringBuilder can avoid the problem of memory explosion.

Second, example learning
  1. ToStringBuilder append method
     ToStringBuilder class is mainly used for formatted output of the class. The append method in ToStringBuilder can add basic types, arrays, and objects to the class, and only the added methods will be output by toString. Such as:
class TaxReturn {
  private String ssn;
  private int year;
  private String lastName;
  private BigDecimal taxableIncome;
  // get/set method omitted
  public TaxReturn() {
  }
 public TaxReturn(String pSsn, int pYear, String pLastName, BigDecimal pTaxableIncome) {
    setSsn(pSsn);
    setYear(pYear);
    setLastName(pLastName);
    setTaxableIncome(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());
  }
}

The results are as follows:
ToStringBuilder: TaxReturn@1503a3[ssn=012-68-3242,year=1998,lastName=O'Brien]

2、ToStringBuilder的reflectionToString方法

     该方法主要是把类对应的基本属性和值输出来。如:
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);
    }
}
The results are as follows:
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


ToStringStyle parameter description:
1. DEFAULT_STYLE
   com.entity.Person@182f0db[name=John Doe,age=33,smoker=false]
2. MULTI_LINE_STYLE
    com.entity.Person@182f0db[
   name=John Doe
   age=33
   smoker=false
]
3. NO_FIELD_NAMES_STYLE
   com.entity.Person@182f0db[John Doe,33,false]
4. SHORT_PREFIX_STYLE (namely truncated package name)
  Person[name=John Doe,age=33,smoker=false]
5. SIMPLE_STYLE
   John Doe, 33,false


############################################### #####################:::
Whether
    you are developing a Java application, you can't write a lot of tool class / tool functions. Did you know that there are many ready-made tool classes available, and the code quality is very good, you don't need to write, you don't need to debug, as long as you find it.
  In Apache Jakarta Common, the Lang Java toolkit is the most widely used in all Apache Jakarta Common projects, and it is used in almost all the famous software you know, including Tomcat, Weblogic, Websphere, Eclipse, etc. . We will start with this package to introduce the entire common project.

There are many tool classes in Lang, here are some main ones:
   ClassUtils : getShortClassName, this function should be in the java.lang.Class class, I see many people write this function by themselves. getAllInterfaces, convertClassNamesToClasses, isAssignable, primitivesToWrappers, isInnerClass.
   NumberUtils : Classes stringToInt, toDouble, createNumber, isAllZeros, int compare(float lhs, float rhs), isNumber(String str), double min(double[] array) about numbers and conversion of numbers and strings.
   RandomUtils : Used to generate random numbers.
   DateFormatUtils : Date time format conversion, as well as local time and UTC time conversion.
   DateUtils : Date utility class. isSameDay, truncate, round, modify.

  Several classes based on reflection mechanism:
   CompareToBuilder : Comparison, used in algorithms, sorting, and comparisons. reflectionCompare, append.
   EqualsBuilder : Compare through reflection mechanism. reflectionEquals is used in many projects.
   HashCodeBuilder : Hash code can be generated through reflection. Many algorithms involve hash code, but not everyone knows a hash code generation method.
   ToStringBuilder : When you need to overload the toString function and do not want to write code to list all the member information of the current class, you can use this function.

  I use few other classes:
   SerializationUtils Serialization   in Java is more subtle and error-prone.
   SystemUtils can read some tool classes about jdk information and operating system information.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326074329&siteId=291194637