• 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 arrayLength the number of parameter types to change
477      * @return the resulting type
478      */
asSpreaderType(Class<?> arrayType, int arrayLength)479     /*non-public*/ MethodType asSpreaderType(Class<?> arrayType, int arrayLength) {
480         assert(parameterCount() >= arrayLength);
481         int spreadPos = ptypes.length - arrayLength;
482         if (arrayLength == 0)  return this;  // nothing to change
483         if (arrayType == Object[].class) {
484             if (isGeneric())  return this;  // nothing to change
485             if (spreadPos == 0) {
486                 // no leading arguments to preserve; go generic
487                 MethodType res = genericMethodType(arrayLength);
488                 if (rtype != Object.class) {
489                     res = res.changeReturnType(rtype);
490                 }
491                 return res;
492             }
493         }
494         Class<?> elemType = arrayType.getComponentType();
495         assert(elemType != null);
496         for (int i = spreadPos; i < ptypes.length; i++) {
497             if (ptypes[i] != elemType) {
498                 Class<?>[] fixedPtypes = ptypes.clone();
499                 Arrays.fill(fixedPtypes, i, ptypes.length, elemType);
500                 return methodType(rtype, fixedPtypes);
501             }
502         }
503         return this;  // arguments check out; no change
504     }
505 
506     /** Return the leading parameter type, which must exist and be a reference.
507      *  @return the leading parameter type, after error checks
508      */
leadingReferenceParameter()509     /*non-public*/ Class<?> leadingReferenceParameter() {
510         Class<?> ptype;
511         if (ptypes.length == 0 ||
512             (ptype = ptypes[0]).isPrimitive())
513             throw newIllegalArgumentException("no leading reference parameter");
514         return ptype;
515     }
516 
517     /** Delete the last parameter type and replace it with arrayLength copies of the component type of arrayType.
518      * @param arrayType any array type
519      * @param arrayLength the number of parameter types to insert
520      * @return the resulting type
521      */
asCollectorType(Class<?> arrayType, int arrayLength)522     /*non-public*/ MethodType asCollectorType(Class<?> arrayType, int arrayLength) {
523         assert(parameterCount() >= 1);
524         assert(lastParameterType().isAssignableFrom(arrayType));
525         MethodType res;
526         if (arrayType == Object[].class) {
527             res = genericMethodType(arrayLength);
528             if (rtype != Object.class) {
529                 res = res.changeReturnType(rtype);
530             }
531         } else {
532             Class<?> elemType = arrayType.getComponentType();
533             assert(elemType != null);
534             res = methodType(rtype, Collections.nCopies(arrayLength, elemType));
535         }
536         if (ptypes.length == 1) {
537             return res;
538         } else {
539             return res.insertParameterTypes(0, parameterList().subList(0, ptypes.length-1));
540         }
541     }
542 
543     /**
544      * Finds or creates a method type with some parameter types omitted.
545      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
546      * @param start  the index (zero-based) of the first parameter type to remove
547      * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
548      * @return the same type, except with the selected parameter(s) removed
549      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
550      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
551      *                                  or if {@code start} is greater than {@code end}
552      */
dropParameterTypes(int start, int end)553     public MethodType dropParameterTypes(int start, int end) {
554         int len = ptypes.length;
555         if (!(0 <= start && start <= end && end <= len))
556             throw newIndexOutOfBoundsException("start="+start+" end="+end);
557         if (start == end)  return this;
558         Class<?>[] nptypes;
559         if (start == 0) {
560             if (end == len) {
561                 // drop all parameters
562                 nptypes = NO_PTYPES;
563             } else {
564                 // drop initial parameter(s)
565                 nptypes = Arrays.copyOfRange(ptypes, end, len);
566             }
567         } else {
568             if (end == len) {
569                 // drop trailing parameter(s)
570                 nptypes = Arrays.copyOfRange(ptypes, 0, start);
571             } else {
572                 int tail = len - end;
573                 nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
574                 System.arraycopy(ptypes, end, nptypes, start, tail);
575             }
576         }
577         return makeImpl(rtype, nptypes, true);
578     }
579 
580     /**
581      * Finds or creates a method type with a different return type.
582      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
583      * @param nrtype a return parameter type to replace the old one with
584      * @return the same type, except with the return type change
585      * @throws NullPointerException if {@code nrtype} is null
586      */
changeReturnType(Class<?> nrtype)587     public MethodType changeReturnType(Class<?> nrtype) {
588         if (returnType() == nrtype)  return this;
589         return makeImpl(nrtype, ptypes, true);
590     }
591 
592     /**
593      * Reports if this type contains a primitive argument or return value.
594      * The return type {@code void} counts as a primitive.
595      * @return true if any of the types are primitives
596      */
hasPrimitives()597     public boolean hasPrimitives() {
598         return form.hasPrimitives();
599     }
600 
601     /**
602      * Reports if this type contains a wrapper argument or return value.
603      * Wrappers are types which box primitive values, such as {@link Integer}.
604      * The reference type {@code java.lang.Void} counts as a wrapper,
605      * if it occurs as a return type.
606      * @return true if any of the types are wrappers
607      */
hasWrappers()608     public boolean hasWrappers() {
609         return unwrap() != this;
610     }
611 
612     /**
613      * Erases all reference types to {@code Object}.
614      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
615      * All primitive types (including {@code void}) will remain unchanged.
616      * @return a version of the original type with all reference types replaced
617      */
erase()618     public MethodType erase() {
619         return form.erasedType();
620     }
621 
622     // BEGIN Android-removed: Implementation methods unused on Android.
623     /*
624     /**
625      * Erases all reference types to {@code Object}, and all subword types to {@code int}.
626      * This is the reduced type polymorphism used by private methods
627      * such as {@link MethodHandle#invokeBasic invokeBasic}.
628      * @return a version of the original type with all reference and subword types replaced
629      *
630     /*non-public* MethodType basicType() {
631         return form.basicType();
632     }
633 
634     /**
635      * @return a version of the original type with MethodHandle prepended as the first argument
636      *
637     /*non-public* MethodType invokerType() {
638         return insertParameterTypes(0, MethodHandle.class);
639     }
640     */
641     // END Android-removed: Implementation methods unused on Android.
642 
643     /**
644      * Converts all types, both reference and primitive, to {@code Object}.
645      * Convenience method for {@link #genericMethodType(int) genericMethodType}.
646      * The expression {@code type.wrap().erase()} produces the same value
647      * as {@code type.generic()}.
648      * @return a version of the original type with all types replaced
649      */
generic()650     public MethodType generic() {
651         return genericMethodType(parameterCount());
652     }
653 
isGeneric()654     /*non-public*/ boolean isGeneric() {
655         return this == erase() && !hasPrimitives();
656     }
657 
658     /**
659      * Converts all primitive types to their corresponding wrapper types.
660      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
661      * All reference types (including wrapper types) will remain unchanged.
662      * A {@code void} return type is changed to the type {@code java.lang.Void}.
663      * The expression {@code type.wrap().erase()} produces the same value
664      * as {@code type.generic()}.
665      * @return a version of the original type with all primitive types replaced
666      */
wrap()667     public MethodType wrap() {
668         return hasPrimitives() ? wrapWithPrims(this) : this;
669     }
670 
671     /**
672      * Converts all wrapper types to their corresponding primitive types.
673      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
674      * All primitive types (including {@code void}) will remain unchanged.
675      * A return type of {@code java.lang.Void} is changed to {@code void}.
676      * @return a version of the original type with all wrapper types replaced
677      */
unwrap()678     public MethodType unwrap() {
679         MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
680         return unwrapWithNoPrims(noprims);
681     }
682 
wrapWithPrims(MethodType pt)683     private static MethodType wrapWithPrims(MethodType pt) {
684         assert(pt.hasPrimitives());
685         MethodType wt = pt.wrapAlt;
686         if (wt == null) {
687             // fill in lazily
688             wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP);
689             assert(wt != null);
690             pt.wrapAlt = wt;
691         }
692         return wt;
693     }
694 
unwrapWithNoPrims(MethodType wt)695     private static MethodType unwrapWithNoPrims(MethodType wt) {
696         assert(!wt.hasPrimitives());
697         MethodType uwt = wt.wrapAlt;
698         if (uwt == null) {
699             // fill in lazily
700             uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP);
701             if (uwt == null)
702                 uwt = wt;    // type has no wrappers or prims at all
703             wt.wrapAlt = uwt;
704         }
705         return uwt;
706     }
707 
708     /**
709      * Returns the parameter type at the specified index, within this method type.
710      * @param num the index (zero-based) of the desired parameter type
711      * @return the selected parameter type
712      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
713      */
parameterType(int num)714     public Class<?> parameterType(int num) {
715         return ptypes[num];
716     }
717     /**
718      * Returns the number of parameter types in this method type.
719      * @return the number of parameter types
720      */
parameterCount()721     public int parameterCount() {
722         return ptypes.length;
723     }
724     /**
725      * Returns the return type of this method type.
726      * @return the return type
727      */
returnType()728     public Class<?> returnType() {
729         return rtype;
730     }
731 
732     /**
733      * Presents the parameter types as a list (a convenience method).
734      * The list will be immutable.
735      * @return the parameter types (as an immutable list)
736      */
parameterList()737     public List<Class<?>> parameterList() {
738         return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
739     }
740 
lastParameterType()741     /*non-public*/ Class<?> lastParameterType() {
742         int len = ptypes.length;
743         return len == 0 ? void.class : ptypes[len-1];
744     }
745 
746     /**
747      * Presents the parameter types as an array (a convenience method).
748      * Changes to the array will not result in changes to the type.
749      * @return the parameter types (as a fresh copy if necessary)
750      */
parameterArray()751     public Class<?>[] parameterArray() {
752         return ptypes.clone();
753     }
754 
755     /**
756      * Compares the specified object with this type for equality.
757      * That is, it returns <tt>true</tt> if and only if the specified object
758      * is also a method type with exactly the same parameters and return type.
759      * @param x object to compare
760      * @see Object#equals(Object)
761      */
762     @Override
equals(Object x)763     public boolean equals(Object x) {
764         return this == x || x instanceof MethodType && equals((MethodType)x);
765     }
766 
equals(MethodType that)767     private boolean equals(MethodType that) {
768         return this.rtype == that.rtype
769             && Arrays.equals(this.ptypes, that.ptypes);
770     }
771 
772     /**
773      * Returns the hash code value for this method type.
774      * It is defined to be the same as the hashcode of a List
775      * whose elements are the return type followed by the
776      * parameter types.
777      * @return the hash code value for this method type
778      * @see Object#hashCode()
779      * @see #equals(Object)
780      * @see List#hashCode()
781      */
782     @Override
hashCode()783     public int hashCode() {
784       int hashCode = 31 + rtype.hashCode();
785       for (Class<?> ptype : ptypes)
786           hashCode = 31*hashCode + ptype.hashCode();
787       return hashCode;
788     }
789 
790     /**
791      * Returns a string representation of the method type,
792      * of the form {@code "(PT0,PT1...)RT"}.
793      * The string representation of a method type is a
794      * parenthesis enclosed, comma separated list of type names,
795      * followed immediately by the return type.
796      * <p>
797      * Each type is represented by its
798      * {@link java.lang.Class#getSimpleName simple name}.
799      */
800     @Override
toString()801     public String toString() {
802         StringBuilder sb = new StringBuilder();
803         sb.append("(");
804         for (int i = 0; i < ptypes.length; i++) {
805             if (i > 0)  sb.append(",");
806             sb.append(ptypes[i].getSimpleName());
807         }
808         sb.append(")");
809         sb.append(rtype.getSimpleName());
810         return sb.toString();
811     }
812 
813     // BEGIN Android-removed: Implementation methods unused on Android.
814     /*
815     /** True if the old return type can always be viewed (w/o casting) under new return type,
816      *  and the new parameters can be viewed (w/o casting) under the old parameter types.
817      *
818     /*non-public*
819     boolean isViewableAs(MethodType newType, boolean keepInterfaces) {
820         if (!VerifyType.isNullConversion(returnType(), newType.returnType(), keepInterfaces))
821             return false;
822         return parametersAreViewableAs(newType, keepInterfaces);
823     }
824     /** True if the new parameters can be viewed (w/o casting) under the old parameter types. *
825     /*non-public*
826     boolean parametersAreViewableAs(MethodType newType, boolean keepInterfaces) {
827         if (form == newType.form && form.erasedType == this)
828             return true;  // my reference parameters are all Object
829         if (ptypes == newType.ptypes)
830             return true;
831         int argc = parameterCount();
832         if (argc != newType.parameterCount())
833             return false;
834         for (int i = 0; i < argc; i++) {
835             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i), keepInterfaces))
836                 return false;
837         }
838         return true;
839     }
840     */
841     // END Android-removed: Implementation methods unused on Android.
842 
843     /*non-public*/
isConvertibleTo(MethodType newType)844     boolean isConvertibleTo(MethodType newType) {
845         MethodTypeForm oldForm = this.form();
846         MethodTypeForm newForm = newType.form();
847         if (oldForm == newForm)
848             // same parameter count, same primitive/object mix
849             return true;
850         if (!canConvert(returnType(), newType.returnType()))
851             return false;
852         Class<?>[] srcTypes = newType.ptypes;
853         Class<?>[] dstTypes = ptypes;
854         if (srcTypes == dstTypes)
855             return true;
856         int argc;
857         if ((argc = srcTypes.length) != dstTypes.length)
858             return false;
859         if (argc <= 1) {
860             if (argc == 1 && !canConvert(srcTypes[0], dstTypes[0]))
861                 return false;
862             return true;
863         }
864         if ((oldForm.primitiveParameterCount() == 0 && oldForm.erasedType == this) ||
865             (newForm.primitiveParameterCount() == 0 && newForm.erasedType == newType)) {
866             // Somewhat complicated test to avoid a loop of 2 or more trips.
867             // If either type has only Object parameters, we know we can convert.
868             assert(canConvertParameters(srcTypes, dstTypes));
869             return true;
870         }
871         return canConvertParameters(srcTypes, dstTypes);
872     }
873 
874     /** Returns true if MHs.explicitCastArguments produces the same result as MH.asType.
875      *  If the type conversion is impossible for either, the result should be false.
876      */
877     /*non-public*/
explicitCastEquivalentToAsType(MethodType newType)878     boolean explicitCastEquivalentToAsType(MethodType newType) {
879         if (this == newType)  return true;
880         if (!explicitCastEquivalentToAsType(rtype, newType.rtype)) {
881             return false;
882         }
883         Class<?>[] srcTypes = newType.ptypes;
884         Class<?>[] dstTypes = ptypes;
885         if (dstTypes == srcTypes) {
886             return true;
887         }
888         assert(dstTypes.length == srcTypes.length);
889         for (int i = 0; i < dstTypes.length; i++) {
890             if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) {
891                 return false;
892             }
893         }
894         return true;
895     }
896 
897     /** Reports true if the src can be converted to the dst, by both asType and MHs.eCE,
898      *  and with the same effect.
899      *  MHs.eCA has the following "upgrades" to MH.asType:
900      *  1. interfaces are unchecked (that is, treated as if aliased to Object)
901      *     Therefore, {@code Object->CharSequence} is possible in both cases but has different semantics
902      *  2a. the full matrix of primitive-to-primitive conversions is supported
903      *      Narrowing like {@code long->byte} and basic-typing like {@code boolean->int}
904      *      are not supported by asType, but anything supported by asType is equivalent
905      *      with MHs.eCE.
906      *  2b. conversion of void->primitive means explicit cast has to insert zero/false/null.
907      *  3a. unboxing conversions can be followed by the full matrix of primitive conversions
908      *  3b. unboxing of null is permitted (creates a zero primitive value)
909      * Other than interfaces, reference-to-reference conversions are the same.
910      * Boxing primitives to references is the same for both operators.
911      */
explicitCastEquivalentToAsType(Class<?> src, Class<?> dst)912     private static boolean explicitCastEquivalentToAsType(Class<?> src, Class<?> dst) {
913         if (src == dst || dst == Object.class || dst == void.class)  return true;
914         if (src.isPrimitive()) {
915             // Could be a prim/prim conversion, where casting is a strict superset.
916             // Or a boxing conversion, which is always to an exact wrapper class.
917             return canConvert(src, dst);
918         } else if (dst.isPrimitive()) {
919             // Unboxing behavior is different between MHs.eCA & MH.asType (see 3b).
920             return false;
921         } else {
922             // R->R always works, but we have to avoid a check-cast to an interface.
923             return !dst.isInterface() || dst.isAssignableFrom(src);
924         }
925     }
926 
canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes)927     private boolean canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes) {
928         for (int i = 0; i < srcTypes.length; i++) {
929             if (!canConvert(srcTypes[i], dstTypes[i])) {
930                 return false;
931             }
932         }
933         return true;
934     }
935 
936     /*non-public*/
canConvert(Class<?> src, Class<?> dst)937     static boolean canConvert(Class<?> src, Class<?> dst) {
938         // short-circuit a few cases:
939         if (src == dst || src == Object.class || dst == Object.class)  return true;
940         // the remainder of this logic is documented in MethodHandle.asType
941         if (src.isPrimitive()) {
942             // can force void to an explicit null, a la reflect.Method.invoke
943             // can also force void to a primitive zero, by analogy
944             if (src == void.class)  return true;  //or !dst.isPrimitive()?
945             Wrapper sw = Wrapper.forPrimitiveType(src);
946             if (dst.isPrimitive()) {
947                 // P->P must widen
948                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
949             } else {
950                 // P->R must box and widen
951                 return dst.isAssignableFrom(sw.wrapperType());
952             }
953         } else if (dst.isPrimitive()) {
954             // any value can be dropped
955             if (dst == void.class)  return true;
956             Wrapper dw = Wrapper.forPrimitiveType(dst);
957             // R->P must be able to unbox (from a dynamically chosen type) and widen
958             // For example:
959             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
960             //   Character/Comparable/Object -> dw:Character -> char
961             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
962             // This means that dw must be cast-compatible with src.
963             if (src.isAssignableFrom(dw.wrapperType())) {
964                 return true;
965             }
966             // The above does not work if the source reference is strongly typed
967             // to a wrapper whose primitive must be widened.  For example:
968             //   Byte -> unbox:byte -> short/int/long/float/double
969             //   Character -> unbox:char -> int/long/float/double
970             if (Wrapper.isWrapperType(src) &&
971                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
972                 // can unbox from src and then widen to dst
973                 return true;
974             }
975             // We have already covered cases which arise due to runtime unboxing
976             // of a reference type which covers several wrapper types:
977             //   Object -> cast:Integer -> unbox:int -> long/float/double
978             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
979             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
980             // subclass of Number which wraps a value that can convert to char.
981             // Since there is none, we don't need an extra check here to cover char or boolean.
982             return false;
983         } else {
984             // R->R always works, since null is always valid dynamically
985             return true;
986         }
987     }
988 
989     /// Queries which have to do with the bytecode architecture
990 
991     /** Reports the number of JVM stack slots required to invoke a method
992      * of this type.  Note that (for historical reasons) the JVM requires
993      * a second stack slot to pass long and double arguments.
994      * So this method returns {@link #parameterCount() parameterCount} plus the
995      * number of long and double parameters (if any).
996      * <p>
997      * This method is included for the benefit of applications that must
998      * generate bytecodes that process method handles and invokedynamic.
999      * @return the number of JVM stack slots for this type's parameters
1000      */
parameterSlotCount()1001     /*non-public*/ int parameterSlotCount() {
1002         return form.parameterSlotCount();
1003     }
1004 
1005     // BEGIN Android-removed: Cache of higher order adapters.
1006     /*
1007     /*non-public* Invokers invokers() {
1008         Invokers inv = invokers;
1009         if (inv != null)  return inv;
1010         invokers = inv = new Invokers(this);
1011         return inv;
1012     }
1013     */
1014     // END Android-removed: Cache of higher order adapters.
1015 
1016     // BEGIN Android-removed: Implementation methods unused on Android.
1017     /*
1018     /** Reports the number of JVM stack slots which carry all parameters including and after
1019      * the given position, which must be in the range of 0 to
1020      * {@code parameterCount} inclusive.  Successive parameters are
1021      * more shallowly stacked, and parameters are indexed in the bytecodes
1022      * according to their trailing edge.  Thus, to obtain the depth
1023      * in the outgoing call stack of parameter {@code N}, obtain
1024      * the {@code parameterSlotDepth} of its trailing edge
1025      * at position {@code N+1}.
1026      * <p>
1027      * Parameters of type {@code long} and {@code double} occupy
1028      * two stack slots (for historical reasons) and all others occupy one.
1029      * Therefore, the number returned is the number of arguments
1030      * <em>including</em> and <em>after</em> the given parameter,
1031      * <em>plus</em> the number of long or double arguments
1032      * at or after after the argument for the given parameter.
1033      * <p>
1034      * This method is included for the benefit of applications that must
1035      * generate bytecodes that process method handles and invokedynamic.
1036      * @param num an index (zero-based, inclusive) within the parameter types
1037      * @return the index of the (shallowest) JVM stack slot transmitting the
1038      *         given parameter
1039      * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
1040      *
1041     /*non-public* int parameterSlotDepth(int num) {
1042         if (num < 0 || num > ptypes.length)
1043             parameterType(num);  // force a range check
1044         return form.parameterToArgSlot(num-1);
1045     }
1046 
1047     /** Reports the number of JVM stack slots required to receive a return value
1048      * from a method of this type.
1049      * If the {@link #returnType() return type} is void, it will be zero,
1050      * else if the return type is long or double, it will be two, else one.
1051      * <p>
1052      * This method is included for the benefit of applications that must
1053      * generate bytecodes that process method handles and invokedynamic.
1054      * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
1055      * Will be removed for PFD.
1056      *
1057     /*non-public* int returnSlotCount() {
1058         return form.returnSlotCount();
1059     }
1060     */
1061     // END Android-removed: Implementation methods unused on Android.
1062 
1063     /**
1064      * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
1065      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
1066      * Any class or interface name embedded in the descriptor string
1067      * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
1068      * on the given loader (or if it is null, on the system class loader).
1069      * <p>
1070      * Note that it is possible to encounter method types which cannot be
1071      * constructed by this method, because their component types are
1072      * not all reachable from a common class loader.
1073      * <p>
1074      * This method is included for the benefit of applications that must
1075      * generate bytecodes that process method handles and {@code invokedynamic}.
1076      * @param descriptor a bytecode-level type descriptor string "(T...)T"
1077      * @param loader the class loader in which to look up the types
1078      * @return a method type matching the bytecode-level type descriptor
1079      * @throws NullPointerException if the string is null
1080      * @throws IllegalArgumentException if the string is not well-formed
1081      * @throws TypeNotPresentException if a named type cannot be found
1082      */
fromMethodDescriptorString(String descriptor, ClassLoader loader)1083     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
1084         throws IllegalArgumentException, TypeNotPresentException
1085     {
1086         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
1087             descriptor.indexOf(')') < 0 ||
1088             descriptor.indexOf('.') >= 0)
1089             throw newIllegalArgumentException("not a method descriptor: "+descriptor);
1090         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
1091         Class<?> rtype = types.remove(types.size() - 1);
1092         checkSlotCount(types.size());
1093         Class<?>[] ptypes = listToArray(types);
1094         return makeImpl(rtype, ptypes, true);
1095     }
1096 
1097     /**
1098      * Produces a bytecode descriptor representation of the method type.
1099      * <p>
1100      * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
1101      * Two distinct classes which share a common name but have different class loaders
1102      * will appear identical when viewed within descriptor strings.
1103      * <p>
1104      * This method is included for the benefit of applications that must
1105      * generate bytecodes that process method handles and {@code invokedynamic}.
1106      * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
1107      * because the latter requires a suitable class loader argument.
1108      * @return the bytecode type descriptor representation
1109      */
toMethodDescriptorString()1110     public String toMethodDescriptorString() {
1111         String desc = methodDescriptor;
1112         if (desc == null) {
1113             desc = BytecodeDescriptor.unparse(this);
1114             methodDescriptor = desc;
1115         }
1116         return desc;
1117     }
1118 
toFieldDescriptorString(Class<?> cls)1119     /*non-public*/ static String toFieldDescriptorString(Class<?> cls) {
1120         return BytecodeDescriptor.unparse(cls);
1121     }
1122 
1123     /// Serialization.
1124 
1125     /**
1126      * There are no serializable fields for {@code MethodType}.
1127      */
1128     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
1129 
1130     /**
1131      * Save the {@code MethodType} instance to a stream.
1132      *
1133      * @serialData
1134      * For portability, the serialized format does not refer to named fields.
1135      * Instead, the return type and parameter type arrays are written directly
1136      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
1137      * as follows:
1138      * <blockquote><pre>{@code
1139 s.writeObject(this.returnType());
1140 s.writeObject(this.parameterArray());
1141      * }</pre></blockquote>
1142      * <p>
1143      * The deserialized field values are checked as if they were
1144      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
1145      * For example, null values, or {@code void} parameter types,
1146      * will lead to exceptions during deserialization.
1147      * @param s the stream to write the object to
1148      * @throws java.io.IOException if there is a problem writing the object
1149      */
writeObject(java.io.ObjectOutputStream s)1150     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
1151         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
1152         s.writeObject(returnType());
1153         s.writeObject(parameterArray());
1154     }
1155 
1156     /**
1157      * Reconstitute the {@code MethodType} instance from a stream (that is,
1158      * deserialize it).
1159      * This instance is a scratch object with bogus final fields.
1160      * It provides the parameters to the factory method called by
1161      * {@link #readResolve readResolve}.
1162      * After that call it is discarded.
1163      * @param s the stream to read the object from
1164      * @throws java.io.IOException if there is a problem reading the object
1165      * @throws ClassNotFoundException if one of the component classes cannot be resolved
1166      * @see #MethodType()
1167      * @see #readResolve
1168      * @see #writeObject
1169      */
readObject(java.io.ObjectInputStream s)1170     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
1171         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
1172 
1173         Class<?>   returnType     = (Class<?>)   s.readObject();
1174         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
1175 
1176         // Probably this object will never escape, but let's check
1177         // the field values now, just to be sure.
1178         checkRtype(returnType);
1179         checkPtypes(parameterArray);
1180 
1181         parameterArray = parameterArray.clone();  // make sure it is unshared
1182         MethodType_init(returnType, parameterArray);
1183     }
1184 
1185     /**
1186      * For serialization only.
1187      * Sets the final fields to null, pending {@code Unsafe.putObject}.
1188      */
MethodType()1189     private MethodType() {
1190         this.rtype = null;
1191         this.ptypes = null;
1192     }
MethodType_init(Class<?> rtype, Class<?>[] ptypes)1193     private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
1194         // In order to communicate these values to readResolve, we must
1195         // store them into the implementation-specific final fields.
1196         checkRtype(rtype);
1197         checkPtypes(ptypes);
1198         UNSAFE.putObject(this, rtypeOffset, rtype);
1199         UNSAFE.putObject(this, ptypesOffset, ptypes);
1200     }
1201 
1202     // Support for resetting final fields while deserializing
1203     private static final long rtypeOffset, ptypesOffset;
1204     static {
1205         try {
1206             rtypeOffset = UNSAFE.objectFieldOffset
1207                 (MethodType.class.getDeclaredField("rtype"));
1208             ptypesOffset = UNSAFE.objectFieldOffset
1209                 (MethodType.class.getDeclaredField("ptypes"));
1210         } catch (Exception ex) {
1211             throw new Error(ex);
1212         }
1213     }
1214 
1215     /**
1216      * Resolves and initializes a {@code MethodType} object
1217      * after serialization.
1218      * @return the fully initialized {@code MethodType} object
1219      */
readResolve()1220     private Object readResolve() {
1221         // Do not use a trusted path for deserialization:
1222         //return makeImpl(rtype, ptypes, true);
1223         // Verify all operands, and make sure ptypes is unshared:
1224         return methodType(rtype, ptypes);
1225     }
1226 
1227     /**
1228      * Simple implementation of weak concurrent intern set.
1229      *
1230      * @param <T> interned type
1231      */
1232     private static class ConcurrentWeakInternSet<T> {
1233 
1234         private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
1235         private final ReferenceQueue<T> stale;
1236 
ConcurrentWeakInternSet()1237         public ConcurrentWeakInternSet() {
1238             this.map = new ConcurrentHashMap<>();
1239             this.stale = new ReferenceQueue<>();
1240         }
1241 
1242         /**
1243          * Get the existing interned element.
1244          * This method returns null if no element is interned.
1245          *
1246          * @param elem element to look up
1247          * @return the interned element
1248          */
get(T elem)1249         public T get(T elem) {
1250             if (elem == null) throw new NullPointerException();
1251             expungeStaleElements();
1252 
1253             WeakEntry<T> value = map.get(new WeakEntry<>(elem));
1254             if (value != null) {
1255                 T res = value.get();
1256                 if (res != null) {
1257                     return res;
1258                 }
1259             }
1260             return null;
1261         }
1262 
1263         /**
1264          * Interns the element.
1265          * Always returns non-null element, matching the one in the intern set.
1266          * Under the race against another add(), it can return <i>different</i>
1267          * element, if another thread beats us to interning it.
1268          *
1269          * @param elem element to add
1270          * @return element that was actually added
1271          */
add(T elem)1272         public T add(T elem) {
1273             if (elem == null) throw new NullPointerException();
1274 
1275             // Playing double race here, and so spinloop is required.
1276             // First race is with two concurrent updaters.
1277             // Second race is with GC purging weak ref under our feet.
1278             // Hopefully, we almost always end up with a single pass.
1279             T interned;
1280             WeakEntry<T> e = new WeakEntry<>(elem, stale);
1281             do {
1282                 expungeStaleElements();
1283                 WeakEntry<T> exist = map.putIfAbsent(e, e);
1284                 interned = (exist == null) ? elem : exist.get();
1285             } while (interned == null);
1286             return interned;
1287         }
1288 
expungeStaleElements()1289         private void expungeStaleElements() {
1290             Reference<? extends T> reference;
1291             while ((reference = stale.poll()) != null) {
1292                 map.remove(reference);
1293             }
1294         }
1295 
1296         private static class WeakEntry<T> extends WeakReference<T> {
1297 
1298             public final int hashcode;
1299 
WeakEntry(T key, ReferenceQueue<T> queue)1300             public WeakEntry(T key, ReferenceQueue<T> queue) {
1301                 super(key, queue);
1302                 hashcode = key.hashCode();
1303             }
1304 
WeakEntry(T key)1305             public WeakEntry(T key) {
1306                 super(key);
1307                 hashcode = key.hashCode();
1308             }
1309 
1310             @Override
equals(Object obj)1311             public boolean equals(Object obj) {
1312                 if (obj instanceof WeakEntry) {
1313                     Object that = ((WeakEntry) obj).get();
1314                     Object mine = get();
1315                     return (that == null || mine == null) ? (this == obj) : mine.equals(that);
1316                 }
1317                 return false;
1318             }
1319 
1320             @Override
hashCode()1321             public int hashCode() {
1322                 return hashcode;
1323             }
1324 
1325         }
1326     }
1327 
1328 }
1329