How to run Java source code within a Java program

后端 未结 3 875
遇见更好的自我
遇见更好的自我 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: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?

提交回复
热议问题