Created
October 12, 2017 12:02
-
-
Save hengyunabc/644f8e84908b7b405c532a51d8e34ba9 to your computer and use it in GitHub Desktop.
Get SystemClassLoader/ClassLoader urls in java9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author hengyunabc 2017-10-12 | |
* | |
*/ | |
public class ClassLoaderUtils { | |
@SuppressWarnings({ "restriction", "unchecked" }) | |
public static URL[] getUrls(ClassLoader classLoader) { | |
if (classLoader instanceof URLClassLoader) { | |
return ((URLClassLoader) classLoader).getURLs(); | |
} | |
// jdk9 | |
if (classLoader.getClass().getName().startsWith("jdk.internal.loader.ClassLoaders$")) { | |
try { | |
Field field = Unsafe.class.getDeclaredField("theUnsafe"); | |
field.setAccessible(true); | |
Unsafe unsafe = (Unsafe) field.get(null); | |
// jdk.internal.loader.ClassLoaders.AppClassLoader.ucp | |
Field ucpField = classLoader.getClass().getDeclaredField("ucp"); | |
long ucpFieldOffset = unsafe.objectFieldOffset(ucpField); | |
Object ucpObject = unsafe.getObject(classLoader, ucpFieldOffset); | |
// jdk.internal.loader.URLClassPath.path | |
Field pathField = ucpField.getType().getDeclaredField("path"); | |
long pathFieldOffset = unsafe.objectFieldOffset(pathField); | |
ArrayList<URL> path = (ArrayList<URL>) unsafe.getObject(ucpObject, pathFieldOffset); | |
return path.toArray(new URL[path.size()]); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment