How would one go about checking to see if a method exists for a class in Java? Would a try {...} catch {...} statement be good practice?
How would one go about checking to see if a method exists for a
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I assume that you want to check the method
doSomething(String, Object).You might try this:
This will not work, since the method will be resolved at compile-time.
You really need to use reflection for it. And if you have access to the source code of the method you want to call, it’s even better to create an interface with the method you want to call.
[Update] The additional information is: There is an interface that may exist in two versions, an old one (without the wanted method) and a new one (with the wanted method). Based on that, I suggest the following:
This code tests whether the method
getAllowedNetherexists in the interface, so it doesn’t matter whether the actual objects have the method or not.If the method
getAllowedNethermust be called very often and you run into performance problems because of that, I will have to think of a more advanced answer. This one should be fine for now.