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