Domanda

I am doing some logging using org.slf4j.Logger in my code. There are places where it comes, i want to see the contents of the array, which mostly array of strings, array of object types. if object types mostly implemented with toString().
Is there any apache utils or something that gives arrays to to understandable strings?

È stato utile?

Soluzione

As suggested in other answer, you can use Arrays.toString() to construct the "meaningful" string presentation for an Array. Of course, it is assumed that you are using JDK 5+

A even more "correct" result should be using Arrays.deepToString(), for which if it is an other array instance contained in the array, the contained array is also properly converted to string.

If you are not using JDK5+, in Apache Commons Lang, you can make use of ArrayUtils.toString()

Given that you have mentioned about SLF4J Logger, there is something worth to look into.

When we are using SLF4J Logger, we always do something like

logger.info("data is {}", data);

The reason to do this instead of logger.info("data is " + data); is because the log message can be lazy-evaluated, only if the logger actually have INFO level enabled. It is especially useful when the message is expensive to construct.

However, simply using Arrays.deepToString() is going to take away this advantage:

logger.info("data is {}", Arrays.deepToString(dataArray));

Expensive dataArray to string conversion is happening no matter the logger is enabled with INFO level.

In order to solve it, you can explicitly check for logger level before logging:

if (logger.isInfoEnabled()) {
    logger.info("data is {}", Arrays.deepToString(arrayData));
}

You may also consider making a helper like this (pseudo-code):

public class ArrayToStringHelper {
    Object[] arrayData;
    public ArrayToStringHelper(Object[] arrayData) {
        this.arrayData = arrayData;
    }
    @Override
    public String toString() {
        return Arrays.deepToString(arrayData);
    }
}

So that the Array to String conversion is delayed until it is actually needed:

logger.info("data is {}", new ArrayToStringHelper(arrayData));

Altri suggerimenti

No need for any third party library to do this. Just use Arrays.toString

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top