LapisSea

Untitled

Sep 25th, 2020
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. public static <FInter, T extends FInter> T makeLambda(Method method, Class<FInter> functionalInterface){
  2.     try{
  3.         var lookup=MethodHandles.privateLookupIn(method.getDeclaringClass(), MethodHandles.lookup());
  4.         method.setAccessible(true);
  5.         var handle=lookup.unreflect(method);
  6.        
  7.         Method functionalInterfaceFunction=Arrays.stream(functionalInterface.getMethods()).filter(m->!Modifier.isStatic(m.getModifiers())).findAny().orElseThrow();
  8.        
  9.         MethodType signature=MethodType.methodType(functionalInterfaceFunction.getReturnType(), functionalInterfaceFunction.getParameterTypes());
  10.        
  11.         CallSite site=LambdaMetafactory.metafactory(lookup,
  12.                                                     functionalInterfaceFunction.getName(),
  13.                                                     MethodType.methodType(functionalInterface),
  14.                                                     signature,
  15.                                                     handle,
  16.                                                     handle.type());
  17.        
  18.         //noinspection unchecked
  19.         return (T)site.getTarget().invoke();
  20.     }catch(Throwable e){
  21.         throw new RuntimeException("failed to create lambda\n"+method+"\n"+functionalInterface, e);
  22.     }
  23. }
Add Comment
Please, Sign In to add comment