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