Java Dynamic Loading

Source: Internet
Author: User

Put a note first, follow-up need to dig deeper.

 Packagetest;ImportJava.io.File;Importjava.io.IOException;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;ImportJava.net.URL;ImportJava.net.URLClassLoader;Importjava.nio.charset.StandardCharsets;ImportJava.nio.file.Files;ImportJavax.tools.JavaCompiler;ImportJavax.tools.ToolProvider; Public classSimplerun { Public Static voidShowcompile () {//Prepare source somehow.String Source = "Package test; public class Test {static {System.out.println (\ "hello\"),} public Test () {System.out.println (\ "world\"), public void Hello () {System.out.println (\ "Fuck\");}} "; //Save source in. java file.File root =NewFile ("~/temp");//On Windows running on \ c \, this is//C:\java.File sourcefile =NewFile (Root, "Test/test.java");        Sourcefile.getparentfile (). Mkdirs (); Try{files.write (Sourcefile.topath (), Source.getbytes (Standardcharsets.utf_8)); //Compile source file.Javacompiler compiler =Toolprovider.getsystemjavacompiler (); intSuccess = Compiler.run (NULL,NULL,NULL, Sourcefile.getpath ()); if(Success = = 0) {                //Load and instantiate compiled class.URLClassLoader ClassLoader = urlclassloader.newinstance (Newurl[] {Root.touri (). Tourl ()}); Class<?>CLS; Try {                    //should print "Hello".CLS = Class.forName ("Test. Test ",true, ClassLoader); //should print "World".Object instance =cls.newinstance (); //should print "[email protected]".System.out.println (instance); Method m= Cls.getmethod ("Hello",NewClass<?>[] {});                    System.out.println (m); M.invoke (instance,Newobject[]{}); } Catch(ClassNotFoundException | instantiationexception |illegalaccessexception e)                {E.printstacktrace (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(SecurityException e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); }            } Else{System.out.println ("Compile Failed"); }        } Catch(IOException e) {e.printstacktrace (); }    }    Private Static DoubleCalculate (String expr) {string ClassName= "Calculator"; String MethodName= "Calculate"; String Source= "Package test; public class ' + ClassName + ' {public static double ' + MethodName + ' () {return ' +Expr+ "; } }"; //Set Work directoryFile root =NewFile ("~/temp"); //Set Work packageFile sourcefile =NewFile (Root, "Test/calculator.java");        Sourcefile.getparentfile (). Mkdirs (); Try{files.write (Sourcefile.topath (), Source.getbytes (Standardcharsets.utf_8)); //Compile source file.Javacompiler compiler =Toolprovider.getsystemjavacompiler (); intSuccess = Compiler.run (NULL,NULL,NULL, Sourcefile.getpath ()); if(Success = = 0) {                //Load and instantiate compiled class.URLClassLoader ClassLoader = urlclassloader.newinstance (Newurl[] {Root.touri (). Tourl ()}); Class<?>CLS; Try{CLS= Class.forName ("Test. Calculator ",true, ClassLoader); Object instance=cls.newinstance (); Method Method= Cls.getmethod (MethodName,NewClass<?>[] {}); Object value= Method.invoke (instance,Newobject[] {}); return(Double) value; } Catch(ClassNotFoundException |illegalaccessexception e)                {E.printstacktrace (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(SecurityException e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); } Catch(instantiationexception e) {e.printstacktrace (); }            } Else{System.out.println ("Compile Failed"); }        } Catch(IOException e) {e.printstacktrace (); }        return0.0; }     Public Static voidMain (string[] args) {simplerun.showcompile (); if(Args.length >= 1) {System.out.println (args[0] + "=" + simplerun.calculate (args[0])); }    }}

Reference:

Http://www.infoq.com/cn/articles/cf-java-byte-code

Java Dynamic Loading

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.