How to detect types exported by OSGi package without installation / activation?

Basically I want to find out if jar implements any number of interfaces without activating or launching the package. Is it possible to read metadata from meta-inf from the API in the same way as the container does, but without activating the package?

I want to use OSGi to support plugins from which numerous interfaces will be published, and I would like to know which interfaces are implemented by the package when the user loads without activating the package, etc.

+3
source share
2 answers

, , , Java, - . , Declarative Services, . , ( ) , ( ).

, Java , . ( , ) , . Felix Equinox .

Felix. PackageAdmin:

 public void execute(String s, PrintStream out, PrintStream err)
{
    // Get package admin service.
    ServiceReference ref = m_context.getServiceReference(
        org.osgi.service.packageadmin.PackageAdmin.class.getName());
    PackageAdmin pa = (ref == null) ? null : 
        (PackageAdmin) m_context.getService(ref);

    // ... 

    Bundle bundle = m_context.getBundle( bundleId );
    ExportedPackage[] exports = pa.getExportedPackages(bundle);

    // ...
}
+2

- . ".class" bundle.findResource(...).

 BundleContext context = bundle.getBundleContext();
  ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName());
  PackageAdmin packageAdmin = (PackageAdmin)context.getService(ref);
  List<Class> agentClasses = new ArrayList<Class>();
  ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
  for(ExportedPackage ePackage : exportedPackages){
      String packageName = ePackage.getName();
      String packagePath = "/"+packageName.replace('.', '/');
      //find all the class files in current exported package
      Enumeration clazzes = bundle.findEntries(packagePath, "*.class", false);
      while(clazzes.hasMoreElements()){
       URL url = (URL)clazzes.nextElement();
       String path = url.getPath();
       int index = path.lastIndexOf("/");
       int endIndex = path.length()-6;//Strip ".class" substring
       String className = path.substring(index+1, endIndex);
       String fullClassName=packageName+"."+className;
       try {
     Class clazz = bundle.loadClass(fullClassName);
     //check whether the class is annotated with Agent tag.
     if(clazz.isAnnotationPresent(Agent.class))
      agentClasses.add(clazz);
    } catch (ClassNotFoundException e) { 
     e.printStackTrace();
    }
      }
  }
+2

Source: https://habr.com/ru/post/1707031/


All Articles