开发者

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");
        }
    };
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜