19 Ocak 2020 Pazar

ReflectionToStringBuilder Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
Açıklaması şöyle
ReflectionToStringBuilder is a utility class in the Apache Commons Lang library that helps to create a string representation of an object’s state using reflection. It can be useful in debugging, logging, and other scenarios where we need to understand the current state of an object. 
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>
exclude metodu
Açıklaması şöyle
To exclude certain fields from the output string, you can use the exclude method of the ReflectionToStringBuilder class.
Örnek
Şöyle yaparız
String personAsString = new ReflectionToStringBuilder(person)
  .exclude("email")
  .toString();
System.out.println(personAsString);

// Output:
// Person@57a23b66[name=Fake Name,age=30]
Örnek
Şöyle yaparız
// You can also exclude multiple fields by passing them as a 
// comma-separated string or an array

String[] excludeFields = {"age", "email"};
String personAsString = new ReflectionToStringBuilder(person)
  .exclude(excludeFields)
  .toString();
System.out.println(personAsString);

// Output:
// Person@57a23b66[name=Fake Name]
toString metodu
Örnek
Şöyle yaparız
Person person = new Person("Fake Name", 30, "fake.name@example.com");
String personAsString = ReflectionToStringBuilder.toString(person);
System.out.println(personAsString);

// Output:
// Person@57a23b66[name=Fake Name,age=30,email=fake.name@example.com]
Örnek
Şöyle yaparız. Burada her bir Cookie nesnesi String'e çevriliyor ve bu String nesneleri StringJoiner tarafından birleştiriliyor
private String getCookieString(Cookie[] cookies){
  if(cookies == null)
    return "null";
  StringJoiner stringJoiner = new StringJoiner(",","[","]");
  for (Cookie cookie : cookies) {
    stringJoiner.add(ReflectionToStringBuilder.toString(cookie));
  }
  return stringJoiner.toString();
}
Örnek
Şöyle yaparız
// You can also leverage ReflectionToStringBuilder to generate multiline
// string representations of objects.

public class Person {
  private String name;
  private int age;
  private String email;

  // Constructors, getters, setters, and other methods omitted for brevity

  @Override
  public String toString() {
    return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
  }
}
// Output:

Person@1b6d3586[
  name=Fake Name
  age=30
  address=a@b.com
]

Hiç yorum yok:

Yorum Gönder