rev 58769 : [mq]: type-descriptor-name

   1 /*
   2  * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import java.lang.constant.ClassDesc;
  29 import java.lang.constant.Constable;
  30 import java.lang.constant.MethodTypeDesc;
  31 import java.lang.ref.Reference;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.WeakReference;
  34 import java.util.Arrays;
  35 import java.util.Collections;
  36 import java.util.List;
  37 import java.util.NoSuchElementException;
  38 import java.util.Objects;
  39 import java.util.Optional;
  40 import java.util.StringJoiner;
  41 import java.util.concurrent.ConcurrentHashMap;
  42 import java.util.concurrent.ConcurrentMap;
  43 import java.util.stream.Stream;
  44 
  45 import jdk.internal.vm.annotation.Stable;
  46 import sun.invoke.util.BytecodeDescriptor;
  47 import sun.invoke.util.VerifyType;
  48 import sun.invoke.util.Wrapper;
  49 import sun.security.util.SecurityConstants;
  50 
  51 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  52 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  53 import static java.lang.invoke.MethodType.fromDescriptor;
  54 
  55 /**
  56  * A method type represents the arguments and return type accepted and
  57  * returned by a method handle, or the arguments and return type passed
  58  * and expected  by a method handle caller.  Method types must be properly
  59  * matched between a method handle and all its callers,
  60  * and the JVM's operations enforce this matching at, specifically
  61  * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact}
  62  * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution
  63  * of {@code invokedynamic} instructions.
  64  * <p>
  65  * The structure is a return type accompanied by any number of parameter types.
  66  * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects.
  67  * (For ease of exposition, we treat {@code void} as if it were a type.
  68  * In fact, it denotes the absence of a return type.)
  69  * <p>
  70  * All instances of {@code MethodType} are immutable.
  71  * Two instances are completely interchangeable if they compare equal.
  72  * Equality depends on pairwise correspondence of the return and parameter types and on nothing else.
  73  * <p>
  74  * This type can be created only by factory methods.
  75  * All factory methods may cache values, though caching is not guaranteed.
  76  * Some factory methods are static, while others are virtual methods which
  77  * modify precursor method types, e.g., by changing a selected parameter.
  78  * <p>
  79  * Factory methods which operate on groups of parameter types
  80  * are systematically presented in two versions, so that both Java arrays and
  81  * Java lists can be used to work with groups of parameter types.
  82  * The query methods {@code parameterArray} and {@code parameterList}
  83  * also provide a choice between arrays and lists.
  84  * <p>
  85  * {@code MethodType} objects are sometimes derived from bytecode instructions
  86  * such as {@code invokedynamic}, specifically from the type descriptor strings associated
  87  * with the instructions in a class file's constant pool.
  88  * <p>
  89  * Like classes and strings, method types can also be represented directly
  90  * in a class file's constant pool as constants.
  91  * A method type may be loaded by an {@code ldc} instruction which refers
  92  * to a suitable {@code CONSTANT_MethodType} constant pool entry.
  93  * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string.
  94  * (For full details on method type constants, see sections {@jvms
  95  * 4.4.8} and {@jvms 5.4.3.5} of the Java Virtual Machine
  96  * Specification.)
  97  * <p>
  98  * When the JVM materializes a {@code MethodType} from a descriptor string,
  99  * all classes named in the descriptor must be accessible, and will be loaded.
 100  * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.)
 101  * This loading may occur at any time before the {@code MethodType} object is first derived.






























 102  * @author John Rose, JSR 292 EG
 103  * @since 1.7
 104  */
 105 public final
 106 class MethodType
 107         implements Constable,
 108                    TypeDescriptor.OfMethod<Class<?>, MethodType>,
 109                    java.io.Serializable {
 110     @java.io.Serial
 111     private static final long serialVersionUID = 292L;  // {rtype, {ptype...}}
 112 
 113     // The rtype and ptypes fields define the structural identity of the method type:
 114     private final @Stable Class<?>   rtype;
 115     private final @Stable Class<?>[] ptypes;
 116 
 117     // The remaining fields are caches of various sorts:
 118     private @Stable MethodTypeForm form; // erased form, plus cached data about primitives
 119     private @Stable MethodType wrapAlt;  // alternative wrapped/unwrapped version
 120     private @Stable Invokers invokers;   // cache of handy higher-order adapters
 121     private @Stable String methodDescriptor;  // cache for toMethodDescriptorString
 122 
 123     /**
 124      * Constructor that performs no copying or validation.
 125      * Should only be called from the factory method makeImpl
 126      */
 127     private MethodType(Class<?> rtype, Class<?>[] ptypes) {
 128         this.rtype = rtype;
 129         this.ptypes = ptypes;
 130     }
 131 
 132     /*trusted*/ MethodTypeForm form() { return form; }
 133     /*trusted*/ Class<?> rtype() { return rtype; }
 134     /*trusted*/ Class<?>[] ptypes() { return ptypes; }
 135 
 136     void setForm(MethodTypeForm f) { form = f; }
 137 
 138     /** This number, mandated by the JVM spec as 255,
 139      *  is the maximum number of <em>slots</em>
 140      *  that any Java method can receive in its argument list.
 141      *  It limits both JVM signatures and method type objects.
 142      *  The longest possible invocation will look like
 143      *  {@code staticMethod(arg1, arg2, ..., arg255)} or
 144      *  {@code x.virtualMethod(arg1, arg2, ..., arg254)}.
 145      */
 146     /*non-public*/
 147     static final int MAX_JVM_ARITY = 255;  // this is mandated by the JVM spec.
 148 
 149     /** This number is the maximum arity of a method handle, 254.
 150      *  It is derived from the absolute JVM-imposed arity by subtracting one,
 151      *  which is the slot occupied by the method handle itself at the
 152      *  beginning of the argument list used to invoke the method handle.
 153      *  The longest possible invocation will look like
 154      *  {@code mh.invoke(arg1, arg2, ..., arg254)}.
 155      */
 156     // Issue:  Should we allow MH.invokeWithArguments to go to the full 255?
 157     /*non-public*/
 158     static final int MAX_MH_ARITY = MAX_JVM_ARITY-1;  // deduct one for mh receiver
 159 
 160     /** This number is the maximum arity of a method handle invoker, 253.
 161      *  It is derived from the absolute JVM-imposed arity by subtracting two,
 162      *  which are the slots occupied by invoke method handle, and the
 163      *  target method handle, which are both at the beginning of the argument
 164      *  list used to invoke the target method handle.
 165      *  The longest possible invocation will look like
 166      *  {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}.
 167      */
 168     /*non-public*/
 169     static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1;  // deduct one more for invoker
 170 
 171     private static void checkRtype(Class<?> rtype) {
 172         Objects.requireNonNull(rtype);
 173     }
 174     private static void checkPtype(Class<?> ptype) {
 175         Objects.requireNonNull(ptype);
 176         if (ptype == void.class)
 177             throw newIllegalArgumentException("parameter type cannot be void");
 178     }
 179     /** Return number of extra slots (count of long/double args). */
 180     private static int checkPtypes(Class<?>[] ptypes) {
 181         int slots = 0;
 182         for (Class<?> ptype : ptypes) {
 183             checkPtype(ptype);
 184             if (ptype == double.class || ptype == long.class) {
 185                 slots++;
 186             }
 187         }
 188         checkSlotCount(ptypes.length + slots);
 189         return slots;
 190     }
 191 
 192     static {
 193         // MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work:
 194         assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0);
 195     }
 196     static void checkSlotCount(int count) {
 197         if ((count & MAX_JVM_ARITY) != count)
 198             throw newIllegalArgumentException("bad parameter count "+count);
 199     }
 200     private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
 201         if (num instanceof Integer)  num = "bad index: "+num;
 202         return new IndexOutOfBoundsException(num.toString());
 203     }
 204 
 205     static final ConcurrentWeakInternSet<MethodType> internTable = new ConcurrentWeakInternSet<>();
 206 
 207     static final Class<?>[] NO_PTYPES = {};
 208 
 209     /**
 210      * Finds or creates an instance of the given method type.
 211      * @param rtype  the return type
 212      * @param ptypes the parameter types
 213      * @return a method type with the given components
 214      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 215      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 216      */
 217     public static MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
 218         return makeImpl(rtype, ptypes, false);
 219     }
 220 
 221     /**
 222      * Finds or creates a method type with the given components.
 223      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 224      * @param rtype  the return type
 225      * @param ptypes the parameter types
 226      * @return a method type with the given components
 227      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 228      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 229      */
 230     public static MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
 231         boolean notrust = false;  // random List impl. could return evil ptypes array
 232         return makeImpl(rtype, listToArray(ptypes), notrust);
 233     }
 234 
 235     private static Class<?>[] listToArray(List<Class<?>> ptypes) {
 236         // sanity check the size before the toArray call, since size might be huge
 237         checkSlotCount(ptypes.size());
 238         return ptypes.toArray(NO_PTYPES);
 239     }
 240 
 241     /**
 242      * Finds or creates a method type with the given components.
 243      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 244      * The leading parameter type is prepended to the remaining array.
 245      * @param rtype  the return type
 246      * @param ptype0 the first parameter type
 247      * @param ptypes the remaining parameter types
 248      * @return a method type with the given components
 249      * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null
 250      * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class}
 251      */
 252     public static MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
 253         Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
 254         ptypes1[0] = ptype0;
 255         System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
 256         return makeImpl(rtype, ptypes1, true);
 257     }
 258 
 259     /**
 260      * Finds or creates a method type with the given components.
 261      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 262      * The resulting method has no parameter types.
 263      * @param rtype  the return type
 264      * @return a method type with the given return value
 265      * @throws NullPointerException if {@code rtype} is null
 266      */
 267     public static MethodType methodType(Class<?> rtype) {
 268         return makeImpl(rtype, NO_PTYPES, true);
 269     }
 270 
 271     /**
 272      * Finds or creates a method type with the given components.
 273      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 274      * The resulting method has the single given parameter type.
 275      * @param rtype  the return type
 276      * @param ptype0 the parameter type
 277      * @return a method type with the given return value and parameter type
 278      * @throws NullPointerException if {@code rtype} or {@code ptype0} is null
 279      * @throws IllegalArgumentException if {@code ptype0} is {@code void.class}
 280      */
 281     public static MethodType methodType(Class<?> rtype, Class<?> ptype0) {
 282         return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
 283     }
 284 
 285     /**
 286      * Finds or creates a method type with the given components.
 287      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 288      * The resulting method has the same parameter types as {@code ptypes},
 289      * and the specified return type.
 290      * @param rtype  the return type
 291      * @param ptypes the method type which supplies the parameter types
 292      * @return a method type with the given components
 293      * @throws NullPointerException if {@code rtype} or {@code ptypes} is null
 294      */
 295     public static MethodType methodType(Class<?> rtype, MethodType ptypes) {
 296         return makeImpl(rtype, ptypes.ptypes, true);
 297     }
 298 
 299     /**
 300      * Sole factory method to find or create an interned method type.
 301      * @param rtype desired return type
 302      * @param ptypes desired parameter types
 303      * @param trusted whether the ptypes can be used without cloning
 304      * @return the unique method type of the desired structure
 305      */
 306     /*trusted*/
 307     static MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 308         if (ptypes.length == 0) {
 309             ptypes = NO_PTYPES; trusted = true;
 310         }
 311         MethodType primordialMT = new MethodType(rtype, ptypes);
 312         MethodType mt = internTable.get(primordialMT);
 313         if (mt != null)
 314             return mt;
 315 
 316         // promote the object to the Real Thing, and reprobe
 317         MethodType.checkRtype(rtype);
 318         if (trusted) {
 319             MethodType.checkPtypes(ptypes);
 320             mt = primordialMT;
 321         } else {
 322             // Make defensive copy then validate
 323             ptypes = Arrays.copyOf(ptypes, ptypes.length);
 324             MethodType.checkPtypes(ptypes);
 325             mt = new MethodType(rtype, ptypes);
 326         }
 327         mt.form = MethodTypeForm.findForm(mt);
 328         return internTable.add(mt);
 329     }
 330     private static final @Stable MethodType[] objectOnlyTypes = new MethodType[20];
 331 
 332     /**
 333      * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array.
 334      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 335      * All parameters and the return type will be {@code Object},
 336      * except the final array parameter if any, which will be {@code Object[]}.
 337      * @param objectArgCount number of parameters (excluding the final array parameter if any)
 338      * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]}
 339      * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments
 340      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true)
 341      * @see #genericMethodType(int)
 342      */
 343     public static MethodType genericMethodType(int objectArgCount, boolean finalArray) {
 344         MethodType mt;
 345         checkSlotCount(objectArgCount);
 346         int ivarargs = (!finalArray ? 0 : 1);
 347         int ootIndex = objectArgCount*2 + ivarargs;
 348         if (ootIndex < objectOnlyTypes.length) {
 349             mt = objectOnlyTypes[ootIndex];
 350             if (mt != null)  return mt;
 351         }
 352         Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
 353         Arrays.fill(ptypes, Object.class);
 354         if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
 355         mt = makeImpl(Object.class, ptypes, true);
 356         if (ootIndex < objectOnlyTypes.length) {
 357             objectOnlyTypes[ootIndex] = mt;     // cache it here also!
 358         }
 359         return mt;
 360     }
 361 
 362     /**
 363      * Finds or creates a method type whose components are all {@code Object}.
 364      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 365      * All parameters and the return type will be Object.
 366      * @param objectArgCount number of parameters
 367      * @return a generally applicable method type, for all calls of the given argument count
 368      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255
 369      * @see #genericMethodType(int, boolean)
 370      */
 371     public static MethodType genericMethodType(int objectArgCount) {
 372         return genericMethodType(objectArgCount, false);
 373     }
 374 
 375     /**
 376      * Finds or creates a method type with a single different parameter type.
 377      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 378      * @param num    the index (zero-based) of the parameter type to change
 379      * @param nptype a new parameter type to replace the old one with
 380      * @return the same type, except with the selected parameter changed
 381      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 382      * @throws IllegalArgumentException if {@code nptype} is {@code void.class}
 383      * @throws NullPointerException if {@code nptype} is null
 384      */
 385     public MethodType changeParameterType(int num, Class<?> nptype) {
 386         if (parameterType(num) == nptype)  return this;
 387         checkPtype(nptype);
 388         Class<?>[] nptypes = ptypes.clone();
 389         nptypes[num] = nptype;
 390         return makeImpl(rtype, nptypes, true);
 391     }
 392 
 393     /**
 394      * Finds or creates a method type with additional parameter types.
 395      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 396      * @param num    the position (zero-based) of the inserted parameter type(s)
 397      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 398      * @return the same type, except with the selected parameter(s) inserted
 399      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 400      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 401      *                                  or if the resulting method type would have more than 255 parameter slots
 402      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 403      */
 404     public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) {
 405         int len = ptypes.length;
 406         if (num < 0 || num > len)
 407             throw newIndexOutOfBoundsException(num);
 408         int ins = checkPtypes(ptypesToInsert);
 409         checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins);
 410         int ilen = ptypesToInsert.length;
 411         if (ilen == 0)  return this;
 412         Class<?>[] nptypes = new Class<?>[len + ilen];
 413         if (num > 0) {
 414             System.arraycopy(ptypes, 0, nptypes, 0, num);
 415         }
 416         System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen);
 417         if (num < len) {
 418             System.arraycopy(ptypes, num, nptypes, num+ilen, len-num);
 419         }
 420         return makeImpl(rtype, nptypes, true);
 421     }
 422 
 423     /**
 424      * Finds or creates a method type with additional parameter types.
 425      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 426      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 427      * @return the same type, except with the selected parameter(s) appended
 428      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 429      *                                  or if the resulting method type would have more than 255 parameter slots
 430      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 431      */
 432     public MethodType appendParameterTypes(Class<?>... ptypesToInsert) {
 433         return insertParameterTypes(parameterCount(), ptypesToInsert);
 434     }
 435 
 436     /**
 437      * Finds or creates a method type with additional parameter types.
 438      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 439      * @param num    the position (zero-based) of the inserted parameter type(s)
 440      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 441      * @return the same type, except with the selected parameter(s) inserted
 442      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 443      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 444      *                                  or if the resulting method type would have more than 255 parameter slots
 445      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 446      */
 447     public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) {
 448         return insertParameterTypes(num, listToArray(ptypesToInsert));
 449     }
 450 
 451     /**
 452      * Finds or creates a method type with additional parameter types.
 453      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 454      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 455      * @return the same type, except with the selected parameter(s) appended
 456      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 457      *                                  or if the resulting method type would have more than 255 parameter slots
 458      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 459      */
 460     public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) {
 461         return insertParameterTypes(parameterCount(), ptypesToInsert);
 462     }
 463 
 464     /**
 465      * Finds or creates a method type with modified parameter types.
 466      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 467      * @param start  the position (zero-based) of the first replaced parameter type(s)
 468      * @param end    the position (zero-based) after the last replaced parameter type(s)
 469      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 470      * @return the same type, except with the selected parameter(s) replaced
 471      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 472      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 473      *                                  or if {@code start} is greater than {@code end}
 474      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 475      *                                  or if the resulting method type would have more than 255 parameter slots
 476      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 477      */
 478     /*non-public*/
 479     MethodType replaceParameterTypes(int start, int end, Class<?>... ptypesToInsert) {
 480         if (start == end)
 481             return insertParameterTypes(start, ptypesToInsert);
 482         int len = ptypes.length;
 483         if (!(0 <= start && start <= end && end <= len))
 484             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 485         int ilen = ptypesToInsert.length;
 486         if (ilen == 0)
 487             return dropParameterTypes(start, end);
 488         return dropParameterTypes(start, end).insertParameterTypes(start, ptypesToInsert);
 489     }
 490 
 491     /** Replace the last arrayLength parameter types with the component type of arrayType.
 492      * @param arrayType any array type
 493      * @param pos position at which to spread
 494      * @param arrayLength the number of parameter types to change
 495      * @return the resulting type
 496      */
 497     /*non-public*/
 498     MethodType asSpreaderType(Class<?> arrayType, int pos, int arrayLength) {
 499         assert(parameterCount() >= arrayLength);
 500         int spreadPos = pos;
 501         if (arrayLength == 0)  return this;  // nothing to change
 502         if (arrayType == Object[].class) {
 503             if (isGeneric())  return this;  // nothing to change
 504             if (spreadPos == 0) {
 505                 // no leading arguments to preserve; go generic
 506                 MethodType res = genericMethodType(arrayLength);
 507                 if (rtype != Object.class) {
 508                     res = res.changeReturnType(rtype);
 509                 }
 510                 return res;
 511             }
 512         }
 513         Class<?> elemType = arrayType.getComponentType();
 514         assert(elemType != null);
 515         for (int i = spreadPos; i < spreadPos + arrayLength; i++) {
 516             if (ptypes[i] != elemType) {
 517                 Class<?>[] fixedPtypes = ptypes.clone();
 518                 Arrays.fill(fixedPtypes, i, spreadPos + arrayLength, elemType);
 519                 return methodType(rtype, fixedPtypes);
 520             }
 521         }
 522         return this;  // arguments check out; no change
 523     }
 524 
 525     /** Return the leading parameter type, which must exist and be a reference.
 526      *  @return the leading parameter type, after error checks
 527      */
 528     /*non-public*/
 529     Class<?> leadingReferenceParameter() {
 530         Class<?> ptype;
 531         if (ptypes.length == 0 ||
 532             (ptype = ptypes[0]).isPrimitive())
 533             throw newIllegalArgumentException("no leading reference parameter");
 534         return ptype;
 535     }
 536 
 537     /** Delete the last parameter type and replace it with arrayLength copies of the component type of arrayType.
 538      * @param arrayType any array type
 539      * @param pos position at which to insert parameters
 540      * @param arrayLength the number of parameter types to insert
 541      * @return the resulting type
 542      */
 543     /*non-public*/
 544     MethodType asCollectorType(Class<?> arrayType, int pos, int arrayLength) {
 545         assert(parameterCount() >= 1);
 546         assert(pos < ptypes.length);
 547         assert(ptypes[pos].isAssignableFrom(arrayType));
 548         MethodType res;
 549         if (arrayType == Object[].class) {
 550             res = genericMethodType(arrayLength);
 551             if (rtype != Object.class) {
 552                 res = res.changeReturnType(rtype);
 553             }
 554         } else {
 555             Class<?> elemType = arrayType.getComponentType();
 556             assert(elemType != null);
 557             res = methodType(rtype, Collections.nCopies(arrayLength, elemType));
 558         }
 559         if (ptypes.length == 1) {
 560             return res;
 561         } else {
 562             // insert after (if need be), then before
 563             if (pos < ptypes.length - 1) {
 564                 res = res.insertParameterTypes(arrayLength, Arrays.copyOfRange(ptypes, pos + 1, ptypes.length));
 565             }
 566             return res.insertParameterTypes(0, Arrays.copyOf(ptypes, pos));
 567         }
 568     }
 569 
 570     /**
 571      * Finds or creates a method type with some parameter types omitted.
 572      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 573      * @param start  the index (zero-based) of the first parameter type to remove
 574      * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
 575      * @return the same type, except with the selected parameter(s) removed
 576      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 577      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 578      *                                  or if {@code start} is greater than {@code end}
 579      */
 580     public MethodType dropParameterTypes(int start, int end) {
 581         int len = ptypes.length;
 582         if (!(0 <= start && start <= end && end <= len))
 583             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 584         if (start == end)  return this;
 585         Class<?>[] nptypes;
 586         if (start == 0) {
 587             if (end == len) {
 588                 // drop all parameters
 589                 nptypes = NO_PTYPES;
 590             } else {
 591                 // drop initial parameter(s)
 592                 nptypes = Arrays.copyOfRange(ptypes, end, len);
 593             }
 594         } else {
 595             if (end == len) {
 596                 // drop trailing parameter(s)
 597                 nptypes = Arrays.copyOfRange(ptypes, 0, start);
 598             } else {
 599                 int tail = len - end;
 600                 nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
 601                 System.arraycopy(ptypes, end, nptypes, start, tail);
 602             }
 603         }
 604         return makeImpl(rtype, nptypes, true);
 605     }
 606 
 607     /**
 608      * Finds or creates a method type with a different return type.
 609      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 610      * @param nrtype a return parameter type to replace the old one with
 611      * @return the same type, except with the return type change
 612      * @throws NullPointerException if {@code nrtype} is null
 613      */
 614     public MethodType changeReturnType(Class<?> nrtype) {
 615         if (returnType() == nrtype)  return this;
 616         return makeImpl(nrtype, ptypes, true);
 617     }
 618 
 619     /**
 620      * Reports if this type contains a primitive argument or return value.
 621      * The return type {@code void} counts as a primitive.
 622      * @return true if any of the types are primitives
 623      */
 624     public boolean hasPrimitives() {
 625         return form.hasPrimitives();
 626     }
 627 
 628     /**
 629      * Reports if this type contains a wrapper argument or return value.
 630      * Wrappers are types which box primitive values, such as {@link Integer}.
 631      * The reference type {@code java.lang.Void} counts as a wrapper,
 632      * if it occurs as a return type.
 633      * @return true if any of the types are wrappers
 634      */
 635     public boolean hasWrappers() {
 636         return unwrap() != this;
 637     }
 638 
 639     /**
 640      * Erases all reference types to {@code Object}.
 641      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 642      * All primitive types (including {@code void}) will remain unchanged.
 643      * @return a version of the original type with all reference types replaced
 644      */
 645     public MethodType erase() {
 646         return form.erasedType();
 647     }
 648 
 649     /**
 650      * Erases all reference types to {@code Object}, and all subword types to {@code int}.
 651      * This is the reduced type polymorphism used by private methods
 652      * such as {@link MethodHandle#invokeBasic invokeBasic}.
 653      * @return a version of the original type with all reference and subword types replaced
 654      */
 655     /*non-public*/
 656     MethodType basicType() {
 657         return form.basicType();
 658     }
 659 
 660     private static final @Stable Class<?>[] METHOD_HANDLE_ARRAY
 661             = new Class<?>[] { MethodHandle.class };
 662 
 663     /**
 664      * @return a version of the original type with MethodHandle prepended as the first argument
 665      */
 666     /*non-public*/
 667     MethodType invokerType() {
 668         return insertParameterTypes(0, METHOD_HANDLE_ARRAY);
 669     }
 670 
 671     /**
 672      * Converts all types, both reference and primitive, to {@code Object}.
 673      * Convenience method for {@link #genericMethodType(int) genericMethodType}.
 674      * The expression {@code type.wrap().erase()} produces the same value
 675      * as {@code type.generic()}.
 676      * @return a version of the original type with all types replaced
 677      */
 678     public MethodType generic() {
 679         return genericMethodType(parameterCount());
 680     }
 681 
 682     /*non-public*/
 683     boolean isGeneric() {
 684         return this == erase() && !hasPrimitives();
 685     }
 686 
 687     /**
 688      * Converts all primitive types to their corresponding wrapper types.
 689      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 690      * All reference types (including wrapper types) will remain unchanged.
 691      * A {@code void} return type is changed to the type {@code java.lang.Void}.
 692      * The expression {@code type.wrap().erase()} produces the same value
 693      * as {@code type.generic()}.
 694      * @return a version of the original type with all primitive types replaced
 695      */
 696     public MethodType wrap() {
 697         return hasPrimitives() ? wrapWithPrims(this) : this;
 698     }
 699 
 700     /**
 701      * Converts all wrapper types to their corresponding primitive types.
 702      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 703      * All primitive types (including {@code void}) will remain unchanged.
 704      * A return type of {@code java.lang.Void} is changed to {@code void}.
 705      * @return a version of the original type with all wrapper types replaced
 706      */
 707     public MethodType unwrap() {
 708         MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
 709         return unwrapWithNoPrims(noprims);
 710     }
 711 
 712     private static MethodType wrapWithPrims(MethodType pt) {
 713         assert(pt.hasPrimitives());
 714         MethodType wt = pt.wrapAlt;
 715         if (wt == null) {
 716             // fill in lazily
 717             wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP);
 718             assert(wt != null);
 719             pt.wrapAlt = wt;
 720         }
 721         return wt;
 722     }
 723 
 724     private static MethodType unwrapWithNoPrims(MethodType wt) {
 725         assert(!wt.hasPrimitives());
 726         MethodType uwt = wt.wrapAlt;
 727         if (uwt == null) {
 728             // fill in lazily
 729             uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP);
 730             if (uwt == null)
 731                 uwt = wt;    // type has no wrappers or prims at all
 732             wt.wrapAlt = uwt;
 733         }
 734         return uwt;
 735     }
 736 
 737     /**
 738      * Returns the parameter type at the specified index, within this method type.
 739      * @param num the index (zero-based) of the desired parameter type
 740      * @return the selected parameter type
 741      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 742      */
 743     public Class<?> parameterType(int num) {
 744         return ptypes[num];
 745     }
 746     /**
 747      * Returns the number of parameter types in this method type.
 748      * @return the number of parameter types
 749      */
 750     public int parameterCount() {
 751         return ptypes.length;
 752     }
 753     /**
 754      * Returns the return type of this method type.
 755      * @return the return type
 756      */
 757     public Class<?> returnType() {
 758         return rtype;
 759     }
 760 
 761     /**
 762      * Presents the parameter types as a list (a convenience method).
 763      * The list will be immutable.
 764      * @return the parameter types (as an immutable list)
 765      */
 766     public List<Class<?>> parameterList() {
 767         return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
 768     }
 769 
 770     /**
 771      * Returns the last parameter type of this method type.
 772      * If this type has no parameters, the sentinel value
 773      * {@code void.class} is returned instead.
 774      * @apiNote
 775      * <p>
 776      * The sentinel value is chosen so that reflective queries can be
 777      * made directly against the result value.
 778      * The sentinel value cannot be confused with a real parameter,
 779      * since {@code void} is never acceptable as a parameter type.
 780      * For variable arity invocation modes, the expression
 781      * {@link Class#getComponentType lastParameterType().getComponentType()}
 782      * is useful to query the type of the "varargs" parameter.
 783      * @return the last parameter type if any, else {@code void.class}
 784      * @since 10
 785      */
 786     public Class<?> lastParameterType() {
 787         int len = ptypes.length;
 788         return len == 0 ? void.class : ptypes[len-1];
 789     }
 790 
 791     /**
 792      * Presents the parameter types as an array (a convenience method).
 793      * Changes to the array will not result in changes to the type.
 794      * @return the parameter types (as a fresh copy if necessary)
 795      */
 796     public Class<?>[] parameterArray() {
 797         return ptypes.clone();
 798     }
 799 
 800     /**
 801      * Compares the specified object with this type for equality.
 802      * That is, it returns {@code true} if and only if the specified object
 803      * is also a method type with exactly the same parameters and return type.
 804      * @param x object to compare
 805      * @see Object#equals(Object)
 806      */
 807     // This implementation may also return true if x is a WeakEntry containing
 808     // a method type that is equal to this. This is an internal implementation
 809     // detail to allow for faster method type lookups.
 810     // See ConcurrentWeakInternSet.WeakEntry#equals(Object)
 811     @Override
 812     public boolean equals(Object x) {
 813         if (this == x) {
 814             return true;
 815         }
 816         if (x instanceof MethodType) {
 817             return equals((MethodType)x);
 818         }
 819         if (x instanceof ConcurrentWeakInternSet.WeakEntry) {
 820             Object o = ((ConcurrentWeakInternSet.WeakEntry)x).get();
 821             if (o instanceof MethodType) {
 822                 return equals((MethodType)o);
 823             }
 824         }
 825         return false;
 826     }
 827 
 828     private boolean equals(MethodType that) {
 829         return this.rtype == that.rtype
 830             && Arrays.equals(this.ptypes, that.ptypes);
 831     }
 832 
 833     /**
 834      * Returns the hash code value for this method type.
 835      * It is defined to be the same as the hashcode of a List
 836      * whose elements are the return type followed by the
 837      * parameter types.
 838      * @return the hash code value for this method type
 839      * @see Object#hashCode()
 840      * @see #equals(Object)
 841      * @see List#hashCode()
 842      */
 843     @Override
 844     public int hashCode() {
 845         int hashCode = 31 + rtype.hashCode();
 846         for (Class<?> ptype : ptypes)
 847             hashCode = 31 * hashCode + ptype.hashCode();
 848         return hashCode;
 849     }
 850 
 851     /**
 852      * Returns a string representation of the method type,
 853      * of the form {@code "(PT0,PT1...)RT"}.
 854      * The string representation of a method type is a
 855      * parenthesis enclosed, comma separated list of type names,
 856      * followed immediately by the return type.
 857      * <p>
 858      * Each type is represented by its
 859      * {@link java.lang.Class#getSimpleName simple name}.
 860      */
 861     @Override
 862     public String toString() {
 863         StringJoiner sj = new StringJoiner(",", "(",
 864                 ")" + rtype.getSimpleName());
 865         for (int i = 0; i < ptypes.length; i++) {
 866             sj.add(ptypes[i].getSimpleName());
 867         }
 868         return sj.toString();
 869     }
 870 
 871     /** True if my parameter list is effectively identical to the given full list,
 872      *  after skipping the given number of my own initial parameters.
 873      *  In other words, after disregarding {@code skipPos} parameters,
 874      *  my remaining parameter list is no longer than the {@code fullList}, and
 875      *  is equal to the same-length initial sublist of {@code fullList}.
 876      */
 877     /*non-public*/
 878     boolean effectivelyIdenticalParameters(int skipPos, List<Class<?>> fullList) {
 879         int myLen = ptypes.length, fullLen = fullList.size();
 880         if (skipPos > myLen || myLen - skipPos > fullLen)
 881             return false;
 882         List<Class<?>> myList = Arrays.asList(ptypes);
 883         if (skipPos != 0) {
 884             myList = myList.subList(skipPos, myLen);
 885             myLen -= skipPos;
 886         }
 887         if (fullLen == myLen)
 888             return myList.equals(fullList);
 889         else
 890             return myList.equals(fullList.subList(0, myLen));
 891     }
 892 
 893     /** True if the old return type can always be viewed (w/o casting) under new return type,
 894      *  and the new parameters can be viewed (w/o casting) under the old parameter types.
 895      */
 896     /*non-public*/
 897     boolean isViewableAs(MethodType newType, boolean keepInterfaces) {
 898         if (!VerifyType.isNullConversion(returnType(), newType.returnType(), keepInterfaces))
 899             return false;
 900         if (form == newType.form && form.erasedType == this)
 901             return true;  // my reference parameters are all Object
 902         if (ptypes == newType.ptypes)
 903             return true;
 904         int argc = parameterCount();
 905         if (argc != newType.parameterCount())
 906             return false;
 907         for (int i = 0; i < argc; i++) {
 908             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i), keepInterfaces))
 909                 return false;
 910         }
 911         return true;
 912     }
 913     /*non-public*/
 914     boolean isConvertibleTo(MethodType newType) {
 915         MethodTypeForm oldForm = this.form();
 916         MethodTypeForm newForm = newType.form();
 917         if (oldForm == newForm)
 918             // same parameter count, same primitive/object mix
 919             return true;
 920         if (!canConvert(returnType(), newType.returnType()))
 921             return false;
 922         Class<?>[] srcTypes = newType.ptypes;
 923         Class<?>[] dstTypes = ptypes;
 924         if (srcTypes == dstTypes)
 925             return true;
 926         int argc;
 927         if ((argc = srcTypes.length) != dstTypes.length)
 928             return false;
 929         if (argc <= 1) {
 930             if (argc == 1 && !canConvert(srcTypes[0], dstTypes[0]))
 931                 return false;
 932             return true;
 933         }
 934         if ((!oldForm.hasPrimitives() && oldForm.erasedType == this) ||
 935             (!newForm.hasPrimitives() && newForm.erasedType == newType)) {
 936             // Somewhat complicated test to avoid a loop of 2 or more trips.
 937             // If either type has only Object parameters, we know we can convert.
 938             assert(canConvertParameters(srcTypes, dstTypes));
 939             return true;
 940         }
 941         return canConvertParameters(srcTypes, dstTypes);
 942     }
 943 
 944     /** Returns true if MHs.explicitCastArguments produces the same result as MH.asType.
 945      *  If the type conversion is impossible for either, the result should be false.
 946      */
 947     /*non-public*/
 948     boolean explicitCastEquivalentToAsType(MethodType newType) {
 949         if (this == newType)  return true;
 950         if (!explicitCastEquivalentToAsType(rtype, newType.rtype)) {
 951             return false;
 952         }
 953         Class<?>[] srcTypes = newType.ptypes;
 954         Class<?>[] dstTypes = ptypes;
 955         if (dstTypes == srcTypes) {
 956             return true;
 957         }
 958         assert(dstTypes.length == srcTypes.length);
 959         for (int i = 0; i < dstTypes.length; i++) {
 960             if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) {
 961                 return false;
 962             }
 963         }
 964         return true;
 965     }
 966 
 967     /** Reports true if the src can be converted to the dst, by both asType and MHs.eCE,
 968      *  and with the same effect.
 969      *  MHs.eCA has the following "upgrades" to MH.asType:
 970      *  1. interfaces are unchecked (that is, treated as if aliased to Object)
 971      *     Therefore, {@code Object->CharSequence} is possible in both cases but has different semantics
 972      *  2. the full matrix of primitive-to-primitive conversions is supported
 973      *     Narrowing like {@code long->byte} and basic-typing like {@code boolean->int}
 974      *     are not supported by asType, but anything supported by asType is equivalent
 975      *     with MHs.eCE.
 976      *  3a. unboxing conversions can be followed by the full matrix of primitive conversions
 977      *  3b. unboxing of null is permitted (creates a zero primitive value)
 978      * Other than interfaces, reference-to-reference conversions are the same.
 979      * Boxing primitives to references is the same for both operators.
 980      */
 981     private static boolean explicitCastEquivalentToAsType(Class<?> src, Class<?> dst) {
 982         if (src == dst || dst == Object.class || dst == void.class)  return true;
 983         if (src.isPrimitive()) {
 984             // Could be a prim/prim conversion, where casting is a strict superset.
 985             // Or a boxing conversion, which is always to an exact wrapper class.
 986             return canConvert(src, dst);
 987         } else if (dst.isPrimitive()) {
 988             // Unboxing behavior is different between MHs.eCA & MH.asType (see 3b).
 989             return false;
 990         } else {
 991             // R->R always works, but we have to avoid a check-cast to an interface.
 992             return !dst.isInterface() || dst.isAssignableFrom(src);
 993         }
 994     }
 995 
 996     private boolean canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes) {
 997         for (int i = 0; i < srcTypes.length; i++) {
 998             if (!canConvert(srcTypes[i], dstTypes[i])) {
 999                 return false;
1000             }
1001         }
1002         return true;
1003     }
1004 
1005     /*non-public*/
1006     static boolean canConvert(Class<?> src, Class<?> dst) {
1007         // short-circuit a few cases:
1008         if (src == dst || src == Object.class || dst == Object.class)  return true;
1009         // the remainder of this logic is documented in MethodHandle.asType
1010         if (src.isPrimitive()) {
1011             // can force void to an explicit null, a la reflect.Method.invoke
1012             // can also force void to a primitive zero, by analogy
1013             if (src == void.class)  return true;  //or !dst.isPrimitive()?
1014             Wrapper sw = Wrapper.forPrimitiveType(src);
1015             if (dst.isPrimitive()) {
1016                 // P->P must widen
1017                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
1018             } else {
1019                 // P->R must box and widen
1020                 return dst.isAssignableFrom(sw.wrapperType());
1021             }
1022         } else if (dst.isPrimitive()) {
1023             // any value can be dropped
1024             if (dst == void.class)  return true;
1025             Wrapper dw = Wrapper.forPrimitiveType(dst);
1026             // R->P must be able to unbox (from a dynamically chosen type) and widen
1027             // For example:
1028             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
1029             //   Character/Comparable/Object -> dw:Character -> char
1030             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
1031             // This means that dw must be cast-compatible with src.
1032             if (src.isAssignableFrom(dw.wrapperType())) {
1033                 return true;
1034             }
1035             // The above does not work if the source reference is strongly typed
1036             // to a wrapper whose primitive must be widened.  For example:
1037             //   Byte -> unbox:byte -> short/int/long/float/double
1038             //   Character -> unbox:char -> int/long/float/double
1039             if (Wrapper.isWrapperType(src) &&
1040                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
1041                 // can unbox from src and then widen to dst
1042                 return true;
1043             }
1044             // We have already covered cases which arise due to runtime unboxing
1045             // of a reference type which covers several wrapper types:
1046             //   Object -> cast:Integer -> unbox:int -> long/float/double
1047             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
1048             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
1049             // subclass of Number which wraps a value that can convert to char.
1050             // Since there is none, we don't need an extra check here to cover char or boolean.
1051             return false;
1052         } else {
1053             // R->R always works, since null is always valid dynamically
1054             return true;
1055         }
1056     }
1057 
1058     /// Queries which have to do with the bytecode architecture
1059 
1060     /** Reports the number of JVM stack slots required to invoke a method
1061      * of this type.  Note that (for historical reasons) the JVM requires
1062      * a second stack slot to pass long and double arguments.
1063      * So this method returns {@link #parameterCount() parameterCount} plus the
1064      * number of long and double parameters (if any).
1065      * <p>
1066      * This method is included for the benefit of applications that must
1067      * generate bytecodes that process method handles and invokedynamic.
1068      * @return the number of JVM stack slots for this type's parameters
1069      */
1070     /*non-public*/
1071     int parameterSlotCount() {
1072         return form.parameterSlotCount();
1073     }
1074 
1075     /*non-public*/
1076     Invokers invokers() {
1077         Invokers inv = invokers;
1078         if (inv != null)  return inv;
1079         invokers = inv = new Invokers(this);
1080         return inv;
1081     }
1082 
1083     /**
1084      * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
1085      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
1086      * Any class or interface name embedded in the descriptor string will be
1087      * resolved by the given loader (or if it is null, on the system class loader).
1088      * <p>
1089      * Note that it is possible to encounter method types which cannot be
1090      * constructed by this method, because their component types are
1091      * not all reachable from a common class loader.
1092      * <p>
1093      * This method is included for the benefit of applications that must
1094      * generate bytecodes that process method handles and {@code invokedynamic}.
1095      * @param descriptor a bytecode-level type descriptor string "(T...)T"
1096      * @param loader the class loader in which to look up the types
1097      * @return a method type matching the bytecode-level type descriptor
1098      * @throws NullPointerException if the string is null
1099      * @throws IllegalArgumentException if the string is not well-formed
1100      * @throws TypeNotPresentException if a named type cannot be found
1101      * @throws SecurityException if the security manager is present and
1102      *         {@code loader} is {@code null} and the caller does not have the
1103      *         {@link RuntimePermission}{@code ("getClassLoader")}
1104      */
1105     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
1106         throws IllegalArgumentException, TypeNotPresentException
1107     {
1108         if (loader == null) {
1109             SecurityManager sm = System.getSecurityManager();
1110             if (sm != null) {
1111                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1112             }
1113         }
1114         return fromDescriptor(descriptor,
1115                               (loader == null) ? ClassLoader.getSystemClassLoader() : loader);
1116     }
1117 
1118     /**
1119      * Same as {@link #fromMethodDescriptorString(String, ClassLoader)}, but
1120      * {@code null} ClassLoader means the bootstrap loader is used here.
1121      * <p>
1122      * IMPORTANT: This method is preferable for JDK internal use as it more
1123      * correctly interprets {@code null} ClassLoader than
1124      * {@link #fromMethodDescriptorString(String, ClassLoader)}.
1125      * Use of this method also avoids early initialization issues when system
1126      * ClassLoader is not initialized yet.
1127      */
1128     static MethodType fromDescriptor(String descriptor, ClassLoader loader)
1129         throws IllegalArgumentException, TypeNotPresentException
1130     {
1131         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
1132             descriptor.indexOf(')') < 0 ||
1133             descriptor.indexOf('.') >= 0)
1134             throw newIllegalArgumentException("not a method descriptor: "+descriptor);
1135         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
1136         Class<?> rtype = types.remove(types.size() - 1);
1137         Class<?>[] ptypes = listToArray(types);
1138         return makeImpl(rtype, ptypes, true);
1139     }
1140 
1141     /**
1142      * Produces a bytecode descriptor representation of the method type.


1143      * <p>
1144      * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
1145      * Two distinct classes which share a common name but have different class loaders
1146      * will appear identical when viewed within descriptor strings.
1147      * <p>
1148      * This method is included for the benefit of applications that must
1149      * generate bytecodes that process method handles and {@code invokedynamic}.
1150      * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
1151      * because the latter requires a suitable class loader argument.
1152      * @return the bytecode type descriptor representation


1153      */
1154     public String toMethodDescriptorString() {
1155         String desc = methodDescriptor;
1156         if (desc == null) {
1157             desc = BytecodeDescriptor.unparseMethod(this.rtype, this.ptypes);
1158             methodDescriptor = desc;
1159         }
1160         return desc;
1161     }
1162 
1163     /**
1164      * Return a field type descriptor string for this type
















1165      *
1166      * @return the descriptor string
1167      * @jvms 4.3.2 Field Descriptors
1168      * @since 12


1169      */
1170     @Override
1171     public String descriptorString() {
1172         return toMethodDescriptorString();
1173     }
1174 
1175     /*non-public*/
1176     static String toFieldDescriptorString(Class<?> cls) {
1177         return BytecodeDescriptor.unparse(cls);
1178     }
1179 
1180     /**
1181      * Return a nominal descriptor for this instance, if one can be
1182      * constructed, or an empty {@link Optional} if one cannot be.
1183      *
1184      * @return An {@link Optional} containing the resulting nominal descriptor,
1185      * or an empty {@link Optional} if one cannot be constructed.
1186      * @since 12

1187      */
1188     @Override
1189     public Optional<MethodTypeDesc> describeConstable() {
1190         try {
1191             return Optional.of(MethodTypeDesc.of(returnType().describeConstable().orElseThrow(),
1192                                                  Stream.of(parameterArray())
1193                                                       .map(p -> p.describeConstable().orElseThrow())
1194                                                       .toArray(ClassDesc[]::new)));
1195         }
1196         catch (NoSuchElementException e) {
1197             return Optional.empty();
1198         }
1199     }
1200 
1201     /// Serialization.
1202 
1203     /**
1204      * There are no serializable fields for {@code MethodType}.
1205      */
1206     @java.io.Serial
1207     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
1208 
1209     /**
1210      * Save the {@code MethodType} instance to a stream.
1211      *
1212      * @serialData
1213      * For portability, the serialized format does not refer to named fields.
1214      * Instead, the return type and parameter type arrays are written directly
1215      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
1216      * as follows:
1217      * <blockquote><pre>{@code
1218 s.writeObject(this.returnType());
1219 s.writeObject(this.parameterArray());
1220      * }</pre></blockquote>
1221      * <p>
1222      * The deserialized field values are checked as if they were
1223      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
1224      * For example, null values, or {@code void} parameter types,
1225      * will lead to exceptions during deserialization.
1226      * @param s the stream to write the object to
1227      * @throws java.io.IOException if there is a problem writing the object
1228      */
1229     @java.io.Serial
1230     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
1231         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
1232         s.writeObject(returnType());
1233         s.writeObject(parameterArray());
1234     }
1235 
1236     /**
1237      * Reconstitute the {@code MethodType} instance from a stream (that is,
1238      * deserialize it).
1239      * This instance is a scratch object with bogus final fields.
1240      * It provides the parameters to the factory method called by
1241      * {@link #readResolve readResolve}.
1242      * After that call it is discarded.
1243      * @param s the stream to read the object from
1244      * @throws java.io.IOException if there is a problem reading the object
1245      * @throws ClassNotFoundException if one of the component classes cannot be resolved
1246      * @see #readResolve
1247      * @see #writeObject
1248      */
1249     @java.io.Serial
1250     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
1251         // Assign temporary defaults in case this object escapes
1252         MethodType_init(void.class, NO_PTYPES);
1253 
1254         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
1255 
1256         Class<?>   returnType     = (Class<?>)   s.readObject();
1257         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
1258         parameterArray = parameterArray.clone();  // make sure it is unshared
1259 
1260         // Assign deserialized values
1261         MethodType_init(returnType, parameterArray);
1262     }
1263 
1264     // Initialization of state for deserialization only
1265     private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
1266         // In order to communicate these values to readResolve, we must
1267         // store them into the implementation-specific final fields.
1268         checkRtype(rtype);
1269         checkPtypes(ptypes);
1270         UNSAFE.putReference(this, OffsetHolder.rtypeOffset, rtype);
1271         UNSAFE.putReference(this, OffsetHolder.ptypesOffset, ptypes);
1272     }
1273 
1274     // Support for resetting final fields while deserializing. Implement Holder
1275     // pattern to make the rarely needed offset calculation lazy.
1276     private static class OffsetHolder {
1277         static final long rtypeOffset
1278                 = UNSAFE.objectFieldOffset(MethodType.class, "rtype");
1279 
1280         static final long ptypesOffset
1281                 = UNSAFE.objectFieldOffset(MethodType.class, "ptypes");
1282     }
1283 
1284     /**
1285      * Resolves and initializes a {@code MethodType} object
1286      * after serialization.
1287      * @return the fully initialized {@code MethodType} object
1288      */
1289     @java.io.Serial
1290     private Object readResolve() {
1291         // Do not use a trusted path for deserialization:
1292         //    return makeImpl(rtype, ptypes, true);
1293         // Verify all operands, and make sure ptypes is unshared:
1294         try {
1295             return methodType(rtype, ptypes);
1296         } finally {
1297             // Re-assign defaults in case this object escapes
1298             MethodType_init(void.class, NO_PTYPES);
1299         }
1300     }
1301 
1302     /**
1303      * Simple implementation of weak concurrent intern set.
1304      *
1305      * @param <T> interned type
1306      */
1307     private static class ConcurrentWeakInternSet<T> {
1308 
1309         private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
1310         private final ReferenceQueue<T> stale;
1311 
1312         public ConcurrentWeakInternSet() {
1313             this.map = new ConcurrentHashMap<>(512);
1314             this.stale = new ReferenceQueue<>();
1315         }
1316 
1317         /**
1318          * Get the existing interned element.
1319          * This method returns null if no element is interned.
1320          *
1321          * @param elem element to look up
1322          * @return the interned element
1323          */
1324         public T get(T elem) {
1325             if (elem == null) throw new NullPointerException();
1326             expungeStaleElements();
1327 
1328             WeakEntry<T> value = map.get(elem);
1329             if (value != null) {
1330                 T res = value.get();
1331                 if (res != null) {
1332                     return res;
1333                 }
1334             }
1335             return null;
1336         }
1337 
1338         /**
1339          * Interns the element.
1340          * Always returns non-null element, matching the one in the intern set.
1341          * Under the race against another add(), it can return <i>different</i>
1342          * element, if another thread beats us to interning it.
1343          *
1344          * @param elem element to add
1345          * @return element that was actually added
1346          */
1347         public T add(T elem) {
1348             if (elem == null) throw new NullPointerException();
1349 
1350             // Playing double race here, and so spinloop is required.
1351             // First race is with two concurrent updaters.
1352             // Second race is with GC purging weak ref under our feet.
1353             // Hopefully, we almost always end up with a single pass.
1354             T interned;
1355             WeakEntry<T> e = new WeakEntry<>(elem, stale);
1356             do {
1357                 expungeStaleElements();
1358                 WeakEntry<T> exist = map.putIfAbsent(e, e);
1359                 interned = (exist == null) ? elem : exist.get();
1360             } while (interned == null);
1361             return interned;
1362         }
1363 
1364         private void expungeStaleElements() {
1365             Reference<? extends T> reference;
1366             while ((reference = stale.poll()) != null) {
1367                 map.remove(reference);
1368             }
1369         }
1370 
1371         private static class WeakEntry<T> extends WeakReference<T> {
1372 
1373             public final int hashcode;
1374 
1375             public WeakEntry(T key, ReferenceQueue<T> queue) {
1376                 super(key, queue);
1377                 hashcode = key.hashCode();
1378             }
1379 
1380             /**
1381              * This implementation returns {@code true} if {@code obj} is another
1382              * {@code WeakEntry} whose referent is equal to this referent, or
1383              * if {@code obj} is equal to the referent of this. This allows
1384              * lookups to be made without wrapping in a {@code WeakEntry}.
1385              *
1386              * @param obj the object to compare
1387              * @return true if {@code obj} is equal to this or the referent of this
1388              * @see MethodType#equals(Object)
1389              * @see Object#equals(Object)
1390              */
1391             @Override
1392             public boolean equals(Object obj) {
1393                 Object mine = get();
1394                 if (obj instanceof WeakEntry) {
1395                     Object that = ((WeakEntry) obj).get();
1396                     return (that == null || mine == null) ? (this == obj) : mine.equals(that);
1397                 }
1398                 return (mine == null) ? (obj == null) : mine.equals(obj);
1399             }
1400 
1401             @Override
1402             public int hashCode() {
1403                 return hashcode;
1404             }
1405 
1406         }
1407     }
1408 
1409 }
--- EOF ---