Re: Get Path Where A Class Is Located

  • Thread starter gimme_this_gimme_that
  • Start date
G

gimme_this_gimme_that

Try this ...

Create the following ksh utility and put it in your local bin
directory.
Call it jwhich.

#!/bin/ksh

/usr/j2se/bin/java -classpath $CLASSPATH:/home/emmmcl01/bin JWhich $*

And then use the class file compiled from the code below:

This class does sort of what you want, it locates the class in the jar
files on disk in your classpath.

This gives you a utility that works like

jwhich org.jdom.Element
/home/me/jars/jdom.jar


public class JWhich
{
/**
* Returns the absolute pathname of the class file
* containing the specified class name, as prescribed
* by the current classpath.
*
* @param className The full (package-qualified) name of the class.
* @return the absolute pathname of the file containing the class
specified by <code>className</code>
*/
public static String which( String className )
{
if ( !className.startsWith("/") )
{
className = className.replace( '.', '/' );
className = className + ".class";
className = "/" + className;
}

java.net.URL classUrl = new JWhich().getClass().getResource(
className );

if ( null == classUrl ) return( null );
return( classUrl.getFile() );

}//which( String )


public static void main( String args[] )
{
if ( args.length > 0 )
{
String className = args[0];
String classfilePath = JWhich.which( className );

if ( null != classfilePath )
{
System.out.println( classfilePath );
}
else
{
System.out.print( "Class '" + className + "'" );

char cpSep = System.getProperty( "path.separator" ).charAt(0);
String classPath = System.getProperty( "java.class.path" );
classPath = classPath.replace( cpSep, '\n' );

System.out.println( " not found in\n" + classPath );
}
}
else
{
System.err.println( "Usage: java " + JWhich.class.getName() + "
<classname>" );
}

}//main( String args[] )

}//class JWhich
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top