Questions about (refreshing) .class files
So I'm having some refresh problems with 开发者_如何学编程eclipse. I'm not sure if it's a Java issue or an Eclipse issue.
I'm trying to create a .java file, and then I'm trying to instantiate an object of that type, and run a specific method that I've defined in that class.
The code I'm using to create a source file with the class classname
and run the method method
:
Class cl = Class.forName(classname);
java.lang.reflect.Constructor co = cl.getConstructor();
cl.getMethod(method).invoke(co.newInstance());
When I create a .java file ("dynamic" class/code), my code throws a ClassNotFoundException. If I right click on my project and hit refresh, the .java shows up, a .class is created, and my code runs fine. Obviously this is problem because I'm trying to do this all in one shot, and obviously having to refresh my project's package is a problem.
Any way around this?
You need to (at least conceptually) separate your execution environment from your build environment. If the purpose of your program is to create a Java source file, compile it, and then use it all within the same runtime, you need to find a way to do it programmatically, decoupled from Eclipse. If your goal is to always run your program in a way coupled to Eclipse, you're better off making an Eclipse plug-in.
To do this all within one Java runtime, you need to use the JDK tools to invoke the compiler and then use a custom classloader to load the result.
If you create a Java file on the fly, you probably need to invoke javac
command to compile it first, before you can execute your code. You can programatically invoke javac
command using Runtime.exec(..).
Within the Eclipse environment, when you do changes and the IDE does not accept or recognize them, you should do a Refresh, and you should also go to Project -> Clean and clean that project and all the ones it depends on. Cleaning will often and typically fix the issues.
You should take a look at the Codehaus JANINO project. http://docs.codehaus.org/display/JANINO/Home
I've used it before on a project with a large number of dynamically generated and registered classes.
Here is a part of the excerpt from the project's site.
Janino is a super-small, super-fast Java™ compiler. Not only can it compile a set of source files to a set of class files like the JAVAC tool, but also can it compile a Java™ expression, block, class body or source file in memory, load the bytecode and execute it directly in the same JVM.
精彩评论