0

In my code have a method that is supposed to invoke the method doSomething of an object. Upfront, it is not known if the object's class does have the public method or not. Until now, I used the following code:

try {
  Method method = component.getClass().getMethod("doSomething", Boolean.TYPE);
  method.invoke(component, true);
} catch (final NoSuchMethodException e) {
  // do nothing as for some components the method "doSomething" simply does not exist
} 

I now wonder if I should try to avoid the NoSuchMethodExceptionby checking if the object's class does have the public method doSomething.

final Method method = Arrays.stream(component.getClass().getMethods())
      .filter(m -> m.getName().equals("doSomething")).findFirst().orElse(null);
if (method != null) {
  method.invoke(component, true);
}

What do you think is better?

gabriel
  • 347
  • 3
  • 18
  • none is better IMHO – user85421 Jun 04 '19 at 07:31
  • it depends on how frequently NoSuchMethodException happens, if this is rare 1 is better. – Viet Jun 04 '19 at 07:32
  • @gabriel why NoSuchMethod apears in first place ? Cant it be fixed by fixing up the dependencies ? – Alexander Petrov Jun 04 '19 at 07:37
  • @AlexandarPetrov You got a point here. I just checked the API of the framework the objects are from again. It would be possible to check if the objects implement certain interface before calling the method containing the snippet from above. Thus, it would really be an exception if the method was not available. Is it that what you meant? – gabriel Jun 04 '19 at 07:47
  • Moreover, by checking for the interface reflection is not necessary at all any more. – gabriel Jun 04 '19 at 07:54
  • Unless this is very very high performance code, both are fine. Just depends on which school of thought you like to follow - https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain – Aditya Jun 04 '19 at 07:56
  • If you care enough to be asking this question, you should be benchmarking / profiling this **in your application** rather than asking us what we "think". – Stephen C Jun 04 '19 at 09:00

1 Answers1

2

The real question is if the refection is really necessary here. learning cool tricks and knowing reflection is awesome and important for a developer, and it help you understand a lot about. but its not always the right solution . maybe you should just have in interface something like .

public interface DoingSometing { SomeReturnObject doSomething(Boolean param); }

and the component should implement the interface, and in worst case scenario, you will have to do casting to avoid reflection and you might fly on ClassCastException if the object that you have in your possession

NiNiCkNaMe
  • 181
  • 5
  • As I mentioned in my comment above some of the classes already implemented such an interface - I just was not aware of the fact they did. I already changed it accordingly. – gabriel Jun 05 '19 at 11:28