java输入类string,Java,使用基于字符串输入的类

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值