tags:

views:

64

answers:

2

This goes to the fact that you cannot extend a class with no no-arg constructor in Java. The canonical use for ReflectionToStringBuilder is as follows

public String toString() {
     return (new ReflectionToStringBuilder(this) {
         protected 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 time. I really think so but maybe someone more advanced than me might have a suggestion. What really want to do is actually add a method.

+3  A: 
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.

Jonathan Feinberg
lol u didn't miss a thing but I did -- IBM compiler gave out the wrong message, cheers Jon.
non sequitor
+1  A: 

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");
        }
    };
}
Tom Hawtin - tackline