Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Java Tip 131: Make a statement with javac!

Interactively explore short bits of Java

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Often you may want to test a single piece of code. For example, say you forget how the % operator works with negative numbers, or you must determine how a certain API call operates. Writing, compiling, and running a small program repeatedly just to test small things can prove annoying.

With that in mind, in this Java Tip, I present a short program that compiles and runs Java code statements simply by using tools included in Sun's JDK 1.2 and above.

Note: You can download this article's source code from Resources.

Use javac inside your program

You'll find the javac compiler in the tools.jar library found in the lib/ directory of your JDK 1.2 and higher installation.

Many developers do not realize that an application can access javac programmatically. A class called com.sun.tools.javac.Main acts as the main entry point. If you know how to use javac on the command line, you already know how to use this class: its compile() method takes the familiar command-line input arguments.

Compile a single statement

For javac to compile any statement, the statement must be contained within a complete class. Let's define a minimal class right now:

    /**
     * Source created on <this date>
     */
    public class <Temporary Class Name> {
        public static void main(String[] args) throws Exception {
            <Your Statement>
        }
    }


Can you figure out why the main() method must throw an exception?

Your statement obviously goes inside the main() method, as shown, but what should you write for the class name? The class name must possess the same name as the file in which it is contained because we declared it as public.

Prepare a file for compilation

Two facilities included in the java.io.File class since JDK 1.2 will help. The first facility, creating temporary files, frees us from choosing some temporary name for our source file and class. It also guarantees the file name's uniqueness. To perform this task, use the static createTempFile() method.

The second facility, automatically deleting a file when the VM exits, lets you avoid cluttering a directory or directories with temporary little test programs. You set a file for deletion by calling deleteOnExit().

Create the file

Choose the createTempFile() version with which you can specify the new file's location, instead of relying on some default temporary directory.

Finally, specify that the extension must be .java and that the file prefix should be jav (the prefix choice is arbitrary):

    File file = File.createTempFile("jav", ".java",
            new File(System.getProperty("user.dir")));
    // Set the file to delete on exit
    file.deleteOnExit();
    // Get the file name and extract a class name from it
    String filename = file.getName();
    String classname = filename.substring(0, filename.length()-5);


Note that you extract the class name by removing the .java suffix.

Output the source with your short code segment

Next, write the source code to the file through a PrintWriter for convenience:

    PrintWriter out = new PrintWriter(new FileOutputStream(file));
    out.println("/**");
    out.println(" * Source created on " + new Date());
    out.println(" */");
    out.println("public class " + classname + " {");
    out.println("    public static void main(String[] args) throws Exception {");
    // Your short code segment
    out.print("        "); out.println(text.getText());
    out.println("    }");
    out.println("}");
    // Flush and close the stream
    out.flush();
    out.close();


The generated source code will look nice for later examination, with the added benefit that if the VM exits abnormally without deleting the temporary file, the file will not be a mystery if you stumble upon it later.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (2)
Login
Forgot your account info?

cannot get demo to work in specific enviromentsBy barbloke6 on March 11, 2009, 5:43 amHello, This is an excellent demo! I have a query though, the demo appears to work fine when built and used within the BlueJ IDE, but when i attempt to run it with...

Reply | Read entire comment

how to use com.sun.tools.javac.MainBy nishadbraveman on February 5, 2009, 1:02 amplease hellp me in using the com.sun.tools.javac.Main class,i am not able to use it,please tell me those steps for the same

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources