Skip to content

Instantly share code, notes, and snippets.

@andyscott
Created April 6, 2012 15:35
Show Gist options
  • Save andyscott/2320854 to your computer and use it in GitHub Desktop.
Save andyscott/2320854 to your computer and use it in GitHub Desktop.
import java.lang.reflect.Method;
public class SystemClassLoader {
private static final Method defineClassMethod;
public static Class<?> loadClass(String className, byte[] b) {
// override classDefine (as it is protected) and define the class.
Class<?> clazz = null;
try {
Object[] args = new Object[] { className, b, new Integer(0), new Integer(b.length) };
clazz = (Class<?>) defineClassMethod.invoke(ClassLoader.getSystemClassLoader(), args);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return clazz;
}
static {
Method localMethod;
try {
localMethod = java.lang.ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class, byte[].class, int.class, int.class });
localMethod.setAccessible(true);
} catch (NoSuchMethodException localNoSuchMethodException) {
localMethod = null;
}
defineClassMethod = localMethod;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment