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