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