Compiling Java Code in Memory: Custom File Objects and Dynamic Code Generation
Generating Java source at run time, compiling it from strings into byte arrays with SimpleJavaFileObject and ForwardingJavaFileManager, loading it with a class loader or as a hidden class, a formula compiler and a template engine, and generating bytecode directly with the ClassFile API (Java 24).
kvi5hnuCode Sprout team member11 min readOn this page
Article 77 compiled files on disk. Programs that generate code at run time usually do not want files at all. A rules engine turns user-defined formulas into classes, a template engine turns page templates into renderers, a test tool builds mock classes: the source is a string, the result should be a loaded class, and the disk is just a source of slowness, clutter and security problems. The Compiler API supports this through its abstraction of files, JavaFileObject and JavaFileManager. This article builds a small in-memory compiler, uses it for two realistic generators, and then shows the alternatives that skip the compiler: hidden classes and the ClassFile API.
Sources from strings
To the compiler, a compilation unit is a JavaFileObject. SimpleJavaFileObject implements most of the interface, so a source held in memory only needs a URI and getCharContent:
class StringSource extends SimpleJavaFileObject {
private final String code;
StringSource(String className, String code) {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension),
Kind.SOURCE);
this.code = code;
}
@Override public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
The URI path matters in two ways. Diagnostics use it as the file name (/gen/Bad.java), and the compiler checks that a public class lives in a file with a matching name, so gen.Hello belongs in .../gen/Hello.java. The scheme (string:) is arbitrary.
Class files into byte arrays
On the output side, the compiler asks its file manager for a place to write each class with getJavaFileForOutput. Wrap the standard file manager in a ForwardingJavaFileManager, which delegates everything to it, and override only that method:
class ByteArrayClass extends SimpleJavaFileObject {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayClass(String className) {
super(URI.create("bytes:///" + className.replace('.', '/') + Kind.CLASS.extension), Kind.CLASS);
}
@Override public OutputStream openOutputStream() { return out; }
byte[] bytes() { return out.toByteArray(); }
}
var classes = new LinkedHashMap<String, ByteArrayClass>();
JavaFileManager fm = new ForwardingJavaFileManager<>(standardFileManager) {
@Override public JavaFileObject getJavaFileForOutput(Location location, String className,
JavaFileObject.Kind kind, FileObject sibling) throws IOException {
if (kind == JavaFileObject.Kind.CLASS) {
var c = new ByteArrayClass(className);
classes.put(className, c);
return c;
}
return super.getJavaFileForOutput(location, className, kind, sibling);
}
};

Keep a map from class name to bytes, not a list: one source file can produce several class files. In the demo, gen.Hello yields gen.Hello, gen.Hello$Helper and gen.Hello$1 (an anonymous class), and all of them must be loadable.
Generated code can use any class that the standard file manager can see: the JDK, and by default the application's class path (java.class.path). To compile against other libraries, pass a -classpath option or set StandardLocation.CLASS_PATH. Classes that exist only in memory as well (for example, generated earlier) require overriding list and inferBinaryName in the file manager, which is more work; the simplest approach is to compile related sources in one task.
Loading the bytes
The bytes become a class through a class loader. A minimal one overrides findClass and calls defineClass:
class MemoryClassLoader extends ClassLoader {
private final Map<String, ByteArrayClass> classes;
MemoryClassLoader(Map<String, ByteArrayClass> classes, ClassLoader parent) {
super("memory", parent);
this.classes = classes;
}
@Override protected Class<?> findClass(String name) throws ClassNotFoundException {
ByteArrayClass c = classes.get(name);
if (c == null) throw new ClassNotFoundException(name);
byte[] b = c.bytes();
return defineClass(name, b, 0, b.length);
}
}
Because loadClass asks the parent first, the generated code shares the application's classes, in particular the interfaces it implements. That is the key to using generated code without reflection: let the generated class implement an interface the host already knows (Supplier, DoubleUnaryOperator, your own Rule), then cast the new instance to it. Article 80 explains class loaders and the delegation model in depth.
A useful side effect: when nothing refers to the loader, its classes and the loader itself can be garbage-collected and unloaded. Creating a fresh loader per generated unit lets long-running programs replace generated code without leaking memory.
Example 1: a formula compiler
A spreadsheet-like application lets users type formulas in x. Each formula becomes a tiny class:
String source = """
package gen;
public final class F%d implements java.util.function.DoubleUnaryOperator {
public double applyAsDouble(double x) { return %s; }
}
""".formatted(i, formula);
Once compiled, a formula runs at full JIT-compiled speed, which matters when it is evaluated millions of times. The demo shows two practical points:
- A compilation task succeeds or fails as a whole. Compiling all formulas in one task is faster, but one invalid formula (
x +* 2) fails them all. Compile per formula, or compile together first and fall back to individual compilation to find the culprit. - Error positions refer to the generated source. Map them back to what the user typed, for example by subtracting the offset at which the formula was inserted, before you show them.
Example 2: a template engine
Template engines such as JSP turn markup with embedded expressions into Java classes. The demo's compileTemplate does a miniature version: every literal part of Dear ${name}, your order of ${qty} item${qty == 1 ? "" : "s"} costs ... becomes an sb.append("..."), and every ${...} an sb.append(expr). The generated class implements Function<Map<String, Object>, String>. Literal text must be escaped for a Java string literal (backslashes and quotes), the simplest place to make a mistake in any code generator.
Hidden classes: loading without a class loader
Java 15 added hidden classes (JEP 371), designed for frameworks that generate classes at run time:
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> c = lookup.defineHiddenClass(bytes, true).lookupClass();
A hidden class:
- is defined in the same class loader, runtime package and module as the lookup class (so its bytes must declare a class in that package);
- has a name with a suffix (
Doubler/0x...) and cannot be found byClass.forNameor referenced from other classes by name, so it is only reachable through the returnedClassobject; - can be unloaded as soon as the
Classobject is unreachable, even while its loader is alive (unless defined withClassOption.STRONG).
That makes hidden classes ideal for generated helpers such as lambdas (the JDK uses them for lambda expressions) and for the formula objects above: no custom class loader is needed, and discarded formulas don't pile up. Lookup.defineClass(bytes) defines an ordinary, named class in the lookup's package instead.
Skipping the compiler: the ClassFile API
Generating Java source and compiling it is easy to understand, but javac is a large, slow tool, and it is absent in runtime images without jdk.compiler. Frameworks that generate lots of code produce bytecode directly. For years that required third-party libraries such as ASM or Byte Buddy; Java 24 made the java.lang.classfile API final (JEP 484):
byte[] bytes = ClassFile.of().build(ClassDesc.of("Answer"), cb -> cb
.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_FINAL)
.withInterfaceSymbols(ClassDesc.of("java.util.function.IntSupplier"))
.withMethodBody(ConstantDescs.INIT_NAME, ConstantDescs.MTD_void, ClassFile.ACC_PUBLIC,
code -> code.aload(0)
.invokespecial(ConstantDescs.CD_Object, ConstantDescs.INIT_NAME,
ConstantDescs.MTD_void)
.return_())
.withMethodBody("getAsInt", MethodTypeDesc.of(ConstantDescs.CD_int), ClassFile.ACC_PUBLIC,
code -> code.bipush(42).ireturn()));
Unlike source code, bytecode must spell out everything: the constructor calling Object.<init>, the stack operations, the return instruction. The API computes stack maps and the constant pool for you, and ClassFile.of().parse(bytes) reads class files into a ClassModel, which also makes it a tool for analyzing and transforming existing classes. Because it ships with the JDK, it always supports the current class file version, which external libraries have to catch up with.
| Approach | Needs | Best for |
|---|---|---|
Source + javax.tools | jdk.compiler in the runtime | readable generated code, complex logic, users who write Java |
| ClassFile API | Java 24+ | frameworks, proxies, small adapters, bytecode transformation |
java.lang.reflect.Proxy | nothing | implementing interfaces dynamically without generating classes yourself |
| Method handles and lambdas | nothing | composing behaviour at run time without any class generation |
The program
The demo compiles a class with nested and anonymous classes from a string, reports an error against the in-memory file name, compiles four user formulas (one invalid), generates and runs a template class, defines a compiled class as a hidden class, and finally builds and inspects a class with the ClassFile API. Nothing is written to disk.
import java.io.*;
import java.lang.classfile.*;
import java.lang.constant.*;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.util.*;
import java.util.function.*;
import javax.tools.*;
public class Solution {
/** A source file held in a string. */
static class StringSource extends SimpleJavaFileObject {
private final String code;
StringSource(String className, String code) {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
}
@Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; }
}
/** A class file captured in a byte array. */
static class ByteArrayClass extends SimpleJavaFileObject {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
final String className;
ByteArrayClass(String className) {
super(URI.create("bytes:///" + className.replace('.', '/') + Kind.CLASS.extension), Kind.CLASS);
this.className = className;
}
@Override public OutputStream openOutputStream() { return out; }
byte[] bytes() { return out.toByteArray(); }
}
/** Loads classes from the captured byte arrays, delegating everything else to the parent. */
static class MemoryClassLoader extends ClassLoader {
private final Map<String, ByteArrayClass> classes;
MemoryClassLoader(Map<String, ByteArrayClass> classes, ClassLoader parent) {
super("memory", parent);
this.classes = classes;
}
@Override protected Class<?> findClass(String name) throws ClassNotFoundException {
ByteArrayClass c = classes.get(name);
if (c == null) throw new ClassNotFoundException(name);
byte[] b = c.bytes();
return defineClass(name, b, 0, b.length);
}
}
record Result(boolean ok, Map<String, ByteArrayClass> classes, List<String> problems) {}
static final JavaCompiler COMPILER = ToolProvider.getSystemJavaCompiler();
/** Compiles all sources in memory; nothing touches the file system. */
static Result compile(Map<String, String> sources, List<String> options) throws IOException {
var classes = new LinkedHashMap<String, ByteArrayClass>();
var diagnostics = new DiagnosticCollector<JavaFileObject>();
try (StandardJavaFileManager std = COMPILER.getStandardFileManager(diagnostics, Locale.US, null);
JavaFileManager fm = new ForwardingJavaFileManager<>(std) {
@Override public JavaFileObject getJavaFileForOutput(Location location, String className,
JavaFileObject.Kind kind, FileObject sibling) throws IOException {
if (kind == JavaFileObject.Kind.CLASS) {
var c = new ByteArrayClass(className);
classes.put(className, c);
return c;
}
return super.getJavaFileForOutput(location, className, kind, sibling);
}
}) {
List<StringSource> units = sources.entrySet().stream()
.map(e -> new StringSource(e.getKey(), e.getValue())).toList();
boolean ok = COMPILER.getTask(null, fm, diagnostics, options, null, units).call();
List<String> problems = diagnostics.getDiagnostics().stream()
.map(d -> d.getKind() + " " + d.getSource().getName() + ":" + d.getLineNumber()
+ " " + d.getMessage(Locale.US).lines().findFirst().orElse(""))
.toList();
return new Result(ok, classes, problems);
}
}
public static void main(String[] args) throws Exception {
Locale.setDefault(Locale.US); // the generated template code uses String.format
System.out.println("== 1. Compile and run a class from a string ==");
Result r = compile(Map.of("gen.Hello", """
package gen;
public class Hello implements java.util.function.Supplier<String> {
public String get() {
Runnable r = new Runnable() { public void run() {} }; // anonymous class
r.run();
return "Hello from a class that never existed as a file";
}
static class Helper {}
}
"""), List.of());
System.out.println("ok=" + r.ok() + ", class files=" + r.classes().keySet());
var loader = new MemoryClassLoader(r.classes(), Solution.class.getClassLoader());
@SuppressWarnings("unchecked")
Supplier<String> hello = (Supplier<String>) loader.loadClass("gen.Hello")
.getConstructor().newInstance();
System.out.println(hello.get());
System.out.println("defined by: " + hello.getClass().getClassLoader().getName());
System.out.println("\n== 2. Errors are reported against the in-memory names ==");
Result bad = compile(Map.of("gen.Bad", """
package gen;
public class Bad { int x = "text"; }
"""), List.of());
System.out.println("ok=" + bad.ok());
bad.problems().forEach(System.out::println);
System.out.println("\n== 3. A formula compiler ==");
String[] formulas = {"x * x + 1", "Math.sqrt(x) * 10", "x > 0 ? Math.log10(x) : 0", "x +* 2"};
Map<String, String> sources = new LinkedHashMap<>();
for (int i = 0; i < formulas.length; i++) {
sources.put("gen.F" + i, """
package gen;
public final class F%d implements java.util.function.DoubleUnaryOperator {
public double applyAsDouble(double x) { return %s; }
}
""".formatted(i, formulas[i]));
}
Result all = compile(sources, List.of());
System.out.println("all at once: ok=" + all.ok() + " (one bad formula fails the whole task)");
for (int i = 0; i < formulas.length; i++) {
Result one = compile(Map.of("gen.F" + i, sources.get("gen.F" + i)), List.of());
if (!one.ok()) {
System.out.printf("%-26s -> compile error: %s%n", formulas[i],
one.problems().get(0).replaceAll("^ERROR \\S+ ", ""));
continue;
}
var ld = new MemoryClassLoader(one.classes(), Solution.class.getClassLoader());
var f = (DoubleUnaryOperator) ld.loadClass("gen.F" + i).getConstructor().newInstance();
System.out.printf("%-26s -> f(4)=%.3f f(100)=%.3f%n", formulas[i], f.applyAsDouble(4), f.applyAsDouble(100));
}
System.out.println("\n== 4. A tiny template engine ==");
String template = "Dear ${name}, your order of ${qty} item${qty == 1 ? \"\" : \"s\"} costs ${String.format(\"%.2f\", qty * price)}.";
String code = compileTemplate("gen.OrderMail", template);
System.out.println("generated body: " + code.lines().filter(l -> l.contains("sb.append")).count() + " append calls");
Result tr = compile(Map.of("gen.OrderMail", code), List.of());
var tl = new MemoryClassLoader(tr.classes(), Solution.class.getClassLoader());
@SuppressWarnings("unchecked")
Function<Map<String, Object>, String> mail = (Function<Map<String, Object>, String>)
tl.loadClass("gen.OrderMail").getConstructor().newInstance();
System.out.println(mail.apply(Map.of("name", "Ada", "qty", 1, "price", 9.5)));
System.out.println(mail.apply(Map.of("name", "Linus", "qty", 3, "price", 9.5)));
System.out.println("\n== 5. Hidden classes: no custom class loader needed ==");
Result hr = compile(Map.of("Doubler", """
public class Doubler implements java.util.function.IntUnaryOperator {
public int applyAsInt(int x) { return 2 * x; }
}
"""), List.of());
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> hidden = lookup.defineHiddenClass(hr.classes().get("Doubler").bytes(), true).lookupClass();
var doubler = (IntUnaryOperator) hidden.getConstructor().newInstance();
System.out.println("doubler(21)=" + doubler.applyAsInt(21) + ", hidden=" + hidden.isHidden()
+ ", name starts with Doubler/: " + hidden.getName().startsWith("Doubler/"));
try {
Class.forName(hidden.getName());
} catch (ClassNotFoundException e) {
System.out.println("Class.forName cannot find a hidden class");
}
System.out.println("\n== 6. Skipping the compiler: the ClassFile API (Java 24) ==");
ClassDesc genDesc = ClassDesc.of("Answer");
byte[] bytes = ClassFile.of().build(genDesc, cb -> cb
.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_FINAL)
.withInterfaceSymbols(ClassDesc.of("java.util.function.IntSupplier"))
.withMethodBody(ConstantDescs.INIT_NAME, ConstantDescs.MTD_void, ClassFile.ACC_PUBLIC,
code0 -> code0.aload(0)
.invokespecial(ConstantDescs.CD_Object, ConstantDescs.INIT_NAME, ConstantDescs.MTD_void)
.return_())
.withMethodBody("getAsInt", MethodTypeDesc.of(ConstantDescs.CD_int), ClassFile.ACC_PUBLIC,
code1 -> code1.bipush(42).ireturn()));
System.out.println("generated a class file of " + (bytes.length > 100 ? "a few hundred" : "few") + " bytes");
Class<?> answer = lookup.defineHiddenClass(bytes, true).lookupClass();
System.out.println("getAsInt() = " + ((IntSupplier) answer.getConstructor().newInstance()).getAsInt());
ClassModel model = ClassFile.of().parse(bytes);
model.methods().forEach(m -> System.out.println(" method " + m.methodName().stringValue()
+ m.methodType().stringValue()));
}
/** Turns "text ${expr} text" into a class whose apply method builds the string. */
static String compileTemplate(String className, String template) {
int dot = className.lastIndexOf('.');
var body = new StringBuilder();
Set<String> vars = new TreeSet<>();
int pos = 0;
while (true) {
int start = template.indexOf("${", pos);
if (start < 0) break;
int end = template.indexOf('}', start);
body.append(" sb.append(\"").append(escape(template.substring(pos, start))).append("\");\n");
String expr = template.substring(start + 2, end);
body.append(" sb.append(").append(expr).append(");\n");
for (String var : List.of("name", "qty", "price")) if (expr.contains(var)) vars.add(var);
pos = end + 1;
}
body.append(" sb.append(\"").append(escape(template.substring(pos))).append("\");\n");
var decls = new StringBuilder();
for (String v : vars) {
String type = switch (v) { case "qty" -> "int"; case "price" -> "double"; default -> "String"; };
decls.append(" ").append(type).append(' ').append(v).append(" = (")
.append(type.equals("int") ? "Integer" : type.equals("double") ? "Double" : "String")
.append(") args.get(\"").append(v).append("\");\n");
}
return """
package %s;
public class %s implements java.util.function.Function<java.util.Map<String, Object>, String> {
public String apply(java.util.Map<String, Object> args) {
%s var sb = new StringBuilder();
%s return sb.toString();
}
}
""".formatted(className.substring(0, dot), className.substring(dot + 1), decls, body);
}
static String escape(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"");
}
}
== 1. Compile and run a class from a string ==
ok=true, class files=[gen.Hello$1, gen.Hello$Helper, gen.Hello]
Hello from a class that never existed as a file
defined by: memory
== 2. Errors are reported against the in-memory names ==
ok=false
ERROR /gen/Bad.java:2 incompatible types: java.lang.String cannot be converted to int
== 3. A formula compiler ==
all at once: ok=false (one bad formula fails the whole task)
x * x + 1 -> f(4)=17.000 f(100)=10001.000
Math.sqrt(x) * 10 -> f(4)=20.000 f(100)=100.000
x > 0 ? Math.log10(x) : 0 -> f(4)=0.602 f(100)=2.000
x +* 2 -> compile error: illegal start of expression
== 4. A tiny template engine ==
generated body: 9 append calls
Dear Ada, your order of 1 item costs 9.50.
Dear Linus, your order of 3 items costs 28.50.
== 5. Hidden classes: no custom class loader needed ==
doubler(21)=42, hidden=true, name starts with Doubler/: true
Class.forName cannot find a hidden class
== 6. Skipping the compiler: the ClassFile API (Java 24) ==
generated a class file of a few hundred bytes
getAsInt() = 42
method <init>()V
method getAsInt()I
Common questions
My generated code can't find a class from my application. Why?
The compiler sees the class path from java.class.path, which doesn't include classes loaded from custom locations, such as plugins, application servers or Spring Boot fat JARs. Pass the right -classpath, or implement list and inferBinaryName in the forwarding file manager so the compiler can find those classes.
How do I unload generated classes?
Drop every reference to the class loader, the classes and their instances. The garbage collector can then unload them together. With hidden classes, the class itself becomes collectible when unreferenced, unless it was defined with ClassOption.STRONG.
Should I generate source code or bytecode?
Source is easier to read, debug and get right, but needs jdk.compiler and is slower. Bytecode with the ClassFile API is fast and works on any runtime, but you must spell out every instruction. Frameworks usually generate bytecode; one-off tools and teaching platforms usually generate source.
Is it safe to compile code that users type? No, not without isolation. Since the Security Manager was disabled (Java 24), there's no in-process sandbox. Accept a restricted expression language and translate it yourself, or run the code in a separate process or container with strict limits.
How do I debug generated code?
Write the generated source to a log or a temporary file when a debug flag is on, and include line numbers in your error messages. javap -c on the produced bytes shows what was actually generated.
API reference
| Method | Purpose |
|---|---|
SimpleJavaFileObject(URI, Kind), getCharContent, openOutputStream | in-memory sources and class files |
ForwardingJavaFileManager.getJavaFileForOutput(location, className, kind, sibling) | redirect compiler output |
JavaFileManager.list, inferBinaryName | expose additional in-memory classes to the compiler |
ClassLoader.defineClass(name, bytes, off, len), findClass | load generated bytes |
MethodHandles.Lookup.defineHiddenClass(bytes, initialize, options...) (15) | define a hidden class |
MethodHandles.Lookup.defineClass(bytes) (9) | define a normal class in the lookup's package |
Class.isHidden() | test for hidden classes |
ClassFile.of().build(ClassDesc, Consumer<ClassBuilder>) (24) | generate a class file |
ClassFile.of().parse(bytes), ClassModel.methods() | read a class file |
ClassDesc, MethodTypeDesc, ConstantDescs | symbolic descriptors |
Summary
- Extend
SimpleJavaFileObjectfor sources held in strings (overridegetCharContent) and for class files captured in memory (overrideopenOutputStream). - A
ForwardingJavaFileManagerthat overridesgetJavaFileForOutputcollects the class files; one source may produce several. - Load the bytes with a class loader whose parent is the application loader, and use the generated classes through interfaces the host already knows.
- A failing source fails the whole task; compile untrusted or user-edited fragments separately and map error positions back.
- Compiling user input executes it with full privileges; there is no Security Manager sandbox anymore.
- Hidden classes (Java 15) avoid custom class loaders and can be unloaded individually.
- The ClassFile API (Java 24) generates and parses bytecode without
javacor external libraries.
Practice Questions
1. A generated class compiles, but loading it fails with NoClassDefFoundError: gen/Hello$1. What was forgotten?
The anonymous class inside gen.Hello was compiled into a separate class file, gen.Hello$1, but the file manager or class loader only kept the top-level class (for example, by storing just the last output object, or looking up by the expected name only). Store every class file that getJavaFileForOutput creates, keyed by class name, and let findClass serve all of them.
2. Why should generated classes implement an interface such as DoubleUnaryOperator instead of having a method you call by reflection?
The interface belongs to the host's class loader, so after a cast the host calls the method directly, with compile-time type checking and full JIT optimization. Reflection needs string method names, boxing and exception handling, and it is slower and fragile. The parent-first delegation of the generated class's loader guarantees that both sides see the same interface class.
3. A server compiles thousands of user formulas over its lifetime and eventually runs out of metaspace. How can generated classes be released?
Classes are unloaded only when their class loader (or, for hidden classes, the class itself) becomes unreachable. If all formulas are defined in one long-lived loader, none can ever be unloaded. Use a separate class loader per formula or batch and drop all references when a formula is replaced, or define each formula as a hidden class with Lookup.defineHiddenClass without the STRONG option, so it can be unloaded on its own.
4. What does a hidden class give up compared with a class defined through a custom class loader?
It has no usable name: Class.forName cannot find it and no other class can refer to it in bytecode or source, so it can only be used through its Class object, method handles or an interface. It must also live in the same package and loader as the lookup class. In return it needs no custom loader and can be unloaded independently.
5. When would you generate bytecode with the ClassFile API rather than generate Java source and compile it?
When the runtime may not include jdk.compiler (for example, a jlink image), when generation must be fast and frequent (javac is heavy), when the generated code is small and structural (proxies, adapters, accessors), or when you transform existing class files. Source generation remains easier to write, read and debug for complex logic.
Previous: Invoking the Java Compiler from Code: JavaCompiler, Tasks and Diagnostics
Next: The Java Scripting API: Script Engines, Bindings and Invocable
Related reading
- Invoking the Java Compiler from Code: JavaCompiler, Tasks and Diagnostics
- Resource Bundles in Java: Locating Bundles, Property Files and Bundle Classes
- Text Boundaries, Line Endings, Console and Encodings in Java
- MessageFormat and ChoiceFormat in Java: Placeholders, Plurals and Choices
- Localized Dates, Collation and Unicode Normalization in Java

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.