Dynamically compile the instance code. very simple.

xiaoxiao2021-03-06  55

Dynamically compile the instance code. very simple. I don't have to note.

Import java.io. *;

Import java.util. *;

Import java.lang.reflect. *;

Import java.io.file;

Public class compilest {

Static com.sun.tools.javac.main javac = new com.sun.tools.javac.main ();

Public static void main (String [] args) {

Try {

File file = file.createteTempfile ("Runtime", "Java", New file (System.GetProperty)))));

String filename = file.getname ();

String classname = filename.substring (0, filename.indexof ('.'));

PrintWriter out = new printwriter (new fileoutputstream (file);

Out.println ("Public Class" ClassName "{");

Out.println ("Public Static Void Main (String [] args) {");

Out.println ("System.out.Println (/" yes! / ");");

OUT.PRINTLN ("}}");

Out.flush ();

Out.close ();

String [] arg = new string [] {"- d", system.getproperty ("user.dir"), filename};

Int status = javac.compile (arg);

Class CLS = Class.Forname (classname);

Method main = CLS.GETMETHOD ("main", new class [] {string []. Class};

Main.invoke (null, new object [] {new string [0]});

File.delete ();

File = new file (classname ". Class");

File.delete ();

} catch (exception e) {E.PrintStackTrace ();

}

}

Author: youngmean

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

New Post(0)