如何检查Java中的类是否存在方法? try {...} catch {...}
语句会是一个好习惯吗?
我假设您要检查方法doSomething(String, Object)
。
您可以尝试以下方法:
boolean methodExists = false;
try {
obj.doSomething("", null);
methodExists = true;
} catch (NoSuchMethodError e) {
// ignore
}
这将不起作用,因为该方法将在编译时解决。
您确实需要为此使用反射。而且,如果您可以访问要调用的方法的源代码,则最好使用要调用的方法创建一个接口。
[更新]附加信息是:有一个接口可能存在两个版本,一个是旧版本(不包含所需方法),一个是新版本(具有所需方法)。基于此,我建议以下内容:
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;
}
}));
}
}
此代码测试接口中是否存在方法getAllowedNether
,因此实际对象是否具有该方法都没有关系。
如果必须经常调用方法getAllowedNether
,并且因此而导致性能问题,我将不得不考虑一个更高级的答案。此刻现在应该没问题。
使用NoSuchMethodException
函数时,Reflection API会抛出Class.getMethod(...)
。
否则,Oracle会提供有关反射http://download.oracle.com/javase/tutorial/reflect/index.html的不错的教程>
在Java中,这称为反射。该API允许您发现方法并在运行时调用它们。这是指向文档的指针。这是非常冗长的语法,但可以完成工作:
我将使用单独的方法来处理异常,并进行null检查以检查方法是否存在