How can I dynamically create a new .java file from

2019-07-18 03:20发布

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?

4条回答
时光不老,我们不散
2楼-- · 2019-07-18 03:48

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.

查看更多
男人必须洒脱
3楼-- · 2019-07-18 03:52

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-07-18 04:05

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.
查看更多
\"骚年 ilove
5楼-- · 2019-07-18 04:09

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).

查看更多
登录 后发表回答