Which string library can I use?

Asked

Viewed 198 times

1

I’m refactoring a code that uses the eclipse plug but I want to turn it into pure java. The idea is to transform String into something with this style:

Person@182f0db
[
   name=John Doe
   age=33
   smoker=false
]

Current code is using libraries org.apache.commons.lang3.builder.ToStringBuilder and org.apache.commons.lang3.builder.ToStringStyle:

ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);

What pure java library can I do just that? I know you have one StringBuilderbut I don’t know a method to do the same.

1 answer

1

How are you using this in the call to ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);, I suppose this is precisely the implementation of the toString() method of the Person class.

You can build the String "in hand" like this:

@Override
public String toString() {
    return new String(
        this.getClass().getSimpleName() + "@" + Integer.toHexString(System.identityHashCode(this))
            + "\n["
            + "\n  name=" + name
            + "\n  age=" + age
            + "\n  smoker=" + smoker
            + "\n]");
}

The question is, why would you want to do that?

Tostringbuilder is not from an "eclipse plugin": it is a library added to the project, but specifically Apache’s Commons-lang3. There’s nothing wrong with using loose libraries in your projects. You won’t get very far with an app if you want to do everything "at hand", by the way, it is not recommended to reinvent the wheel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.