-1

I need to create message class that can retrieve the data for message and print it out the problem is that I must provide in the message class to the static filed value like (public static String exc01 ="testErr";) if I remove the equal "testErr"; Im getting an error;

Exception in thread "main" java.lang.NullPointerException
    at java.util.PropertyResourceBundle.handleGetObject(Unknown Source)
    at java.util.ResourceBundle.getObject(Unknown Source)
    at java.util.ResourceBundle.getString(Unknown Source)
    at test1.Messages.getString(Messages.java:19)
    at test1.TestMessageClass.main(TestMessageClass.java:8)

1.why should I provide value to the static string exc01 in class message if the message properties file already contain the error value?

2.there is better/nicer to do this all logic of messages ?

for that I have created message class as follows

package msg;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Messages {
    private static final String BUNDLE_NAME = "test1.messages"; 
    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

    public static String exc01 ="testErr";
    public static String exc02; 

    private Messages() {
    }

    public static String getString(String key) {
        try {
            return RESOURCE_BUNDLE.getString(key);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }
}

I have file for message under the same package which is called messages.properties and contain the following message

exc01=Failed to create the extension for {0}
exc02=Failed to create the extension

I have created simple test program

public class TestMessageClass {
    public static void main(String[] args) {
        System.out.println(Messages.getString("exc01"));
        System.out.println(Messages.getString(Messages.exc01));
    }
}

print

Failed to create the extension for {0} !testErr!

4

1 回答 1

0

您的代码调用

Messages.getString(Messages.exc01)

Messages.exc01是一个变量或字符串类型。它的默认值为空。它不是您似乎相信的“exc01”。您将变量的名称与其值混淆了。

所以,如果你不初始化变量,上面的代码会尝试从属性文件中获取具有空键的消息,这没有意义:你必须提供一个非空键,这就是你得到一个空指针异常。

如果您想获取键“exc01”的消息,那么您可以使用

Messages.getString("exc01")

或者您可以将任何字符串变量初始化为“exc01”,并传递此变量:

public static String exc01 = "exc01";
...
Messages.getString(Messages.exc01);

请注意,exc01 应定义为常量,而不是变量。因此它应该是最终的,并尊重常量的 Java 命名约定:

public static final String EXC01 = "exc01";
...
Messages.getString(Messages.EXC01);

请注意,如果您使用“testErr”初始化变量,正如您所做的那样,代码将在属性文件中查找与键“testErr”关联的消息。由于不存在这样的消息,您将收到 MissingResourceException,因此 ctach 块将返回!testErr!. 这就是为什么你有!testErr!你的测试输出。

于 2013-07-18T08:09:05.120 回答