Java,使用基于字符串输入的类 [英] Java, use a class based on string input
问题描述
我在Java中制作一个基于命令行的工具,我想我可能能够使我对自己更容易一点,如果我可以采取用户输入,并自动找到所需的功能基于用户输入。
我想做的是,如果用户输入:
用户创建新用户
java代码查找一个名为user的类,然后查找一个名为create的函数,并输入newUser作为函数的第一个参数。意思是键入命令User create newUser将使java代码触发这一行代码:
User.create );
原因,如果没有找到类或函数,返回错误。 >
到目前为止我一直在玩
Class.forName(cmdArg [ 0])
其中cmdArg [0]是Scanner提供的第一个字,有空格。
无论如何,是否可以在Java中实现这一点?任何帮助将非常感激。
我的解决方案:
OK,我得到它的工作,我的最终解决方案是duffymo的和user978548的答案的组合,我的解决方案如下:
class comArgs [] = new Class [1];
comArgs [0] = String.class;
String [] args = new String [1];
args [0] = commandArray [2];
Class.forName(code。+ commandArray [0])
.getDeclaredMethod(commandArray [1],comArgs)
.invoke(null,args);
这是被一个try / catch包围的例外,但它可以工作。
我也有一个HashMap用于接收命令。
args
variable可以只要被调用方法所需的参数数量。
Class.forName(args [0])。newInstance();
为类,和Chin Boon说,你有所有你想要的反射方法。喜欢,运行你的方法:
Object.class.getMethods()[在这里找到你的方法] .invoke(obj,args)
I'm making a command-line based tool in Java, and I was thinking I might be able to make it all a bit easier on my self if I could take user input and automatically find the needed functions based on the users input.
What I want to do, is, that if a user types:
User create newUser
The java code looks for a class called user, then looks for a function called create, and inputs newUser as the first argument of the function. Meaning typing the command "User create newUser" would make the java code trigger this line of code:
User.create("newUser");
And of cause, return errors if the class or function was not found, or so.
So far I've been playing with
Class.forName(cmdArg[0])
Where cmdArg[0] is the first word given by the Scanner, found by splitting where there's spaces.
Anyway, is it possible to achieve this in Java? Any help would be much appreciated.
My solution:
Okay, i got it working, my final solution was a combination of duffymo's and user978548's answer, my solution looks like this:
Class comArgs[] = new Class[1];
comArgs[0] = String.class;
String[] args = new String[1];
args[0] = commandArray[2];
Class.forName("code."+commandArray[0])
.getDeclaredMethod(commandArray[1], comArgs)
.invoke(null, args);
This is surrounded by a try/catch with allot of exceptions, but it works.
I also have a HashMap for which commands i want to receive.
The args
variable can should be as long as the number of arguments needed for the called method.
as duffymo said, Class.forName(args[0]).newInstance();
for the class, and as Chin Boon said, you have all that you want in reflections method. Like, to run your method:
Object.class.getMethods()[find your method here].invoke(obj, args)
这篇关于Java,使用基于字符串输入的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!