Class JavaFileWriter

java.lang.Object
com.hedera.pbj.compiler.impl.JavaFileWriter

public final class JavaFileWriter extends Object
An abstraction that allows various Java entity generators to populate a text buffer and then write it to disk as a single .java file. This is useful for supporting inner entities (e.g. classes, enums, etc.) when all of them have to be a part of the same outer entity, and hence have to be written into the same, single file. This abstraction provides support for maintaining a set of import statements that may be required by any java entities being generated using this abstraction.
  • Constructor Details

    • JavaFileWriter

      public JavaFileWriter(@NonNull File javaFile, @NonNull String javaPackage)
      Creates a new JavaFileWriter.
  • Method Details

    • create

      public static JavaFileWriter create(FileType fileType, File outputDir, Protobuf3Parser.MessageDefContext msgDef, ContextualLookupHelper contextualLookupHelper)
      A factory to create JavaFileWriter for messages.
    • addImport

      public void addImport(String symbol)
      Add an imported symbol, including the `static ` prefix and/or `.*` suffix if necessary, but w/o the opening `import ` or closing `;`.
      Parameters:
      symbol - the symbol to add to imports
    • append

      public void append(String str)
      Append a string to the generated text. This should generally be a top-level class or enum definition with any inner definitions, including inner classes or enums, embedded inside. The caller can call this method multiple times to keep building their text.
      Parameters:
      str - a string to append
    • writeFile

      public void writeFile() throws IOException
      Generate the actual file on disk with a proper license header, `package`, `import` directives, and finally the text that has been built by calling the `append()` method.

      It's technically possible to call this method multiple times. It's even possible to add more imports or append more text between the calls. However, it will overwrite the exact same file each time, although it will write all the latest updates to the imports and the text on each invocation. If the imports and/or text are updated and this `writeFile()` method is not invoked after the update, then the latest updates will not be persisted.

      Throws:
      IOException - if an I/O error occurs