Improved MessageFormat?

I used it MessageFormat.format()for a while, but there is one thing that I find annoying.

Each time you declare a parameter in a message, you must know the position of the displayed argument. eg.

MessageFormat.format("{0} is annoying {1}.", "this", "indeed")

Is there the same class as MessageFormat, but allows you to completely omit the position of the argument in the parameter declaration and by default indicate its position in the message, so that the first parameter is mapped to the first argument, the second parameter to the second argument, and so on? eg.

MessageFormat.format("{} is much better{}.", "this", "indeed")

I think later versions of log4j have a similar function, but I just need a formatting class.

Happy New Year!

EDIT . I need this function for approval, so it is really for internal use, but I appreciate your understanding of why MessageFormat works the way it does.

+3
source share
3 answers

Instead, you should use Formatteror interface String.format. You can do:

String.format("%s is much better %s", "this", "indeed");
String.format("%1$s provides positional formatting %2$s", "this", "indeed");
+8
source

, , MessageFormat: I18N L10N. , " " . MessageFormat , &mdash, , , Java ResourceBundle.

(, ), , , , , , .

- , String#format().

+5

, . , . , , . , , , MessageFormat printf -style, String.format(). , " ".

Please note, however, that there is a reason to specify an index: internationalization. If you decide to move format strings to an external message set, it usually allows localization (in other languages), where the word order in a localized sentence may not correspond to the order of the lines in the argument list.

In short, you are better off sticking to your order. This makes it easier if you find that your application is incredibly successful, and you have incredible sales opportunities in any other country, if only you can get all your messages to go out in their language ...

+2
source

Source: https://habr.com/ru/post/1783033/


All Articles