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

如何在eclipsepde片段/插件项目的代码中使用从文件中获取的属性?

  •  0
  • u123  · 技术社区  · 15 年前

    我已经创建了一个eclipse插件项目和一个用于junit测试的相应片段项目。

    source.. = src/
    output.. = bin/
    bin.includes = META-INF/,\
                   .,\
                   my.properties
    

    其中my.properties是位于片段项目根目录下的文件。然后,我编写了一个测试,尝试像这样加载my.properties文件:

    Properties properties = new Properties();
    InputStream istream = this.getClass().getClassLoader()
        .getResourceAsStream("my.properties");
    
    try {
      properties.load(istream);
    } catch (IOException e) {
      e.printStackTrace();
    }
    

    但是 istream 为null,并且在try块中调用load时,测试失败并出现NullPointerException。

    3 回复  |  直到 11 年前
        1
  •  0
  •   Andrew Niefer    15 年前

    Bundle#getEntry . 如果您的插件具有 Activator ,则在插件启动时会得到一个BundleContext对象(使用 Bundle-ActivationPolicy: lazy 在你的舱单上)。您可以从BundleContext获取Bundle对象:

    public class Activator implements BundleActivator {
       private static Bundle bundle;
    
       public static Bundle getBundle() {
          return myBundle;
       }
       public void start(BundleContext context) throws Exception {
          bundle = context.getBundle();
       }
    }
    
    ...
    URL url = Activator.getBundle().getEntry("my.properties");
    InputStream stream = url.openStream();
    properties.load(stream);
    
        2
  •  0
  •   insipid    15 年前

    你可能遇到的一个问题是

    InputStream istream = this.getClass().getClassLoader().
    getResourceAsStream("my.properties");
    

    在“this”位于不同包中的两种情况下行为不同。由于您没有在开始处附加“/”,java将自动开始查看资源的包根,而不是类路径根。如果插件项目和片段项目中的代码存在于不同的包中,则会出现问题。

        3
  •  0
  •   Gangnus    13 年前

    安德鲁尼弗指出了方向,但解决方案是错误的。这是一个有效的方法:

    1) 添加 super(); 到激活器构造函数。
    2) 将其放入插件的构造函数中:

        Properties properties = new Properties();
    
        try {
            Bundle bundle=Activator.getDefault().getBundle();
            URL url = bundle.getEntry("plugin.properties");
            InputStream stream;
            stream = url.openStream();
            properties.load(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    你有功能性的“属性”。


    做(1)你将达到所有的功能:

    public class Activator implements BundleActivator {
       private static Bundle bundle;
    
       public static Bundle getBundle() {
          return myBundle;
       }
       public void start(BundleContext context) throws Exception {
          bundle = context.getBundle();
       }
    }
    

    它已经存在于前父类插件中。你不能把它放到Activator中,因为getBundle()是插件的最终版本。

    注意(2)中的Activator.getDefault()。没有它,捆绑是无法到达的 静态。如果您只是创建一个新的activator实例,那么它的包将是 .


    Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
    

    只检查一下 Activator.PLUGIN_ID 设置为正确的字符串-就像插件概述页的ID字段一样。顺便说一句,你应该检查一下这个 激活器插件ID 每次更改插件ID之后 无论如何