While studying java Gold, I wanted to understand the externalization of information and various properties files using sample code, so I wrote and executed the code in an integrated development environment.
However, no matter how much I try, I get a MissingResoueceException.
Why….
As a result of trial and error while staring at the run-time error, I was able to know the points to be noted. The following is a memorandum.
MyResource.java
package com.example.Locale.properties;
import java.util.ListResourceBundle;
public class MyResource extends ListResourceBundle{
private final static String resources[][] = {
{"helloworld", "Hello, World!"},
{"key","This is MyResource's key!"}
};
@Override
protected Object[][] getContents() {
return resources;
}
}
I would like to get the "key" described in the above code in the execution class.
Also, since ListResourceBundle is an abstract class, it is necessary to implement the abstract method "getContents".
For example, suppose the following sample code is shown.
ResourceBundle rb = ResourceBundle.getBundle("MyResource");
However, I couldn't get it well with this.
As a result of investigating for a small hour, the black book used for studying ([Thorough capture Java SE 8 Gold problem collection](https://www.amazon.co.jp/%E5%BE%B9%E5%BA%95] % E6% 94% BB% E7% 95% A5-Java-Gold-% E5% 95% 8F% E9% A1% 8C% E9% 9B% 86-1Z0-809 / dp / 4295000035 / ref = asc_df_4295000035 /? = jpo-22 & linkCode = df0 & hvadid = 288845875882 & hvpos = 1o1 & hvnetw = g & hvrand = 1789597220371198337 & hvpone = & hvptwo = & hvqmt = / hvdev = c & hvdvcmdl = & hvlocint = & hvlocphy = 1028851 & hvtargid = It was.
[Caution] If the resource bundle class is ** included in the package **, don't forget to qualify it with the package name.
That is, the name to be described in getBundle had to be a fully qualified name including the package name.
In the code above, the MyResource class had to be in the default package. However, since it was actually defined in the package, you need to move the file or write it in parentheses with a fully qualified name.
Below, a part of the execution class described with the fully qualified name and the execution result are listed.
--Execution class
Main.java
//Describe the resource class name as a fully qualified name.
ResourceBundle rb = ResourceBundle.getBundle("com.example.Locale.properties.MyResource");
String message = rb.getString("key");
System.out.println(message);
This is MyResource's key!
Since I am not actually working in the field due to mental and physical problems, the content may be incorrect or old-fashioned, but if I notice or find out in the future, I will write it down as a memorandum I would like to come.
I would be grateful if you could comment on any actual experiences or suggestions.
Thank you for reading.
Recommended Posts