Reflection cost in modern JVMs (6 or more)

I want to know if the cost of thinking in modern JVMs has decreased, that we can use it freely everywhere except for the most critical sections of code.

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

  • Use the if / else / option to determine which method to call. Obviously, this will be a lot of code if there are a large number of cases.

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

Clarification . The above is an example where using reflection can reduce the amount of code. I just wanted to know if this is really an effective strategy for replacing a lot of static code with some reflection magic. Also share your experience if you have done something similar.

+5
source share
3 answers

No, there is another way to do this better, in my opinion: use the Command pattern and a couple of name / command pairs. You can scale this very long way without switches or reflection. It is also polymorphic - much more "object-oriented."

java.lang.Runnable java.util.concurrent.Callable, . , .

, , . , , , . ? , ? - ?

, , , . , , , .

, "- " .

, , Spring , . , HTTP-, URL-, , REST. - , .

+4

, / . , JVM . ? , , , .

0

You must distinguish between two steps in invoking a reflexive method: method search (slow) and method invocation (very fast). So, all you really need to do is cache instances Methodand have a quick search solution. Then you will have a win-win solution.

0
source

All Articles