0

I have the following method:

    @Override public String toString() {
    return new ReflectionToStringBuilder(this, new MultilineRecursiveToStringStyle() {
        {
            setUseShortClassName(true);
            setUseIdentityHashCode(false);
        }
    }).build();
}

As you can see, Double Brace Initialization (DBI) is used. How can I change this code so that I'm not using DBI?

kill-9
  • 104
  • 1
  • 5

1 Answers1

1

You should first understand what double brace initialisation actually does. According to the linked answer, the main drawback of DBI that applies here is that it can create a lot of anonymous classes without you noticing, because the syntax is so lightweight.

According to the documentation, the methods you want to call, like setUseIdentityHashCode are protected, so in order to access it, we must create a subclass of MultilineRecursiveToStringStyle. It doesn't really matter whether you do that with DBI to create an anonymous class:

public static final ToStringStyle MY_CUSTOM_STYLE = new MultilineRecursiveToStringStyle() {{
    setUseIdentityHashCode(false);
    setUseShortClassName(true);
}};

@Override
public String toString() {
    return new ReflectionToStringBuilder(this, MY_CUSTOM_STYLE).build();
}

or by writing a named class:

class MyCustomStyle extends MultilineRecursiveToStringStyle {
    private MyCustomStyle() {
        setUseIdentityHashCode(false);
        setUseShortClassName(true);
    }

    public static final MyCustomStyle INSTANCE = new MyCustomStyle();
}

...

@Override
public String toString() {
    return new ReflectionToStringBuilder(this, MyCustomStyle.INSTANCE).build();
}

Note that in both cases, I only create one new class and one single instance of that class. I put that instance in a static final field, and reuse the static final field whenever I can.

By doing this, you wouldn't end up creating 100 MultilineRecursiveToStringStyle subclasses if you want to override toString 100 times using the same style, which you would have done if you repeated the DBI 100 times.

Sweeper
  • 213,210
  • 22
  • 193
  • 313