Which string library can I use?

1

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

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

The current code is using the org.apache.commons.lang3.builder.ToStringBuilder and org.apache.commons.lang3.builder.ToStringStyle libraries:

ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);

What is the pure java library that can do just that? I know I have StringBuilder but I do not know a method that does this same action.

    
asked by anonymous 01.03.2018 / 17:44

1 answer

1

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

You can build the String "on 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 this?

ToStringBuilder is not an "eclipse plugin": it is a library added to the project, but specifically the commons-lang3, from Apache. There is nothing too much about using separate libraries in your projects. You will not go far with an application if you want to do everything "on hand", in fact, it is not recommended to reinvent the wheel.

    
01.03.2018 / 19:03