Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of Reflection in moderns JVMs (6 onwards)

I want to know if the cost of reflection has gone down in modern JVMs that we can use it freely everywhere except the most critical sections in the code.

For example, if I want to invoke a method based on the method name given by a user as input. Now there are two ways to implemented this:

  1. Use a if/else/switch to determine which method to call. This will obviously be a lot of code if there is a large number of cases.

  2. Use reflection to invoke the method. This is definitely less code.

Clarification: Above is just an example where using reflection can shorten the amount of code. I just wanted to know if it is a valid strategy to replace a large amount of static code with some reflection magic. Also share any experiences if you have done something on the similar lines.

like image 792
Anand Nalya Avatar asked Oct 08 '22 16:10

Anand Nalya


1 Answers

No, there's another way to do it that's better, in my opinion: use a Command pattern and a Map of name/command instance pairs. You can scale that a very long way without switches or reflection. It's polymorphic, too - far more "object oriented".

Take a look at the java.lang.Runnable or java.util.concurrent.Callable if you prefer to not use your own Command. Your methods can be executed asynchronously if you wish.

It's not clear to me how users will specify which method they wish to invoke. If you use reflection, they have to spell out the name of the class, the method, the parameters, and know the return type. How do you intend to show them possible choices? Every class, every method in your application? Is anything fair game?

I think it's far more rational to present a list of choices that are prescribed in such a way that it's easy to specify and call. I don't believe that any solution based on reflection meets that criterion.

You want to offer users a choice, but "anything goes" does not seem practical to me.

As for your concrete example offered below, which includes Spring Controllers and services, I would not use reflection. If your users specify start or stop by passing an HTTP query parameter, better to map individual Controller methods to the specific URL that you have in mind using REST. My preference is clarity, even if it's more verbose.

like image 137
duffymo Avatar answered Oct 10 '22 09:10

duffymo