Skip to content

Latest commit

 

History

History
25 lines (14 loc) · 932 Bytes

README.md

File metadata and controls

25 lines (14 loc) · 932 Bytes

Class File API

JEP 4571 Class-File API is a preview API to provide a standard API for parsing, generating, and transforming Java class files.

This repository demonstrates how to create a class that has a field, invokes a method, and prints a message, and also how to parse it with the said API.

Generating

var className = Info.CLASS_NAME.getClassName();
ClassFile.of().buildTo(Path.of(className + ".class"), of(className),
classBuilder -> classBuilder
.withField("myField", of("java.lang.String"), ACC_PRIVATE)
.withMethodBody("hello", MethodTypeDesc.of(CD_void), ACC_STATIC,
codeBuilder -> codeBuilder
.getstatic(of("java.lang.System"), "out", of("java.io.PrintStream"))
.ldc("Hello, this class is generated by Class-File API which is a preview API to provide a standard API for parsing, generating, and transforming Java class files.")
.invokevirtual(of("java.io.PrintStream"), "println",
MethodTypeDesc.of(CD_void, of("java.lang.Object")))
.return_())
.withMethodBody("main", MethodTypeDesc.of(CD_void, of("java.lang.String").arrayType()), ACC_PUBLIC | ACC_STATIC,
codeBuilder -> codeBuilder
.invoke(Opcode.INVOKESTATIC, of(className), "hello", MethodTypeDesc.of(CD_void), false)
.return_()));
}

Parsing

var classModel = ClassFile.of().parse(getGivenClassBytes(Info.CLASS_NAME.getClassName()));
for (var classElement : classModel) {
switch (classElement) {
case MethodModel mm -> System.out.printf("Method name %s type %s%n", mm.methodName().stringValue(), mm.methodType().stringValue());
case FieldModel fm -> System.out.printf("Field name %s type %s%n", fm.fieldName().stringValue(), fm.fieldType().stringValue());
default -> {
}
}
}

Build and run

sh run.sh

Requirements

JDK 23 or later

Footnotes

  1. This proposal was refined by JEP 466 in JDK 23 and the finalized proposed version is JEP 484 targeted to JDK 24 with minor changes.