Dynamic execution of a piece of code in Java
Last Update:2017-02-28
Source: Internet
Author: User
Dynamic | Executes a simple piece of code, using a generated Java file, invoking Javac compilation, reflection execution.
It's just a simple test, and some places need to be perfected.
The code is as follows
--------------------------------------------------------------------------------
Import java.io.*;
/**
* Dynamic execution of a piece of code (generate file-> compile-> execution)
* @author Kingfish
* @version 1.0
*/
public class TestRun {
Private String FileName = "Test.java";
Private String classname= "Test.class";
Public TestRun () {
File F = new file (fileName);
if (f.exists ()) F.delete ();
f = new File (className);
if (f.exists ()) F.delete ();
}
/**
* Create Java files
*/
public void Createjavafile (String body) {
String head = "public class test{\r\n public static void RunCode () {";
String end = "\ r \ n}\r\n}";
try {
DataOutputStream dos = new DataOutputStream (New FileOutputStream (
FileName));
Dos.writebytes (head);
Dos.writebytes (body);
Dos.writebytes (end);
Dos.close ();
}
catch (Exception e) {
E.printstacktrace ();
}
}
/**
* Compiling
*/
public int Makejavafile () {
int ret = 0;
try {
Runtime RT = Runtime.getruntime ();
Process PS = rt.exec ("cmd/c javac" + fileName);
Ps.waitfor ();
Byte[] out = new byte[1024];
DataInputStream dos = new DataInputStream (Ps.getinputstream ());
Dos.read (out);
string s = new string (out);
if (S.indexof ("Exception") > 0) {
ret =-1;
}
}
catch (Exception e) {
ret =-1;
E.printstacktrace ();
}
return ret;
}
/**
* Reflection Execution
*/
public void Run () {
try {
Class.forName ("Test"). GetMethod ("RunCode", new class[] {}). Invoke (null, new object[]{});
}
catch (Exception e) {
E.printstacktrace ();
}
}
/**
* Test
*/
public static void Main (string[] args) {
String cmd = "System.out.println (\" Usage:java testrun int i=1; System.out.println (i+100);
if (args.length>=1) {
cmd = args[0];
}
TestRun t = new TestRun ();
T.createjavafile (CMD);
if (t.makejavafile () = = 0) {
T.run ();
}
}
}
--------------------------------------------------------------------------------
Test:
Java testrun System.out.println (\ "hello,world!\");
java testrun "int i=1;int j=2; System.out.println (I+J); "
--------------------------------------------------------------------------------
If you have any questions, please correct me.
Kingfish