Programmatic creation of class files and self modifying code
-
liangchenblue at gmail.com
Sun Dec 24 12:10:42 UTC 2023
Hello Keerthivasan,
Currently, most Java applications parse and create Class Files with ASM
(short for "assembly") library, available at https://asm.ow2.io. It
requires Java 6 and above.
Given Java 6 is really old, Java Core Libraries is introducing the
Class-File API https://openjdk.org/jeps/457, allowing the Class File
handling to evolve with Java itself for better forward compatibility, as
existing ASM fails every time Java rolls out a new version.
In addition, javac uses an internal library in com.sun.tools, which is
planned to be replaced by Class-File API in the long run, though it might
be only after everything else has migrated due to javac having high
compatibility requirements.
For executing defined bytecode, there are 2 main ways:
1. You will define a custom ClassLoader with an accessible
defineClass(String, byte[], int, int), which works for all Java versions,
but is chunky (as you need to define a class to access defineClass)
2. You will use MethodHandles.Lookup.defineClass and
MethodHandles.Lookup.defineHiddenClass, available in Java 12 and 16
respectively. They are much more convenient, but can only define classes in
the same package. In addition, defineHiddenClass is the only way to define
"hidden classes", which unlike regular classes, can be unloaded when it's
no longer needed. (Previously, it was done by custom ClassLoaders that are
discarded explicitly)
P.S. The compiler-dev list is focused around development around javac, and
your question seems a bit off-topic. But I don't know which list is proper
for this question either.
Best
On Sun, Dec 24, 2023 at 2:58 AM Keerthivasan Raghavan <
mail2akash97 at gmail.com> wrote:
> Hi All,
>
> I am a newbie to java. How do I programmatically create "*.class" files
> using the compiler API? I do not want to parse "*.java" files , but
> generate "*.class" files. This brings me to the next question of how to
> execute dynamically generated byte code: just like JRE jas JIT I would like
> to programmatically JIT java byte code and execute it. This is inline with
> the concept of self modifying code:
>
> https://en.wikipedia.org/wiki/Self-modifying_code
>
> Any pointers/code-snippets to the compiler API that I can use would be
> helpful.
>
> Thank you,
> Keerthivasan Raghavan
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20231224/4974af86/attachment.htm>
More information about the compiler-dev
mailing list