Advertisement
DasBrain

Untitled

Jun 20th, 2024
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. import static java.lang.invoke.MethodHandles.*;
  2. import static java.lang.invoke.MethodType.methodType;
  3.  
  4. import java.lang.invoke.MethodHandle;
  5. import java.lang.invoke.MethodType;
  6.  
  7. public class MethodHandleChain {
  8.     public static void main(String[] args) {
  9.         Class<?> rt = Object.class;
  10.        
  11.         MethodHandle ctor = empty(methodType(rt, String.class));
  12.         MethodHandle read1 = empty(methodType(void.class, rt, Long.class));
  13.         MethodHandle read2 = empty(methodType(void.class, rt, Integer.class));
  14.        
  15.        
  16.         MethodHandle result = identity(rt);
  17.        
  18.         result = dup(collectArguments(result, 1, read2));
  19.         result = dup(collectArguments(result, 1, read1));
  20.        
  21.         result = collectArguments(result, 0, ctor);
  22.         System.out.println(result);
  23.     }
  24.    
  25.     // Duplicates parameter at pos 0
  26.     private static MethodHandle dup(MethodHandle mh) {
  27.         MethodType mt = mh.type();
  28.         if (mt.parameterType(0) != mt.parameterType(1)) {
  29.             throw new IllegalArgumentException("First 2 parameters need to have the same type, got " + mt);
  30.         }
  31.         MethodType newMT = mt.dropParameterTypes(0, 1);
  32.         int[] permutation = new int[mt.parameterCount()];
  33.         permutation[0] = 0;
  34.         for (int i = 0; i < newMT.parameterCount(); i++) {
  35.             permutation[i + 1] = i;
  36.         }
  37.         return permuteArguments(mh, newMT, permutation);
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement