Invoking JDK Tools at Runtime 转自Brian Maso

来源:互联网 发布:游戏程序员工资待遇 编辑:程序博客网 时间:2024/05/21 09:03

This month's Tips and Tricks column is about how to invoke the JDK command-line tools from within your Java applications and trusted applets. I recently had a chance to actually find this skill useful in a commercial product, so I thought I'd share the technique with you.

There are several command-line-based utility programs that come with the JDK: java', the Java Virtual Machine implementation, jar', for creating and extracting files from Java's new JAR file format, javac' for compiling Java classes and so on. What JavaSoft has done that's pretty cool is added a runtime interface to some of the JDK's command-line based utilities so you can actually call them from within your Java applications and trusted applets.

Here are some potential uses for calling the javac' or jar' tools from within an application or trusted applet:

  • Creating "adapter" objects on-the-fly, which allow you to handle events by exposing a particular interface that's expected by the event source object.
  • One slight annoyance of the serialization API is that you can't "re-start" a serialization file once you've started writing objects to it. Using the jar' tool, you can pack several serialized streams into a single JAR file. This can be useful when communicating over sockets between applications.
  • Use of these tools is almost mandatory when creating JavaBeansª development environments. Case in point: the BeanBox application in the Beans Development Kit.
This is where I first found out about this new feature of the 1.1 JDK: The 1.1 JDK has a companion development kit specifically for developing JavaBeans, appropriately called the Beans Development Kit (BDK). It's nowhere near as large as the 1.1 JDK, and my best guess tells me that the BDK will be folded into the JDK in the future. The most compelling and useful part of the BDK is a standalone application called the BeanBox. The BeanBox is a test bed for running beans that you've written. At some point while playing with the BeanBox I realized, "Hey! This program is actually creating new Java classes on-the-fly!" (Note that I don't have the space to go into why the BeanBox creates its own Java classes. That's not the issue, anyway.) After I figured out that it was generating its own classes, I asked myself, "How is it doing that?"

To find the answer, I went where any good Java programmer goes when he or she wants to know how things work, the source code. Buried deep in the BeanBox application (in the HookupManager class, to be exact) is a large section of code that is responsible for creating new Java classes. An abbreviation of similar code is given here as Listing 1.

Listing 1 shows that an object of class sun.tools.javac.Main is being created and used to actually compile a .JAVA source code file generated by the BeanBox application. So apparently the javac' compiler has been implemented in Java, and there is a programmatic interface to the compiler so we can call it from within other Java applications and trusted applets. Note that we always could invoke the javac' compiler using a System.exec() call, even in the early beta JDK. The nice thing about this programmatic interface to the compiler is that the compiler can now run within the same virtual machine as a running application or trusted applet.

I have since found that at least two of the other JDK tools also have a similar runtime interface: the java' interpreter program itself and the jar' program for constructing and using Java's new JAR file format. (JAR files are almost the same as ZIP files, which are compressed archives.) I haven't thought of a useful reason for invoking a second JVM within my application or trusted applet yet, which is what invoking the java' application would do. The JAR file format is useful for creating Java archives, however. Listing 2 shows how the jar' utility can be invoked through its Main class from within a Java application or trusted applet.

Now, there's at least one major caveat I must warn you about when using these sun.tools classes. That is that they are completely file-based. So, as you can see in Listing 1, the BeanBox must write a new .Java file to the local disk and invoke the 'javac' program. The resultant .Class file(s) also are written out to disk automatically, just as if the 'javac' program were being invoked from the command-line. The interface to the jar' application likewise is completely file-based.

What would be nice is having a completely stream-based interface to these tools. This would allow you to hand the 'javac' compiler an InputStream from which to read a .Java file. The InputStream need not be connected then to the local file system but rather could be a ByteArrayInputStream or some other memory-based character stream. It would also be nice to get the results of the 'javac' compiler, the one or more .Class files it writes, back through another InputStream instead of having to open the file(s) from the local file system. This would allow me to construct new Java classes completely in memory. A similar mechanism when applied to the jar' tool would allow me to stream a compressed file archive to, say, a socket's OutputStream directly.

One final note: The sun.tools classes are not part of the core Java class libraries. This means that you can't expect these classes to be available within every VM. In addition, distribution of these classes by you is restricted by the JDK licensing agreement (although you can license the pertinent classes from Sun/JavaSoft for inclusion in your applications and/or applets). For general programmers, this means you will only be able to use these classes within the 1.1 JDK's own VM. That is, the applications and applets you create will work only when run within the VM distributed with the 1.1 JDK (a.k.a. the java' interpreter). You must adjust your development plans according to these restrictions.

About the Author
Brian Maso is a programming consultant working out of Portland, OR. He is the co-author of The Waite Group Press's upcoming release, "The Java API SuperBible." Before Java, he spent five years corralled in the MS Windows branch of programming, working for such notables as the Hearst Corp., First DataBank and Intel. Readers are encouraged to contact Brian with any comments or questions via e-mail at bmaso@europa.com

 
Listing 1// This method can be called to compile the .Java file with the givenfilename. The reference to method "getCompilerClassPath()" is a placeholderfor whatever mechanism you would use to build the classpath that thecompiler should use. For example, you might give a list of JAR files, ZIPfiles or local file system directories.public static void compile(String fileName) {// Run the javac compiler inside the current address space.String astrArgs[] = {"-classpath",getCompilerClassPath(),"-nowarn",fileName};// The sun.tools.javac.Main constructor takes two args: the error outputstream to use (which may be a file and pipe or whatever) and the string"javac".sun.tools.javac.Main compiler =new sun.tools.javac.Main(System.err, "javac");boolean fOk = compiler.compile(astrArgs);if (!fOk)System.err.println("Compilation of file " + fileName +"failed!");}Listing 2// This static method compresses multiple source files into a single JARfile. The manifest file is an optional parameter which is ignored if it isnull.Public static jar(String jarFile, String[] aFileNames, String manifestFile){String[] astrArgs = null;if(null != manifestFile) {astrArgs = new String[3+aFileNames.length];astrArgs[0] = "cfm";} else {astrArgs = new String[4+aFileNames.length];astrArgs[0] = "cf";}args[1] = jarFile;int i = 2;if(null != manifestFile)args[i++] = manifestFile;for (int j=0; j<aFileNames.length; j++)args[i+j] = aFileNames[j];sun.tools.jar.Main jartool =new sun.tools.jar.Main(System.out, System.err, "jar");boolean ok = jartool.run(args);if (!ok)error("Jar tool invocation failed");}