Java Reference
In-Depth Information
ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(newTCCL);
...
} catch (Throwable e) {
...
} finally {
Thread.currentThread().setContextClassLoader(oldTCCL);
}
Let's see how the TCCL can help you solve a class-loading issue without affecting the
API . Run this example:
$ ./chapter08/classloading/PICK_EXAMPLE 7
You should see an exception when the spoke attempts to load the Auditor class:
java.lang.ClassNotFoundException: org.foo.hub.test.Auditor
If you look at this spoke implementation, you'll see that it uses the TCCL , as shown here.
Listing 8.4 Audited spoke implementation with TCCL
public class SpokeImpl implements Spoke {
String address;
public SpokeImpl(String address) {
this.address = address;
}
public boolean receive(Message message) {
if (address.matches(message.getAddress())) {
Class msgClazz = message.getClass();
String auditorName = msgClazz.getPackage().getName() + ".Auditor";
try {
Class auditClazz = Thread.currentThread()
.getContextClassLoader().loadClass(auditorName);
Uses
current
TCCL
Method method = auditClazz.getDeclaredMethod(
"audit", Spoke.class, Message.class);
method.invoke(null, this, message);
return true;
} catch (Throwable e) {
e.printStackTrace();
return false;
}
}
return false;
}
}
As long as the TCCL is assigned properly by the container or the caller, this should
work. The OSG i standard doesn't define what the default TCCL should be: it's left up
 
Search WWH ::




Custom Search