简体   繁体   English

反射getMethod而不引起异常

[英]Reflection getMethod without causing exceptions

Is there a way in Java reflection to call getMethod or some other one that won't throw an exception if a method isn't found? Java反射中是否有一种方法可以调用getMethod或其他某种方法(如果未找到方法,该方法不会引发异常)? Maybe just return a null instead? 也许只是返回一个null呢?

I'm doing a pass through an application to decrease expected exceptions and this seems like a possible candidate. 我正在通过一个应用程序以减少预期的异常,这似乎是一个可能的候选人。

您可以遍历getMethods(),如果找不到匹配项,则返回null

Depending on your application needs, maybe appropriate to use getMethods() . 根据您的应用程序需求,也许适合使用getMethods() It return an array of all defined methods in your class. 它返回类中所有已定义方法的数组。 You can that map returned methods by name, or use them as you like. 您可以按名称映射返回的方法,也可以根据需要使用它们。 Note, however, that this could be slower than call getMethod() only on the method you need and eventually catch the exception. 但是请注意,这可能比仅在所需的方法上调用getMethod()慢,并且最终捕获异常。 Some caching could help in this case. 在这种情况下,一些缓存可能会有所帮助。

If you haven't already read this article , check it out. 如果您尚未阅读本文 ,请查看。

The Android developer's site doesn't seem to have an issue with using a try-catch block to achieve this effect... I think you should be fine. Android开发人员的网站似乎在使用try-catch块实现此效果方面没有问题...我认为您应该没问题。

If compatibility across multiple SDKs is your main concern, you might be able to avoid reflection all together by wrapping your code in if-else blocks as follows: 如果主要考虑跨多个SDK的兼容性,则可以通过将代码包装在if-else块中,如下所示来避免所有反射:

if (currentAPIVersion >= android.os.Build.VERSION_CODES.FROYO){
    // Do something for froyo and above versions
} else{
    // do something for phones running an SDK before froyo
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM