更新时间:2023-11-28 23:12:40
@missingfaktor提到了一种方法,下面是另一种方法(如果知道名称和参数) api)。
One method is mentioned by @missingfaktor and another is below (if you know the name and parameters of the api).
假设您有一种不带args的方法:
Say you have one method which takes no args:
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:
Say you have one method which takes native 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)));
}
假设您有一个盒装方法整数
args:
Say you have one method which takes boxed 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更新
Using the above soln to invoke method won't give you compilation errors. Updated as per @Foumpie