/**
How to obtain the actual path of the loaded class in Java debugging
Java. Security. codesource;
Java. Security. protectiondomain;
Codesource can give the location of the class's original URL, but not every class has codesource. Codesource is empty if the class is loaded by the bootstrap loader.
**/
Import java. Lang. Reflect. method;
Import java.net. url;
Import java. Security. codesource;
Import java. Security. protectiondomain;
Public class findclasspath
{
Public static void displayclassinfo (class clazz, stringbuffer results)
{
Displayclassinfo (clazz, results, true );
}
Public static void displayclassinfo (class clazz, stringbuffer results,
Boolean showparentclassloaders)
{
Classloader Cl = clazz. getclassloader ();
Results. append ("/N" + clazz. getname () + "(" + integer. tohexstring (clazz. hashcode () + "). classloader =" + Cl );
Classloader parent = Cl;
While (parent! = NULL)
{
Results. append ("/n .." + parent );
URL [] URLs = getclassloaderurls (parent );
Int length = URLs! = NULL? URLs. Length: 0;
For (INT u = 0; U <length; U ++)
{
Results. append ("/n..." + URLs [u]);
}
If (showparentclassloaders = false)
Break;
If (parent! = NULL)
Parent = parent. getparent ();
}
Codesource clazzcs = clazz. getprotectiondomain (). getcodesource ();
If (clazzcs! = NULL)
Results. append ("/n ++ the codesource is:" + clazzcs );
Else
Results. append ("/n ++ can't find the codesource ");
Results. append ("/nimplemented interfaces :");
Class [] ifaces = clazz. getinterfaces ();
For (INT I = 0; I <ifaces. length; I ++)
{
Class iface = ifaces [I];
Results. append ("/n ++" + iface + "(" + integer. tohexstring (iface. hashcode () + ")");
Classloader loader = ifaces [I]. getclassloader ();
Results. append ("/n ++ classloader:" + loader );
Protectiondomain Pd = ifaces [I]. getprotectiondomain ();
Codesource cs = Pd. getcodesource ();
If (CS! = NULL)
Results. append ("/n ++ the codesource is:" + CS );
Else
Results. append ("/n ++ can't find the codesource ");
}
}
/** Use reflection to access a URL [] geturls or ULR [] getallurls method so
That non-urlclassloader class loaders, or class loaders that override
Geturls to return null or empty, can provide the true classpath info.
*/
Public static URL [] getclassloaderurls (classloader cl)
{
URL [] URLs = {};
Try
{
Class returntype = URLs. getclass ();
Class [] parametertypes = {};
Method geturls = Cl. getclass (). getmethod ("geturls", parametertypes );
If (returntype. isassignablefrom (geturls. getreturntype ()))
{
Object [] ARGs = {};
URLs = (URL []) geturls. Invoke (CL, argS );
}
}
Catch (exception ignore)
{
}
Return URLs;
}
Public static void main (string [] ARGs)
{
Stringbuffer sb = new stringbuffer ();
Findclasspath. displayclassinfo (testlong. Class, Sb );
System. Out. println ("the path is:" + sb. tostring ());
}
}