Owen:
I looked into that code's origins, and now I realize that I found that
tutorial in the NetBeans site. It seems that it has been pulled off,
as the link is dead now. However, the page is still cached here:
http://tinyurl.com/38ne7e
In the author's discharge, he made an effort to explain his reasoning,
and he concludes: "it's a dirty hack", as you did.
Thanks!
-Ramon
---------
Working with bootstraps.
The OpenOffice.org Java API has its own methods for bootstrapping
OpenOffice.org. By "bootstrapping" OpenOffice.org, we simply mean
"starting up" or "launching" the OpenOffice.org application launcher.
This is done by finding the location of the juh.jar library and
looking for the soffice(.exe) executable in that location, or in one
directory above that location. This requires the juh.jar library to be
put on the CLASSPATH, enabling the application that you create in this
tutorial to find it. However, here we want to ship our own juh.jar
file (and others) with the application. In this case, this approach to
the bootstrapping mechanism doesn't work.
In order to solve this issue, there are two possibilities. First, it
is possible to make sure that Java can find the soffice(.exe)
executable every time. This can be done by putting the directory
containing the executable on the PATH in Windows, or on
LD_LIBRARY_PATH in Mac, Unix, and Linux. This requires action from
potential users and we want to prevent that.
So we choose the second possibility, which involves working with
access modifiers. In the Sun JDK, the system ClassLoader is an
instance of the class URLClassLoader. This class has a private method
called addURL, which is called when Java starts and which will add all
JARs and other resources needed. Using Reflection, we request an
instance of the URLClassLoader, make the addURL method accessible to
us, and add the directory containing the soffice(.exe) executable to
the stack of URLs in the URLClassLoader. It is a dirty hack, but it
works.
But, does it? Messing around with access modifiers of system classes
always is a risky business. The addURL method is declared protected
and there is a reason for this. Besides that, what if someone does not
use the Sun JDK? Or what if Sun decides to deprecate the addURL
method? Well, the Java specification is unclear about all of this, so
other JDKs may not use the URLClassLoader class as system ClassLoader.
For this reason, we have wrapped our code in a "loader instanceof
URLClassLoader" check to make sure nothing will break. This is the
price we have to pay for making our application work without the users
having to do anything for it, except use the Sun JDK.