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