Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do exclude a single variable using ToStringBuilder

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?

like image 214
user1605665 Avatar asked Sep 17 '13 03:09

user1605665


People also ask

How do I exclude a field in ToString?

If you want to skip some fields, you can annotate these fields with @ToString. Exclude . Alternatively, you can specify exactly which fields you wish to be used by using @ToString(onlyExplicitlyIncluded = true) , then marking each field you want to include with @ToString.

How do I exclude ToString in Lombok?

Exclude indicates which fields have to be excluded in the string representation of the object. To exclude a field annotate the respective field with @ToString. Exclude .


2 Answers

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");
}
like image 103
Olivier Avatar answered Sep 23 '22 04:09

Olivier


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();
}
like image 29
Duncan Jones Avatar answered Sep 26 '22 04:09

Duncan Jones