8 Ekim 2018 Pazartesi

Apache Commons ToStringBuilder Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
reflectionToString metodu - Object
Açıklaması şöyle.
Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are usually private, the method, reflectionToString, uses AccessibleObject.setAccessible to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are set up correctly. It is also slower than testing explicitly. 
Şöyle yaparız.
public String toString() {
  return ToStringBuilder.reflectionToString(this);
}
reflectionToString metodu - Object + ToStringStyle
Örnek
Şöyle yaparız.
public class Address {

  private String addressKey;
  private String postalCode;
  private String country;
  ...

  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE,
     false);
  }
}
toString metodu
Örnek
Şöyle yaparız.
@Override
public String toString() {
  return new org.apache.commons.lang3.builder.ToStringBuilder(this).
    append("field1", field1).
    append("field2", field2).
    toString();
}

Hiç yorum yok:

Yorum Gönder