Add method to define class for existing classloader

This commit is contained in:
Mark Vainomaa 2016-12-16 17:16:19 +02:00
parent 3a303ed20b
commit 9034371326
1 changed files with 28 additions and 0 deletions

View File

@ -160,4 +160,32 @@ public class Reflect {
f.set(instance, value);
} catch (NoSuchFieldException|IllegalAccessException ignored){}
}
/**
* Load class from bytearray to existing class loader. Useful when you need to
* add generated class to classpath
*
* @param classLoader Class loader which defines given class
* @param name Class name
* @param data Class in bytearray
* @return Defined class
* @throws ClassFormatError thrown by ClassLoader
*/
@Nullable
public static Class<?> defineClass(@NotNull ClassLoader classLoader, @NotNull String name, @NotNull byte[] data)
throws ClassFormatError {
Method defineClassMethod = Reflect.getMethod(ClassLoader.class, "defineClass",
String.class, byte[].class, int.class, int.class);
if(defineClassMethod != null){
try {
defineClassMethod.invoke(classLoader, name, data, 0, data.length);
} catch (InvocationTargetException e) {
if(e.getTargetException() instanceof ClassFormatError){
throw (ClassFormatError)e.getTargetException();
}
}
catch (IllegalAccessException ignored){}
}
return null;
}
}