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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.