Skip to content

Instantly share code, notes, and snippets.

@fmcarvalho
Created September 20, 2017 11:49
Show Gist options
  • Save fmcarvalho/1fecd5310f74c1153154886202a1e133 to your computer and use it in GitHub Desktop.
Save fmcarvalho/1fecd5310f74c1153154886202a1e133 to your computer and use it in GitHub Desktop.
ClassLoader interceptor
class ClassLoaderGw extends ClassLoader {
public ClassLoaderGw() {
super(null);
}
public Class<?> findClass(String name) throws ClassNotFoundException {
System.out.println("Loading...");
try{
InputStream classData = ClassLoader.getSystemResourceAsStream(name.replace('.', '/') + ".class");
if(classData == null) {
throw new ClassNotFoundException("class " + name + " is not findable");
}
byte[] array = bytes(classData);
return defineClass(name, array, 0, array.length);
} catch(IOException ex) {
throw new ClassNotFoundException(name);
}
}
private static byte[] bytes(InputStream is) throws IOException{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment