Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Checking that your classpath is valid

JavaFAQ Home » Story by Dr. Kabutz Go to all tips in Story by Dr. Kabutz

Bookmark and Share

The Java Specialists' Newsletter [Issue 037] - Checking that your classpath is valid

Author: Sydney Redelinghuys (with Dr. Heinz M. Kabutz in the peanut gallery)

JDK version:

Category: Software Engineering

You can subscribe from our home page: http://www.javaspecialists.co.za (which also hosts all previous issues, available free of charge Smile

Welcome to the 37th edition of "The Java(tm) Specialists' Newsletter", sent to 2103 Java experts in 62 countries. This week, my friend Sydney Redelinghuys has stepped in and provided the ideas for this newsletter, as well as most of the writing. Sydney was the brain behind the SoftHashMap newsletter that also made it onto DevX . I consider Sydney to be the 2nd best Java programmer that I know (position #1 is already given to Paul), [SR: So what position is given to HK] [HK: Position # 0 of course! ;-] but I marvel at the designs Sydney comes up with, I don't know anyone with such a knack for cool designs. Sydney found a copy of the Design Patterns book in the home economics section of his university (I will refrain from making comments regarding his university based on that last comment Wink)).

How do you go from being an OO beginner to an OO guru? Simple answer: Experience! But what if you can't wait 10 years to get that experience? Simple answer: Design Patterns! How can you learn Design Patterns from someone who has used them in the real world? Simple answer: Ask about my new course "Design Patterns - The Timeless Way of Coding".

Enough of my jabbering, let's see what Sydney, the one-legged Java Guru has to say ...

Checking Your Classpath Validity

The classpath - like most programmers, I really struggled with it in the beginning. I first cut my teeth on Java in middle of 1996 when I was a student doing some vacation work, as part of an experiment of using JDK 1.0 to solve the world's problems. As you might imagine, I caused more problems than I solved. I must've been the most underpaid Java programmer of all time - in today's South African currency terms, I only got US$ 272 for 2 months work (and that was with a 100% bonus)! Enough reminiscing, back to class paths. It is not that class paths are difficult to understand, it is just that it is too easy to get them wrong and not easy enough to locate errors, especially if you are used to case-insensitive NT paths. The classpath problem is so part of the Java culture that even The Onion reports on it! [HK: A must-read magazine for TJSN subscribers]

Even after I got more experienced it still seemed to eek its way into builds. In those days (before Ant and what not) we used to write huge batch files to check that all the required jars were available, I believe the company in question still does it Wink [HK: Actually, we had a chap who had an MCSE in WinNT 3.51 who was a real whizz at batch files. This, perhaps, was to our disadvantage.]

These days I am involved with Websphere, a product aimed at the Java professional who thinks he knows how Java works. This product will make even the seasoned Java expert quiver at his knees when he gets a MarshallException at run-time due to linkage errors often caused by an incorrect classpath. Note: in Websphere the classpath can be specified on at least three levels (container, server and node levels).

My first attempt at solving the marshall exception was to add another dynamic layer like any true geek developer. [HK: Sydney is truly the master of adding dynamic layers. That first Java program that he wrote for US$ 272 over 2 months took US$ 13500 of real professional Java programmers' time to debug.] Java does tend to make it too easy to do this with reflection, dynamic class loaders, dynamic proxies, soft references and all other kinds of weird & wonderful constructs this newsletter likes to comment on.

So, my first solution was to load the class files dynamically (via Class.forName(...)) and then to simply try catching the ClassNotFoundException:

try {
  Class my_class = Class.forName("ClassName");
} catch(ClassNotFoundException cnfe) {

Of course this worked, so now I could see the exception other application servers probably would have provided me with originally.

This really bugged me. I had to write compilers at varsity and I always thought I was doing the world a favour by doing compile time type checking etc. It surely is better to find a bug at compile time than at run-time, especially if your build-deploy cycle spirals into an affair that can take hours. [HK: With the batch files that we had originally the build cycle took so long that we could only do a weekly build!] [SR: I think the most time consuming part of that process was actually Source Safe]

Ant (or other similar build-tools) could solve some of these problems, unfortunately some of our components have to be deployed manually due to our IDE keeping information hidden. [HK: Isn't your IDE written in Java - perhaps you could use reflection to find the information dynamically and ... ] [SR: No such luck it is actually written in SmallTalk.]

So I asked myself: "Why does Sun keep the classpath hidden at runtime?" I decided to start digging in the jdk api's.

To load classes, the default class loader needs access to the classpath. The default class loader is very easy to get hold of, via the java.lang.ClassLoader.getSystemClassLoader static method. Unfortunately, the interface of java.lang.ClassLoader does not contain any methods that appear to be useful to us.

Just before I decided to start digging in the Sun source code, I noticed that java.security.SecureClassLoader extended java.lang.ClassLoader and java.net.URLClassLoader extended java.security.SecureClassLoader. By doing a quick experiment, I discovered that the System class loader (in the SUN VM) is indeed an instance of java.net.URLClassLoader. [HK: *evil grin*]

At this point I got all excited. Why? Because URLClassLoader contains a method getURLs() which returns the current classpath. So by writing the following small class, I can validate the classpath (i.e. make sure all the jars exist).

import java.net.*;
import java.io.*;

public class ClassPathInfo {
  private final ClassLoader classLoader;

  public ClassPathInfo(ClassLoader classLoader) {
    this.classLoader = classLoader;

  public ClassPathInfo() {

   * validates classpath, throws an LinkageError if invalid
   * classpath was specified
  public void validateClassPath() {
    try {
      URL[] urls = ((URLClassLoader)classLoader).getURLs();
      for(int i=0; itry {
        } catch(IllegalArgumentException iae) {
          throw new LinkageError(
            "malformed class path url:
        } catch(IOException ioe) {
          throw new LinkageError(
            "invalid class path url:
    } catch(ClassCastException e) {
      throw new IllegalArgumentException(
        "The current VM's System classloader is not a "
        + "subclass of java.net.URLClassLoader");

  public static void main(String[] args) {
    ClassPathInfo info = new ClassPathInfo();

Now it is possible to add batch or script files to replace java and javac. I was planning to leave this as an exercise for the reader but Heinz would have none of that [HK: Incidentally, someone sent me the "exercise to the reader" parts of the CircularArrayList, if any of you are interested]. It turned out to be more difficult than it initially seemed, as it is tricky to make sure that ClassPathInfo is in the classpath.

Firstly if you are a Unix user I shall leave this as an exercise for the reader. [HK: awww, come-on Syd] If you are using Windows you need to copy the following three batch files with ClassPathInfo.class to somewhere on your PATH. You also need to change the STRICTHOME enviroment variable in checkcp.bat to the directory these files were copied into.


@echo off 
rem Set STRICTHOME to the directory you're deploying this file to.
set STRICTHOME=C:strictjava

if ""=="%3" (
) else (
  if -classpath==%1 (
  )else (
    echo If more than three parameters are specified,
    echo the first has to be -classpath.
    set ERRORLEVEL=1
    goto end

java -classpath %STRICTCP% ClassPathInfo



@echo off
call checkcp %1 %2 %3
if not %errorlevel%==0 goto END
javac %1 %2 %3 %4 %5 %6 %7 %8 %9


@echo off
call checkcp %1 %2 %3
if not %errorlevel%==0 goto END
java %1 %2 %3 %4 %5 %6 %7 %8 %9

Please note that if you supply the classpath to these batch files, you will have to put it in quotes (i.e. strictjava -classpath "c:subjar1.jar;c:sub2jar2.jar" MyClass).


Sydney Redelinghuys (aka hopalong)

Copyright 2000-2004 Maximum Solutions, South Africa

Reprint Rights. Copyright subsists in all the material included in this email, but you may freely share the entire email with anyone you feel may be interested, and you may reprint excerpts both online and offline provided that you acknowledge the source as follows: This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa). Please contact Maximum Solutions for more information.

Java and Sun are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Maximum Solutions is independent of Sun Microsystems, Inc.

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy