Dynamically generate and compile and run Java classes

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.