开发者

How can I dynamically create a new .java file from a Java program?

I want to create a one .java from the Java program. When I run the program, automatically one Java file will created in my project, and also create some run time (dynamic) variable in that file. How can I do this?

开发者_运维技巧

I know for this I have to use a Reflection API like Class and Method, but what are the methods in Class and Method to do this?


You cannot create new classes or methods using the reflection APIs. They are not designed for this. (The Class and Method APIs are for performing operations on object instances in a dynamic fashion.)

If you want to create new code on the fly, there are two basic approaches to doing this:

  1. Generate Java source code, write it to a file, use the Java compiler to compile it to a bytecode file, and then load the bytecodes. (There are standard APIs for running the Java compiler within the JVM of a running application.)

  2. Use BCEL or equivalent to construct a bytecode file from scratch, and then load the bytecodes.

Both approaches are tricky and computationally expensive. The BCEL approach is particularly tricky because you need to understand a lot about the JVM to do the job.


Apparently you want to create a new class at Runtime and use it. You can sure create a .javafile, compile it and load it from a custom class loader but that's probably not the best/easiest thing to do. Here are a bunch of solutions:

  1. First of all if you want to extend an interface, you can use the Proxy from the Java Reflection API.
  2. It you want to extend a class rather than implements an interface or create a class out of the blue you need to use a library to create bytecode. You can find a bunch of them on http://www.java-opensource.com/open-source/bytecode-libraries.html. Among these libraries I like javassist mainly because it is the only library to my knowledge letting you enter Java code directly rather than bytecode.
  3. A last solution should be to use a framework like Groovy or BSH to interpret pseudo-java code.


No, you can't generate new .java files using Reflection. You could perhaps create a new class, and use this class, in runtime, but you can't write that class out to file in the form of a .java source file.

Have a look at the JustAdd framework for instance. This framework solves this type of problems IIRC.


Java is a strongly typed language( As opposed to a weakly typed language). Simply put you need to have a Class (prototype) to create a instance of object. What you are trying to do is not natural in java (or any strongly typed language).

If you have to have this functionality in java, you need to use groovy. Groovy is a dynamic language that can run in Java JVM. You need to check Expandos in groovy.(ofcourse it still will not create a .java file).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜