Search code examples
javaintellij-ideajarexecutable-jarpackaging

How to package a .jar file using a java program


How does one package a jar file using java code? I want a .jar file to be created with custom code whenever (for example) a button is pressed, how would I do this? There doesn't seem to be any documentation about this so I figured I would go here, I've tried searching everywhere on the web.


Solution

  • Yes, this is possible.

    The sequence of actions:

    1. Need to pass Java code into the JavaCompiler API
    2. FileManager extracts the source code for JavaCompiler
    3. JavaCompiler compiles it and returns the bytecode
    4. Generate an executable JAR. Create a JarOutputStream with a manifest that declares the main class.

    Technical articles on the topic:

    Baeldung: Compiling and Executing Code From a String in Java

    Baeldung: Creating JAR Files Programmatically