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?
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.
You cannot create new classes or methods using the reflection APIs. They are not designed for this. (The
Class
andMethod
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:
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.)
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
.java
file, 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: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).