NetBeans Platform ClassLoader Trick

Note: You can use Lookup.getDefault().lookup(ClassLoader.class); This will get you classloader capable of loading resources from any enabled module. (David Strupl comment in this blog entry)

As you probably know in NetBeans Platform each module has its own ClassLoader. So if you want to load resources (eg: properties file, xml file, image file, etc) from another module basicly you are out of luck.

Just out of my head, there are at least 2 solutions avaiable:

  • Create Utility or Factory class in other module to return resources
  • Using other module ClassLoader to resolve the resources

However, if you are not careful the first method could lead to circular dependency problem. So I will focus on the second methods to get the resources from other modules using ClassLoader trick

Note: this is tested on NetBeans 6 beta1

Consider this scenario, you have API/SPI module, which you let other modules to implement that API eg:

  • API Module (MaskProvider API)
  • Impl Module 1 (MaskProvider Implementation 1)
  • Impl Module 2 (MaskProvider Implementation 2)
  • Impl Module xxx (MaskProvider Implementation xxx)

MaskProvider API is providing a list of Mask Image, where additional Mask Image could be added by installing the Impl Module xxx. You do not know, who will implement the API and how many implementation is available during design time. The API Module will be loaded on demand, and there is no way for the Impl Module xxx to register itself to API Module using ModuleInstall.restored() eg: Impl Module xxx tell its existence in the layer.xml that will be parsed by API Module when needed.

Now the problem is to allow code in API Module to get resources from registered Impl Module xxx. This is done by passing the Impl Module xxx object into the API Module, so the API Module could load the resources using the passed object ClassLoader.

This passing object could be done by using

  • Lookup
// this code is placed inside API Module, where SomeObject.class is
// located at Impl Module xxx
SomeObject obj = Lookup.getDefault().lookup(SomeObject.class);
SomeResources resources =  obj.getClass().getReourcesAsStream(...);
// or
ClassLoader cl = obj.getClass().getClassLoader();
  • Explicitly pass the object
// MaskItem is placed inside API Module, and the MaskProvider (owner) is
// located in Impl Module xxx
public MaskItem(MaskProvider owner,....) {
	SomeObject resources =  owner.getClass().getReourcesAsStream(...);
	// or
	ClassLoader cl = owner.getClass().getClassLoader();
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo