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