Java dynamically compiles the class file and loads it into memory

Source: Internet
Author: User

If you want to use Hibernate's data provider to manipulate the class in an object-oriented manner after you have compiled and loaded the class dynamically, please refer to the author's blog post-(this blog post is not published)

The so-called dynamic compilation is the Java class generated when the program is run and compiled into a class file.

Here are two ways to dynamically compile Java files.

First: Use runtime to execute the JAVAC command

/*** Compile Java class * Use runtime to execute JAVAC command *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@throwsjava.io.IOException*/     Public Static voidJavac (String name)throwsIOException {String javapackagename= Name.replace (".", File.separator) + ". Java"; String Javaabsolutepath= classpath+Javapackagename; Process Process= Runtime.getruntime (). EXEC ("Javac-classpath" + jarabsolutepath+ "" +Javaabsolutepath); Try{InputStream Errorstream=Process.geterrorstream (); InputStreamReader InputStreamReader=NewInputStreamReader (Errorstream); BufferedReader BufferedReader=NewBufferedReader (InputStreamReader); String Line=NULL;  while((Line=bufferedreader.readline ())! =NULL) {System.out.println (line); }            intExitval =process.waitfor (); System.out.println ("Process exitvalue:" +exitval); } Catch(interruptedexception e) {e.printstacktrace (); }    }
View Code

The second type: The compiler provided by the Javax.tools package in the Rt.jar that comes with the JDK

/*** Compiling Java class * Using compiler provided by Javax.tools package in Rt.jar *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@throwsjava.io.IOException*/     Public Static voidCompiler (String name)throwsIOException {String javapackagename= Name.replace (".", File.separator) + ". Java"; String Javaabsolutepath= classpath+Javapackagename; Javacompiler compiler=Toolprovider.getsystemjavacompiler (); Compiler.run (NULL,NULL,NULL, "-encoding", "UTF-8", "-classpath", Jarabsolutepath.tostring (), Javaabsolutepath); }
View Code

Second, use Class.forName (""); Load class file into memory and get class object

/*** Dynamically compile a Java source file and load the compiled generated class *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@throwsjava.io.IOException*/     Public StaticClass<?> Dynamicloadclass (String name)throwsIOException, ClassNotFoundException {if(!isclassexist (name))        {compiler (name); }        if(isjavaexist (name)) {if(! Fileutil.destroyfile (ClassPath + name.replace (".", File.separator) + ". Java") {System.out.println ("========================================>>>> Delete source file failed!"); }        }        returnclass.forname (name); }
View Code

Here's the whole code:

 PackageCom.basic.core.classloader;ImportCom.basic.core.util.FileUtil;ImportSun.tools.jar.Main;ImportJavax.tools.JavaCompiler;ImportJavax.tools.ToolProvider;ImportJava.io.*;ImportJava.nio.file.Files;Importjava.nio.file.Paths;/*** Desc: Custom class loader for dynamic loading of classes*/ Public classMyclassloaderextendsClassLoader {//class Path    Private StaticString ClassPath; Private StaticString Jarprefix; Private StaticStringBuilder Jarabsolutepath; Static{ClassPath= Myclassloader.class. getClassLoader (). GetResource (""). GetPath (); ClassPath=!classpath.startswith ("/")? ClassPath:classPath.substring (1);//Remove the start position/ClassPath = Classpath.endswith (file.separator)? classpath:classpath+File.separator; Jarprefix= Classpath.substring (0,classpath.lastindexof ("Classes")) +file.separator+ "Lib" +File.separator; Jarabsolutepath=NewStringBuilder (). Append (Jarprefix). Append ("Hibernate-core-4.2.0.final.jar;"). Append (Jarprefix). Append ("Hibernate-jpa-2.0-api-1.0.1.final.jar;"). Append (Jarprefix). Append ("Validation-api-1.0.0.ga.jar;"); }    /*** If the class specified by name is not found in the parent's ClassLoader, * This method is called to load a class from disk *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@return     * @throwsjava.io.IOException*/@OverrideprotectedClass<?> Findclass (String name)throwsClassNotFoundException {byte[] Classbytes =NULL; Class<?> Clazz =NULL; Try {            //byte code of the Load classClassbytes =loadclassbytes (name); //giving the bytecode to the JVMClazz = DefineClass (name,classbytes,0, classbytes.length); if(Clazz = =NULL){                Throw Newclassnotfoundexception (name); }        } Catch(IOException e) {e.printstacktrace (); }        returnClazz; }    /*** Byte code of the load class *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@return     * @throwsjava.io.IOException*/    Private byte[] Loadclassbytes (String name)throwsIOException {String classpackagename= Name.replace (".", File.separator) + ". Class"; String Classabsolutepath= classpath+Classpackagename; //Compiling Java filesJavac (name); byte[] bytes =files.readallbytes (Paths.get (Classabsolutepath)); returnbytes; }    /*** The class of the specified classes is present *@paramname *@return     * @throwsIOException*/     Public Static BooleanIsclassexist (String name)throwsIOException {String classpackagename= Name.replace (".", File.separator) + ". Class"; returnFileutil.isexists (classpath+classpackagename)?true:false; }    /*** The specified class is present *@paramname *@return     * @throwsIOException*/     Public Static BooleanIsjavaexist (String name)throwsIOException {String classpackagename= Name.replace (".", File.separator) + ". Java"; returnFileutil.isexists (classpath+classpackagename)?true:false; }    /*** Compile Java class * Use runtime to execute JAVAC command *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@throwsjava.io.IOException*/     Public Static voidJavac (String name)throwsIOException {String javapackagename= Name.replace (".", File.separator) + ". Java"; String Javaabsolutepath= classpath+Javapackagename; Process Process= Runtime.getruntime (). EXEC ("Javac-classpath" + jarabsolutepath+ "" +Javaabsolutepath); Try{InputStream Errorstream=Process.geterrorstream (); InputStreamReader InputStreamReader=NewInputStreamReader (Errorstream); BufferedReader BufferedReader=NewBufferedReader (InputStreamReader); String Line=NULL;  while((Line=bufferedreader.readline ())! =NULL) {System.out.println (line); }            intExitval =process.waitfor (); System.out.println ("Process exitvalue:" +exitval); } Catch(interruptedexception e) {e.printstacktrace (); }    }    /*** Compiling Java class * Using compiler provided by Javax.tools package in Rt.jar *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@throwsjava.io.IOException*/     Public Static voidCompiler (String name)throwsIOException {String javapackagename= Name.replace (".", File.separator) + ". Java"; String Javaabsolutepath= classpath+Javapackagename; Javacompiler compiler=Toolprovider.getsystemjavacompiler (); Compiler.run (NULL,NULL,NULL, "-encoding", "UTF-8", "-classpath", Jarabsolutepath.tostring (), Javaabsolutepath); }    /*** Dynamically compile a Java source file and load the compiled generated class *@paramthe fully qualified package name for the name class does not have a suffix such as com.test.Notice instead of Com.test.Notice.java *@throwsjava.io.IOException*/     Public StaticClass<?> Dynamicloadclass (String name)throwsIOException, ClassNotFoundException {if(!isclassexist (name))        {compiler (name); }        if(isjavaexist (name)) {if(! Fileutil.destroyfile (ClassPath + name.replace (".", File.separator) + ". Java") {System.out.println ("========================================>>>> Delete source file failed!"); }        }        returnclass.forname (name); }     Public Static voidMain (string[] args) {}}
View Code

  

 

Java dynamically compiles the class file and loads it into memory

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.