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