0

I am trying to write a wrapper method to prefix my log messages with method name and user id. I am using String.format to compose the message structure, but the problem comes with interpretation of varargs by String.format()

private String logMessage(@NonNull String methodName, @NonNull String userId, @NonNull String message, Object... arguments) {
    //String temp = String.format(message, arguments);
    //String msg = String.format("%s:: User:%s : %s", methodName, userId, temp);<--This works
    String msg = String.format("%s:: User:%s : " + message, methodName, userId, arguments);<--This prints address of arguments object
   log.info(msg);
}

Calling the above method as

logMessage(methodName, userId, "Some text here: %s",
                "test"));

The above call prints

someMethod:: User:1266 : Some text here: [Ljava.lang.Object;@705a8dbc

Why is String.format printing address of the String "test"?

learningtocode
  • 755
  • 2
  • 13
  • 27

2 Answers2

0

The argument object is actually an array of objects. And when you call the toString() method on this kind of object, you usually get something like you got :

[Ljava.lang.Object;@705a8dbc

In fact, [Ljava.lang.Object is a java bytecode type descriptor that means "This is an array ( '[' ) of java.lang.Object types ( 'Ljava.lang.Object')

705a8dbc

This is the hashCode hex value of the array. If you look at this SO question, you can see that, in the accepted answer, the documentation says that hashCode() method must return a unique identifier, and it is generally implemented by converting the internal address of the object to an integer, but it is not required

If you want to get the toString() value of each object in an array, you should use :

Arrays.toString(argument);

This static method retuns a string containing all the toString value of each objects separated by a comma, between square brackets like this :

[null, null, null, null, null] // Example with System.out.println(Arrays.toString(new Object[5]));
HatsuPointerKun
  • 637
  • 1
  • 5
  • 14
0

I see the problem, the varargs is actually an array and String.format is not expanding the arguments. I worked around the issue by passing the method name and user id after message like this:

logMessageWithPrefix("Some text here: %s",
                methodName, userId, "test")

and modifying the method as:

private String logMessageWithPrefix(@NonNull String message, Object... arguments) {
    String msg = String.format("%s:: Profile:%s : " + message, arguments);
    return msg;
}

Not a ideal solution as ppl might not pass in methodname and userid as method expects,but will add some notes on the method to prevent confusion.

learningtocode
  • 755
  • 2
  • 13
  • 27