Ant within Eclipse: switching JDKs and finding tools.jar – com.sun.tools.javac.Main is not on the classpath.

I've been doing quite a lot of work creating new Ant build processes and grokking Eclipse (installing and reinstalling on different machines), and this is a problem that keeps recurring. This morning I cleaned up vast amounts of garbage on my main Windows machine, garbage left over from old J2SDK installs (I had FOUR–when will Sun fix the install problem?) and I reinstalled JDK 1.4.2_03 and then tried running everything again within Eclipse (v3.0 M7). Needless to say, Ant was running fine before, after I had pointed to tools.jar but now that I had changed JDKs it wasn't guaranteed that it would run–and it didn't. While it is possible that this is so well known that people do it without thinking, it certainly isn't clearly documented, and it's a situation that people will probably find regularly doing a clean install of Eclipse and the JDK on a machine, or when upgrading JDKs after the settings have been done long ago–and forgotten. 🙂

First, the situation. On restart, Eclipse correctly detected the new JRE (clearly from the registry entries created by the JDK/JRE install) to the one the JSDK installs in C:\Program Files\Java\… but it's better to change the pointer to the JRE within the JDK IMO. Even then, Ant doesn't work. The error message you get is for Ant:

[javac] BUILD FAILED: [build file location here]
Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK

Of course, JAVA_HOME is pointing to the right location, in both the OS environment and within Eclipse (This variable can be set within Eclipse through Window > Preferences > Java > Classpath Variables).

So how to fix the Ant build problem?

I found various solutions searching, for example running Eclipse with "eclipse -vm [JDKPATH]\bin" but that didn't quite satisfy me (I wanted something that could be configured within the environment). Other solutions to the problem where even more esoteric.

The best solution I've found (after a little bit of digging through Eclipse's options) is to edit Ant's runtime properties. Go to Window > Preferences > Ant > Runtime. Choose the Classpath tab. Select the Global Properties node in the tree and click Add External JARs. Select tools.jar from your JDK directory (e.g., j2sdk1.4.2_03\lib\tools.jar). Click Apply and OK, and you should be on your way. Not too hard when you know what to do. Now if this could only be done automatically by Eclipse on install…

4 Replies to “Ant within Eclipse: switching JDKs and finding tools.jar – com.sun.tools.javac.Main is not on the classpath.”

  1. Hi there
    Thank you so much..
    Only this info could help me to fix the build problem for me..
    Great help..thanks a lot 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *