is there a way to search the java classpath to find duplicate classes

I suspect that I have a duplicate class somewhere on a long and complicated classpath. Is there any easy way to find it other than by searching manually?
leo laydenAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
Is it a path composed of directories or jars, or both?
gurpsbassiCommented:
if your project is in an IDE then you should get multiple choices.
However there could of course be some proprietary jars providers by the environment too.
leo laydenAuthor Commented:
There are directories and jars in the classpath but I know the problem is in the directories. I'm confident about the contents of the jars.
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

leo laydenAuthor Commented:
... and I'm using Textpad to do the compile.
gurpsbassiCommented:
you are doing this  because you have a classpath conflict?
How did you come to this conclusion?
leo laydenAuthor Commented:
I SUSPECT that I MAY have a classpath conflict and am looking for a way to exclude the suspicion. I am using a utility that generates code (Altova Mapforce) and I'm invoking the code using reflection. I suspect that code from an earlier version may have been generated in the wrong place and is now interfering.
CEHJCommented:
Since you think the problem involves classes in directories, you could try a little Powershell

http://powershell.com/cs/blogs/tips/archive/2008/11/17/finding-duplicate-files.aspx
leo laydenAuthor Commented:
I was hoping there was some obscure method buried deep in Java that I could pass a Class to and it would tell me where on disk it would load the class from.

When the pressure came off me I wrote the following:

import java.util.StringTokenizer;
import java.io.File;
import java.io.PrintStream;

public class CheckClasspath
{      public static void main(String[] args)
      {      try { System.setOut(new PrintStream("C:/java/classpath.csv"));} catch (Exception e) {}
            String cp = System.getenv("CLASSPATH");
            StringTokenizer tkzer = new StringTokenizer(cp,";");
            while (tkzer.hasMoreTokens())
            {      String nextCandidate = tkzer.nextToken().replace("\\","/");
                  File nextFile = new File(nextCandidate);
                  if (nextFile.isFile()) System.out.println(nextCandidate);
                  else process(nextCandidate, nextCandidate);
            }
      }

      private static void process(String root, String directory)
      {      String[] filelist = new File(directory).list();
            for (int j = 0; j<filelist.length; j++)
            {      if (new File(directory+"/"+filelist[j]).isFile())
                        {      if (filelist[j].indexOf(".class")>0)
                              {      try
                                    {      String pckage = directory.replace(root,"").replace("/",".")+".";
                                          if (pckage.indexOf(".")==0) pckage = pckage.substring(1);
                                          String classname = filelist[j].replace(".class","");
                                          Class c = Class.forName(pckage+classname);
                                          System.out.println(classname+";"+pckage+";"+root);
                                    }
                                    catch (Exception e) {} //if no Class object was created, it doesn't work from this root
                              }
                        }
                  else process(root,directory+"/"+filelist[j]);
            }
      }
}

Then I just took the output and loaded it into Excel, sorted and looked for my offending class. Easy! I had over 12,000 classes on my classpath but that was not the source of my problem.

Thanks for your efforts trying to help me.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
leo laydenAuthor Commented:
Here's a better version.

It checks the jars/zips as well, including the ones in the /lib/ext folder

Still OS dependent but not difficult to rectify that

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class CheckClasspath
{      public static int count = 0;
      public static PrintStream p = null;
      public static String outfile = "C:/java/classpath.csv";
      // '/'s in paths is OS dependent

      public static void main(String[] args)
      {      if (args.length >0) outfile = args[0].replace("\\","/");
            listClasspath(outfile);
      }

      public static void listClasspath(String ofile)
      {      try { p = new PrintStream(ofile);} catch (Exception e) {e.printStackTrace();}
            p.println("class,package, root, order, error");
            String cp = System.getenv("CLASSPATH");
            StringTokenizer tkzer = new StringTokenizer(cp,";"); // ";" - OS Dependant
            String dotpath = new File(".").getAbsolutePath().replace("\\","/");
            dotpath = dotpath.substring(0,dotpath.length()-2);
            // process extensions directory
            String libext = System.getProperty("java.home").replace("\\","/")+"/lib/ext"; //default location
            String[] filelist = new File(libext).list();
            for (int j = 0; j<filelist.length;j++) processZip(libext+"/"+filelist[j]);
            while (tkzer.hasMoreTokens())
            {      String nextCandidate = tkzer.nextToken().replace("\\","/");
                  if (nextCandidate.equals(".")) nextCandidate = dotpath;
                  File nextFile = new File(nextCandidate);
                  if (nextCandidate != null)
                  {      if (nextFile.isFile()) processZip(nextCandidate);
                        else process(nextCandidate, nextCandidate);
                  }
            }
      }

      private static void process(String root, String directory)
      {      String[] filelist = new File(directory).list();
            for (int j = 0; j<filelist.length; j++)
            {      if (new File(directory+"/"+filelist[j]).isFile())
                        {      if (filelist[j].indexOf(".class")>0)
                              {      try
                                    {      String pckage = directory.replace(root,"").replace("/",".")+".";
                                          if (pckage.indexOf(".")==0) pckage = pckage.substring(1);
                                          String classname = filelist[j].replace(".class","");
                                          Class c = Class.forName(pckage+classname);
                                          count++;
                                          p.println(classname+","+pckage+","+root.toUpperCase()+","+count);
                                          // toUpperCase to make it easire to remove duplicates in Excel - OS Dependant
                                    }
                                    catch (Exception e) {}
                                    catch (Error er) {} ///if no Class object was created, it doesn't work from this root so ignore
                              }
                        }
                  else process(root,directory+"/"+filelist[j]);
            }
      }

      private static void processZip(String zipf)
      {      try
            {      ZipFile zip = new ZipFile(new File(zipf),ZipFile.OPEN_READ);
                  Enumeration<? extends ZipEntry> entries = zip.entries();
                  while (entries.hasMoreElements())
                  {      String ze = entries.nextElement().getName();
                        if (ze.endsWith(".class"))
                        {      ze = ze.substring(0,ze.length()-6);
                              try
                              {      Class.forName(ze.replace("/","."));
                                    count++;
                                    if (ze.indexOf("/")>=0) p.println(ze.substring(ze.lastIndexOf("/")+1)+","+ze.substring(0,ze.lastIndexOf("/"))+","+zipf.toUpperCase()+","+count);
                                    else p.println(ze+",, "+zipf+","+count);
                              }
                              catch (ClassNotFoundException e) {}
                               catch (Error er) // classes in jar files should be instantiable - so report errors to user
                               {      count++;
                                     if (ze.indexOf("/")>=0) p.println(ze.substring(ze.lastIndexOf("/")+1)+","+ze.substring(0,ze.lastIndexOf("/"))+","+zipf.toUpperCase()+","+count+" ,"+er);
                                    else p.println(ze+",, "+zipf+","+count+","+er);
                               }
                        }
                  }
                  zip.close();
            }
            catch (ZipException zexc) {p.println("zz ZipError in jar "+zipf+","+zexc);}
            catch (IOException e) {}
            catch (Error er) {p.println("zz Error in jar " + zipf.toUpperCase()+","+er);}
            // zz to put them at end of sort in Excel
      }
}
leo laydenAuthor Commented:
Solves the problem but is not elegant.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.