vasekt
vasekt

Reputation: 2095

Eclipse Virgo - classloader returns old class after bundle reload

I have bundle A and bundle B. Bundle B imports packages from bundle A and bundle B has Eclipse-RegisterBuddy set to bundle A. Bundle A loads class which is exported by B by Java reflection (Class.forName). When bundle B is redeployed, bundle A still has reference to classloader from old version of B, so Class.forName returns old class version from B. This causes that calling Class.isInstance from A returns false when argument is instance created in B and passed to method in A. Is there some way to refresh classloader in A to be able return new version of classes from B? It is possible to call bundle refresh A command from Virgo console, this solves this problem, but this refresh causes that all dependent bundles (B and others) are stopped and started again. This is not suitable in our application because bundle B and others which import packages from A are long running batch jobs and cannot be stopped.

Upvotes: 0

Views: 219

Answers (1)

Balazs Zsoldos
Balazs Zsoldos

Reputation: 6046

Class.forName() is an anti-pattern in OSGi, do not use that: http://wiki.osgi.org/wiki/Avoid_Classloader_Hacks

You should create an interface for your class. The interface should be stable. You should put this interface into a separate bundle like B.API. In bundle A, you should use this interface, instead of the class. After having the stable interface in a separate bundle, refreshing B will not cause the restart of your dependent bundles. You have several options to get the instance that you want:

Option 1

You should think in OSGi services and in their lifecycles. Bundle B should register an OSGi service that bundle A uses. You can write a ServiceTracker or use Declarative Services to get the service.

Option 2

You should choose option 1. I do not recommend option 2, but it can work if you do not want to use OSGi services due to some reason. Get bundle B in bundle A. Use bundleB.loadClass() to load the class type and cast it to the interface that is located in B.API.

Upvotes: 0

Related Questions