How to wrap Java String.format()?
Asked Answered
A

2

6

I would like to wrap the String.format() method with in my own Logger class. I can't figure a way how to pass arguments from my method to String.format().

public class Logger
{
    public static void format(String format, Object... args)
    {
         print(String.format(format, args)); // <-- this gives an error obviously.
    }

    public static void print(String s)
    {
         System.out.println(s);
    }
}
Athwart answered 6/6, 2010 at 11:56 Comment(8)
And what would that error be?Pluckless
Yeah. What's the error? It looks fine to me.Thiol
error probably comes if you pass more than one argArrio
Yes, eugenK is right. When I pass more than one arg the var "args" is an array. And the function String.format() doesn't accept array as its second arg. As a last resort I will do something which looks like this: wrapper.tanukisoftware.org/jdoc/org/tanukisoftware/wrapper/…Athwart
Yes, String.format() DOES accept an array as its second arg... varargs is just a different syntax for an array parameter, effectively. What's the error?Coagulase
Compiles fine for me, for the record.Coagulase
and if I add a main method with just 'format("This is %s %s!", "pretty", "cool");', I get the expected output.Coagulase
Sorry guys. False alarm. (: I am using lejos Java virtual machine. And they do not have String.format(String format, Objects[] args) method implemented.Athwart
M
5

Your code works. The vararg is more or less simply a syntactic boxing of the vararg.

In other words,the following two statements are actually identical:

String.format("%s %s", "Foo", "Bar")
String.format("%s %s", new Object[] {"Foo", "Bar"})

Your args in your code will always be an Object[], no matter if you have 0, 1, 2 or any other number of arguments.

Note that this is determined at compile time and looks at the static type of the object, so String.format("%s %s", (Object)new Object[] {"Foo", "Bar"}) will cause the array to be treated as a single object (and in this case cause a runtime error to be thrown).

If you still have problems with your code, please check that your example really is identical to how your code works.

Mats answered 6/6, 2010 at 14:3 Comment(0)
A
1

I think this will work:

print(String.format(format, (Object[])args));

Hope it works. I have not tested it. Good luck

Antonina answered 6/6, 2010 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.