Created
April 9, 2016 13:40
-
-
Save heipacker/ef641b43b52979f9c2c0320cc83a10d3 to your computer and use it in GitHub Desktop.
injectClassLoading
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
@Override | |
public Map<TypeDescription, Class<?>> inject(Map<? extends TypeDescription, byte[]> types) { | |
File jarFile = new File(folder, String.format("%s%s.jar", PREFIX, randomString.nextString())); | |
try { | |
if (!jarFile.createNewFile()) { | |
throw new IllegalStateException("Cannot create file " + jarFile); | |
} | |
JarOutputStream jarOutputStream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile))); | |
try { | |
for (Map.Entry<? extends TypeDescription, byte[]> entry : types.entrySet()) { | |
jarOutputStream.putNextEntry(new JarEntry(entry.getKey().getInternalName() + CLASS_FILE_EXTENSION)); | |
jarOutputStream.write(entry.getValue()); | |
} | |
} finally { | |
jarOutputStream.close(); | |
} | |
target.inject(instrumentation, new JarFile(jarFile)); | |
Map<TypeDescription, Class<?>> loaded = new HashMap<TypeDescription, Class<?>>(); | |
ClassLoader classLoader = ClassLoader.getSystemClassLoader(); | |
for (TypeDescription typeDescription : types.keySet()) { | |
loaded.put(typeDescription, classLoader.loadClass(typeDescription.getName())); | |
} | |
return loaded; | |
} catch (IOException exception) { | |
throw new IllegalStateException("Cannot write jar file to disk", exception); | |
} catch (ClassNotFoundException exception) { | |
throw new IllegalStateException("Cannot load injected class", exception); | |
} | |
} | |
/** | |
* Representation of the bootstrap class loader. | |
*/ | |
BOOTSTRAP { | |
@Override | |
protected void inject(Instrumentation instrumentation, JarFile jarFile) { | |
instrumentation.appendToBootstrapClassLoaderSearch(jarFile); | |
} | |
}, | |
/** | |
* Representation of the system class loader. | |
*/ | |
SYSTEM { | |
@Override | |
protected void inject(Instrumentation instrumentation, JarFile jarFile) { | |
instrumentation.appendToSystemClassLoaderSearch(jarFile); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment