Java implementation method for dynamically generating byte code from a string _java

Source: Internet
Author: User

can generate an executable class file

Can execute code directly:

Copy Code code as follows:

public class Test {

/**
* @param args
*/
@SuppressWarnings ("Static-access")
public static void Main (string[] args) {
try {
New Test (). Calculate ("234-(1 + 45 * 4)/5");
catch (Exception e) {
E.printstacktrace ();
}
}

Private static double calculate (String expr) throws Exception {
  string className = "Calculatormain";
  String methodname = "Calculate";
  String Source = "Class" + className
    + "{public static void main (string[] args) {System. Out.println (Calculate ());} public static Double "+ methodname +" () {return "
    + expr +;}}";
  Javacompiler compiler = Toolprovider.getsystemjavacompiler ();
  Standardjavafilemanager FileManager = Compiler.getstandardfilemanager (
    null, NULL, NULL);
  Stringsourcejavaobject sourceObject = new Test.stringsourcejavaobject (
    "Main", SOURCE);
  iterable< extends javafileobject> fileobjects = Arrays
   . aslist (sourceObject);
  Compilationtask task = Compiler.gettask (null, filemanager, NULL, NULL,
    null, fileobjects);

Boolean result = Task.call ();
if (result) {
ClassLoader loader = Thread.CurrentThread (). GetClass ()
. getClassLoader ();
try {
Class<?> clazz = Loader.loadclass (className);
Method method = Clazz.getmethod (methodname, new class<?>[] {});
Object value = Method.invoke (null, new object[] {});
Return (Double) value;
catch (Exception e) {
throw new Calculationexception ("Internal error.") ");
}
} else {
/New Calculationexception ("Wrong expression"). ");
}
return 0;
}

Static Class Stringsourcejavaobject extends Simplejavafileobject {

Private String content = null;

Public Stringsourcejavaobject (string name, string content)
Throws URISyntaxException {
Super (Uri.create ("string:///" + name.replace ('. ', '/')
+ Kind.SOURCE.extension), kind.source);
this.content = content;
}

Public Charsequence getcharcontent (Boolean ignoreencodingerrors)
Throws IOException {
return content;
}
}

}

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.