eclipse中形如$NON-NLS-1$注释的含义

刚刚接触eclipse时,经常在官方的例子中看到一些奇怪的注释,例如:shell.setText(Messages.getString("TestRef.hello")); //$NON-NLS-1$
这$NON-NLS-1$到底代表什么呢?当时在一阵浅尝辄止之后,也就忽略了这个问题,今天在阅读Rich Client Tutorial Part 2时,意外的发现了这行注释的真实含义……
^_^真是意外中的收获。

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

现在大家也许对注释$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

public class TestRef {                                
 public static void main(String[] args) {        
  Shell shell =new Shell();                          
  shell.setText(Messages.getString("TestRef.hello")); //$NON-NLS-1$               
 }
               

Messages.java

public class Messages {                                      
 private static final String BUNDLE_NAME = "test";//$NON-NLS-1$                                                     
 private static final ResourceBundle                       RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);                              
 private Messages() {                                                     
 }                                                                     
 public static String getString(String key) {            
  try {                                                               
   return RESOURCE_BUNDLE.getString(key);         
  } catch (MissingResourceException e) {              
   return '!' + key + '!';                                       
  }                                                                   
 }                                                                    
}

test.properties

TestRef.hello=Hello                                          

你可能感兴趣的:(eclipse中形如$NON-NLS-1$注释的含义)