Rol*_*lig 27
我假设您要检查方法doSomething(String, Object).
你可以试试这个:
boolean methodExists = false;
try {
obj.doSomething("", null);
methodExists = true;
} catch (NoSuchMethodError e) {
// ignore
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为该方法将在编译时解决.
你真的需要使用反射.如果您可以访问要调用的方法的源代码,则最好使用要调用的方法创建接口.
[更新]附加信息是:有一个接口可能存在两个版本,一个旧版本(没有想要的方法)和一个新版本(使用想要的方法).基于此,我建议如下:
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;
}
}));
}
}
Run Code Online (Sandbox Code Playgroud)
此代码测试该方法是否getAllowedNether存在于接口中,因此实际对象是否具有该方法无关紧要.
如果getAllowedNether必须经常调用该方法并因此遇到性能问题,我将不得不考虑更高级的答案.这个应该没问题.
NoSuchMethodException使用Class.getMethod(...)函数时,Reflection API会抛出.
否则,Oracle有一个很好的反思教程http://download.oracle.com/javase/tutorial/reflect/index.html
| 归档时间: |
|
| 查看次数: |
53404 次 |
| 最近记录: |