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