Java: Find Where the Class Come From with JWhich
September 25, 2008 02:58:27 Last update: October 14, 2008 22:49:32
This following code came from a JavaWorld tip, with some minor modifications.
public class JWhich { /** * Returns the absolute pathname of the class file * containing the specified class name, as prescribed * by the current classpath. * @param className Name of the class. */ public static String which(String className) { // It is necessary to prepend the slash (/). Otherwise, Class.getResource will // prepend the package name of the current class. if (!className.startsWith("/")) { className = "/" + className; } className = className.replace('.', '/'); className = className + ".class"; java.net.URL classUrl = new JWhich().getClass().getResource(className); return (classUrl == null) ? null : classUrl.getFile(); } public static void main(String args[]) { if (args.length == 0) { System.err.println("Usage: java JWhich <classname>"); return; } String path = JWhich.which(args[0]); if (path == null) { System.out.printf("Class '%s' not found on classpath\n", args[0]); } else { System.out.printf("Class '%s' found in: %s\n", args[0], path); } } }