4

In my project I need to dynamically access getters and setters of different objects many times. Due to that I would like a fast method for accessing a method dynamically.

Java 7 introduced the MethodHandle class for dynamically executing a method of a given class. From what I can see there is no such thing on the Android port of the JDK. Is there any workaround that can be used to circumvent this, other than using the standard reflection classes?

LazyOfT
  • 1,428
  • 7
  • 20
  • "_other than using the standard reflection classes_" Why? – Unihedron Aug 01 '14 at 16:23
  • is it for simple getter/setters or something more complicated ? – radai Aug 01 '14 at 16:24
  • @Unihedron my understanding is that a MethodHandle will be faster than standard reflection and for my needs I need a faster method than reflection. See here for a reference: http://stackoverflow.com/questions/14146570/calling-a-getter-in-java-though-reflection-whats-the-fastest-way-to-repeatedly – LazyOfT Aug 01 '14 at 16:25
  • @radai getters and setters would suffice, I edited my question so that ti is more clear – LazyOfT Aug 01 '14 at 16:27

2 Answers2

2

you could obviously just get the appropriate Method object and call it.

but if you want something faster you could generate a class at runtime that calls your target method. so you locate the method using normal reflection, generate a MethodCaller class that implements some interface that you define beforehand (callMethod() ?), load that newly generated class and use it. there's a library thats compatible with the android runtime here and a long discussion listing other possible alternatives here.

while this is doable, its certainly not easy and i'd recommend trying normal reflection and measuring the performance. maybe it'll work well enough.

radai
  • 23,949
  • 10
  • 71
  • 115
  • I feared something like that. I will look into that and see if I can manage to do what I want. – LazyOfT Aug 01 '14 at 18:29
  • I managed to test the code, and even if it's a bit trickier it appears to be working. Thanks. – LazyOfT Aug 07 '14 at 17:40
  • Looks like `Method` won't let you call super methods directly (e.g. Method can't call `ListView#arrowScroll` from `MyListViewSubclass#arrowScroll`) – nmr Mar 29 '15 at 21:31
0

It seems with API level 26 (Oreo 2017) method handles are also part of the Android platform. They are useful to perform an invoke special.

This might be needed for reflective call of a default method from within a Proxy or simply do a reflective super call.

What I don't know yet whether some lookup issues have been fixed in Android.