java类是否包含方法名_如何检查Java类中是否包含特定方法?

小编典典

@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值