关于国际化中的$NON-NLS-1$

百度百科解释:

这实际与eclipse中支持i18n的一种方式eclipse的标准结构,将所有string常量定义到·properties中,例如下面程序段中的TestRef.hello实际上是·properties中的一个key TestRef.hello=Hello

eclipse时,经常在官方的例子中看到一些奇怪的注释,例如: shell.setText(Messages.getString("TestRef.hello")); //$NON-NLS-1$
这$NON-NLS-1$到底代表什么呢?当时在一阵浅尝辄止之后,也就忽略了这个问题,如下图:
 
现在大家也许对注释$NON-NLS-1$的含义就能够猜到个大概了,我个人猜测他也许就是non need localize string 1的缩写
rcp的文档里是这样表述的The string $NON-NLS-1$ is a hint for both the compiler and the Externalization(客观性,外表性,外部化) wizard that the first character string on this line is a tag or keyword of some sort and should not be localized.
也就是说$NON-NLS-1$表明本行的第一个string型变量是一个标签或者关键字,不需要被本地化.

 

 

TestRef.java文件

 

 1 import org.eclipse.swt.widgets.Display;
 2 import org.eclipse.swt.widgets.Shell;
 3 //TestRef.java文件
 4 public class TestRef {
 5     public static void main(String[] args) {
 6         TestRef window = new TestRef();
 7         window.open();
 8     }
 9     public void open() {
10         final Display display = Display.getDefault();
11         final Shell shell = new Shell();
12         shell.setSize(500, 375);
13         shell.setText(Messages.getString("TestRef.hello"));
14  
15         shell.layout();
16         shell.open();
17         while (!shell.isDisposed()) {
18             if (!display.readAndDispatch()) {
19                 display.sleep();
20             }
21         }
22     }    
23 }

Messages.java

 1 import java.util.MissingResourceException;
 2 import java.util.ResourceBundle;
 3 
 4 //Messages.java文件
 5 public class Messages {
 6     private static final String BUNDLE_NAME = "test";//$NON-NLS-1$
 7     private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
 8             .getBundle(BUNDLE_NAME);
 9 
10     private Messages() {
11     }
12 
13     public static String getString(String key) {
14         try{
15             return RESOURCE_BUNDLE.getString(key);
16         }catch(MissingResourceException e){
17             return '!' + key + '!';
18         }
19 
20     }
21 }

test.properties

TestRef.hello=Hellokxh
//TestRef.hello5=Hellokxh

运行结果:

如果在test.properties中没有这个对应的key就是文件中注释的部分的话

但是注意着几个文件之间的位置

test.properties文件是在src资源文件夹下.不能更换位置.

 

 
 
 
 
 
 
 
posted @ 2015-01-19 19:17  SummerChill  阅读(1509)  评论(0编辑  收藏  举报