代码之家  ›  专栏  ›  技术社区  ›  polygenelubricants

在Eclipse中配置字符串外部化以使用${key}作为字段名

  •  2
  • polygenelubricants  · 技术社区  · 15 年前

    public class ExternalizeStringDemo {
        public static void main(String[] args) {
            System.out.println("Hello world");
        }
    }
    

    现在,我想将问候语外部化,也许是为了促进国际化/本地化等。使用Eclipse,我可以使用字符串外部化向导(Source/externalize Strings),并将其配置为:

    alt text

    • 创建文件 Personal Toys/src/Messages.java
    • Personal Toys/src/messages.properties
    • 编辑 ExternalizeStringDemo.java
      • "Hello World" Messages.getString("DEMO_GREETING")

    我的问题很简单:我是否可以让Eclipse将访问外部化,以将键用作字段名?也就是说,我希望访问是例如。 Messages.DEMO_GREETING .

    注:如果 [Substitution pattern] ${key} ,则生成的代码为 Messages."DEMO_GREETING" ,这不是有效的Java代码。


    1 回复  |  直到 15 年前
        1
  •  5
  •   polygenelubricants    15 年前

    Eclipse有一个新的字符串外部化机制,可以做到这一点;它使用自己的新消息包而不是Java的。你需要包括 org.eclipse.osgi….jar 在项目的生成路径中使用它。

    help.eclipse.org - Java development user guide > Reference > Wizards and Dialogs > Externalize Strings Wizard

    • 使用Eclipse的字符串外部化机制
      • 否则将使用新的Eclipse字符串外部化机制。
      • 注意:仅当项目生成路径包含 org.eclipse.osgi.util.NLS

    feature documentation :

    public class MyClass {
       public void myMethod() {
          String message;
          ...
          // no args
          message = Messages.getString("key.one"); //$NON-NLS-1$
          ...
          // bind one arg
          message = MessageFormat.format(
              Messages.getString("key.two"),
              new Object[] {"example usage"}
            ); //$NON-NLS-1$ //$NON-NLS-2$
          ...
       }
    }
    

    新代码:

    public class MyClass {
       public void myMethod() {
          String message;
          ...
          // no args
          message = Messages.key_one;
          ...
          // bind one arg
          message = NLS.bind(Messages.key_two, "example usage"); //$NON-NLS-1$
          ...
       }
    }
    

    截图

    alt text

    然后,提议的变更:

    alt text