0

I'm viewing somebody's code, and find that he once changed a method from running directly to use method.invoke, which is a public method (to be precise, it's sun.jvm.hotspot.tools.jcore.ClassDump.main in sa-jdi.jar).

And If I modify it back to running directly, it seems working all fine.

So anyone can tell be what's the difference between running directly and using method.invoke? I'm really curious about why he changed the code.

Mobility
  • 3,117
  • 18
  • 31
  • why don't you simply ask him directly? – Timothy Truckle May 05 '17 at 09:19
  • There should be no difference in the end, that's precisely the point. Calling method reflectively usually slower than direct call (expected), but it can also be optimized. What pe probably did is made attempt to indirect the call so that what method is actually called can be changed at some future point. – M. Prokhorov May 05 '17 at 09:21
  • @TimothyTruckle of course I can't get touch with that man now, or I can ask him directly. – Mobility May 05 '17 at 09:26

2 Answers2

0

Reflection in Java has a cost in terms of performance: if you can just call a method directly, just do it. You can find similar questions here and here and an informal benchmark here.

Community
  • 1
  • 1
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

To quote the official tutorial:

Reflection provides a means for invoking methods on a class. Typically, this would only be necessary if it is not possible to cast an instance of the class to the desired type in non-reflective code. Methods are invoked with java.lang.reflect.Method.invoke().

And you know the Direct way is just to initialize the class and call the method.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86