简体   繁体   中英

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? Maybe just return a null instead?

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() . 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. 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.

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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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