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