How to generate bytecode of existing class at Runtime in Java?
My Existing class is say Foo.java
public class Foo {
public String saySomething() {
return "Hello World";
}
}
Now I want to generate byte code of this existing class Foo.java
and probably use it in another instance of JVM. Please understand I am not creating a class at runtime since I already have an existing class called Foo.java
. Open to any libraries such as ASM or ByteBuddy etc.
[Edited following the clarification in the comments]
The following article describes how to compile a class from source code at runtime, using ToolProvider.getSystemJavaCompiler()
.
You do not need a library for that, any class file is just a resource just like any other file which can be located by Foo.class.getResource("Foo.class")
. You can open a stream of this resource and read its byte just as of any other resource.
If you are already using Byte Buddy, you can get hold of the bytes by: ClassFileLocator.ForClassLoader.read(Foo.class)
but if that is all you need, using a library would be an overkill.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.