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