I have the following scenario, I have a class loader and a class it loaded, and now I need the bytecode for that class. Here is what I have tried so far:
Field f = ClassLoader.class.getDeclaredField("classes");
f.setAccessible(true);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Vector<Class> classes = (Vector<Class>) f.get(classLoader);
for(Class loadedClass : classes)
{
String className = loadedClass.getName();
String classFileResourcePath = "/" + className.replace(".", "/") + ".class";
InputStream inputStream = classLoader.getResourceAsStream(classFileResourcePath);
System.out.println(">>>> " + className + " => " + classFileResourcePath + " => " + inputStream);
}
This code prints null
for each class file. But when I change it to classLoader.getClass().getResourceAsStream(classFileResourcePath)
it works if run in a standalone Main class in an IDE, but when I get to the actual context where this is needed, this returns null as well, presumably because there are "special" things happening with the jars and the classes behind the scenes. Without being able to discuss those details, it suffices to say what I have is a class and the class loader that loaded it, and now I need the byte code. How do I do this? If this is not possible in the Java layer, I may be able to fetch the original Jar itself and read it as a zip file, but that would be last resort.