具体代码如下:
public static void main(String[] args) {
URL[] urLs = Launcher.getBootstrapClassPath().getURLs();
System.out.println("启动类加载器加载的jar:");
for (URL urL : urLs) {
System.out.println("==> " + urL.toExternalForm());
}
printClassLoader("扩展类加载器和其加载的jar:",ClassLoaderJarPrint.class.getClassLoader().getParent());
printClassLoader("应用类加载器和其加载的jar:",ClassLoaderJarPrint.class.getClassLoader());
}
public static void printClassLoader(String name, ClassLoader CL) {
if (CL != null) {
System.out.println(name + " ClassLoader -> " + CL.toString());
printURLForClassLoader(CL);
} else {
System.out.println(name + " ClassLoader -> null");
}
}
public static void printURLForClassLoader(ClassLoader CL) {
Object ucp = insightField(CL, "ucp");
Object path = insightField(ucp, "path");
ArrayList ps = (ArrayList) path;
for (Object p : ps) {
System.out.println(" -=>" + p.toString());
}
}
private static Object insightField(Object obj, String fName) {
try {
Field f = null;
if (obj instanceof URLClassLoader) {
f = URLClassLoader.class.getDeclaredField(fName);
} else {
f = obj.getClass().getDeclaredField(fName);
}
f.setAccessible(true);
return f.get(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}