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