How to exclude one variable using ToStringBuilder

I have an object that includes several variables, but one of them is byteArray, for example.

public class DataWithFields { private String string1; private String string2; .... private byte[] data public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } } 

In the above code, I want to exclude the data variable from the toString table without explicitly defining each value. How to do it?

+7
java apache-commons-lang
source share
2 answers

Simplified solution:

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

If DefaultToStringStyle does not meet the needs of your application, be sure to call

 ReflectionToStringBuilder.setDefaultStyle(style); 

when you start the application.

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

 @Override public String toString() { return ReflectionToStringBuilder.toStringExclude(this, "fieldX","data", "fieldY"); } 
+12
source share

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(); } 
+3
source share

All Articles