一种方法是通过@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
ARGS:
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
ARGS:
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更新
谢谢。我想使用该方法,并且必须在该类中编写所有可能的方法,但自动生成的类可能没有该方法。如何让编译器在编译时忽略它? – Dilawar
使用调用不会给你编译错误...检查更新的答案。 – havexz
非常感谢。将它封入'try-catch'后,它就像一个魅力。 – Dilawar