Java Magazine, July/August 2018
Real World Bytecode Handling with ASM Scan inspect generate and transform bytecodes on the fly with the ASM library BEN EVANS ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 39 libraries The ASM library is a production quality open source library for reading writing and manipulating JVM bytecode It is used as part of many projects including Gradle and the Kotlin compiler and is used in shaded form that is as copied code with renamed packages to avoid namespace collisions inside the JDK In fact it is used as the code generation engine to enable runtime support of lambda expressions Note that when you are working with ASM you should use the external version not the shaded version present inside the JDK In this article I explain how to use ASM to perform some useful operations In what follows I assume that the reader is already familiar with some basics of JVM bytecode and the structure of class files You can find the code from this article on the Java Magazine download page A Hello World Example Lets take a look at a very traditional example namely creating a class that will print Hello World I will use ASMs ClassWriter API for this exercise It is a simple API that makes heavy use of the Visitor pattern to achieve its goals My example produces a new class file HelloWorld class completely from scratch This class will not have any Java source code representation that is it will exist only as a compiled class The HelloWorld class file will be created by another class MakeHelloWorld which will use the ASM libraries to assemble HelloWorld class as output However the generated output class will run completely standalone and will not need ASM or any other JAR as a runtime dependency PHOTOGRAPH BY JOHN BLYTHE
You must have JavaScript enabled to view digital editions.