Reputation: 1809
Alright, I know this is a very common, very simple question, but mine comes with rather unusual circumstances. (Circumstances which I was unable to find a solution to elsewhere on the internet.) So, I have some source code which I am programmatically compiling via JavaCompiler
. I then attempt to execute the compiled code with Runtime. (That is, Runtime.getRuntime().exec(String[])
.) However, when I attempt to execute said code, I get Could not find or load main class.
The source code in question follows this base-model:
package compiledCode;
public class Compiled
{
public Compiled(){}
public static void main(String[] args)
{
System.out.println("Hello!! ;D");
}
}
Even that code won't execute. I still get the same error. Thanks in advance for your help. :)
*Edit: The steps I take in detail are as follows:
I start with the code mentioned above in a String called code. I then make a File object (in this case, Compiled.java.)
I use a custom method of mine which I have tested and have ensured it works to compile the file (and optionally get a Class object from it, though, for specific reasons, I can't do it that way for this.) into a .class file. (Using the JavaCompiler
API.)
I then use Runtime.getRuntime.exec(new String[]{"java",[location of .class file]});
to execute it.
It is at this point that I get an error.
The exact code I am using, as requested, is this..
ClassFileHelper.toClass(src, "C:/Users/Steven/Desktop/ /Eclipse/Workspace/RoccedGame/ServiceCoder", "ServiceCoder");
System.out.println("java "+src.getAbsolutePath().substring(0,src.getAbsolutePath().lastIndexOf(".java"))+".class");
final Process p = Runtime.getRuntime().exec(new String[]{"java",src.getAbsolutePath().substring(0,src.getAbsolutePath().lastIndexOf(".java"))+".class"});
The String manipulation in the 3rd line is a bit messy, but I've triple-checked to ensure that it works - which it does. If you would like to see the code for the .toClass()
bit, go here.
Upvotes: 1
Views: 811
Reputation: 1663
You're not passing the correct parameters to Runtime.exec()
.
You pass the actual location of the compiled classfile. However, you should be passing a class name, and if your class is in a package you'll also need to pass the root of the package hierarchy as a -classpath
parameter.
This is described in the JDK documentation: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html
Upvotes: 3