How to run Java source code within a Java program

后端 未结 3 876
遇见更好的自我
遇见更好的自我 2021-01-03 04:49

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 pro

相关标签:
3条回答
  • 2021-01-03 05:16

    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

    0 讨论(0)
  • 2021-01-03 05:22

    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?
    0 讨论(0)
  • 2021-01-03 05:27

    You need to create a classloader (a URLClassLoader will probably be fine) which will load the just-compiled class file. (So for a URLClassLoader, the compilation output path should be one of the URLs).

    Then, load the compiled class using the classloader, and execute it using reflection.

    Class c = cl.loadClass("ClassName");

    ... etc.

    0 讨论(0)
提交回复
热议问题