简体   繁体   中英

Is it possible to compile a class on the fly in Java without using external libraries?

It seems to me that the Java Compiler API allows to compile at runtime a class, writing its output (the .class file) to the file system. However, in-memory compilation is not supported. Is this correct ? or is possible to use this API to compile a class in memory (from a String) and instantiating such class afterwards ?

(I know I can compile the class to the file system and load it afterwards with a custom class loader, but I am wondering if I can compile it in memory, without passing by the file system).

Is there another alternative mechanism to do such in memory compilation using the J2SE only? BeanShell (I library that can do what I want) mentions in its web page that it may be included in the J2SE at "some point in the future", however, the status of its JSR is "Dormant" (whatever does it mean).

Update:

Ideally, I would like to know if this can be done with the J2SE only (or if there are any expected enhancements to J2SE that will allow me to do this in, for example, Java 8). However, tips about how to do that requirying the JDK to be installed are also appreciated (thanks Evgeniy).

It is possible if you have JDK, java complier is in tools.jar which comes with JDK only. See http://docs.oracle.com/javase/7/docs/api/javax/tools/package-summary.html

Java Compiler API .. in-memory compilation is not supported. Is this correct?

No. The STBC uses the JavaCompiler to do exactly that.

..and instantiating such class afterwards?

The STBC does not go as far as trying to load/run the class, but I believe it should be possible. I imagine it might require a custom 'in memory' class loader though.

..the JavaCompiler API can do that independently if the JDK is installed or not?

From the page..

System Requirements

STBC will run on any computer with a version 1.6+ Java Plug-In * JDK (AKA SDK).

* The API that STBC uses is merely a public interface to the compiler in the tools.jar that is distributed only with JDKs (though the 'public JRE' of the JDK also seems to acquire a tools.jar ). ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM