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