OSGiTools implements OSGiToolsMXBean { @Override public long getLoadClassOrigin(long bundleID, String clazz) { Bundle b = bundleContext.getBundle(bundleID); if (b == null) throw new IllegalArgumentException("Not a valid bundle ID: " + bundleID); try { Class<?> cls = b.loadClass(clazz); ClassLoader classLoader = cls.getClassLoader(); if (classLoader instanceof BundleReference) return ((BundleReference) classLoader).getBundle().getBundleId(); else return 0; } catch (ClassNotFoundException e) { } return -1; } OSGiTools(BundleContext bc); @Override long getLoadClassOrigin(long bundleID, String clazz); @Override String getResourceURL(long bundleID, String resource);  }
@Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testGetLoadClassOrigin() throws Exception { URL res = getClass().getClassLoader().getResource( getClass().getName().replace('.', '/') + ".class"); File dir = new File(new File(res.getFile()).getParentFile(), "test"); Bundle b1 = Mockito.mock(Bundle.class); Mockito.when(b1.getBundleId()).thenReturn(1L); TestClassLoader tcl = new TestClassLoader(b1, dir.toURI().toURL()); Class barClass = tcl.loadClass("org.foo.Bar"); Class stringClass = String.class; Bundle b2 = Mockito.mock(Bundle.class); Mockito.when(b2.getBundleId()).thenReturn(2L); Mockito.when(b2.loadClass("org.foo.Bar")).thenReturn(barClass); Mockito.when(b2.loadClass("org.foo.Bazzz")).thenThrow(ClassNotFoundException.class); Mockito.when(b2.loadClass("java.lang.String")).thenReturn(stringClass); BundleContext bc = Mockito.mock(BundleContext.class); Mockito.when(bc.getBundle(1)).thenReturn(b1); Mockito.when(bc.getBundle(2)).thenReturn(b2); OSGiTools tools = new OSGiTools(bc); Assert.assertEquals(1, tools.getLoadClassOrigin(2, "org.foo.Bar")); Assert.assertEquals(-1, tools.getLoadClassOrigin(2, "org.foo.Bazzz")); Assert.assertEquals(0, tools.getLoadClassOrigin(2, "java.lang.String")); try { tools.getLoadClassOrigin(5, "org.foo.Baz"); Assert.fail("Should have thrown an IllegalArgumentException, bundle 5 doesn't exist"); } catch (IllegalArgumentException iae) { } }