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