How to run Java source code within a Java program

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

提交回复
热议问题