如何检查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
方法,并且由于此原因而遇到性能问题,那么我将不得不考虑更高级的答案。但目前这个答案应该可以满足要求。
接口
吗?那么你可以使用instanceof
运算符来查询它的存在。 - Roland Illig当使用Class.getMethod(...)
函数时,反射API会抛出NoSuchMethodException
异常。
除此之外,Oracle有一个关于反射的不错教程:http://download.oracle.com/javase/tutorial/reflect/index.html
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
if (null != getDeclaredMethod(obj, "getId", null))
,然后进行你的操作...private Method getDeclaredMethod(Object obj, String name, Class<?>... parameterTypes) {
// TODO Auto-generated method stub
try {
return obj.getClass().getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
class World {
public void star(String str) {}
private void mars(String str) {}
}
try {
World.class.getMethod("star", String.class);
World.class.getDeclaredMethod("mars", String.class);
} catch (Exception e) {}
其他解决方案:
public static <O> boolean existsMethod(final String methodName, final O o) {
return Stream.of(o.getClass().getMethods()).map(Method::getName).anyMatch(methodName::equals);
}
Iterator
接口这样的情况,其中对于remove
的实现可以抛出UnsupportedOperationException
? - Ken Wayne VanderLinde