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