gpt4 book ai didi

Java反射,获取方法append并使用它

转载 作者:行者123 更新时间:2023-12-02 08:00:08 25 4
gpt4 key购买 nike

我写了一个程序,它必须询问要使用的方法(我使用 java.lang.StringBuffer.append),然后它必须说明它最大需要多少个参数,我认为在本例中是 3 个。用户可以输入任意数量的参数,只要他想要所有字符串,然后程序附加它们并打印字符串。但有一些问题,我只是没有找到错误。

import java.lang.reflect.*;

import tio.*;
public class MethodExecutor {
public static void main(String [] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException
{
String input = "";
String input1 = "";
String input2 = "";
String argumenten[];
int aantal = 0;
System.out.println("What method to invoke?");
input = Console.in.readLine();

input1 = input.substring(0,input.lastIndexOf("."));
input2 = input.substring(input.lastIndexOf(".")+1,input.length());
System.out.println(input2);

Class<?> c = Class.forName(input1);
Method m = c.getMethod(input2, null);
Class<?>[] parameterTypes = m.getParameterTypes();

System.out.println("Needs max " + parameterTypes.length + " parameters.");
System.out.println("How many will you provide?");
aantal = Console.in.readInt();
argumenten = new String[aantal];
for(int i = 0; i < argumenten.length; i++)
argumenten[i] = Console.in.readLine();

System.out.println("Success");

}
}

Tio 只是一个获取控制台输入的库。

有人可以帮忙吗?

亲切的问候,

最佳答案

我认为这...

Method m = c.getMethod(input2, null);

... 将查找名称存储在 input2 中的方法,该方法不带任何参数。

相反,我认为您需要搜索类上的每个方法,然后打印出名称匹配的方法的长度

(来自 getMethod 的 javadoc:)

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method. The parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order. If parameterTypes is null, it is treated as if it were an empty array.

关于Java反射,获取方法append并使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9017553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com