获取另一个包中的私有包的捆绑类

时间:2016-06-18 09:27:03

标签: java osgi

我有两个osgi捆绑包A和B.捆绑包A的所有包都是私有的。在B组中,我使用了https://stackoverflow.com/a/22800118/5057736中的代码:

BundleA

class ClassA extends ClassB{
    ClassA(){
      super(ClassA.class);
    }
}

捆绑B

class ClassB{
...
public void doFoo(){
{ 
Bundle bundle = FrameworkUtil.getBundle(ClassAReference);  
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
// Getting all the class files (also from imported packages)
Collection<String> resources = bundleWiring.listResources("/", "*.class", BundleWiring.LISTRESOURCES_RECURSE);

List<String> classNamesOfCurrentBundle = new ArrayList<String>();
for (String resource : resources) {
    URL localResource = bundle.getEntry(resource);
    // Bundle.getEntry() returns null if the resource is not located in the specific bundle
    if (localResource != null) {
        String className = resource.replaceAll("/", ".");
        classNamesOfCurrentBundle.add(className);
    }
}

但是,我获得了资源 - 所有捆绑了类加载器的类。但是我只需要包含在A组中的类。我的意思是我需要属于bundle A的类。按照我的理解我需要localResource。但是,localResource始终为null,但类完全在bundle A中 - 例如ClassA。如何在ClassB中获取属于bundle A的类?

1 个答案:

答案 0 :(得分:1)

而不是

Collection<String> resources = bundleWiring.listResources("/", "*.class", BundleWiring.LISTRESOURCES_RECURSE);

使用

List<URL> resources = bundleWiring.findEntries("/", "*.class", BundleWiring.FINDENTRIES_RECURSE);

第二个函数仅查找特定包及其片段包中的资源。请参阅javadoc:https://osgi.org/javadoc/r4v43/core/org/osgi/framework/wiring/BundleWiring.html#findEntries(java.lang.String,%20java.lang.String,%20int)