Dynamic call method instance

xiaoxiao2021-03-06  39

Import java.io. *; import java.lang.reflect.method; import com.sun.tools.javac. *;

Public class myclass {

Private static main javac = new main ();

public static void main (String [] args) throws Exception {String str = ""; MyClass mc = new MyClass (); DataInputStream bd = new DataInputStream (System.in); byte [] brray = new byte [200]; int i = bd.read (brray); str = new string (brRay, 0, i); // EVAL (STR); EVAL ("MC" STR "();");}

Public Static Object Eval (String Str) throws exception {// Generate Java file string s = "class temp {"; s = "public static void main (string [] args) throws Exception {"; s = "TEST. Myclass mc = new test.myclass (); "; // s = Str; s =" mc. " Str; s ="} "; s ="} "; file f = new file (" Temp.java "); PrintWriter PW = New PrintWriter (New FileWriter (f)); PW.Println (s); pw.close (); // Dynamically compiled com.sun.tools.javac.main javac = new COM. Sun.Tools.javac.main (); String [] cpargs = new string [] {"-d", system.getproperty ("user.dir") "/ src / test", "temp.java"}; Int status = javac.compile (cpargs); if (status! = 0) {system.out.println ("No successful compilation of raw file!"); Return Null;} // Call the main method of TEMP Returns:

Class Clasz = Class.Forname ("temp"); method main = Clasz.getMethod ("main", new class [] {string []. Class}; return main.invoke (null, new object [] {new string [0]}); // If the method does not return, it is directly called} public object mc1 () {Object obj = "str"; system.out.print ("mc1"); returnobj;}

Void mc2 () {system.out.print ("mc2");}}

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

New Post(0)