Java dynamometer execution one code

xiaoxiao2021-03-06  20

Dynamic execution of a simple code, uses a way to generate Java files, call Javac compilation, reflection execution.

Just a simple test, some places have to be improved.

code show as below

Import java.io. *;

/ ** * Dynamic execution of a code (generated file -> compile -> execution) * @Author kingfish * @version 1.0 * / public class test testun {private string filename = "test.java"; private string classname = "Test.class "; PUBLIC TESTRUN () {file f = new file (file f =); if (f.exists ()) f.delete ();

f = new file (classname); if (f.exiss ()) f.delete ();

/ ** * Create a Java file * / public void createjavafile (String body) {string head = "public class test {/ r / n public static void runcode () {"

String end = "/ r / n} / r / n}"; try {dataputstream dos = new dataputstream (new fileoutputstream (fileoutputstream (filename)); dos.writebytes (body); dos.writebytes (end); dos.writebytes ); Dos.close ();} catch (exception e) {E.PrintStackTrace ();}}

/ ** * Compile * / public int makejavafile () {int RET = 0; try {runtime = runtime.getime (); 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 return;}

/ ** * Reflection Perform * / 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 testln (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 there is any problem, please correct it!

Kingfish

2005.4.3

转载请注明原文地址:https://www.9cbs.com/read-40245.html

New Post(0)