How can I extend ReflectionToStringBuilder to avoid duplication?
The canonical use for ReflectionToStringBuilder
is as follows
public String toString() {
return (new ReflectionToStringBuilder(this) {
p开发者_如何学JAVArotected boolean accept(Field f) {
return super.accept(f) && !f.getName().equals("password");
}
}).toString();
}
Is it possible to somehow not repeat this if it has to be done multiple times. I really think so but maybe someone more advanced than me might have a suggestion. What I really want to do is actually add a method.
class NonPasswordShowingStringBuilder extends ReflectionToStringBuilder
{
protected boolean accept(Field f) {
return super.accept(f) && !f.getName().equals("password");
}
public NonPasswordShowingStringBuilder(Object o) { super(o); }
}
unless I'm missing something.
Another approach, useful if there are other parameters to be passed to your code is to put the anonymous inner class in a method:
public static ReflectionToStringBuilder toStringBuilder(Object obj) {
return new ReflectionToStringBuilder(obj) {
@Override protected boolean accept(Field f) {
return super.accept(f) && !f.getName().equals("password");
}
};
}
精彩评论