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