@missingfaktor提到了一种方法,下面是另一种方法(如果您知道api的名称和参数)。
假设您有一种不带参数的方法:
Method methodToFind = null;try { methodToFind = YouClassName.class.getMethod("myMethodToFind", (Class<?>[]) null);} catch (NoSuchMethodException | SecurityException e) { // Your exception handling goes here}调用它(如果存在):
if(methodToFind == null) { // Method not found.} else { // Method found. You can invoke the method like methodToFind.invoke(<object_on_which_to_call_the_method>, (Object[]) null);}假设您有一种采用本地
int参数的方法:
Method methodToFind = null;methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { int.class });调用它(如果存在):
if(methodToFind == null) { // Method not found.} else { // Method found. You can invoke the method like methodToFind.invoke(<object_on_which_to_call_the_method>, invoke(this, Integer.valueOf(10)));}假设您有一种采用盒装
Integer参数的方法:
Method methodToFind = null;methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { Integer.class });调用它(如果存在):
if(methodToFind == null) { // Method not found.} else { // Method found. You can invoke the method like methodToFind.invoke(<object_on_which_to_call_the_method>, invoke(this, Integer.valueOf(10)));}使用上述soln调用方法不会给您带来编译错误。按照@Foumpie更新



