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