<div dir="ltr">Hello Keerthivasan,<div>Currently, most Java applications parse and create Class Files with ASM (short for "assembly") library, available at <a href="https://asm.ow2.io">https://asm.ow2.io</a>. It requires Java 6 and above.</div><div>Given Java 6 is really old, Java Core Libraries is introducing the Class-File API <a href="https://openjdk.org/jeps/457">https://openjdk.org/jeps/457</a>, 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.</div><div>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.</div><div><br></div><div>For executing defined bytecode, there are 2 main ways:</div><div>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)</div><div>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)</div><div><br></div><div>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.</div><div><br></div><div>Best<br></div></div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Sun, Dec 24, 2023 at 2:58 AM Keerthivasan Raghavan <<a href="mailto:mail2akash97@gmail.com">mail2akash97@gmail.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr"><div><div><div><div>Hi All,<br><br></div>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:<br><br><a href="https://en.wikipedia.org/wiki/Self-modifying_code" target="_blank">https://en.wikipedia.org/wiki/Self-modifying_code</a><br><br></div>Any pointers/code-snippets to the compiler API that I can use would be helpful.<br><br></div>Thank you,<br></div>Keerthivasan Raghavan<br></div>
</blockquote></div>