如何包装Java String.format()?
我想将 String.format() 方法包装在我自己的 Logger 类中。我不知道如何将参数从我的方法传递到 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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码有效。可变参数或多或少只是可变参数的语法装箱。
换句话说,以下两条语句实际上是相同的:
代码中的
args
将始终是一个Object[]
,无论您是否有 0、1、2 或任何其他数量的参数。请注意,这是在编译时确定的,并查看对象的静态类型,因此 String.format("%s %s", (Object)new Object[] {"Foo ", "Bar"}) 将导致数组被视为单个对象(在这种情况下会导致抛出运行时错误)。
如果您的代码仍然存在问题,请检查您的示例是否确实与您的代码的工作方式相同。
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:
Your
args
in your code will always be anObject[]
, 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.
我认为这会起作用:
希望它有效。我还没有测试过。
祝你好运
I think this will work:
Hope it works. I have not tested it.
Good luck