Is it possible to force someone else's java ClassLoader to load an external byte array containing the bytecode of a valid Java class?

▼魔方 西西 提交于 2019-12-04 15:52:34

You can use Reflection with access override:

Method define = ClassLoader.class.getDeclaredMethod("defineClass",
                                      String.class, byte[].class, int.class, int.class);
define.setAccessible(true);
Class<?> clazz = (Class<?>)define.invoke(ClassLoader.getSystemClassLoader(),
                                      null, array, 0, array.length);

The access override is needed because we’re invoking a protected method, but being a protected method, it’s still part of the API, which exists in all implementations and won’t go away in future versions.


Java 9 introduced an astonishing simple way to achieve the same without a hack, as long as your own class has been loaded through the application class loader as well (as is the default):

Class<?> clazz = MethodHandles.lookup().defineClass(array);

This simply creates the class within the same class loading context as the class containing this statement.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!