[英]How to invoke a Java method that is in a Array of Strings? (java.lang.NoSuchMethodException)
我有一個帶有Method names
的Strings
Array
,我試圖在循環中調用它。 我已經檢索了類中所有變量的名稱並添加了所需的文本以填充整個函數並將整個字符串添加到列表中:
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 - 您的 Telegramm 課程:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.