小编典典
@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[]) 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(, 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(, invoke(this,
Integer.valueOf(10)));
}
使用上述soln调用方法不会给您带来编译错误。按照@Foumpie更新
2020-12-03