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 assert(dstTypes.length == srcTypes.length); 873 for (int i = 0; i < dstTypes.length; i++) { 874 if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) { 875 return false; 876 } 877 } 878 return true; 879 } 880 881 /** Reports true if the src can be converted to the dst, by both asType and MHs.eCE, 882 * and with the same effect. 883 * MHs.eCA has the following "upgrades" to MH.asType: 884 * 1. interfaces are unchecked (that is, treated as if aliased to Object) 885 * Therefore, {@code Object->CharSequence} is possible in both cases but has different semantics 886 * 2. the full matrix of primitive-to-primitive conversions is supported 887 * Narrowing like {@code long->byte} and basic-typing like {@code boolean->int} 888 * are not supported by asType, but anything supported by asType is equivalent 889 * with MHs.eCE. 890 * 3a. unboxing conversions can be followed by the full matrix of primitive conversions 891 * 3b. unboxing of null is permitted (creates a zero primitive value) 892 * Other than interfaces, reference-to-reference conversions are the same. 893 * Boxing primitives to references is the same for both operators. 894 */ 895 private static boolean explicitCastEquivalentToAsType(Class<?> src, Class<?> dst) { 896 if (src == dst || dst == Object.class || dst == void.class) return true; 897 if (src.isPrimitive()) { 898 // Could be a prim/prim conversion, where casting is a strict superset. 899 // Or a boxing conversion, which is always to an exact wrapper class. 900 return canConvert(src, dst); 901 } else if (dst.isPrimitive()) { 902 // Unboxing behavior is different between MHs.eCA & MH.asType (see 3b). 903 return false; 904 } else { 905 // R->R always works, but we have to avoid a check-cast to an interface. 906 return !dst.isInterface() || dst.isAssignableFrom(src); 907 } 908 } 909 910 private boolean canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes) { 911 for (int i = 0; i < srcTypes.length; i++) { 912 if (!canConvert(srcTypes[i], dstTypes[i])) { 913 return false; 914 } 915 } 916 return true; 917 } 918 919 /*non-public*/ 920 static boolean canConvert(Class<?> src, Class<?> dst) { 921 // short-circuit a few cases: 922 if (src == dst || src == Object.class || dst == Object.class) return true; 923 // the remainder of this logic is documented in MethodHandle.asType 924 if (src.isPrimitive()) { 925 // can force void to an explicit null, a la reflect.Method.invoke 926 // can also force void to a primitive zero, by analogy 927 if (src == void.class) return true; //or !dst.isPrimitive()? 928 Wrapper sw = Wrapper.forPrimitiveType(src); 929 if (dst.isPrimitive()) { 930 // P->P must widen 931 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw); 932 } else { 933 // P->R must box and widen 934 return dst.isAssignableFrom(sw.wrapperType()); 935 } 936 } else if (dst.isPrimitive()) { 937 // any value can be dropped 938 if (dst == void.class) return true; 939 Wrapper dw = Wrapper.forPrimitiveType(dst); 940 // R->P must be able to unbox (from a dynamically chosen type) and widen 941 // For example: 942 // Byte/Number/Comparable/Object -> dw:Byte -> byte. 943 // Character/Comparable/Object -> dw:Character -> char 944 // Boolean/Comparable/Object -> dw:Boolean -> boolean 945 // This means that dw must be cast-compatible with src. 946 if (src.isAssignableFrom(dw.wrapperType())) { 947 return true; 948 } 949 // The above does not work if the source reference is strongly typed 950 // to a wrapper whose primitive must be widened. For example: 951 // Byte -> unbox:byte -> short/int/long/float/double 952 // Character -> unbox:char -> int/long/float/double 953 if (Wrapper.isWrapperType(src) && 954 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) { 955 // can unbox from src and then widen to dst 956 return true; 957 } 958 // We have already covered cases which arise due to runtime unboxing 959 // of a reference type which covers several wrapper types: 960 // Object -> cast:Integer -> unbox:int -> long/float/double 961 // Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double 962 // An marginal case is Number -> dw:Character -> char, which would be OK if there were a 963 // subclass of Number which wraps a value that can convert to char. 964 // Since there is none, we don't need an extra check here to cover char or boolean. 965 return false; 966 } else { 967 // R->R always works, since null is always valid dynamically 968 return true; 969 } 970 } 971 972 /// Queries which have to do with the bytecode architecture 973 974 /** Reports the number of JVM stack slots required to invoke a method 975 * of this type. Note that (for historical reasons) the JVM requires 976 * a second stack slot to pass long and double arguments. 977 * So this method returns {@link #parameterCount() parameterCount} plus the 978 * number of long and double parameters (if any). 979 * <p> 980 * This method is included for the benefit of applications that must 981 * generate bytecodes that process method handles and invokedynamic. 982 * @return the number of JVM stack slots for this type's parameters 983 */ 984 /*non-public*/ int parameterSlotCount() { 985 return form.parameterSlotCount(); 986 } 987 988 /*non-public*/ Invokers invokers() { 989 Invokers inv = invokers; 990 if (inv != null) return inv; 991 invokers = inv = new Invokers(this); 992 return inv; 993 } 994 995 /** Reports the number of JVM stack slots which carry all parameters including and after 996 * the given position, which must be in the range of 0 to 997 * {@code parameterCount} inclusive. Successive parameters are 998 * more shallowly stacked, and parameters are indexed in the bytecodes 999 * according to their trailing edge. Thus, to obtain the depth 1000 * in the outgoing call stack of parameter {@code N}, obtain 1001 * the {@code parameterSlotDepth} of its trailing edge 1002 * at position {@code N+1}. 1003 * <p> 1004 * Parameters of type {@code long} and {@code double} occupy 1005 * two stack slots (for historical reasons) and all others occupy one. 1006 * Therefore, the number returned is the number of arguments 1007 * <em>including</em> and <em>after</em> the given parameter, 1008 * <em>plus</em> the number of long or double arguments 1009 * at or after after the argument for the given parameter. 1010 * <p> 1011 * This method is included for the benefit of applications that must 1012 * generate bytecodes that process method handles and invokedynamic. 1013 * @param num an index (zero-based, inclusive) within the parameter types 1014 * @return the index of the (shallowest) JVM stack slot transmitting the 1015 * given parameter 1016 * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()} 1017 */ 1018 /*non-public*/ int parameterSlotDepth(int num) { 1019 if (num < 0 || num > ptypes.length) 1020 parameterType(num); // force a range check 1021 return form.parameterToArgSlot(num-1); 1022 } 1023 1024 /** Reports the number of JVM stack slots required to receive a return value 1025 * from a method of this type. 1026 * If the {@link #returnType() return type} is void, it will be zero, 1027 * else if the return type is long or double, it will be two, else one. 1028 * <p> 1029 * This method is included for the benefit of applications that must 1030 * generate bytecodes that process method handles and invokedynamic. 1031 * @return the number of JVM stack slots (0, 1, or 2) for this type's return value 1032 * Will be removed for PFD. 1033 */ 1034 /*non-public*/ int returnSlotCount() { 1035 return form.returnSlotCount(); 1036 } 1037 1038 /** 1039 * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor. 1040 * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. 1041 * Any class or interface name embedded in the descriptor string 1042 * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)} 1043 * on the given loader (or if it is null, on the system class loader). 1044 * <p> 1045 * Note that it is possible to encounter method types which cannot be 1046 * constructed by this method, because their component types are 1047 * not all reachable from a common class loader. 1048 * <p> 1049 * This method is included for the benefit of applications that must 1050 * generate bytecodes that process method handles and {@code invokedynamic}. 1051 * @param descriptor a bytecode-level type descriptor string "(T...)T" 1052 * @param loader the class loader in which to look up the types 1053 * @return a method type matching the bytecode-level type descriptor 1054 * @throws NullPointerException if the string is null 1055 * @throws IllegalArgumentException if the string is not well-formed 1056 * @throws TypeNotPresentException if a named type cannot be found 1057 */ 1058 public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader) 1059 throws IllegalArgumentException, TypeNotPresentException 1060 { 1061 if (!descriptor.startsWith("(") || // also generates NPE if needed 1062 descriptor.indexOf(')') < 0 || 1063 descriptor.indexOf('.') >= 0) 1064 throw newIllegalArgumentException("not a method descriptor: "+descriptor); 1065 List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader); 1066 Class<?> rtype = types.remove(types.size() - 1); 1067 checkSlotCount(types.size()); 1068 Class<?>[] ptypes = listToArray(types); 1069 return makeImpl(rtype, ptypes, true); 1070 } 1071 1072 /** 1073 * Produces a bytecode descriptor representation of the method type. 1074 * <p> 1075 * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}. 1076 * Two distinct classes which share a common name but have different class loaders 1077 * will appear identical when viewed within descriptor strings. 1078 * <p> 1079 * This method is included for the benefit of applications that must 1080 * generate bytecodes that process method handles and {@code invokedynamic}. 1081 * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString}, 1082 * because the latter requires a suitable class loader argument. 1083 * @return the bytecode type descriptor representation 1084 */ 1085 public String toMethodDescriptorString() { 1086 String desc = methodDescriptor; 1087 if (desc == null) { 1088 desc = BytecodeDescriptor.unparse(this); 1089 methodDescriptor = desc; 1090 } 1091 return desc; 1092 } 1093 1094 /*non-public*/ static String toFieldDescriptorString(Class<?> cls) { 1095 return BytecodeDescriptor.unparse(cls); 1096 } 1097 1098 /// Serialization. 1099 1100 /** 1101 * There are no serializable fields for {@code MethodType}. 1102 */ 1103 private static final java.io.ObjectStreamField[] serialPersistentFields = { }; 1104 1105 /** 1106 * Save the {@code MethodType} instance to a stream. 1107 * 1108 * @serialData 1109 * For portability, the serialized format does not refer to named fields. 1110 * Instead, the return type and parameter type arrays are written directly 1111 * from the {@code writeObject} method, using two calls to {@code s.writeObject} 1112 * as follows: 1113 * <blockquote><pre>{@code 1114 s.writeObject(this.returnType()); 1115 s.writeObject(this.parameterArray()); 1116 * }</pre></blockquote> 1117 * <p> 1118 * The deserialized field values are checked as if they were 1119 * provided to the factory method {@link #methodType(Class,Class[]) methodType}. 1120 * For example, null values, or {@code void} parameter types, 1121 * will lead to exceptions during deserialization. 1122 * @param s the stream to write the object to 1123 * @throws java.io.IOException if there is a problem writing the object 1124 */ 1125 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { 1126 s.defaultWriteObject(); // requires serialPersistentFields to be an empty array 1127 s.writeObject(returnType()); 1128 s.writeObject(parameterArray()); 1129 } 1130 1131 /** 1132 * Reconstitute the {@code MethodType} instance from a stream (that is, 1133 * deserialize it). 1134 * This instance is a scratch object with bogus final fields. 1135 * It provides the parameters to the factory method called by 1136 * {@link #readResolve readResolve}. 1137 * After that call it is discarded. 1138 * @param s the stream to read the object from 1139 * @throws java.io.IOException if there is a problem reading the object 1140 * @throws ClassNotFoundException if one of the component classes cannot be resolved 1141 * @see #MethodType() 1142 * @see #readResolve 1143 * @see #writeObject 1144 */ 1145 private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { 1146 s.defaultReadObject(); // requires serialPersistentFields to be an empty array 1147 1148 Class<?> returnType = (Class<?>) s.readObject(); 1149 Class<?>[] parameterArray = (Class<?>[]) s.readObject(); 1150 1151 // Probably this object will never escape, but let's check 1152 // the field values now, just to be sure. 1153 checkRtype(returnType); 1154 checkPtypes(parameterArray); 1155 1156 parameterArray = parameterArray.clone(); // make sure it is unshared 1157 MethodType_init(returnType, parameterArray); 1158 } 1159 1160 /** 1161 * For serialization only. 1162 * Sets the final fields to null, pending {@code Unsafe.putObject}. 1163 */ 1164 private MethodType() { 1165 this.rtype = null; 1166 this.ptypes = null; 1167 } 1168 private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) { 1169 // In order to communicate these values to readResolve, we must 1170 // store them into the implementation-specific final fields. 1171 checkRtype(rtype); 1172 checkPtypes(ptypes); 1173 UNSAFE.putObject(this, rtypeOffset, rtype); 1174 UNSAFE.putObject(this, ptypesOffset, ptypes); 1175 } 1176 1177 // Support for resetting final fields while deserializing 1178 private static final long rtypeOffset, ptypesOffset; 1179 static { 1180 try { 1181 rtypeOffset = UNSAFE.objectFieldOffset 1182 (MethodType.class.getDeclaredField("rtype")); 1183 ptypesOffset = UNSAFE.objectFieldOffset 1184 (MethodType.class.getDeclaredField("ptypes")); 1185 } catch (Exception ex) { 1186 throw new Error(ex); 1187 } 1188 } 1189 1190 /** 1191 * Resolves and initializes a {@code MethodType} object 1192 * after serialization. 1193 * @return the fully initialized {@code MethodType} object 1194 */ 1195 private Object readResolve() { 1196 // Do not use a trusted path for deserialization: 1197 //return makeImpl(rtype, ptypes, true); 1198 // Verify all operands, and make sure ptypes is unshared: 1199 return methodType(rtype, ptypes); 1200 } 1201 1202 /** 1203 * Simple implementation of weak concurrent intern set. 1204 * 1205 * @param <T> interned type 1206 */ 1207 private static class ConcurrentWeakInternSet<T> { 1208 1209 private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map; 1210 private final ReferenceQueue<T> stale; 1211 1212 public ConcurrentWeakInternSet() { 1213 this.map = new ConcurrentHashMap<>(); 1214 this.stale = new ReferenceQueue<>(); 1215 } 1216 1217 /** 1218 * Get the existing interned element. 1219 * This method returns null if no element is interned. 1220 * 1221 * @param elem element to look up 1222 * @return the interned element 1223 */ 1224 public T get(T elem) { 1225 if (elem == null) throw new NullPointerException(); 1226 expungeStaleElements(); 1227 1228 WeakEntry<T> value = map.get(new WeakEntry<>(elem)); 1229 if (value != null) { 1230 T res = value.get(); 1231 if (res != null) { 1232 return res; 1233 } 1234 } 1235 return null; 1236 } 1237 1238 /** 1239 * Interns the element. 1240 * Always returns non-null element, matching the one in the intern set. 1241 * Under the race against another add(), it can return <i>different</i> 1242 * element, if another thread beats us to interning it. 1243 * 1244 * @param elem element to add 1245 * @return element that was actually added 1246 */ 1247 public T add(T elem) { 1248 if (elem == null) throw new NullPointerException(); 1249 1250 // Playing double race here, and so spinloop is required. 1251 // First race is with two concurrent updaters. 1252 // Second race is with GC purging weak ref under our feet. 1253 // Hopefully, we almost always end up with a single pass. 1254 T interned; 1255 WeakEntry<T> e = new WeakEntry<>(elem, stale); 1256 do { 1257 expungeStaleElements(); 1258 WeakEntry<T> exist = map.putIfAbsent(e, e); 1259 interned = (exist == null) ? elem : exist.get(); 1260 } while (interned == null); 1261 return interned; 1262 } 1263 1264 private void expungeStaleElements() { 1265 Reference<? extends T> reference; 1266 while ((reference = stale.poll()) != null) { 1267 map.remove(reference); 1268 } 1269 } 1270 1271 private static class WeakEntry<T> extends WeakReference<T> { 1272 1273 public final int hashcode; 1274 1275 public WeakEntry(T key, ReferenceQueue<T> queue) { 1276 super(key, queue); 1277 hashcode = key.hashCode(); 1278 } 1279 1280 public WeakEntry(T key) { 1281 super(key); 1282 hashcode = key.hashCode(); 1283 } 1284 1285 @Override 1286 public boolean equals(Object obj) { 1287 if (obj instanceof WeakEntry) { 1288 Object that = ((WeakEntry) obj).get(); 1289 Object mine = get(); 1290 return (that == null || mine == null) ? (this == obj) : mine.equals(that); 1291 } 1292 return false; 1293 } 1294 1295 @Override 1296 public int hashCode() { 1297 return hashcode; 1298 } 1299 1300 } 1301 } 1302 1303 }