java - How can I use method handles with JDK 6? -


strange situation here. need invoke same class instance method many many times (1000/second range) without ability import or build against library needed. trying call method within jee project uses class application server's provided library. jee project still needs run on other application servers cannot build against library. reflection solution think.

when going rapidly, time execute orders of magnitude slower using reflection direct invocation.

after research, discovered static final methodhandles:

import java.lang.invoke.methodhandle; import java.lang.invoke.methodhandles; import java.lang.reflect.method;    public class test {      static final methodhandle sfmh;      static {         methodhandle mh = null;         try {             final class<?> clazz = class.forname("com.me.lib");             method m = clazz.getmethod("mymethod");             mh = methodhandles.lookup().unreflect(m);         } catch (throwable e) {             mh = null;         }          sfmh = mh;     }      public static void main(string[] args) throws throwable {         int = 0;         system.out.println("starting");         long start = system.currenttimemillis();         for(i = 0; < 1000000000; i++) {             sfmh.invokeexact();         }         long total = system.currenttimemillis() - start;         system.out.println("time: " + total + " milliseconds");     }  } 

the works great , gets me acceptable speed result (2-4 times slower instead of 200x slower). there seems issue perfect solution -- need run on java 6 (boo, hiss, it's requirement)

when compiling against 1.6 get:

invocation of polymorphic methods not allowed source level below 1.7

on line

sfmh.invokeexact(); 

is there solution takes advantage of concept of methodhandle works 1.6?

no, method handles added in jdk 7 , not accessible before that. neither can compile class against method handle api jdk 6 not understand @polymorphicsignature annotation; method handles compiled different other methods using synthetic signature.

beyond that, reflection not slower on modern jvms, maybe run application on recent jvm instead? fine run java 6 code on jvm v8. finally, benchmark flawed many reasons. maybe reflection code not slow today? jvm knows concept known inflation avoids performance overhead of jni call.

here results using harness on v8 jvm, comparing reflection, common invocation , method handles: https://gist.github.com/raphw/881e1745996f9d314ab0