Function generateJavaFile

  • Generates a Java source file with proper package declaration, imports, and body content.

    This function simplifies the generation of Java files by handling common boilerplate code such as package declarations and import statements. It leverages a JavaImportManager to manage imports automatically based on the classes used in the body content.

    Parameters

    • fileName: string

      The name of the Java file to be generated (without the .java extension).

    • packageName: string

      The package name for the Java file (e.g., com.example.project).

    • generatorManager: GeneratorManager

      The manager responsible for handling file creation and output.

    • bodyGenerator: (importManager: (fqn: string) => string) => CompositeGeneratorNode

      A function that generates the body of the Java file. It receives an importManager function to handle class imports and returns a CompositeGeneratorNode representing the body content.

    • Optionaloptions: CreateFileOptions

      Optional settings for file creation, such as encoding or overwrite behavior.

    Returns void

    generateJavaFile(
    'MyClass',
    'com.example.project',
    generatorManager,
    (importClass) => expandToNode`
    public class MyClass {
    public ${imp('java.util.Properties')} getProperties() {
    // ...
    }
    }
    }`
    );

    The above example generates a Java class MyClass in the package com.example.project, with an imported java.util.Properties. The imp function handles the import management, ensuring that java.util.Properties is imported and conflicts are resolved.