Java: Getting Bytecode of Class at Runtime from within the Same JVM

☆樱花仙子☆ 提交于 2019-11-29 03:48:11

You could write your own ClassLoader and hack up a scheme which records the bytecode as classes are loaded.

You would need to override findClass to find the class file yourself, load it into memory, save the data somewhere (for later serialization), then call defineClass to define that class in the JVM.

Unless you are running code via a tricky classloader, you should be able to do something like this:

Class<?> clazz = ....
String className = clazz.getCanonicalName();  // e.g. "foo.Bar"
String resourceName = ... // map className to a resource name; e.g. "/foo/Bar.class" 
InputStream is = clazz.getClassLoader.getResourceAsStream(resourceName);

This gives you a handle on the contents of the ".class" file ... if it can be found.

Caveats. Some classloaders might:

  • not let to open the ".class" resources at all,
  • give you an encrypted bytecode stream, or
  • give you bytecodes that are nor exactly what is being run, due to some on-the-fly transformation performed by the classloader.

If this approach doesn't work, you are pretty much out of options because the JVM does not provide a way to access the actual bytecodes that were loaded.

You can also use the Java Instrumentation API for this. You get access to the bytes of the classfile before defineClass is invoked. You can change them too!

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