简体   繁体   中英

Is there a way in Java to call methods from the console?

Is there a way in Java to call methods from the console?

I know that it is possible to use the args array, for example args[0] , to get the name of an input file, but I do not know if Java allows method calls from the console.

Well, you could use reflection and pass the name of the method that you would like to invoke as one of the arguments for your program and then use it to reflectively invoke it.

Depending on what you really want to do you might like to consider something like BeanShell which would let you interact with Java from the Beanshell console in more simple ways, provided that your questions is "how to use Java from a Console?" and not how to do this programatically.

For instance, from the Beanshell console I could do something as follows:

print(eval("Math.max(1,2)"));

And it would yield 2 to my console.

You can also add the beanshell.jar to your application class path and use the eval method programatically.

import bsh.Interpreter;
//...
Interpreter i = new Interpreter();  
Integer r = (Integer) i.eval("Math.max(1,2)");

Do you just want to trigger execution of methods from command line or is there something else running in the background?

If there is something else, then you need to think about threads since otherwise your application would be blocked waiting for IO on command line.

Depending on how many methods there are to be called and how dynamic you want to be... you can use the reflection (It takes the classname and the method name as parameters and executes them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM