Class CompactCodeAttributeComposer

  • All Implemented Interfaces:
    AttributeVisitor

    public class CompactCodeAttributeComposer
    extends java.lang.Object
    implements AttributeVisitor
    This AttributeVisitor accumulates instructions, exceptions and line numbers, in a compact and fluent style, and then adds them to a method or copies them into code attributes that it visits.

    The class supports composing instructions (appendInstruction(Instruction)), labels (createLabel() and label(Label)), exception handlers (catch_(Label, Label, String, Clazz)), and line numbers (line(int)).

    The labels are numeric labels that you can choose freely, for example instruction offsets from existing code that you are copying. You can then refer to them in branches and exception handlers. You can compose the code as a hierarchy of code fragments with their own local labels.

    You should provide an estimated maximum size (expressed in number of bytes in the bytecode), so the implementation can efficiently allocate the necessary internal buffers without reallocating them as the code grows.

    For example:

         ProgramClass  programClass  = ...
         ProgramMethod programMethod = ...
    
         // Compose the code.
         CompactCodeAttributeComposer composer =
             new CompactCodeAttributeComposer(programClass);
    
         final Label TRY_START = composer.createLabel();
         final Label TRY_END   = composer.createLabel();
         final Label ELSE      = composer.createLabel();
    
         composer
             .beginCodeFragment(50)
             .label(TRY_START)
             .iconst_1()
             .iconst_2()
             .ificmplt(ELSE)
    
             .iconst_1()
             .ireturn()
    
             .label(ELSE)
             .iconst_2()
             .ireturn()
             .label(TRY_END)
    
             .catch_(TRY_START, TRY_END, "java/lang/Exception", null)
             .iconst_m1()
             .ireturn()
             .endCodeFragment();
    
          // Add the code as a code attribute to the given method.
          composer.addCodeAttribute(programClass, programMethod);
     

    This class is mostly convenient to compose code programmatically from scratch. To compose code based on existing code, where the instructions are already available, see CodeAttributeComposer.

    If you're building many method bodies, it is more efficient to reuse a single instance of this composer for all methods that you add.