2 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
要通過(guò)反射調(diào)用方法,您需要三件事:
對(duì)象的類(lèi)名
為其調(diào)用方法的類(lèi)實(shí)例
方法參數(shù)。
直接從官方文檔中拿一個(gè)例子,調(diào)用一個(gè)方法只需寫(xiě):
Class<?> c = Class.forName(args[0]);
Class[] argTypes = new Class[] { String[].class };
Method main = c.getDeclaredMethod("main", argTypes);
String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
System.out.format("invoking %s.main()%n", c.getName());
main.invoke(null, (Object)mainArgs);
要顯示參數(shù)名稱(chēng),只需查閱java官方文檔的另一頁(yè),討論它。
我希望它有幫助。

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用AdminLogin.class.getDeclaredMethods()for 循環(huán)將所有方法映射到某些操作,然后您可以使用讀取參數(shù),method.getParameters()但請(qǐng)注意參數(shù)可能沒(méi)有名稱(chēng) - 這必須在編譯器中使用-parameters標(biāo)志啟用。
概念證明:
Map<String, Callable> mappedMethods = new HashMap<>(); // you can use runnable etc, I used callable as I don't want to catch exceptions in this example code - you should.
AdminLogin instance = new AdminLogin();
WebElement usernameElement = null; // idk how you get instance of this
WebElement passwordElement = null; // idk how you get instance of this
for (Method method : AdminLogin.class.getDeclaredMethods()) {
Parameter[] parameters = method.getParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if ((parameter.getType() == WebElement.class) && parameter.getName().equals("username")) {
args[i] = usernameElement;
}
else if ((parameter.getType() == WebElement.class) && parameter.getName().equals("password")) {
args[i] = passwordElement;
} else {
// log some info/throw exception, whatever you need for methods that can't be mapped
break;
}
}
mappedMethods.put(method.getName(), () -> method.invoke(instance, args));
}
現(xiàn)在您可以從地圖中按名稱(chēng)調(diào)用可調(diào)用對(duì)象。
但是請(qǐng)注意,您應(yīng)該在此處添加更多抽象,因?yàn)槿绻懈鄥?shù)類(lèi)型來(lái)處理或?yàn)槊總€(gè)類(lèi)復(fù)制此代碼,則 ifs 之墻將是一個(gè)壞主意。
另請(qǐng)閱讀 Java 中的注解,它們對(duì)于標(biāo)記這樣的特殊方法和參數(shù)很有用,但不要過(guò)度使用它們。
另請(qǐng)注意,getDeclaredMethods返回方法沒(méi)有特定的順序,并且肯定與類(lèi)中聲明的順序不同。
添加回答
舉報(bào)