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