Java Reference
In-Depth Information
Don't include a copy of package javax.servlet in its bundle JAR file, and import
it instead.
Include a copy of package javax.servlet in its bundle JAR file, and also export it.
If the approach in option 1 is taken
(see figure 5.1), bundle C can't be
used unless bundle B is present,
because it has a dependency on pack-
age javax.servlet and only bundle
B provides the package (that is, bun-
dle C isn't self-contained).
On the other hand, if the
approach in option 2 is taken (see fig-
ure 5.2), bundle C is self-contained,
and both B and C can be used
independently. But what happens if
you want bundle A to interact with
the javax.servlet.Servlet objects
from bundles B and C at the same time? It can't do so. Why?
The answer is technical, so we'll only briefly explain it. To use a class, Java must
load it into the JVM using a class loader. The identity of a class at execution time is not
only associated with its fully qualified class name, it's also scoped by the class loader
that loaded it. The exact same class loaded by two different class loaders is loaded
twice by the Java VM and is treated as two different and incompatible types. This
means if you try to cast an instance of one to the other, you receive a ClassCast-
Exception . Combine this knowledge with the fact that the OSG i specification requires
each bundle to have its own class loader for loading its classes, and you begin to
understand the issue with the second option we described.
If bundles B and C both include and export a copy of the javax.servlet package,
then there are two copies of the javax.servlet.Servlet class. Bundle A can't use
both instances, because they come from different class loaders and are incompatible.
Due to this incompatibility, the OSG i framework only allows bundle A to see one copy,
which means A can't collaborate with both B and C at the same time.
import
javax.servlet
C
One copy of
javax.servlet.Servlet
B
.cl as s
export
javax.servlet
A
import
javax.servlet
Figure 5.1 If bundle C imports from B, both can share
servlet instances with A because there's only one copy
of the Servlet class; but this creates a dependency for
C on B.
C
.cla s s
A
export
javax.servlet
Two copies of
javax.servlet.Servlet
import
javax.servlet
B
Figure 5.2 If B and C each have a copy of the
Servlet class, A can only share Servlet
instances with either B or C because it can
only see one definition of a class.
.cla s s
export
javax.servlet
Search WWH ::




Custom Search