Tuesday, September 23, 2008

Be careful when setting java.ext.dirs to include your JARs

When I found out that you can set java.ext.dirs to link a directory of JARs to your program, I was very happy, as was this guy. Normal way of linking JARs:
java -cp lib/helloworld.jar lib/foo.jar lib/bar.jar lib/jar.jar lib/cookie.jar ...
Easy way:
java -Djava.ext.dirs=lib ...
It's so much easier than adding 20 JARs to your classpath right? I found out that (surprise, surprise) this approach can cause pain too.

Sure it will work most of the time, but it turns out java.ext.dirs is already set to a directory in your JRE, such as C:\Program Files\Java\jdk1.6.0_07\jre\lib\ext. Ext stands for extension, which you can read about at Sun, but the takeaway is that you probably want to append to it rather than replace it. The more correct usage:
java -Djava.ext.dirs=jarlibdir;"C:\Program Files\Java\jdk1.6.0_07\jre\lib\ext" ...
Just make sure you have the right ext path for the JRE you're using.

In case you're wondering, I was getting an exception "com.jcraft.jsch.JSchException: Session.connect: java.security.NoSuchAlgorithmException: DH KeyPairGenerator not available" when I replaced the extension directory with my own, starting my program from the command line. It seemed strange since it was working in Eclipse. I found out after a while of poking around that SunJCE was involved. And where are the SunJCE JARs? That's right, in jre\lib\ext, which I had unwittingly unlinked. The lesson I guess is to be aware of what you're doing when you take shortcuts.

4 comments:

Anonymous said...

Thanks!
Its really nice to know this

Anonymous said...

Thanks!
Its really nice to know this

Anonymous said...

You save my day !

Thanks alot

Anonymous said...

By the way, it is possible to use the wildcard (*) in your classpath since Java 6. See http://stackoverflow.com/a/5039973/837703.