Skip to content

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

Notifications You must be signed in to change notification settings

hakdogan/class-file-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Class File API

JEP 457 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(STR."\{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
.invokeInstruction(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

About

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

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published