16

I have an object that includes a number of variables but one is a byteArray e.g.

public class DataWithFields {
   private String string1;
   private String string2;
   ....

   private byte[] data    

   public String toString() {
       return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
   }

}

For the above code, I want to exclude the data variable from the toString without having to explicitly define each value. How do I do this?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user1605665
  • 3,771
  • 10
  • 36
  • 54
  • It's important to note that while ReflectionToStringBuilder is a great solution (one that I have used myself), it is probably the slowest solution. If performance is key, you'll probably want to reference this: https://antoniogoncalves.org/2015/06/30/who-cares-about-tostring-performance/ – Lezorte Jul 20 '18 at 14:29

2 Answers2

26

Simplier solution :

@Override
public String toString() {
    return ReflectionToStringBuilder.toStringExclude(this, "data");
}

If DefaultToStringStyle is doesn't fit your application needs, make sure to call

ReflectionToStringBuilder.setDefaultStyle(style);

at application start.

If you have more fields to exclude, just add them after or before "data"

@Override
public String toString() {
    return ReflectionToStringBuilder.toStringExclude(this, "fieldX","data", "fieldY");
}
Olivier
  • 3,465
  • 2
  • 23
  • 26
7

Extend ReflectionToStringBuilder and override the accept method:

public String toString() {
    ReflectionToStringBuilder builder = new ReflectionToStringBuilder(
            this, ToStringStyle.SHORT_PREFIX_STYLE) {
        @Override
        protected boolean accept(Field field) {
            return !field.getName().equals("data");
        }
    };

    return builder.toString();
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254