This code is not original. It was read from my previous study notes. It was a reply from a friend called Lu renjia in csdn in the Forum, it may help many friends. in fact, it is very simple without comments. There are three steps in total to generate java files, compile Java files, and run Java classes,
Package com. syj;
Import java. Io. file;
Import java. Io. filewriter;
Import java. Lang. Reflect. method;
Public class createclass {
Private Static string class_name = "createclasstest ";
Private Static string class_file = class_name + ". Java ";
Public static void main (string ARGs []) {
Createclass MTC = new createclass ();
MTC. createclass ();
System. Out. println ("javac" + class_file );
MTC. compileclass ();
System. Out. println ("Java" + class_name );
MTC. runclass ();
}
Public void createclass (){
Try {
New file (class_file). Delete ();
Filewriter awriter = new filewriter (class_file, true );
Awriter. Write ("public class" + class_name + "{");
Awriter. Write ("Public void println (){");
Awriter. Write ("system. Out. println (" = "+ class_name +" = ");");
Awriter. Write ("}}");
Awriter. Flush ();
Awriter. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
Public void compileclass (){
String filepath = new file (createclass. Class. getclassloader ()
. Getresource (""). GetFile (). getabsolutepath ();
String [] source = {"-d", filepath, new string (class_file )};
System. Out. println ("javac out :"
+ COM. Sun. Tools. javac. Main. Compile (source ));
}
Public void runclass (){
Try {
Class Params [] = {};
Object paramsobj [] = {};
Class testclass = Class. forname (class_name );
Object iclass = testclass. newinstance ();
Method thismethod = testclass. getdeclaredmethod ("println", Params );
Thismethod. Invoke (iclass, paramsobj );
} Catch (exception e ){
E. printstacktrace ();
}
}
}
You need to introduce % java_home %/lib/tools. Jar. This is the only use of tools. jar that I have encountered.