如何检查 Java 中的类是否存在方法? try {...} catch {...}
语句是好的做法吗?
最佳答案
我假设您想检查方法 doSomething(String, Object)
。
你可以试试这个:
boolean methodExists = false;
try {
obj.doSomething("", null);
methodExists = true;
} catch (NoSuchMethodError e) {
// ignore
}
这行不通,因为该方法将在编译时解析。
您确实需要为此使用反射。而且,如果您可以访问要调用的方法的源代码,则最好为要调用的方法创建一个接口(interface)。
[更新] 附加信息是:有一个接口(interface)可能存在两个版本,一个旧的(没有想要的方法)和一个新的(有想要的方法)。基于此,我提出以下建议:
package so7058621;
import java.lang.reflect.Method;
public class NetherHelper {
private static final Method getAllowedNether;
static {
Method m = null;
try {
m = World.class.getMethod("getAllowedNether");
} catch (Exception e) {
// doesn't matter
}
getAllowedNether = m;
}
/* Call this method instead from your code. */
public static boolean getAllowedNether(World world) {
if (getAllowedNether != null) {
try {
return ((Boolean) getAllowedNether.invoke(world)).booleanValue();
} catch (Exception e) {
// doesn't matter
}
}
return false;
}
interface World {
//boolean getAllowedNether();
}
public static void main(String[] args) {
System.out.println(getAllowedNether(new World() {
public boolean getAllowedNether() {
return true;
}
}));
}
}
此代码测试接口(interface)中是否存在方法getAllowedNether
,因此实际对象是否具有该方法并不重要。
如果必须经常调用方法 getAllowedNether
并且您因此遇到性能问题,我将不得不考虑更高级的答案。这个现在应该没问题。
关于java - 如何在 Java 运行时检查方法是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058621/