Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get bytecode from loaded class

Suppose in my JVM I have a loaded class Class<C> myClass. Is there a reliable way to ask the JVM for the bytecode contents of the .class? I.e. something like this:

<C> byte[] getClassBytecode(Class<C> myClass) {
    return /* the contents of the .class resource where C was loaded from */;
}

(obviously an InputStream would be as good as the byte[]). I know I can use myClass.getResource() (and friends) to fetch the class file, but hammering on the class name to get an URL to feed to getResource feels wrong. Also, I am not sure how this would behave in case C was dynamically generated (e.g. using javax.tools.JavaCompiler).

Any (better) idea?

note: the goal is to be able to push the bytecode classes to a different JVM and use a custom classloader to load them there

like image 771
CAFxX Avatar asked Jun 26 '13 13:06

CAFxX


People also ask

How do I read a .CLASS file bytecode?

Using javap. The Java command-line comes with the javap tool that displays information about the fields, constructors, and methods of a class file. Based on the options used, it can disassemble a class and show the instructions that comprise the Java bytecode.

Is .CLASS file a bytecode?

Yes, a Java class file is a file containing Java bytecode that can be executed on the Java Virtual Machine (JVM).

Is jar a bytecode?

jar and bytecode. bytecode is generate when java source code is compiled and byte code is platform independent, compiled byte code can run on any platform where jar or executable file which are platform dependent and after completing code that file are made/ given to end user.


1 Answers

note: the goal is to be able to load the bytecode using a custom classloader on a different JVM

A classloader doesn't just load bytecode. Therefore, if you were able to get the bytecode out of the JVM memory (which is theoretically possible if you write a lot of implementation-specific native code), it would be useless to your remote classloader. You need to give it an actual .class file.

And Class.getResource() is the best way to accomplish this task. Since it looks in the same package as the invoking class, all you need to do is take the class' simple name, append ".class" and you're done.

It does become a little more difficult if you have inner or nested classes, but that's an implementation detail that you'll have to deal with regardless (if you push the initial class, you'll still need to pull any dependent classes).

like image 73
parsifal Avatar answered Oct 01 '22 11:10

parsifal