Wednesday, April 30, 2008

Create java Classes Dynamically and Run It

This program needs a com.sun.tools.javac.Main.compile for that u need to add the tools.jar file to your class path..


RunIt.java


/** *

* @author SJoshi

*/

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;

import java.lang.reflect.*;


public class RunIt extends JFrame {

JPanel contentPane;

JScrollPane jScrollPane1 = new JScrollPane();

JTextArea source = new JTextArea();

JPanel jPanel1 = new JPanel();

JLabel classNameLabel = new JLabel("Class Name");

GridLayout gridLayout1 = new GridLayout(2,1);

JTextField className = new JTextField();

JButton compile = new JButton("Go");

Font boldFont = new java.awt.Font("SansSerif", 1, 11);


public RunIt() {

super("Editor");

setDefaultCloseOperation(EXIT_ON_CLOSE);

contentPane = (JPanel) this.getContentPane();

this.setSize(400, 300);

classNameLabel.setFont(boldFont);

jPanel1.setLayout(gridLayout1);

compile.setFont(boldFont);

compile.setForeground(Color.black);

compile.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

try {

doCompile();

} catch (Exception ex) {

System.err.println(

"Error during save/compile: " + ex);

ex.printStackTrace();

}

}

});

contentPane.add(jScrollPane1, BorderLayout.CENTER);

contentPane.add(jPanel1, BorderLayout.NORTH);

jPanel1.add(classNameLabel);

jPanel1.add(className);

jScrollPane1.getViewport().add(source);

contentPane.add(compile, BorderLayout.SOUTH);

}

public static void main(String[] args) {

Frame frame = new RunIt();

// Center screen

Dimension screenSize =

Toolkit.getDefaultToolkit().getScreenSize();

Dimension frameSize = frame.getSize();

if (frameSize.height > screenSize.height) {

frameSize.height = screenSize.height;

}

if (frameSize.width > screenSize.width) {

frameSize.width = screenSize.width;

}

frame.setLocation(

(screenSize.width - frameSize.width) / 2,

(screenSize.height - frameSize.height) / 2);

frame.show();

}

private void doCompile() throws Exception {

// write source to file

String sourceFile = className.getText() + ".java";


FileWriter fw = new FileWriter(sourceFile);

fw.write(source.getText());

fw.close();

// compile it

int compileReturnCode =

com.sun.tools.javac.Main.compile(

new String[] {sourceFile});

if (compileReturnCode == 0) {

// run it

Object objectParameters[] = {new String[]{}};

Class classParameters[] =

{objectParameters[0].getClass()};

Class aClass =

Class.forName(className.getText());

Object instance = aClass.newInstance();

Method theMethod = aClass.getDeclaredMethod(

"main", classParameters);

theMethod.invoke(instance, objectParameters);

}

}

}


Sample Code for :

public class Sample {

public static void main(String args[]) {

System.out.println(new java.util.Date());

}

}

Output Window :




Reference Link :


Thanks & Regards

Joshi Shirin

No comments:

Contributors