访问另一个osgi包中的资源?

u12*_*123 13 java eclipse osgi bundle

我使用eclipse Plug-in项目向导(使用eclipse Helios)创建了两个OSGI包A和B.

在bundle BI的清单文件中添加了bundle A作为依赖项.此外,我已经在A中导出了包,因此它们对于B是可见的.我还在捆绑包A中有一个.properties文件,我希望它对bundle B可见.在bundle AI的build.properties窗格中指定了:

source.. = src/
bin.includes = META-INF/,\
               .,\
               bundle_A.properties
Run Code Online (Sandbox Code Playgroud)

现在在BI中尝试使用以下命令加载.properties文件:

  private Properties loadProperties() {
    Properties properties = new Properties();
    InputStream istream = this.getClass().getClassLoader().getResourceAsStream(
        "bundle_A.properties");
    try {
      properties.load(istream);
    } catch (IOException e) {
      logger.error("Properties file not found!", e);
    }
    return properties;
  }
Run Code Online (Sandbox Code Playgroud)

但是这会产生一个nullpointer异常(在类路径中找不到该文件).

是否可以从bundle A导出资源(就像导出包时一样)或者以某种方式从B以另一种方式访问​​A中的文件(从bundle B访问bundle A的类加载器)?

Nei*_*ett 16

getEntry(String)方法Bundle用于此目的.您可以使用它从任何捆绑包加载任何资源.另请参阅方法findEntries(),getEntryPaths()如果您不知道bundle中资源的确切路径.

没有必要掌握bundle的类加载器来做到这一点.

  • 哇,对 12 年前的答案的评论!我认为这种混乱是由我的陈述“使用它从任何捆绑包加载任何资源”引起的。你是对的,它只搜索一个包的内容。但是,如果您拥有该捆绑包对象,则可以获取任何捆绑包的内容。 (2认同)

Joh*_*ter 4

如果您正在编写 Eclipse 插件,您可以尝试以下操作:

Bundle bundle = Platform.getBundle("your.plugin.id");

Path path = new Path("path/to/a/file.type");

URL fileURL = Platform.find(bundle, path);

InputStream in = fileURL.openStream();
Run Code Online (Sandbox Code Playgroud)