Reasons for using on-the-fly compilation in Java
I saw some are writing out java files and THEN call the compiler, Doesn't that produce overhead while doing it 开发者_StackOverflowin runtime mode?
Runtime compilation does add quite a bit of overhead - the compilation step is (somewhat) slow.
It does, however, add a huge amount of flexibility. By compiling new code for each run of an application, you allow the application to change based on things that can't be known at (pre-deployment) "compile time".
This isn't something you want to do normally, but when it's appropriate, it's a very valuable, powerful technique.
Performing compilation during runtime obviously introduces some overhead but, as pointed out by Reed, the idea it to use this for things that you don't know at compile time.
But actually, according to Peter von der Ahé who is behind the JSR 199 - Compiler API (have a look at his (former) weblog or this interview), the Java Compiler API is not really for everybody:
99% of Java developers will newer need to know anything about the Java Compiler API (JSR 199). A small number of Java developers will use the API directly. However, the software these few developers make is used by all Java developers. I'm talking about software such as IDEs (NetBeans, Eclipse, IntelliJ IDEA, etc), Java EE application server, build infrastructures such as Maven and Ant, and test frame works. All these pieces of software have one thing in common: they all need to invoke a compiler to translate Java source code to class files. However, 99% of all developers will not and should not care about how the compiler is invoked.
精彩评论