0

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

在片段中,我将插件项目指定为“主机插件”。此外,我在 build.properties 窗格中指定以下内容:

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。

我试图在主机插件中做同样的事情,它工作正常。关于为什么我在使用 Junit 时无法读取 PDE 片段中的资源的任何想法?

4

3 回答 3

0

您可能遇到的一个问题是

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

在“this”位于不同包中的两种情况下表现不同。由于您没有在开头附加“/”,java 将自动开始查看包根目录而不是资源的类路径根目录。如果你的插件项目和你的fragment项目中的代码存在于不同的包中,那你就有问题了。

于 2010-08-06T21:55:36.183 回答
0

尝试使用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);
于 2010-08-07T16:14:51.183 回答
0

Andrew Niefer 指出了方向,但解决方案是错误的。那是一个有效的方法:

1)添加super();到您的 Activator 构造函数。
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() 在 Plugin 中是 final 的。

注意 (2) 中的 Activator.getDefault()。没有它捆绑是无法访问的,它不是静态的。如果您只是创建一个新的 activator 实例,它的 bundle 将为null


还有另一种获取捆绑包的方法:

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

仅检查Activator.PLUGIN_ID是否设置为正确的字符串 - 就像插件概览页面的 ID 字段中一样。顺便说一句,无论如何,您应该在每次更改插件 ID 后检查Activator.PLUGIN_ID一点。

于 2012-05-18T15:04:31.350 回答