How to load a class by class name from OSGi runtime?

I am creating a package to connect to OSGi to provide the user with a function:

Usercase: User input the classname string and click "list" button, the corresponding class will be decompiled and show the text on GUI for user.

So here is my problem: I only have the class loader of my package, how can I get the OSGi container class loader to load a class by name from the entire OSGi container? (I expect that when OSGi starts, it will load all the packages and the entire class into memory, any class can be loaded with the OSGi container class loader, if it really exists and can)

Does anyone know how to do this? Sample codes are highly appreciated.

+5
source share
4 answers

I see two possible situations that can help you.

Any visible class

You can add an instruction like

DynamicImport-Package: *

, ,

Class.forName("com.company.class");

,

, , , , " . , .

-

private List<Class<?>> findClass(BundleContext context, String name) {
    List<Class<?>> result = new ArrayList<Class<?>>();
    for (Bundle b : context.getBundles()) {
        try {
            Class<?> c = b.loadClass(name);
            result.add(c);
        } catch (ClassNotFoundException e) {
            // No problem, this bundle doesn't have the class
        }
    }
    return result;
}
+8

OSGi , . , -. , , , A lib v1.0, B lib 2.0.

, . , (Bundle bundle, String fqClassname)

, BundleContext. , .

, . , . , .

, API: Bundle [] BundleContext.getBundles() Bundle.loadClass()

+8

I assume that you have the import directive in the package manifest to get the packages you need. If this is done, then all the classes you are looking for should be part of your class loader, and loading a class by name should work.

So, you are sure that you have something similar in META-INF / MANIFEST.MF in your kit:

Import-Package: foo.bar.com;
0
source

All Articles