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