Home > other >  Is there a way to run a Java Program when you don't know its name?
Is there a way to run a Java Program when you don't know its name?

Time:05-21

I'm making a game engine using LWJGL. The developer using it has to be able to use scripts. I decided to just make them use Java because writing an API in another language wasn't something I'm going to have the time nor experience to do. Anyways, I would have used x.main(); to run it, but The developer tells what the script is named, and that is stored in a variable. I just thought I could run a command to do that, using a method like exec() in python or eval() in JavaScript. I couldn't find a library that has this execution functionality and if there was, it just wasn't straightforward enough for me to wrap my mind around it. if you don't know any libraries that have this functionality, but have a recommendation of something I should try, I'd love to hear it.

To summarize this paragraph, I need a Java Library that can use a method like JavaScript's eval() or python's exec()

Any help would be greatly appreciated.

CodePudding user response:

I dont know If I understood the problem, but I have focused on part of having "script name stored as variable" which sounds to me like a method name. You can invoke method by its name using reflections

public class MCAlu {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String scriptName = "sayHello";
        Method scriptMethod = MyScript.class.getMethod(scriptName);
        scriptMethod.invoke(null, null);
    }
}

class MyScript {
    public static void sayHello() {
        System.out.println("Hi there!");
    }
}

Since class has to be known and on the classpath (unless you will load it in the runtime), class name can be as well provided as string resulting in

String scriptClass="MyScript";
String scriptName = "sayHello";
Method scriptMethod = Class.forName(scriptClass).getMethod(scriptName);
scriptMethod.invoke(null, null);

CodePudding user response:

One (quite popular) tool that can help you run Java sources as scripts is JBang. Java programs have to be compiled (to Java class files) to be able to run by a JVM. So, basically, JBang hides this compilation step and invokes the JVM with our compiled class.

  • Related