智能 Java 格式化程序
我正在寻找一个类似于标准格式化程序的智能Java字符串格式化程序:
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer);
formatter.format("hello %1$s, %2$s and %3$s", "me", "myself", "I");
问题是,如果您在格式中犯了错误(例如您忘记了$s
),则会抛出异常。在格式化错误消息时,这并不是我真正想要的(因为它不在应用程序的常规路径中,并且可能未经过测试)。
我当然可以定义自己的类,假设接受像 "hello $1, $2 and $3
这样的字符串,用 ($1
-> % 进行替换1$s
)并为所有参数调用 toString()
但我确信已经
在某个 jar 中开发了更好的解决方案...
感谢您提供任何有用的指针。
编辑
我正在寻找类似以下内容的内容:
String out = MySpecialFormatter.format("hello $1, $2 and $3", "me", "myself", "I");
如果您的格式有错误(好吧,存在拼写错误),它会尽力填写绑定变量,或返回原始值。格式字符串。
I'm looking for a smart Java String formatter similar to the standard Formatter:
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer);
formatter.format("hello %1$s, %2$s and %3$s", "me", "myself", "I");
The problem is that if you make a mistake in the format (e.g. you forget the $s
) an exception will be thrown. Not really what I want when formatting an error message (since it's not in the regular path of the application and may not be tested).
I could of course define my own class, let's say accept a string like "hello $1, $2 and $3
, do the replacement with ($1
-> %1$s
) and invoke the toString()
for all parameters but I'm sure a better solution has been already developed.
Somewhere, in some jar...
Thanks for any useful pointer.
EDIT
I'm looking for something that like the following:
String out = MySpecialFormatter.format("hello $1, $2 and $3", "me", "myself", "I");
if you have an error in your format (well, typos exist), it tries its best to fill in the bind variables, or return the original format string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有时答案就在那里……
是的,匿名,显然 Sun 认为所有程序员都那么懒。
Sometimes the answer is right there...
And yes, Anon, apparently Sun thought that all the programmers where that lazy.
所以你基本上会问“如果我没有测试我的代码并且它是错误的,我可以用什么来隐藏它而不是必须处理它?”
解决方案是正确测试所有代码。当你写的时候,最好。
如果您坚持掩盖错误代码并假装它不存在,您可以执行以下操作:
So you're basically asking "If I haven't tested my code and it's wrong, what can I use to hide that instead of having to deal with it?"
The solution is to properly test all your code. When you write it, preferably.
If you insist on covering up your bad code and pretending it's not there, you could do the following:
String.format 不适合您正在寻找的内容吗? Java 文档 用于字符串格式。
Is String.format not suitable for what you are looking for? Java doc for string format.