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