【问题标题】:Enum constant display name from properties file属性文件中的枚举常量显示名称
【发布时间】:2019-03-22 16:30:15
【问题描述】:

我的 EMF 模型中有一个枚举数据类型。

这就是我想要的:

  1. 我想为枚举常量提供漂亮的显示名称。
  2. 应在plugin.properties 文件中设置显示名称。
  3. 的机制必须与 EMF 系统很好地集成以从属性中获取值,以便我可以以统一的方式处理所有值,无论是否枚举。这可能意味着解决方案必须以某种方式使用IItemPropertyDescriptor

我可以看到枚举常量在我的 EMF 编辑项目中的 plugin.properties 中生成了条目。所以应该有一些方法可以得到这些名字。但我不知道怎么做。

我可以在我的 Xcore 模型文件中设置显示名称,但这不是我想要的。我希望从我的plugin.properties 文件中读取它们。

从属性文件中手动获取枚举显示名称很简单。但是应该有一些方法可以让 EMF 处理这个问题。每次从模型中获取值时,我都必须编写特殊代码来处理枚举值,这似乎很奇怪。

【问题讨论】:

    标签: java enums eclipse-emf emf


    【解决方案1】:

    这是一个例子:

    public enum Constants {
        PROP1,
        PROP2;
    
        private static final String PATH            = "/constants.properties";
    
        private static final Logger logger          = LoggerFactory.getLogger(Constants.class);
    
        private static Properties   properties;
    
        private String          value;
    
        private void init() {
            if (properties == null) {
                properties = new Properties();
                try {
                    properties.load(Constants.class.getResourceAsStream(PATH));
                }
                catch (Exception e) {
                    logger.error("Unable to load " + PATH + " file from classpath.", e);
                    System.exit(1);
                }
            }
            value = (String) properties.get(this.toString());
        }
    
        public String getValue() {
            if (value == null) {
                init();
            }
            return value;
        }
    
    }
    

    这可以是constans.properties 文件:

    #This is property file...
    PROP1=some text
    PROP2=some other text
    

    【讨论】:

    • 请注意,问题是关于 Eclipse 建模框架的。请参阅要求编号 3。这不是问题的相关答案。
    【解决方案2】:

    我已经设法使用 EMF 获取枚举显示值。但是有一个服务器限制,所以我不认为这可以解决。

    该解决方案通过调用ItemPropertyDescriptor.getLabelProvider 起作用。返回的标签提供程序是ItemDelegator,这是我发现的唯一一个具有从属性文件读取枚举文字的代码的类。因此,只需在该标签提供程序上调用 getText

    IItemPropertySource adapter = (IItemPropertySource) adapterFactory.adapt(eObject, IItemPropertySource.class);
    IItemPropertyDescriptor descriptor = adapter.getPropertyDescriptor(eObject, feature);
    Object propertyValue = descriptor.getPropertyValue(eObject);
    Object value = ((IItemPropertySource) propertyValue).getEditableValue(null);    
    String text descriptor.getLabelProvider(value).getText(value);
    

    限制是ItemDelegator“裁剪”返回的文本,将换行符后的所有文本替换为...

    不幸的是,我必须在我的应用程序的某些地方处理多行字符串,所以我仍然无法使用此解决方案以统一的方式处理所有功能。所以我真的很想找到一个更好的。

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2016-01-18
      • 1970-01-01
      • 2017-04-14
      • 2013-09-15
      相关资源
      最近更新 更多