How to avoid class.forName () in OSGi?

I am relatively new to OSGi and our department. goes into the scope of OSGi. I have two packages A and B. B depends on A, so I included it in the manifest file B as Import-Package: A.

In addition, I have a specific class in A that uses reflection to access a specific class from B. Class in uses the class .forName (class in B). I want to get rid of this reflection, as this can cause problems when switching to OSGi. How can I get rid of this .forName () class?

Thanks!!

+4
source share
3 answers

At OSGi, you'll want to stay away from thinking for the reasons outlined in many other places.

So your situation is that package A requires some instance of the class that is in package B For A to understand this instance, I assume that it has some interface that it will use to talk to the instance. Let me make it a little more specific.

 /Bundle A /ThingyInterface.class /Bundle B /ThingyImplementation.class (implements ThingyInterface.class) 

This is a regular template: one package provides an interface, and the other provides an implementation. Now two situations are possible:

  • A requires exactly one copy of the implementation. In this case, register Thingy as a service.
  • A few instances of the implementation are required. In this case, enter ThingyFactory in A and create an implementation of this factory in B , which then registers as a service.

In any case, you allow B to actually create the instance, you have no dependency on A to B , and B does not need reflection to create the objects.

In short, services are your friend.

+4
source

In my opinion, two ways to create objects in Java

  • Call Designer with the new
  • use reflection

So, if u wants to avoid reflection, you can only import the class into bundle A, then new () instance (for this you need imprt B in bundle A). But since the B alreadys bundle depends on A, this will cause cross-dependency, which is not allowed in OSGi. Therefore, I suggest that you reorganize your class to extract such code from package A and move it to package B.

0
source

I don't know your specific use case, but it looks like you have spaghetti. You said that Bundle B depends on A, and yet A has to load the class from B through reflection. This means that A also depends on B. Since you cannot have B → A → B, you need to remove one of the dependencies.

Or maybe you need another C kit that contains all the classes common to A and B. Remember that OSGi helps you create modules with clean interfaces. If you find that you have problems working with OSGi, this may be due to some abstractions or some kind of dependency that was not well developed.

0
source

All Articles