Changing java file
Can I change a java file, when I'm开发者_运维百科 running it on JVM, using this file?
For example: I run abc.java. In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes. Is it possible?
3 steps:
modify your .java file just like you would modify a text file.
compile that .java file from within your already running JVM using javax.tools compilation tools
Instantiate your freshly compiled class using the ClassLoader.
No. Maybe what you want is dynamic define classes at runtime. If so, you could choose dynamic language like Groovy.
The JVM runs class files (.class) and not Java (.java) files. To "convert" a *.java file to a *.class file it needs to be compiled firs.
So change a *.java File will not infuent the JVM in any way, because it is compleatly not interessed in.
Only because of a totality answer You can write a programm (.java) that when it is compiled an run (.class) change its own source file (.java) (for example changing a string by user input) compiles it (.class), and restart it selfe with its new compiled form. But this is defently not what you want! One would write this kind of software only to prove that this insane idea would work.
Anyway, what you need is a way to store data, in a file or a database. (Have a look at the java.io package for file handling, and for an tutorial).
(new answer for updated question)
"In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes."
This seems like a strange loop, self-modifying java code?
Then yes, the tools nrobey describes would be the way to go, though I agree with Ralph that it might be a bad idea.
精彩评论