Class ClassBuilder

  • All Implemented Interfaces:
    AccessFlags

    public class ClassBuilder
    extends Object
    implements AccessFlags
    Fluent builder that assembles a ClassFile from scratch - version, access, hierarchy, fields, methods, annotations, and bootstrap methods.
    • Method Detail

      • create

        public static ClassBuilder create​(String className)
        Starts a new class with public access, java/lang/Object superclass, and Java 11 version.
        Parameters:
        className - the internal name of the class to build
        Returns:
        a new builder
      • version

        public ClassBuilder version​(int major,
                                    int minor)
        Sets the class-file version.
        Parameters:
        major - the major version
        minor - the minor version
        Returns:
        this builder
      • access

        public ClassBuilder access​(int... flags)
        Replaces the access flags with the given flags ORed onto ACC_SUPER.
        Parameters:
        flags - the access flags to combine
        Returns:
        this builder
      • superClass

        public ClassBuilder superClass​(String superName)
        Sets the superclass.
        Parameters:
        superName - the superclass internal name
        Returns:
        this builder
      • interfaces

        public ClassBuilder interfaces​(String... interfaceNames)
        Adds implemented interfaces.
        Parameters:
        interfaceNames - the interfaces' internal names
        Returns:
        this builder
      • addField

        public FieldBuilder addField​(int access,
                                     String name,
                                     String descriptor)
        Opens a field on this class; call FieldBuilder.end() to return here.
        Parameters:
        access - the field's access flags
        name - the field name
        descriptor - the field descriptor
        Returns:
        the nested field builder
      • addMethod

        public MethodBuilder addMethod​(int access,
                                       String name,
                                       String descriptor)
        Opens a method on this class; call MethodBuilder.end() to return here.
        Parameters:
        access - the method's access flags
        name - the method name
        descriptor - the method descriptor
        Returns:
        the nested method builder
      • build

        public ClassFile build()
        Assembles the accumulated specification into a ClassFile.
        Returns:
        the built class file
        Throws:
        RuntimeException - if assembling the class fails
      • toByteArray

        public byte[] toByteArray()
        Serializes the class to class-file bytes, building it first if needed.
        Returns:
        the serialized class-file bytes
        Throws:
        RuntimeException - if building or serializing the class fails