Tech and Academic things for Chianshin

Thursday, April 09, 2009

Java Tip 105: Mastering the classpath with JWhich - JavaWorld

Java Tip 105: Mastering the classpath with JWhich - JavaWorld

1: public class JWhich {
2:
3: /**
4: * Prints the absolute pathname of the class file
5: * containing the specified class name, as prescribed
6: * by the current classpath.
7: *
8: * @param className Name of the class.
9: */
10: public static void which(String className) {
11:
12: if (!className.startsWith("/")) {
13: className = "/" + className;
14: }
15: className = className.replace('.', '/');
16: className = className + ".class";
17:
18: java.net.URL classUrl =
19: new JWhich().getClass().getResource(className);
20:
21: if (classUrl != null) {
22: System.out.println("\nClass '" + className +
23: "' found in \n'" + classUrl.getFile() + "'");
24: } else {
25: System.out.println("\nClass '" + className +
26: "' not found in \n'" +
27: System.getProperty("java.class.path") + "'");
28: }
29: }
30:
31: public static void main(String args[]) {
32: if (args.length > 0) {
33: JWhich.which(args[0]);
34: } else {
35: System.err.println("Usage: java JWhich ");
36: }
37: }
38: }

classpath : Java Glossary

classpath : Java Glossary: "import java.net.URL;
import java.security.CodeSource;

/**
* Find out where a class on the classpath will be loaded from.
* Fully qualified classname goes on the command line.
*/
public class Where
{
/**
* main
* @param args name of fully qualified class to find, using dots, but no dot class.
* e.g. java.exe Where javax.mail.internet.MimeMessage
*/
public static void main ( String[] args )
{
try
{
String qualifiedClassName = args[0];
Class qc = Class.forName( qualifiedClassName );
CodeSource source = qc.getProtectionDomain().getCodeSource();
if ( source != null )
{
URL location = source.getLocation();
System.out.println ( qualifiedClassName + ' : ' + location );
}
else
{
System.out.println ( qualifiedClassName + ' : ' + 'unknown source, likely rt.jar' );
}
}
catch ( Exception e )
{
System.err.println( 'Unable to locate class on command line.' );
e.printStackTrace();
}
}
}"