public abstract class KeyedMessage extends Object
MessageBundle
.
Such a message can be easily identified in a large system with thousands of
messages. In large systems, messages are grouped in categories with
corresponding textual resources. Within each category, each message has a
unique key. The messages themselves contain parameters following the
MessageFormat
convention.
Messages are only prepared when fetched with getMessage()
. Preparation
involves looking up messages in a resource bundle and formatting parameters.
Avoiding this overhead is especially useful when messages are sent to a logging
facility without knowing for sure that they will actually be logged.
Thanks to this feature, it is not necessary to bracket the logging calls with
tests of the current logging level. To force preparation of the message, for example
because objects passed as parameter are about to change, use getMessage()
,
which makes a copy of the formatted string the first time it is called, and
returns the copy on subsequent calls.
An application would extend this class as follows:
The property file ch/agent/foo/FOOMsg.properties would contains lines like:public class FOOMsg extends KeyedMessage { public class M { public static final String A123 = "A123"; public static final String X124 = "X124"; } private static final MessageBundle BUNDLE = new MessageBundle("FOO", ResourceBundle.getBundle("ch.agent.foo.FOOMsg")); public static KeyedMessage exception(String code, Object... arg) { return new KeyedMessage(new FOOMsg(code, arg)); } public static KeyedMessage exception(Throwable cause, String code, Object... arg) { return new KeyedMessage(new FOOMsg(code, arg), cause); } public FOOMsg(String code, Object... args) { super(code, BUNDLE, args); } }
Clients would throw exceptions and write messages so:A123=The answer is {0}. X124=What is the question?
The user would see:System.error.println(new FOOMsg(M.X124)); throw FOOMsg.exception(M.A123, 42);
FOO.X124 - What is the question? FOO.A123 - The answer is 42.
Constructor and Description |
---|
KeyedMessage(String key,
MessageBundle bundle,
Object... args)
Construct a keyed message.
|
Modifier and Type | Method and Description |
---|---|
String |
getCategory()
Return the message category.
|
String |
getKey()
Return the message key.
|
String |
getMessage()
Return the formatted text of the message.
|
String |
toString() |
public KeyedMessage(String key, MessageBundle bundle, Object... args)
nullis inserted, else the method
toString()
is
applied to the argument before it is inserted. Refer to
MessageFormat
for details on the format of arguments.key
- a String identifying the textbundle
- a MessageBundle
containing the wanted textargs
- zero of more argumentspublic String getCategory()
MessageBundle
.public String getKey()
public String getMessage()
Copyright © 2017. All rights reserved.