Skip to content

Instantly share code, notes, and snippets.

@heipacker
Created April 9, 2016 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heipacker/ef641b43b52979f9c2c0320cc83a10d3 to your computer and use it in GitHub Desktop.
Save heipacker/ef641b43b52979f9c2c0320cc83a10d3 to your computer and use it in GitHub Desktop.
injectClassLoading
@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