1

I am doing some mapping right now using reflection. This is a bottleneck in my code so I'm aiming to improve the performance. I've created the following method for my builder setter:

private static <T, R, S> BiFunction<T, R, S> createBuilderSetter(Method builderSetterMethod) {
    try {
        builderSetterMethod.setAccessible(true);
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle mh = lookup.unreflect(builderSetterMethod);
        return (BiFunction<T, R, S>) LambdaMetafactory.metafactory(lookup, "apply", MethodType.methodType(BiFunction.class), mh.type().generic(), mh, mh.type())
            .getTarget()
            .invokeExact();
    } catch (Throwable t) {
        throw new IllegalStateException(t);
    }
}

which is being used something like:

BiFunction<MyType.Builder, Object, MyType.Builder> setter = createBuilderSetter(...);

My question is around the middle generic type Object. This is a generic setter (one of many) that I don't know the type of at compile time. Is the JVM going to be doing any additional type checking above and beyond what it usually does that will slow me down? And if so, can my solution be improved?

Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • For performance you may read http://stackoverflow.com/questions/19557829/faster-alternatives-to-javas-reflection – Jean-Baptiste Yunès Mar 10 '17 at 17:04
  • What kind of _additional_ type checking are you thinking of? I know the MethodHandle will check the type of the arguments and return type. But the generics are gone after compilation. – Jorn Vernee Mar 10 '17 at 17:14
  • @JornVernee - I guess that kinda answers my question....I was wondering if the LambdaMetafactory did something I wasn't aware of.... – Cheetah Mar 12 '17 at 10:13
  • Not even remotely. Besides the fact that the generic signature of `BiFunction` will not be available at runtime due to type erasure, the `LambdaMetafactory` will not perform *any* check whether the arguments are compatible with the specified interface, not its signature and not even the name or, in other words, it avoids performing a reflective lookup of the functional interface’s method altogether. If you get the name or the raw signature wrong, you’ll get an `AbstractMethodError` when trying to invoke the correct method. Having a wrong generic signature is harmless compared to that… – Holger Sep 14 '17 at 15:06

0 Answers0