Generate JAR file during RunTime

I just created a simple Java application that will generate entity classes for our database. These are java classes that I will save on my local disk. So far, everything is working fine.

Now I want to generate a JAR file from these Java classes in the main application. I know that I can manipulate jar files, and I also read about adding classes to the jar file at runtime.

But in my case, I have no classes in my build path. I need to create class files from newly created java files and put them in a jar file.

Is this possible in my java application?

The reason I do this is because our database will be expanded by many people all the time, and I don’t want to add these fields to my entity manually. Therefore, I wanted to create an application that scans systables from our database and generates java entity files from this information. But now I need to compile these java files in class files after they are created and add them to my last jar file.

Thanks for any help and / or information about this issue.

Many greetings, Hauke

+4
source share
1 answer

See the java.util.jar.JarOutputStream class (and many examples of use on the Internet). For instance:

 FileOutputStream fout = new FileOutputStream("c:/tmp/foo.jar"); JarOutputStream jarOut = new JarOutputStream(fout); jarOut.putNextEntry(new ZipEntry("com/foo/")); // Folders must end with "/". jarOut.putNextEntry(new ZipEntry("com/foo/Foo.class")); jarOut.write(getBytes("com/foo/Foo.class")); jarOut.closeEntry(); jarOut.putNextEntry(new ZipEntry("com/foo/Bar.class")); jarOut.write(getBytes("com/foo/Bar.class")); jarOut.closeEntry(); jarOut.close(); fout.close(); 

Of course, your program will most likely check the file system and go through the path to the directory and file structure to create the names and contents of the entries, but this example shows the key functions. Remember to handle the exceptions correctly and close the threads in the finally block.

Also, remember that the manifest file is only an entry in " META-INF/MANIFEST.MF ", which is just a text file with formatting rules in the manifest file description .

Compiling Java source files into class files on the fly is a separate task, fraught with its difficulties, but the javax.tools.JavaCompiler class is a good starting point. This question is also a good introduction: How to programmatically compile and instantiate a Java class?

+8
source

Source: https://habr.com/ru/post/1386544/


All Articles