I would like to know if it is possible to get the bytes of a class loaded by the bootstrap class loader. Everywhere I look, people suggest to get the bytes of an arbitrary class, one must simply do
Class.forName(className).getClassLoader().getResourceAsStream(className.replace('.', '/') + ".class");
And then read the InputStream
with a method of your choice, however this is not possible on classes loaded by the bootstrap class loader (such as java.lang.Object
), as for those classes Class#getClassLoader()
returns null
.
> Class.forName("java.lang.Object").getClassLoader()
null
Is this even possible? I've heard it can be done with instrumentation but I'm hoping there's a "better" way to do it (outside of locating rt.jar
in the Java installation and reading the class data from there or something)
I've figured it out. You just have to get the system class loader from ClassLoader#getSystemClassLoader()
.
ClassLoader loader = Class.forName(className).getClassLoader();
if (loader == null) loader = ClassLoader.getSystemClassLoader();
final URL url = loader.getResourceAsStream(className.replace('.', '/') + ".class");
// read...