简体   繁体   中英

Generate JAR file during RunTime

I just created a simple java application that will generate entity classes for our database. Those java classes I will save to my local disc. So far everything works fine.

Now I want to genereate a JAR file from those java classes within my main application. I know, that I can manipulate jar files and I also read about adding classes to a jar file during runtime.

But in my case I don't have the classes in my build path. What I need is the create the class files from my just created java files and put them into my jar file.

Is that possible inside my java application?

The reason why I am doing that is that our database will be extended by many persons all the time and I don't want to add those fields to my entity manually. So I wanted to create an application that scanns the systables from our database and generates from those information the java entity files. But now I need to compile those java files in class files after generating them and to add them to my final jar file.

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

Many greetings, Hauke

See the class java.util.jar.JarOutputStream (and many examples of usage on the web). For example:

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 likely inspect the filesystem and traverse the directory and file structure to generate the entry names and contents but this example shows the key features. Don't forget to handle exceptions properly and close the streams in a finally block.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM