FranXh
FranXh

Reputation: 4771

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.

Upvotes: 1

Views: 2158

Answers (2)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78619

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)");

Upvotes: 3

Lion
Lion

Reputation: 19037

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).

Upvotes: 0

Related Questions