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