javaosgiosgi-bundleeclipse-virgo

OSGi: How to get Classloader of other bundle


I have a Virgo-Tomcat-Server running. There is an EnumMap, whose key is

bundle.a.MyEnum

Context from this map is received via

bundle.b

and Spring expression language using a SpelExpressionParser, a sample expression would be "get(T(bundle.a.MyEnum).SAMPLEKEY)". The Parser (respectively its TypeLocator) needs access to the ClassLoader of bundle.a.

So I did:

TypeLocator typeLocator = new StandardTypeLocator(getBundleAClassLoader());
StandardEvaluationContext evaluationContext  = new StandardEvaluationContext();
evaluationContext.setTypeLocator(typeLocator);
spelExpressionParser = new SpelExpressionParser();
spelExpressionParser.parseExpression(expression)).getValue(evaluationContext, context);

The question is, what is the proper way to get the class loader of bundle.a in a class of bundle.b? After a couple of attempts, the only working solution I found is:

private static ClassLoader getBundleAClassLoader() {
    MyEnum bundleARef = MyEnum.SAMPLEKEY;
    return bundleARef.getClass().getClassLoader();
}

Edit: Solution

getBundleAClassLoader()

is not necessary,

TypeLocator typeLocator = new StandardTypeLocator(this.getClass().getClassLoader());

works fine.


Solution

  • This sounds too complicated. Just do an Import-Package in the Manifest of bundle.b and you can access the type in the same way as your own type.