开发者

How can I extend ReflectionToStringBuilder to avoid duplication?

开发者 https://www.devze.com 2022-12-08 17:33 出处:网络
The canonical use for ReflectionToStringBuilder is as follows public String toString() { return (new ReflectionToStringBuilder(this) {

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

精彩评论

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