Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...