Interface CodeBuilder

All Superinterfaces:
ClassFileBuilder<CodeElement, CodeBuilder>, Consumer<CodeElement>
All Known Subinterfaces:
CodeBuilder.BlockCodeBuilder

public sealed interface CodeBuilder extends ClassFileBuilder<CodeElement, CodeBuilder> permits CodeBuilder.BlockCodeBuilder (not exhaustive)
A builder for Code attributes (method bodies). MethodBuilder.withCode(java.util.function.Consumer<? super java.lang.classfile.CodeBuilder>) is the basic way to obtain a code builder; ClassBuilder.withMethodBody(java.lang.classfile.constantpool.Utf8Entry, java.lang.classfile.constantpool.Utf8Entry, int, java.util.function.Consumer<? super java.lang.classfile.CodeBuilder>) is a shortcut. There are also derived code builders from block(java.util.function.Consumer<java.lang.classfile.CodeBuilder.BlockCodeBuilder>), which handles code blocks and transforming(java.lang.classfile.CodeTransform, java.util.function.Consumer<java.lang.classfile.CodeBuilder>), which runs transforms on existing handlers, both of which requires a code builder to be available first.

Refer to ClassFileBuilder for general guidance and caution around the use of builders for structures in the class file format. Unlike in other builders, the order of member elements in a code builder is significant: they affect the resulting bytecode. Many Class-File API options affect code builders: ClassFile.DeadCodeOption and ClassFile.ShortJumpsOption affect the resulting bytecode, and ClassFile.DeadLabelsOption, ClassFile.DebugElementsOption, ClassFile.LineNumbersOption, ClassFile.StackMapsOption, and ClassFile.AttributesProcessingOption affect the resulting attributes on the built Code attribute, that some elements sent to a code builder is otherwise ignored.

Instruction Factories

CodeBuilder provides convenience methods to create instructions (See JVMS 6.5 Instructions) by their mnemonic, taking necessary operands.
  • Instructions that encode their operands in their opcode, such as aload_<n>, share their factories with their generic version like aload. Note that some constant instructions, such as iconst_1, do not have generic versions, and thus have their own factories.
  • Instructions that accept wide operands, such as ldc2_w or wide, share their factories with their regular version like ldc(java.lang.constant.ConstantDesc). Note that goto_w has its own factory to avoid short jumps.
  • The goto, instanceof, new, and return instructions' factories are named goto_, instanceOf, new_, and return_ respectively, due to clashes with keywords in the Java programming language.
  • Factories are not provided for instructions jsr, jsr_w, ret, and wide ret, which cannot appear in class files with major version 51 or higher. (JVMS 4.9.1) They can still be provided via ClassFileBuilder.with(E).
Since:
24
See Also: