08
Oct
12

Java Compiler API


This page describes a sample application to compile a class file from a String that is pasted in.

package com.test;

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class TestApp extends JFrame {

	private Container c;
	JTextArea txtSource;
	
	public TestApp() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        c = this.getContentPane();
        setLayout(new FlowLayout());
        this.setTitle("Class Loader Test App");
        txtSource = getTextArea();
        c.add(txtSource);
        c.add(compileButton());
        c.add(executeButton());
        this.pack();
        this.setVisible(true);        
	}
	
	private Component executeButton() {
		JButton executeButton = new JButton("execute");
		executeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
	            try {
					new URLClassLoader(new URL[] { new File("").toURI()
							.toURL() }).loadClass("Test").newInstance();
	            } catch (Exception ex) {
	            	ex.printStackTrace();
	            }
			}
		});
		return executeButton;
	}

	private JButton compileButton() {
		JButton btnCompile = new JButton("Compile");
		
		btnCompile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("Compiling...");
				
				compile(txtSource.getText());
			}
			SimpleJavaFileObject getJavaFileContentsAsString() {
				StringBuilder javaFileContents = new StringBuilder(txtSource.getText());
				JavaObjectFromString javaFileObject = null;
				try {
					javaFileObject = new TestApp.JavaObjectFromString("Test.java",
							javaFileContents.toString());
				} catch (Exception exception) {
					exception.printStackTrace();
				}
				return javaFileObject;
			}
			private void compile(String text) {
				JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
				DiagnosticCollector diagnosticsCollector = new DiagnosticCollector();
				StandardJavaFileManager fileManager  =
					compiler.getStandardFileManager(diagnosticsCollector, null, null);
				
				Iterable fileObjects = null;
				boolean fromFile = false;
				if(fromFile) {
					String fileToCompile = "Test.java";
					fileObjects = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(fileToCompile)); // Line 5
				} else {
					JavaFileObject javaObjectFromString = getJavaFileContentsAsString();
					fileObjects = Arrays.asList(javaObjectFromString);
				}
				
				CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects);
				
		        Boolean result = task.call(); // Line 7
		        
		        List<Diagnostic> diagnostics = diagnosticsCollector.getDiagnostics();
		        
		        for(Diagnostic d : diagnostics){
		            // Print all the information here.
		        	System.out.println(d.getMessage(null));
		        }
		        
		        if(result == true){
		            System.out.println("Compilation is successful");
		        }else{
		            System.out.println("Compilation Failed");
		        }
			}
		});
		return btnCompile;
	}

	static class JavaObjectFromString extends SimpleJavaFileObject {
		private String contents = null;

		public JavaObjectFromString(String className, String contents)
				throws Exception {
			super(new URI(className), Kind.SOURCE);
			this.contents = contents;
		}

		public CharSequence getCharContent(boolean ignoreEncodingErrors)
				throws IOException {
			return contents;
		}
	}

	
	private JTextArea getTextArea() {
		JTextArea txtSource = new JTextArea(25, 80);
		return txtSource;
	}

	public static void main(String args[]) {
		new TestApp();
	}
}
Advertisements

0 Responses to “Java Compiler API”



  1. Leave a Comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

October 2012
S M T W T F S
« Jun   Nov »
 123456
78910111213
14151617181920
21222324252627
28293031  

Blog Stats

  • 830,821 hits

%d bloggers like this: