我有一个Array
的Strings
与Method names
我正努力在一个循环中调用。我已经检索了该类中所有变量的名称,并添加了所需的文本以填充整个函数,并将整个字符串添加到列表中:
String[] methodNames= new String[16];
Class c = telegramm.class;
Field[] fields = c.getDeclaredFields();
int x=0;
for (Field field : fields)
{
String str = field.getName();
String variableName = str.substring(0, 1).toUpperCase() + str.substring(1);
// This is how I initially intended to call the method
// methodNames[x] = "set" + variableName + "(parts[" + x + "]);";
// but with the method I found I used this
methodNames[x] = "set" + variableName";
Method gs1Method = tClass.getMethod("getString1", new Class[] {});
//String str1 = (String) gs1Method.invoke(t, new Object[] {});
//System.out.println("getString1 returned: " + str1);
x++;
}
因此,我将一个名为String的方法添加到数组中methodNames
。
而且我找到了一种调用方法的方法:
Method gs1Method = tClass.getMethod("getString1", new Class[] {});
String str1 = (String) gs1Method.invoke(t, new Object[] {});
System.out.println("getString1 returned: " + str1);
该方法有效,但是仅当您对方法名称(“ getString1”)进行硬编码时才有效。
现在,我想实现一种通过methodNames
数组调用这些函数的方法。
当我将methodNames数组的对象作为参数传递时:
getMethod(methodNames[x], new Class[] {});
我得到错误:
Exception in thread "main" java.lang.NoSuchMethodException:
kin.gateway.adient.Testing.setBoolean1(java.lang.String)
at java.lang.Class.getMethod(Class.java:1786)
at kin.gateway.adient.ClassMethodTest.main(ClassMethodTest.java:31)
我还尝试将字符串添加到单个变量中,String variableName = "set" + variableName;
但是得到了相同的结果。
为什么不接受String作为变量?
在您可以根据自己的方法在其上添加循环之后,尝试此示例应该可以帮助您找到错误:
1-您的电报课程:
public class Telegramm {
String value1;
String value2;
public String getValue1() {
return this.value1;
}
public void setValue1(String value) {
this.value1 = value;
}
public String getValue2() {
return this.value2;
}
public String setValue2(String value) {
this.value2 = value;
return this.value2;
}
}
2-方法的调用:getValue1()和setValue2()
try {
// Create our Telegramm instance
Telegramm telegramm = new Telegramm();
telegramm.setValue1("value1");
telegramm.setValue2("value2");
// Invoke public static String getValue1()
Method getValue1Method = telegramm.getClass().getMethod("getValue1", null);
String result = (String)getValue1Method.invoke(telegramm);
System.out.println("result invocation getValue1() : " + result);
// Invoke public static String setValue2()
getValue1Method = telegramm.getClass().getMethod("setValue2", new Class[] {String.class});
result = (String)getValue1Method.invoke(telegramm, "ValueX");
System.out.println("result invocation setValue2() : " + result);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句