Java Reference
In-Depth Information
were serialized. This is fine for classes that came from the bundle doing the deserial-
ization, but not for ones that came from another bundle, which are almost certainly
not exported. Unless the object graph is entirely contained within a single bundle,
this will always be a problem.
You may think that things are alright as long as all the types in the object graph are
visible through package imports, which is partly true. In cases where all types are
either contained within a single bundle or visible to that bundle as package imports,
you may find it helpful to write a custom serializer that accepts that bundle's class-
loader of the serialized class as a parameter, as shown in the following listing.
Listing 12.8
An ObjectInputStream that can handle restricted class visibility
public class SmartObjectInputStream extends ObjectInputStream {
private ClassLoader loader;
public SmartObjectInputStream(InputStream in, ClassLoader loader)
throws IOException {
super(in);
this.loader = loader;
Accept classloader
as parameter
}
protected Class resolveClass(ObjectStreamClass clazz)
throws IOException, ClassNotFoundException {
if (loader == null) {
return super.resolveClass(clazz);
} else {
String name = clazz.getName();
return Class.forName(name, false, loader);
Delegate to
superclass if needed
Use appropriate
classloader
}
}
}
Even in the ideal case where all classes are visible to a nominated classloader, there's
the potential for more subtle problems. If the bundle has been reresolved since it seri-
alized the object, then it may have been resolved to different packages. To combat
this, it's important to make sure serialization versioning is included in any declared
package versions.
One commonly used type of library that demonstrates several of the problem patterns
described in this section is the logging framework.
12.3
An example library conversion—logging frameworks in OSGi
A large number of logging frameworks are available, and it isn't our intent to name
and shame any particular implementation, but to point out the common patterns they
use, and why this is a problem in OSG i. We'll assume that you've already run the log-
ging framework JAR (s) through a tool to convert them into OSG i bundles.
Logging frameworks are typically structured with an independent API . This is the
part of the framework that applications code to, and typically has static factory meth-
ods for obtaining logger implementations. The applications then use the API to log
out messages independently from the underlying logging implementation.
 
Search WWH ::




Custom Search