1 /*
   2  * Copyright (c) 2008, 2023, 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.util.Arrays;
  32 import java.util.Collections;
  33 import java.util.function.Supplier;
  34 import java.util.List;
  35 import java.util.Map;
  36 import java.util.NoSuchElementException;
  37 import java.util.Objects;
  38 import java.util.Optional;
  39 import java.util.StringJoiner;
  40 import java.util.concurrent.ConcurrentHashMap;
  41 import java.util.stream.Stream;
  42 
  43 import jdk.internal.util.ReferencedKeySet;
  44 import jdk.internal.util.ReferenceKey;
  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 
  54 /**
  55  * A method type represents the arguments and return type accepted and
  56  * returned by a method handle, or the arguments and return type passed
  57  * and expected  by a method handle caller.  Method types must be properly
  58  * matched between a method handle and all its callers,
  59  * and the JVM's operations enforce this matching at, specifically
  60  * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact}
  61  * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution
  62  * of {@code invokedynamic} instructions.
  63  * <p>
  64  * The structure is a return type accompanied by any number of parameter types.
  65  * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects.
  66  * (For ease of exposition, we treat {@code void} as if it were a type.
  67  * In fact, it denotes the absence of a return type.)
  68  * <p>
  69  * All instances of {@code MethodType} are immutable.
  70  * Two instances are completely interchangeable if they compare equal.
  71  * Equality depends on pairwise correspondence of the return and parameter types and on nothing else.
  72  * <p>
  73  * This type can be created only by factory methods.
  74  * All factory methods may cache values, though caching is not guaranteed.
  75  * Some factory methods are static, while others are virtual methods which
  76  * modify precursor method types, e.g., by changing a selected parameter.
  77  * <p>
  78  * Factory methods which operate on groups of parameter types
  79  * are systematically presented in two versions, so that both Java arrays and
  80  * Java lists can be used to work with groups of parameter types.
  81  * The query methods {@code parameterArray} and {@code parameterList}
  82  * also provide a choice between arrays and lists.
  83  * <p>
  84  * {@code MethodType} objects are sometimes derived from bytecode instructions
  85  * such as {@code invokedynamic}, specifically from the type descriptor strings associated
  86  * with the instructions in a class file's constant pool.
  87  * <p>
  88  * Like classes and strings, method types can also be represented directly
  89  * in a class file's constant pool as constants.
  90  * A method type may be loaded by an {@code ldc} instruction which refers
  91  * to a suitable {@code CONSTANT_MethodType} constant pool entry.
  92  * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string.
  93  * (For full details on method type constants, see sections {@jvms
  94  * 4.4.8} and {@jvms 5.4.3.5} of the Java Virtual Machine
  95  * Specification.)
  96  * <p>
  97  * When the JVM materializes a {@code MethodType} from a descriptor string,
  98  * all classes named in the descriptor must be accessible, and will be loaded.
  99  * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.)
 100  * This loading may occur at any time before the {@code MethodType} object is first derived.
 101  * <p>
 102  * <b><a id="descriptor">Nominal Descriptors</a></b>
 103  * <p>
 104  * A {@code MethodType} can be described in {@linkplain MethodTypeDesc nominal form}
 105  * if and only if all of the parameter types and return type can be described
 106  * with a {@link Class#describeConstable() nominal descriptor} represented by
 107  * {@link ClassDesc}.  If a method type can be described nominally, then:
 108  * <ul>
 109  * <li>The method type has a {@link MethodTypeDesc nominal descriptor}
 110  *     returned by {@link #describeConstable() MethodType::describeConstable}.</li>
 111  * <li>The descriptor string returned by
 112  *     {@link #descriptorString() MethodType::descriptorString} or
 113  *     {@link #toMethodDescriptorString() MethodType::toMethodDescriptorString}
 114  *     for the method type is a method descriptor (JVMS {@jvms 4.3.3}).</li>
 115  * </ul>
 116  * <p>
 117  * If any of the parameter types or return type cannot be described
 118  * nominally, i.e. {@link Class#describeConstable() Class::describeConstable}
 119  * returns an empty optional for that type,
 120  * then the method type cannot be described nominally:
 121  * <ul>
 122  * <li>The method type has no {@link MethodTypeDesc nominal descriptor} and
 123  *     {@link #describeConstable() MethodType::describeConstable} returns
 124  *     an empty optional.</li>
 125  * <li>The descriptor string returned by
 126  *     {@link #descriptorString() MethodType::descriptorString} or
 127  *     {@link #toMethodDescriptorString() MethodType::toMethodDescriptorString}
 128  *     for the method type is not a type descriptor.</li>
 129  * </ul>
 130  *
 131  * @author John Rose, JSR 292 EG
 132  * @since 1.7
 133  */
 134 public final
 135 class MethodType
 136         implements Constable,
 137                    TypeDescriptor.OfMethod<Class<?>, MethodType>,
 138                    java.io.Serializable {
 139     @java.io.Serial
 140     private static final long serialVersionUID = 292L;  // {rtype, {ptype...}}
 141 
 142     // The rtype and ptypes fields define the structural identity of the method type:
 143     private final @Stable Class<?>   rtype;
 144     private final @Stable Class<?>[] ptypes;
 145 
 146     // The remaining fields are caches of various sorts:
 147     private @Stable MethodTypeForm form; // erased form, plus cached data about primitives
 148     private @Stable Object wrapAlt;  // alternative wrapped/unwrapped version and
 149                                      // private communication for readObject and readResolve
 150     private @Stable Invokers invokers;   // cache of handy higher-order adapters
 151     private @Stable String methodDescriptor;  // cache for toMethodDescriptorString
 152 
 153     /**
 154      * Constructor that performs no copying or validation.
 155      * Should only be called from the factory method makeImpl
 156      */
 157     private MethodType(Class<?> rtype, Class<?>[] ptypes) {
 158         this.rtype = rtype;
 159         this.ptypes = ptypes;
 160     }
 161 
 162     /*trusted*/ MethodTypeForm form() { return form; }
 163     /*trusted*/ Class<?> rtype() { return rtype; }
 164     /*trusted*/ Class<?>[] ptypes() { return ptypes; }
 165 
 166     void setForm(MethodTypeForm f) { form = f; }
 167 
 168     /** This number, mandated by the JVM spec as 255,
 169      *  is the maximum number of <em>slots</em>
 170      *  that any Java method can receive in its argument list.
 171      *  It limits both JVM signatures and method type objects.
 172      *  The longest possible invocation will look like
 173      *  {@code staticMethod(arg1, arg2, ..., arg255)} or
 174      *  {@code x.virtualMethod(arg1, arg2, ..., arg254)}.
 175      */
 176     /*non-public*/
 177     static final int MAX_JVM_ARITY = 255;  // this is mandated by the JVM spec.
 178 
 179     /** This number is the maximum arity of a method handle, 254.
 180      *  It is derived from the absolute JVM-imposed arity by subtracting one,
 181      *  which is the slot occupied by the method handle itself at the
 182      *  beginning of the argument list used to invoke the method handle.
 183      *  The longest possible invocation will look like
 184      *  {@code mh.invoke(arg1, arg2, ..., arg254)}.
 185      */
 186     // Issue:  Should we allow MH.invokeWithArguments to go to the full 255?
 187     /*non-public*/
 188     static final int MAX_MH_ARITY = MAX_JVM_ARITY-1;  // deduct one for mh receiver
 189 
 190     /** This number is the maximum arity of a method handle invoker, 253.
 191      *  It is derived from the absolute JVM-imposed arity by subtracting two,
 192      *  which are the slots occupied by invoke method handle, and the
 193      *  target method handle, which are both at the beginning of the argument
 194      *  list used to invoke the target method handle.
 195      *  The longest possible invocation will look like
 196      *  {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}.
 197      */
 198     /*non-public*/
 199     static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1;  // deduct one more for invoker
 200 
 201     /** Return number of extra slots (count of long/double args). */
 202     private static int checkPtypes(Class<?>[] ptypes) {
 203         int slots = 0;
 204         for (Class<?> ptype : ptypes) {
 205             Objects.requireNonNull(ptype);
 206             if (ptype == void.class)
 207                 throw newIllegalArgumentException("parameter type cannot be void");
 208             if (ptype == double.class || ptype == long.class) {
 209                 slots++;
 210             }
 211         }
 212         checkSlotCount(ptypes.length + slots);
 213         return slots;
 214     }
 215 
 216     static {
 217         // MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work:
 218         assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0);
 219     }
 220     static void checkSlotCount(int count) {
 221         if ((count & MAX_JVM_ARITY) != count)
 222             throw newIllegalArgumentException("bad parameter count "+count);
 223     }
 224     private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
 225         if (num instanceof Integer)  num = "bad index: "+num;
 226         return new IndexOutOfBoundsException(num.toString());
 227     }
 228 
 229     static final ReferencedKeySet<MethodType> internTable =
 230         ReferencedKeySet.create(false, true, new Supplier<>() {
 231             @Override
 232             public Map<ReferenceKey<MethodType>, ReferenceKey<MethodType>> get() {
 233                 return new ConcurrentHashMap<>(512);
 234             }
 235         });
 236 
 237     static final Class<?>[] NO_PTYPES = {};
 238 
 239     /**
 240      * Finds or creates an instance of the given method type.
 241      * @param rtype  the return type
 242      * @param ptypes the parameter types
 243      * @return a method type with the given components
 244      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 245      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 246      */
 247     public static MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
 248         return methodType(rtype, ptypes, false);
 249     }
 250 
 251     /**
 252      * Finds or creates a method type with the given components.
 253      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 254      * @param rtype  the return type
 255      * @param ptypes the parameter types
 256      * @return a method type with the given components
 257      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 258      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 259      */
 260     public static MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
 261         boolean notrust = false;  // random List impl. could return evil ptypes array
 262         return methodType(rtype, listToArray(ptypes), notrust);
 263     }
 264 
 265     private static Class<?>[] listToArray(List<Class<?>> ptypes) {
 266         // sanity check the size before the toArray call, since size might be huge
 267         checkSlotCount(ptypes.size());
 268         return ptypes.toArray(NO_PTYPES);
 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 leading parameter type is prepended to the remaining array.
 275      * @param rtype  the return type
 276      * @param ptype0 the first parameter type
 277      * @param ptypes the remaining parameter types
 278      * @return a method type with the given components
 279      * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null
 280      * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class}
 281      */
 282     public static MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
 283         int len = ptypes.length;
 284         if (rtype == Object.class && ptype0 == Object.class) {
 285             if (len == 0) {
 286                 return genericMethodType(1, false);
 287             }
 288             if (isAllObject(ptypes, len - 1)) {
 289                 Class<?> lastParam = ptypes[len - 1];
 290                 if (lastParam == Object.class) {
 291                     return genericMethodType(len + 1, false);
 292                 } else if (lastParam == Object[].class) {
 293                     return genericMethodType(len, true);
 294                 }
 295             }
 296         }
 297         Class<?>[] ptypes1 = new Class<?>[1 + len];
 298         ptypes1[0] = ptype0;
 299         System.arraycopy(ptypes, 0, ptypes1, 1, len);
 300         return makeImpl(rtype, ptypes1, true);
 301     }
 302 
 303     /**
 304      * Finds or creates a method type with the given components.
 305      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 306      * The resulting method has no parameter types.
 307      * @param rtype  the return type
 308      * @return a method type with the given return value
 309      * @throws NullPointerException if {@code rtype} is null
 310      */
 311     public static MethodType methodType(Class<?> rtype) {
 312         if (rtype == Object.class) {
 313             return genericMethodType(0, false);
 314         }
 315         return makeImpl(rtype, NO_PTYPES, true);
 316     }
 317 
 318     /**
 319      * Finds or creates a method type with the given components.
 320      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 321      * The resulting method has the single given parameter type.
 322      * @param rtype  the return type
 323      * @param ptype0 the parameter type
 324      * @return a method type with the given return value and parameter type
 325      * @throws NullPointerException if {@code rtype} or {@code ptype0} is null
 326      * @throws IllegalArgumentException if {@code ptype0} is {@code void.class}
 327      */
 328     public static MethodType methodType(Class<?> rtype, Class<?> ptype0) {
 329         if (rtype == Object.class) {
 330             if (ptype0 == Object.class) {
 331                 return genericMethodType(1, false);
 332             } else if (ptype0 == Object[].class) {
 333                 return genericMethodType(0, true);
 334             }
 335         }
 336         return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
 337     }
 338 
 339     /**
 340      * Finds or creates a method type with the given components.
 341      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 342      * The resulting method has the same parameter types as {@code ptypes},
 343      * and the specified return type.
 344      * @param rtype  the return type
 345      * @param ptypes the method type which supplies the parameter types
 346      * @return a method type with the given components
 347      * @throws NullPointerException if {@code rtype} or {@code ptypes} is null
 348      */
 349     public static MethodType methodType(Class<?> rtype, MethodType ptypes) {
 350         return methodType(rtype, ptypes.ptypes, true);
 351     }
 352 
 353     private static boolean isAllObject(Class<?>[] ptypes, int to) {
 354         for (int i = 0; i < to; i++) {
 355             if (ptypes[i] != Object.class) {
 356                 return false;
 357             }
 358         }
 359         return true;
 360     }
 361 
 362     /*trusted*/
 363     static MethodType methodType(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 364         if (rtype == Object.class) {
 365             int last = ptypes.length - 1;
 366             if (last < 0) {
 367                 return genericMethodType(0, false);
 368             }
 369             if (isAllObject(ptypes, last)) {
 370                 Class<?> lastParam = ptypes[last];
 371                 if (lastParam == Object.class) {
 372                     return genericMethodType(last + 1, false);
 373                 } else if (lastParam == Object[].class) {
 374                     return genericMethodType(last, true);
 375                 }
 376             }
 377         }
 378         return makeImpl(rtype, ptypes, trusted);
 379     }
 380 
 381     /**
 382      * Sole factory method to find or create an interned method type. Will perform
 383      * input validation on behalf of factory methods
 384      *
 385      * @param rtype desired return type
 386      * @param ptypes desired parameter types
 387      * @param trusted whether the ptypes can be used without cloning
 388      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 389      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 390      * @return the unique method type of the desired structure
 391      */
 392     private static MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 393         if (ptypes.length == 0) {
 394             ptypes = NO_PTYPES; trusted = true;
 395         }
 396         MethodType primordialMT = new MethodType(rtype, ptypes);
 397         MethodType mt = internTable.get(primordialMT);
 398         if (mt != null)
 399             return mt;
 400 
 401         // promote the object to the Real Thing, and reprobe
 402         Objects.requireNonNull(rtype);
 403         if (trusted) {
 404             MethodType.checkPtypes(ptypes);
 405             mt = primordialMT;
 406         } else {
 407             // Make defensive copy then validate
 408             ptypes = Arrays.copyOf(ptypes, ptypes.length);
 409             MethodType.checkPtypes(ptypes);
 410             mt = new MethodType(rtype, ptypes);
 411         }
 412         mt.form = MethodTypeForm.findForm(mt);
 413         return internTable.intern(mt);
 414     }
 415     private static final @Stable MethodType[] objectOnlyTypes = new MethodType[20];
 416 
 417     /**
 418      * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array.
 419      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 420      * All parameters and the return type will be {@code Object},
 421      * except the final array parameter if any, which will be {@code Object[]}.
 422      * @param objectArgCount number of parameters (excluding the final array parameter if any)
 423      * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]}
 424      * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments
 425      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true)
 426      * @see #genericMethodType(int)
 427      */
 428     public static MethodType genericMethodType(int objectArgCount, boolean finalArray) {
 429         MethodType mt;
 430         checkSlotCount(objectArgCount);
 431         int ivarargs = (!finalArray ? 0 : 1);
 432         int ootIndex = objectArgCount*2 + ivarargs;
 433         if (ootIndex < objectOnlyTypes.length) {
 434             mt = objectOnlyTypes[ootIndex];
 435             if (mt != null)  return mt;
 436         }
 437         Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
 438         Arrays.fill(ptypes, Object.class);
 439         if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
 440         mt = makeImpl(Object.class, ptypes, true);
 441         if (ootIndex < objectOnlyTypes.length) {
 442             objectOnlyTypes[ootIndex] = mt;     // cache it here also!
 443         }
 444         return mt;
 445     }
 446 
 447     /**
 448      * Finds or creates a method type whose components are all {@code Object}.
 449      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 450      * All parameters and the return type will be Object.
 451      * @param objectArgCount number of parameters
 452      * @return a generally applicable method type, for all calls of the given argument count
 453      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255
 454      * @see #genericMethodType(int, boolean)
 455      */
 456     public static MethodType genericMethodType(int objectArgCount) {
 457         return genericMethodType(objectArgCount, false);
 458     }
 459 
 460     /**
 461      * Finds or creates a method type with a single different parameter type.
 462      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 463      * @param num    the index (zero-based) of the parameter type to change
 464      * @param nptype a new parameter type to replace the old one with
 465      * @return the same type, except with the selected parameter changed
 466      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 467      * @throws IllegalArgumentException if {@code nptype} is {@code void.class}
 468      * @throws NullPointerException if {@code nptype} is null
 469      */
 470     public MethodType changeParameterType(int num, Class<?> nptype) {
 471         if (parameterType(num) == nptype)  return this;
 472         Class<?>[] nptypes = ptypes.clone();
 473         nptypes[num] = nptype;
 474         return makeImpl(rtype, nptypes, true);
 475     }
 476 
 477     /**
 478      * Finds or creates a method type with additional parameter types.
 479      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 480      * @param num    the position (zero-based) of the inserted parameter type(s)
 481      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 482      * @return the same type, except with the selected parameter(s) inserted
 483      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 484      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 485      *                                  or if the resulting method type would have more than 255 parameter slots
 486      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 487      */
 488     public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) {
 489         int len = ptypes.length;
 490         if (num < 0 || num > len)
 491             throw newIndexOutOfBoundsException(num);
 492         int ins = checkPtypes(ptypesToInsert);
 493         checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins);
 494         int ilen = ptypesToInsert.length;
 495         if (ilen == 0)  return this;
 496         Class<?>[] nptypes = new Class<?>[len + ilen];
 497         if (num > 0) {
 498             System.arraycopy(ptypes, 0, nptypes, 0, num);
 499         }
 500         System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen);
 501         if (num < len) {
 502             System.arraycopy(ptypes, num, nptypes, num+ilen, len-num);
 503         }
 504         return makeImpl(rtype, nptypes, true);
 505     }
 506 
 507     /**
 508      * Finds or creates a method type with additional parameter types.
 509      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 510      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 511      * @return the same type, except with the selected parameter(s) appended
 512      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 513      *                                  or if the resulting method type would have more than 255 parameter slots
 514      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 515      */
 516     public MethodType appendParameterTypes(Class<?>... ptypesToInsert) {
 517         return insertParameterTypes(parameterCount(), ptypesToInsert);
 518     }
 519 
 520     /**
 521      * Finds or creates a method type with additional parameter types.
 522      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 523      * @param num    the position (zero-based) of the inserted parameter type(s)
 524      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 525      * @return the same type, except with the selected parameter(s) inserted
 526      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 527      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 528      *                                  or if the resulting method type would have more than 255 parameter slots
 529      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 530      */
 531     public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) {
 532         return insertParameterTypes(num, listToArray(ptypesToInsert));
 533     }
 534 
 535     /**
 536      * Finds or creates a method type with additional parameter types.
 537      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 538      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 539      * @return the same type, except with the selected parameter(s) appended
 540      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 541      *                                  or if the resulting method type would have more than 255 parameter slots
 542      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 543      */
 544     public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) {
 545         return insertParameterTypes(parameterCount(), ptypesToInsert);
 546     }
 547 
 548     /**
 549      * Finds or creates a method type with modified parameter types.
 550      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 551      * @param start  the position (zero-based) of the first replaced parameter type(s)
 552      * @param end    the position (zero-based) after the last replaced parameter type(s)
 553      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 554      * @return the same type, except with the selected parameter(s) replaced
 555      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 556      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 557      *                                  or if {@code start} is greater than {@code end}
 558      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 559      *                                  or if the resulting method type would have more than 255 parameter slots
 560      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 561      */
 562     /*non-public*/
 563     MethodType replaceParameterTypes(int start, int end, Class<?>... ptypesToInsert) {
 564         if (start == end)
 565             return insertParameterTypes(start, ptypesToInsert);
 566         int len = ptypes.length;
 567         if (!(0 <= start && start <= end && end <= len))
 568             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 569         int ilen = ptypesToInsert.length;
 570         if (ilen == 0)
 571             return dropParameterTypes(start, end);
 572         return dropParameterTypes(start, end).insertParameterTypes(start, ptypesToInsert);
 573     }
 574 
 575     /** Replace the last arrayLength parameter types with the component type of arrayType.
 576      * @param arrayType any array type
 577      * @param pos position at which to spread
 578      * @param arrayLength the number of parameter types to change
 579      * @return the resulting type
 580      */
 581     /*non-public*/
 582     MethodType asSpreaderType(Class<?> arrayType, int pos, int arrayLength) {
 583         assert(parameterCount() >= arrayLength);
 584         int spreadPos = pos;
 585         if (arrayLength == 0)  return this;  // nothing to change
 586         if (arrayType == Object[].class) {
 587             if (isGeneric())  return this;  // nothing to change
 588             if (spreadPos == 0) {
 589                 // no leading arguments to preserve; go generic
 590                 MethodType res = genericMethodType(arrayLength);
 591                 if (rtype != Object.class) {
 592                     res = res.changeReturnType(rtype);
 593                 }
 594                 return res;
 595             }
 596         }
 597         Class<?> elemType = arrayType.getComponentType();
 598         assert(elemType != null);
 599         for (int i = spreadPos; i < spreadPos + arrayLength; i++) {
 600             if (ptypes[i] != elemType) {
 601                 Class<?>[] fixedPtypes = ptypes.clone();
 602                 Arrays.fill(fixedPtypes, i, spreadPos + arrayLength, elemType);
 603                 return methodType(rtype, fixedPtypes);
 604             }
 605         }
 606         return this;  // arguments check out; no change
 607     }
 608 
 609     /** Return the leading parameter type, which must exist and be a reference.
 610      *  @return the leading parameter type, after error checks
 611      */
 612     /*non-public*/
 613     Class<?> leadingReferenceParameter() {
 614         Class<?> ptype;
 615         if (ptypes.length == 0 ||
 616             (ptype = ptypes[0]).isPrimitive())
 617             throw newIllegalArgumentException("no leading reference parameter");
 618         return ptype;
 619     }
 620 
 621     /** Delete the last parameter type and replace it with arrayLength copies of the component type of arrayType.
 622      * @param arrayType any array type
 623      * @param pos position at which to insert parameters
 624      * @param arrayLength the number of parameter types to insert
 625      * @return the resulting type
 626      */
 627     /*non-public*/
 628     MethodType asCollectorType(Class<?> arrayType, int pos, int arrayLength) {
 629         assert(parameterCount() >= 1);
 630         assert(pos < ptypes.length);
 631         assert(ptypes[pos].isAssignableFrom(arrayType));
 632         MethodType res;
 633         if (arrayType == Object[].class) {
 634             res = genericMethodType(arrayLength);
 635             if (rtype != Object.class) {
 636                 res = res.changeReturnType(rtype);
 637             }
 638         } else {
 639             Class<?> elemType = arrayType.getComponentType();
 640             assert(elemType != null);
 641             res = methodType(rtype, Collections.nCopies(arrayLength, elemType));
 642         }
 643         if (ptypes.length == 1) {
 644             return res;
 645         } else {
 646             // insert after (if need be), then before
 647             if (pos < ptypes.length - 1) {
 648                 res = res.insertParameterTypes(arrayLength, Arrays.copyOfRange(ptypes, pos + 1, ptypes.length));
 649             }
 650             return res.insertParameterTypes(0, Arrays.copyOf(ptypes, pos));
 651         }
 652     }
 653 
 654     /**
 655      * Finds or creates a method type with some parameter types omitted.
 656      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 657      * @param start  the index (zero-based) of the first parameter type to remove
 658      * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
 659      * @return the same type, except with the selected parameter(s) removed
 660      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 661      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 662      *                                  or if {@code start} is greater than {@code end}
 663      */
 664     public MethodType dropParameterTypes(int start, int end) {
 665         int len = ptypes.length;
 666         if (!(0 <= start && start <= end && end <= len))
 667             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 668         if (start == end)  return this;
 669         Class<?>[] nptypes;
 670         if (start == 0) {
 671             if (end == len) {
 672                 // drop all parameters
 673                 nptypes = NO_PTYPES;
 674             } else {
 675                 // drop initial parameter(s)
 676                 nptypes = Arrays.copyOfRange(ptypes, end, len);
 677             }
 678         } else {
 679             if (end == len) {
 680                 // drop trailing parameter(s)
 681                 nptypes = Arrays.copyOfRange(ptypes, 0, start);
 682             } else {
 683                 int tail = len - end;
 684                 nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
 685                 System.arraycopy(ptypes, end, nptypes, start, tail);
 686             }
 687         }
 688         return methodType(rtype, nptypes, true);
 689     }
 690 
 691     /**
 692      * Finds or creates a method type with a different return type.
 693      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 694      * @param nrtype a return parameter type to replace the old one with
 695      * @return the same type, except with the return type change
 696      * @throws NullPointerException if {@code nrtype} is null
 697      */
 698     public MethodType changeReturnType(Class<?> nrtype) {
 699         if (returnType() == nrtype)  return this;
 700         return methodType(nrtype, ptypes, true);
 701     }
 702 
 703     /**
 704      * Reports if this type contains a primitive argument or return value.
 705      * The return type {@code void} counts as a primitive.
 706      * @return true if any of the types are primitives
 707      */
 708     public boolean hasPrimitives() {
 709         return form.hasPrimitives();
 710     }
 711 
 712     /**
 713      * Reports if this type contains a wrapper argument or return value.
 714      * Wrappers are types which box primitive values, such as {@link Integer}.
 715      * The reference type {@code java.lang.Void} counts as a wrapper,
 716      * if it occurs as a return type.
 717      * @return true if any of the types are wrappers
 718      */
 719     public boolean hasWrappers() {
 720         return unwrap() != this;
 721     }
 722 
 723     /**
 724      * Erases all reference types to {@code Object}.
 725      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 726      * All primitive types (including {@code void}) will remain unchanged.
 727      * @return a version of the original type with all reference types replaced
 728      */
 729     public MethodType erase() {
 730         return form.erasedType();
 731     }
 732 
 733     /**
 734      * Erases all reference types to {@code Object}, and all subword types to {@code int}.
 735      * This is the reduced type polymorphism used by private methods
 736      * such as {@link MethodHandle#invokeBasic invokeBasic}.
 737      * @return a version of the original type with all reference and subword types replaced
 738      */
 739     /*non-public*/
 740     MethodType basicType() {
 741         return form.basicType();
 742     }
 743 
 744     private static final @Stable Class<?>[] METHOD_HANDLE_ARRAY
 745             = new Class<?>[] { MethodHandle.class };
 746 
 747     /**
 748      * @return a version of the original type with MethodHandle prepended as the first argument
 749      */
 750     /*non-public*/
 751     MethodType invokerType() {
 752         return insertParameterTypes(0, METHOD_HANDLE_ARRAY);
 753     }
 754 
 755     /**
 756      * Converts all types, both reference and primitive, to {@code Object}.
 757      * Convenience method for {@link #genericMethodType(int) genericMethodType}.
 758      * The expression {@code type.wrap().erase()} produces the same value
 759      * as {@code type.generic()}.
 760      * @return a version of the original type with all types replaced
 761      */
 762     public MethodType generic() {
 763         return genericMethodType(parameterCount());
 764     }
 765 
 766     /*non-public*/
 767     boolean isGeneric() {
 768         return this == erase() && !hasPrimitives();
 769     }
 770 
 771     /**
 772      * Converts all primitive types to their corresponding wrapper types.
 773      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 774      * All reference types (including wrapper types) will remain unchanged.
 775      * A {@code void} return type is changed to the type {@code java.lang.Void}.
 776      * The expression {@code type.wrap().erase()} produces the same value
 777      * as {@code type.generic()}.
 778      * @return a version of the original type with all primitive types replaced
 779      */
 780     public MethodType wrap() {
 781         return hasPrimitives() ? wrapWithPrims(this) : this;
 782     }
 783 
 784     /**
 785      * Converts all wrapper types to their corresponding primitive types.
 786      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 787      * All primitive types (including {@code void}) will remain unchanged.
 788      * A return type of {@code java.lang.Void} is changed to {@code void}.
 789      * @return a version of the original type with all wrapper types replaced
 790      */
 791     public MethodType unwrap() {
 792         MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
 793         return unwrapWithNoPrims(noprims);
 794     }
 795 
 796     private static MethodType wrapWithPrims(MethodType pt) {
 797         assert(pt.hasPrimitives());
 798         MethodType wt = (MethodType)pt.wrapAlt;
 799         if (wt == null) {
 800             // fill in lazily
 801             wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP);
 802             assert(wt != null);
 803             pt.wrapAlt = wt;
 804         }
 805         return wt;
 806     }
 807 
 808     private static MethodType unwrapWithNoPrims(MethodType wt) {
 809         assert(!wt.hasPrimitives());
 810         MethodType uwt = (MethodType)wt.wrapAlt;
 811         if (uwt == null) {
 812             // fill in lazily
 813             uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP);
 814             if (uwt == null)
 815                 uwt = wt;    // type has no wrappers or prims at all
 816             wt.wrapAlt = uwt;
 817         }
 818         return uwt;
 819     }
 820 
 821     /**
 822      * Returns the parameter type at the specified index, within this method type.
 823      * @param num the index (zero-based) of the desired parameter type
 824      * @return the selected parameter type
 825      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 826      */
 827     public Class<?> parameterType(int num) {
 828         return ptypes[num];
 829     }
 830     /**
 831      * Returns the number of parameter types in this method type.
 832      * @return the number of parameter types
 833      */
 834     public int parameterCount() {
 835         return ptypes.length;
 836     }
 837     /**
 838      * Returns the return type of this method type.
 839      * @return the return type
 840      */
 841     public Class<?> returnType() {
 842         return rtype;
 843     }
 844 
 845     /**
 846      * Presents the parameter types as a list (a convenience method).
 847      * The list will be immutable.
 848      * @return the parameter types (as an immutable list)
 849      */
 850     public List<Class<?>> parameterList() {
 851         return List.of(ptypes);
 852     }
 853 
 854     /**
 855      * Returns the last parameter type of this method type.
 856      * If this type has no parameters, the sentinel value
 857      * {@code void.class} is returned instead.
 858      * @apiNote
 859      * <p>
 860      * The sentinel value is chosen so that reflective queries can be
 861      * made directly against the result value.
 862      * The sentinel value cannot be confused with a real parameter,
 863      * since {@code void} is never acceptable as a parameter type.
 864      * For variable arity invocation modes, the expression
 865      * {@link Class#getComponentType lastParameterType().getComponentType()}
 866      * is useful to query the type of the "varargs" parameter.
 867      * @return the last parameter type if any, else {@code void.class}
 868      * @since 10
 869      */
 870     public Class<?> lastParameterType() {
 871         int len = ptypes.length;
 872         return len == 0 ? void.class : ptypes[len-1];
 873     }
 874 
 875     /**
 876      * Presents the parameter types as an array (a convenience method).
 877      * Changes to the array will not result in changes to the type.
 878      * @return the parameter types (as a fresh copy if necessary)
 879      */
 880     public Class<?>[] parameterArray() {
 881         return ptypes.clone();
 882     }
 883 
 884     /**
 885      * Compares the specified object with this type for equality.
 886      * That is, it returns {@code true} if and only if the specified object
 887      * is also a method type with exactly the same parameters and return type.
 888      * @param x object to compare
 889      * @see Object#equals(Object)
 890      */
 891     @Override
 892     public boolean equals(Object x) {
 893         if (this == x) {
 894             return true;
 895         }
 896         if (x instanceof MethodType mt) {
 897             return equals(mt);
 898         }
 899         return false;
 900     }
 901 
 902     private boolean equals(MethodType that) {
 903         return this.rtype == that.rtype
 904             && Arrays.equals(this.ptypes, that.ptypes);
 905     }
 906 
 907     /**
 908      * Returns the hash code value for this method type.
 909      * It is defined to be the same as the hashcode of a List
 910      * whose elements are the return type followed by the
 911      * parameter types.
 912      * @return the hash code value for this method type
 913      * @see Object#hashCode()
 914      * @see #equals(Object)
 915      * @see List#hashCode()
 916      */
 917     @Override
 918     public int hashCode() {
 919         int hashCode = 31 + rtype.hashCode();
 920         for (Class<?> ptype : ptypes)
 921             hashCode = 31 * hashCode + ptype.hashCode();
 922         return hashCode;
 923     }
 924 
 925     /**
 926      * Returns a string representation of the method type,
 927      * of the form {@code "(PT0,PT1...)RT"}.
 928      * The string representation of a method type is a
 929      * parenthesis enclosed, comma separated list of type names,
 930      * followed immediately by the return type.
 931      * <p>
 932      * Each type is represented by its
 933      * {@link java.lang.Class#getSimpleName simple name}.
 934      */
 935     @Override
 936     public String toString() {
 937         StringJoiner sj = new StringJoiner(",", "(",
 938                 ")" + rtype.getSimpleName());
 939         for (int i = 0; i < ptypes.length; i++) {
 940             sj.add(ptypes[i].getSimpleName());
 941         }
 942         return sj.toString();
 943     }
 944 
 945     /** True if my parameter list is effectively identical to the given full list,
 946      *  after skipping the given number of my own initial parameters.
 947      *  In other words, after disregarding {@code skipPos} parameters,
 948      *  my remaining parameter list is no longer than the {@code fullList}, and
 949      *  is equal to the same-length initial sublist of {@code fullList}.
 950      */
 951     /*non-public*/
 952     boolean effectivelyIdenticalParameters(int skipPos, List<Class<?>> fullList) {
 953         int myLen = ptypes.length, fullLen = fullList.size();
 954         if (skipPos > myLen || myLen - skipPos > fullLen)
 955             return false;
 956         List<Class<?>> myList = Arrays.asList(ptypes);
 957         if (skipPos != 0) {
 958             myList = myList.subList(skipPos, myLen);
 959             myLen -= skipPos;
 960         }
 961         if (fullLen == myLen)
 962             return myList.equals(fullList);
 963         else
 964             return myList.equals(fullList.subList(0, myLen));
 965     }
 966 
 967     /** True if the old return type can always be viewed (w/o casting) under new return type,
 968      *  and the new parameters can be viewed (w/o casting) under the old parameter types.
 969      */
 970     /*non-public*/
 971     boolean isViewableAs(MethodType newType, boolean keepInterfaces) {
 972         if (!VerifyType.isNullConversion(returnType(), newType.returnType(), keepInterfaces))
 973             return false;
 974         if (form == newType.form && form.erasedType == this)
 975             return true;  // my reference parameters are all Object
 976         if (ptypes == newType.ptypes)
 977             return true;
 978         int argc = parameterCount();
 979         if (argc != newType.parameterCount())
 980             return false;
 981         for (int i = 0; i < argc; i++) {
 982             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i), keepInterfaces))
 983                 return false;
 984         }
 985         return true;
 986     }
 987     /*non-public*/
 988     boolean isConvertibleTo(MethodType newType) {
 989         MethodTypeForm oldForm = this.form();
 990         MethodTypeForm newForm = newType.form();
 991         if (oldForm == newForm)
 992             // same parameter count, same primitive/object mix
 993             return true;
 994         if (!canConvert(returnType(), newType.returnType()))
 995             return false;
 996         Class<?>[] srcTypes = newType.ptypes;
 997         Class<?>[] dstTypes = ptypes;
 998         if (srcTypes == dstTypes)
 999             return true;
1000         int argc;
1001         if ((argc = srcTypes.length) != dstTypes.length)
1002             return false;
1003         if (argc <= 1) {
1004             if (argc == 1 && !canConvert(srcTypes[0], dstTypes[0]))
1005                 return false;
1006             return true;
1007         }
1008         if ((!oldForm.hasPrimitives() && oldForm.erasedType == this) ||
1009             (!newForm.hasPrimitives() && newForm.erasedType == newType)) {
1010             // Somewhat complicated test to avoid a loop of 2 or more trips.
1011             // If either type has only Object parameters, we know we can convert.
1012             assert(canConvertParameters(srcTypes, dstTypes));
1013             return true;
1014         }
1015         return canConvertParameters(srcTypes, dstTypes);
1016     }
1017 
1018     /** Returns true if MHs.explicitCastArguments produces the same result as MH.asType.
1019      *  If the type conversion is impossible for either, the result should be false.
1020      */
1021     /*non-public*/
1022     boolean explicitCastEquivalentToAsType(MethodType newType) {
1023         if (this == newType)  return true;
1024         if (!explicitCastEquivalentToAsType(rtype, newType.rtype)) {
1025             return false;
1026         }
1027         Class<?>[] srcTypes = newType.ptypes;
1028         Class<?>[] dstTypes = ptypes;
1029         if (dstTypes == srcTypes) {
1030             return true;
1031         }
1032         assert(dstTypes.length == srcTypes.length);
1033         for (int i = 0; i < dstTypes.length; i++) {
1034             if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) {
1035                 return false;
1036             }
1037         }
1038         return true;
1039     }
1040 
1041     /** Reports true if the src can be converted to the dst, by both asType and MHs.eCE,
1042      *  and with the same effect.
1043      *  MHs.eCA has the following "upgrades" to MH.asType:
1044      *  1. interfaces are unchecked (that is, treated as if aliased to Object)
1045      *     Therefore, {@code Object->CharSequence} is possible in both cases but has different semantics
1046      *  2. the full matrix of primitive-to-primitive conversions is supported
1047      *     Narrowing like {@code long->byte} and basic-typing like {@code boolean->int}
1048      *     are not supported by asType, but anything supported by asType is equivalent
1049      *     with MHs.eCE.
1050      *  3a. unboxing conversions can be followed by the full matrix of primitive conversions
1051      *  3b. unboxing of null is permitted (creates a zero primitive value)
1052      * Other than interfaces, reference-to-reference conversions are the same.
1053      * Boxing primitives to references is the same for both operators.
1054      */
1055     private static boolean explicitCastEquivalentToAsType(Class<?> src, Class<?> dst) {
1056         if (src == dst || dst == Object.class || dst == void.class)  return true;
1057         if (src.isPrimitive()) {
1058             // Could be a prim/prim conversion, where casting is a strict superset.
1059             // Or a boxing conversion, which is always to an exact wrapper class.
1060             return canConvert(src, dst);
1061         } else if (dst.isPrimitive()) {
1062             // Unboxing behavior is different between MHs.eCA & MH.asType (see 3b).
1063             return false;
1064         } else {
1065             // R->R always works, but we have to avoid a check-cast to an interface.
1066             return !dst.isInterface() || dst.isAssignableFrom(src);
1067         }
1068     }
1069 
1070     private boolean canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes) {
1071         for (int i = 0; i < srcTypes.length; i++) {
1072             if (!canConvert(srcTypes[i], dstTypes[i])) {
1073                 return false;
1074             }
1075         }
1076         return true;
1077     }
1078 
1079     /*non-public*/
1080     static boolean canConvert(Class<?> src, Class<?> dst) {
1081         // short-circuit a few cases:
1082         if (src == dst || src == Object.class || dst == Object.class)  return true;
1083         // the remainder of this logic is documented in MethodHandle.asType
1084         if (src.isPrimitive()) {
1085             // can force void to an explicit null, a la reflect.Method.invoke
1086             // can also force void to a primitive zero, by analogy
1087             if (src == void.class)  return true;  //or !dst.isPrimitive()?
1088             Wrapper sw = Wrapper.forPrimitiveType(src);
1089             if (dst.isPrimitive()) {
1090                 // P->P must widen
1091                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
1092             } else {
1093                 // P->R must box and widen
1094                 return dst.isAssignableFrom(sw.wrapperType());
1095             }
1096         } else if (dst.isPrimitive()) {
1097             // any value can be dropped
1098             if (dst == void.class)  return true;
1099             Wrapper dw = Wrapper.forPrimitiveType(dst);
1100             // R->P must be able to unbox (from a dynamically chosen type) and widen
1101             // For example:
1102             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
1103             //   Character/Comparable/Object -> dw:Character -> char
1104             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
1105             // This means that dw must be cast-compatible with src.
1106             if (src.isAssignableFrom(dw.wrapperType())) {
1107                 return true;
1108             }
1109             // The above does not work if the source reference is strongly typed
1110             // to a wrapper whose primitive must be widened.  For example:
1111             //   Byte -> unbox:byte -> short/int/long/float/double
1112             //   Character -> unbox:char -> int/long/float/double
1113             if (Wrapper.isWrapperType(src) &&
1114                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
1115                 // can unbox from src and then widen to dst
1116                 return true;
1117             }
1118             // We have already covered cases which arise due to runtime unboxing
1119             // of a reference type which covers several wrapper types:
1120             //   Object -> cast:Integer -> unbox:int -> long/float/double
1121             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
1122             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
1123             // subclass of Number which wraps a value that can convert to char.
1124             // Since there is none, we don't need an extra check here to cover char or boolean.
1125             return false;
1126         } else {
1127             // R->R always works, since null is always valid dynamically
1128             return true;
1129         }
1130     }
1131 
1132     /// Queries which have to do with the bytecode architecture
1133 
1134     /** Reports the number of JVM stack slots required to invoke a method
1135      * of this type.  Note that (for historical reasons) the JVM requires
1136      * a second stack slot to pass long and double arguments.
1137      * So this method returns {@link #parameterCount() parameterCount} plus the
1138      * number of long and double parameters (if any).
1139      * <p>
1140      * This method is included for the benefit of applications that must
1141      * generate bytecodes that process method handles and invokedynamic.
1142      * @return the number of JVM stack slots for this type's parameters
1143      */
1144     /*non-public*/
1145     int parameterSlotCount() {
1146         return form.parameterSlotCount();
1147     }
1148 
1149     /*non-public*/
1150     Invokers invokers() {
1151         Invokers inv = invokers;
1152         if (inv != null)  return inv;
1153         invokers = inv = new Invokers(this);
1154         return inv;
1155     }
1156 
1157     /**
1158      * Finds or creates an instance of a method type of the given method descriptor
1159      * (JVMS {@jvms 4.3.3}). This method is a convenience method for
1160      * {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
1161      * Any class or interface name embedded in the descriptor string will be
1162      * resolved by the given loader (or if it is {@code null}, on the system class loader).
1163      *
1164      * @apiNote
1165      * It is possible to encounter method types that have valid descriptors but
1166      * cannot be constructed by this method, because their component types are
1167      * not visible from a common class loader.
1168      * <p>
1169      * This method is included for the benefit of applications that must
1170      * generate bytecodes that process method handles and {@code invokedynamic}.
1171      * @param descriptor a method descriptor string
1172      * @param loader the class loader in which to look up the types
1173      * @return a method type of the given method descriptor
1174      * @throws NullPointerException if the string is {@code null}
1175      * @throws IllegalArgumentException if the string is not a method descriptor
1176      * @throws TypeNotPresentException if a named type cannot be found
1177      * @throws SecurityException if the security manager is present and
1178      *         {@code loader} is {@code null} and the caller does not have the
1179      *         {@link RuntimePermission}{@code ("getClassLoader")}
1180      * @jvms 4.3.3 Method Descriptors
1181      */
1182     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
1183         throws IllegalArgumentException, TypeNotPresentException
1184     {
1185         if (loader == null) {
1186             @SuppressWarnings("removal")
1187             SecurityManager sm = System.getSecurityManager();
1188             if (sm != null) {
1189                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1190             }
1191         }
1192         return fromDescriptor(descriptor,
1193                               (loader == null) ? ClassLoader.getSystemClassLoader() : loader);
1194     }
1195 
1196     /**
1197      * Same as {@link #fromMethodDescriptorString(String, ClassLoader)}, but
1198      * {@code null} ClassLoader means the bootstrap loader is used here.
1199      * <p>
1200      * IMPORTANT: This method is preferable for JDK internal use as it more
1201      * correctly interprets {@code null} ClassLoader than
1202      * {@link #fromMethodDescriptorString(String, ClassLoader)}.
1203      * Use of this method also avoids early initialization issues when system
1204      * ClassLoader is not initialized yet.
1205      */
1206     static MethodType fromDescriptor(String descriptor, ClassLoader loader)
1207         throws IllegalArgumentException, TypeNotPresentException
1208     {
1209         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
1210             descriptor.indexOf(')') < 0 ||
1211             descriptor.indexOf('.') >= 0)
1212             throw newIllegalArgumentException("not a method descriptor: "+descriptor);
1213         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
1214         Class<?> rtype = types.remove(types.size() - 1);
1215         Class<?>[] ptypes = listToArray(types);
1216         return methodType(rtype, ptypes, true);
1217     }
1218 
1219     /**
1220      * {@return the descriptor string for this method type} This method
1221      * is equivalent to calling {@link #descriptorString() MethodType::descriptorString}.
1222      *
1223      * @apiNote
1224      * This is not a strict inverse of {@link #fromMethodDescriptorString
1225      * fromMethodDescriptorString} which requires a method type descriptor
1226      * (JVMS {@jvms 4.3.3}) and a suitable class loader argument.
1227      * Two distinct {@code MethodType} objects can have an identical
1228      * descriptor string as distinct classes can have the same name
1229      * but different class loaders.
1230      *
1231      * <p>
1232      * This method is included for the benefit of applications that must
1233      * generate bytecodes that process method handles and {@code invokedynamic}.
1234      * @jvms 4.3.3 Method Descriptors
1235      * @see <a href="#descriptor">Nominal Descriptor for {@code MethodType}</a>
1236      */
1237     public String toMethodDescriptorString() {
1238         String desc = methodDescriptor;
1239         if (desc == null) {
1240             desc = BytecodeDescriptor.unparseMethod(this.rtype, this.ptypes);
1241             methodDescriptor = desc;
1242         }
1243         return desc;
1244     }
1245 
1246     /**
1247      * {@return the descriptor string for this method type}
1248      *
1249      * <p>
1250      * If this method type can be {@linkplain ##descriptor described nominally},
1251      * then the result is a method type descriptor (JVMS {@jvms 4.3.3}).
1252      * {@link MethodTypeDesc MethodTypeDesc} for this method type
1253      * can be produced by calling {@link MethodTypeDesc#ofDescriptor(String)
1254      * MethodTypeDesc::ofDescriptor} with the result descriptor string.
1255      * <p>
1256      * If this method type cannot be {@linkplain ##descriptor described nominally}
1257      * and the result is a string of the form:
1258      * <blockquote>{@code "(<parameter-descriptors>)<return-descriptor>"}</blockquote>
1259      * where {@code <parameter-descriptors>} is the concatenation of the
1260      * {@linkplain Class#descriptorString() descriptor string} of all
1261      * of the parameter types and the {@linkplain Class#descriptorString() descriptor string}
1262      * of the return type. No {@link java.lang.constant.MethodTypeDesc MethodTypeDesc}
1263      * can be produced from the result string.
1264      *
1265      * @since 12
1266      * @jvms 4.3.3 Method Descriptors
1267      * @see <a href="#descriptor">Nominal Descriptor for {@code MethodType}</a>
1268      */
1269     @Override
1270     public String descriptorString() {
1271         return toMethodDescriptorString();
1272     }
1273 
1274     /*non-public*/
1275     static String toFieldDescriptorString(Class<?> cls) {
1276         return BytecodeDescriptor.unparse(cls);
1277     }
1278 
1279     /**
1280      * Returns a nominal descriptor for this instance, if one can be
1281      * constructed, or an empty {@link Optional} if one cannot be.
1282      *
1283      * @return An {@link Optional} containing the resulting nominal descriptor,
1284      * or an empty {@link Optional} if one cannot be constructed.
1285      * @since 12
1286      * @see <a href="#descriptor">Nominal Descriptor for {@code MethodType}</a>
1287      */
1288     @Override
1289     public Optional<MethodTypeDesc> describeConstable() {
1290         try {
1291             return Optional.of(MethodTypeDesc.of(returnType().describeConstable().orElseThrow(),
1292                                                  Stream.of(parameterArray())
1293                                                       .map(p -> p.describeConstable().orElseThrow())
1294                                                       .toArray(ClassDesc[]::new)));
1295         }
1296         catch (NoSuchElementException e) {
1297             return Optional.empty();
1298         }
1299     }
1300 
1301     /// Serialization.
1302 
1303     /**
1304      * There are no serializable fields for {@code MethodType}.
1305      */
1306     @java.io.Serial
1307     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
1308 
1309     /**
1310      * Save the {@code MethodType} instance to a stream.
1311      *
1312      * @serialData
1313      * For portability, the serialized format does not refer to named fields.
1314      * Instead, the return type and parameter type arrays are written directly
1315      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
1316      * as follows:
1317      * <blockquote><pre>{@code
1318 s.writeObject(this.returnType());
1319 s.writeObject(this.parameterArray());
1320      * }</pre></blockquote>
1321      * <p>
1322      * The deserialized field values are checked as if they were
1323      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
1324      * For example, null values, or {@code void} parameter types,
1325      * will lead to exceptions during deserialization.
1326      * @param s the stream to write the object to
1327      * @throws java.io.IOException if there is a problem writing the object
1328      */
1329     @java.io.Serial
1330     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
1331         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
1332         s.writeObject(returnType());
1333         s.writeObject(parameterArray());
1334     }
1335 
1336     /**
1337      * Reconstitute the {@code MethodType} instance from a stream (that is,
1338      * deserialize it).
1339      * This instance is a scratch object with bogus final fields.
1340      * It provides the parameters to the factory method called by
1341      * {@link #readResolve readResolve}.
1342      * After that call it is discarded.
1343      * @param s the stream to read the object from
1344      * @throws java.io.IOException if there is a problem reading the object
1345      * @throws ClassNotFoundException if one of the component classes cannot be resolved
1346      * @see #readResolve
1347      * @see #writeObject
1348      */
1349     @java.io.Serial
1350     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
1351         // Assign defaults in case this object escapes
1352         UNSAFE.putReference(this, OffsetHolder.rtypeOffset, void.class);
1353         UNSAFE.putReference(this, OffsetHolder.ptypesOffset, NO_PTYPES);
1354 
1355         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
1356 
1357         Class<?>   returnType     = (Class<?>)   s.readObject();
1358         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
1359 
1360         // Verify all operands, and make sure ptypes is unshared
1361         // Cache the new MethodType for readResolve
1362         wrapAlt = new MethodType[]{MethodType.methodType(returnType, parameterArray)};
1363     }
1364 
1365     // Support for resetting final fields while deserializing. Implement Holder
1366     // pattern to make the rarely needed offset calculation lazy.
1367     private static class OffsetHolder {
1368         static final long rtypeOffset
1369                 = UNSAFE.objectFieldOffset(MethodType.class, "rtype");
1370 
1371         static final long ptypesOffset
1372                 = UNSAFE.objectFieldOffset(MethodType.class, "ptypes");
1373     }
1374 
1375     /**
1376      * Resolves and initializes a {@code MethodType} object
1377      * after serialization.
1378      * @return the fully initialized {@code MethodType} object
1379      */
1380     @java.io.Serial
1381     private Object readResolve() {
1382         // Do not use a trusted path for deserialization:
1383         //    return makeImpl(rtype, ptypes, true);
1384         // Verify all operands, and make sure ptypes is unshared:
1385         // Return a new validated MethodType for the rtype and ptypes passed from readObject.
1386         MethodType mt = ((MethodType[])wrapAlt)[0];
1387         wrapAlt = null;
1388         return mt;
1389     }
1390 }