1010import java .net .URL ;
1111
1212public class JarLoader {
13+ private static sun .misc .Unsafe unsafe ;
14+ private static long offset ;
15+ private static Object parentUcp ;
1316 private static Object ucp ;
1417 private static MethodHandle addURLMethodHandle ;
1518
@@ -23,12 +26,26 @@ public static File load(File file) {
2326 return file ;
2427 }
2528
29+ @ SneakyThrows
30+ public static File parentLoad (File file ) {
31+ if (parentUcp == null )
32+ throw new IllegalStateException ("parentUcp is null." );
33+ addURLMethodHandle .invoke (parentUcp , file .toURI ().toURL ());
34+ return file ;
35+ }
36+
37+ @ SneakyThrows
38+ public static File load (File file , ClassLoader loader ) {
39+ addURLMethodHandle .invoke (unsafe .getObject (loader , offset ), file .toURI ().toURL ());
40+ return file ;
41+ }
42+
2643 private static void initReflect () {
2744 try {
28- ClassLoader loader = ClassLoader . getSystemClassLoader ();
45+ ClassLoader loader = JarLoader . class . getClassLoader ();
2946 Field theUnsafe = sun .misc .Unsafe .class .getDeclaredField ("theUnsafe" );
3047 theUnsafe .setAccessible (true );
31- sun . misc . Unsafe unsafe = (sun .misc .Unsafe ) theUnsafe .get (null );
48+ unsafe = (sun .misc .Unsafe ) theUnsafe .get (null );
3249 Field field = MethodHandles .Lookup .class .getDeclaredField ("IMPL_LOOKUP" );
3350 MethodHandles .Lookup lookup = (MethodHandles .Lookup ) unsafe .getObject (unsafe .staticFieldBase (field ), unsafe .staticFieldOffset (field ));
3451 Field ucpField ;
@@ -37,11 +54,13 @@ private static void initReflect() {
3754 } catch (NoSuchFieldException e ) {
3855 ucpField = loader .getClass ().getSuperclass ().getDeclaredField ("ucp" );
3956 }
40- long offset = unsafe .objectFieldOffset (ucpField );
57+ offset = unsafe .objectFieldOffset (ucpField );
4158 ucp = unsafe .getObject (loader , offset );
4259 Method method = ucp .getClass ().getDeclaredMethod ("addURL" , URL .class );
4360 addURLMethodHandle = lookup .unreflect (method );
44- } catch (Exception e ) {
61+ if (loader .getParent () != null )
62+ parentUcp = unsafe .getObject (loader .getParent (), offset );
63+ } catch (Throwable e ) {
4564 throw new RuntimeException (e );
4665 }
4766 }
0 commit comments