In eclipse, How to call a function read from the console?
I want to read a function's name from the console, and then calling it in that class. So, instead of checking wh开发者_StackOverflow中文版ich function it is using the "IF" statement, I wish it to happen automatically.
Exmp.
_ (CONSOLE)
BuildDatabase (WRITTEN IN CONSOLE)
---> What happens in class : Class.BuildDataBase();
Can it be done? Another question - how can I run my class' main from a command line?
Thanks ahead
You can use reflection for that:
Method method = YourClass.getMethod(nameReadFromConsole); //no parameters
method.invoke(null); // invoking without a target object - i.e. static
Running from console is done via the java
command - java ClassName
when u say command line do u mean the terminal? if you want to run the main method inside a class u can just call this:
java MyClass
But must be the compiled file(the .class)
or you can write a custom reader for your console (this code needs to be cleaned/refactored):
public static void main(String[] args) {
MyClass instance = new MyClass();
while(true) {
System.out.print("> ");
String input = new BufferedReader(new InputStreamReader(System.in)).readLine();
Method method = MyClass.getDeclaredMethod(input);
Object returnValue = method.invoke(instance);
System.out.println(returnValue);
}
}
- Edited to add the 'readLine' call!
精彩评论