OSGI

Page 85

3.9 JRE Packages

67

Fifth, the class loader searches the internal classes of any fragments that might be currently attached to the bundle. Fragments will be discussed in Section 3.11. There is a sixth step that is omitted by Figure 3.7, which is related to dynamic class loading. This is an advanced topic that will be discussed in Chapter ??. Figure 3.8 shows the full class search order in the form of a flowchart. This diagram is derived from Figure 3.18 in the OSGi R4.1 Core Specification. The class search algorithm as described always attempts to load classes from another bundle in preference to classes that may be on the classpath of the present bundle. This may seem counterintuitive at first, but in fact it makes a lot of sense, and it fits perfectly with the conventional Java approach. A traditional Java class loader always first delegates to its parent before attempting to define a class itself. This helps to ensure that classes are loaded as few times as possible, by favouring already-defined copies of a class over redefining it in a lower-level class loader. The opposite approach would result in many copies of the same class, which would be considered incompatible because they were defined by different class loaders. Back in OSGi, where the class loaders are arranged in a graph rather than a tree, the same principle of minimising class loading translates to making every effort to find a class from a bundle’s imports rather than loading it from the internal bundle classpath. Remember, the identity of a class is defined by the combination of its fully qualified name and the class loader which loaded it, so class org.foo.Bar loaded by class loader A is considered different from org.foo.Bar loaded by class loader B, even if they were loaded from the same physical bytes on disk. When this happens the result can be very confusing, for example a ClassCastException being thrown on assignment of a value of type org.foo.Bar to a variable of type org.foo.Bar!

3.9. JRE Packages In Section 3.4 we saw that it is necessary to always import all packages used in the bundle except for java.*. Therefore all of the other packages in the base JRE libraries, e.g. those beginning javax.*, org.omg.*, org.w3c.* etc must all be imported if used. As ordinary imports, these packages are not subject to parent delegation, so they must be supplied in the normal way by wiring the import to a bundle that provides them as an export. However, you do not need to create that bundle yourself: the system bundle performs this task. Recall from Section ?? that the system bundle is always present, and it represents the framework itself as a bundle. One of the jobs performed by the

DRAFT PREVIEW prepared for Christopher Brind


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.