Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Java source code within a Java program

I have wrote some code to compile a Java source code. It then produces the .class file. The problem is how do I run it?

For example, I am ok with the name of the program and class being set, I've used prog p = new prog(), in this case, however, the class file does not yet exist until I compile it. Not really sure what to do. Can someone give me an advice?

btw, the class looks like this:

public void compile{
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();  
  int compilationResult = compiler.run(null, null, null, fileToCompile);  
}

public void run(){
  Prog prog = new Prog();
  prog.run();
}
like image 200
gerky Avatar asked Feb 11 '11 03:02

gerky


People also ask

How is Java source code executed?

In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension .

Can I run Java code with JRE?

Java source code is compiled and converted to Java bytecode. If you want to run this bytecode on any platform, you need JRE.

Can you run Java without compiling?

Starting with Java SE 11 and for the first time in the programming language's history, you can execute a script containing Java code directly without compilation. The Java 11 source execution feature makes it possible to write scripts in Java and execute them directly from the *inx command line.


2 Answers

If you just want to run it, you could launch a java process using Runtime.exec or ProcessBuilder. These will create a seperate java process to run your java program. This is more likely what you want. You can essentially do the equivelant of:

>java someClass

from within your application. This link may help.

If you want to actually load the classfile and use it in your current application, I think something along the lines of this, or dynamically loading Java Classes ought to help. Basically (directly from the link, slightly modified):

public class MainClass {

  public static void main(String[] args){

    ClassLoader classLoader = MainClass.class.getClassLoader();

    try {
        Class aClass = classLoader.loadClass("MyClass");
        System.out.println("aClass.getName() = " + aClass.getName());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

Once you loaded the class, you have a Class object, and you can create an instance of the class represented by aClass by calling aClass.newInstance(), which is like

MyClass newObj = new MyClass()

Or you can use any of the other methods the Class object exposes.

As pointed out by davmac, the code sample above presumes that the code you're loading is on your applications classpath. If the class files you want to run are not in your classpath, you might want to look into URLClassLoader

like image 182
Zach L Avatar answered Oct 16 '22 16:10

Zach L


Load it by URLClassLoader.

File root = new File("/java"); // The package root.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("test.Test", true, classLoader); // Assuming package test and class Test.
Object instance = cls.newInstance();
// ...

See also:

  • How do I instantiate a class dynamically in Java?
like image 27
BalusC Avatar answered Oct 16 '22 17:10

BalusC