< prev index next >

src/java.base/share/classes/java/lang/invoke/MethodHandle.java

Print this page
rev 52865 : [mq]: 8210031


  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 
  29 import jdk.internal.HotSpotIntrinsicCandidate;
  30 






  31 import java.util.Arrays;
  32 import java.util.Objects;

  33 

  34 import static java.lang.invoke.MethodHandleStatics.*;

  35 
  36 /**
  37  * A method handle is a typed, directly executable reference to an underlying method,
  38  * constructor, field, or similar low-level operation, with optional
  39  * transformations of arguments or return values.
  40  * These transformations are quite general, and include such patterns as
  41  * {@linkplain #asType conversion},
  42  * {@linkplain #bindTo insertion},
  43  * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
  44  * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
  45  *
  46  * <h1>Method handle contents</h1>
  47  * Method handles are dynamically and strongly typed according to their parameter and return types.
  48  * They are not distinguished by the name or the defining class of their underlying methods.
  49  * A method handle must be invoked using a symbolic type descriptor which matches
  50  * the method handle's own {@linkplain #type() type descriptor}.
  51  * <p>
  52  * Every method handle reports its type descriptor via the {@link #type() type} accessor.
  53  * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
  54  * whose structure is a series of classes, one of which is


 411  * The JVM imposes on all methods and constructors of any kind an absolute
 412  * limit of 255 stacked arguments.  This limit can appear more restrictive
 413  * in certain cases:
 414  * <ul>
 415  * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
 416  * <li>A non-static method consumes an extra argument for the object on which the method is called.
 417  * <li>A constructor consumes an extra argument for the object which is being constructed.
 418  * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
 419  *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
 420  * </ul>
 421  * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
 422  * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
 423  * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
 424  * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
 425  *
 426  * @see MethodType
 427  * @see MethodHandles
 428  * @author John Rose, JSR 292 EG
 429  * @since 1.7
 430  */
 431 public abstract class MethodHandle {
 432 
 433     /**
 434      * Internal marker interface which distinguishes (to the Java compiler)
 435      * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
 436      */
 437     @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
 438     @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
 439     @interface PolymorphicSignature { }
 440 
 441     private final MethodType type;
 442     /*private*/ final LambdaForm form;
 443     // form is not private so that invokers can easily fetch it
 444     /*private*/ MethodHandle asTypeCache;
 445     // asTypeCache is not private so that invokers can easily fetch it
 446     /*non-public*/ byte customizationCount;
 447     // customizationCount should be accessible from invokers
 448 
 449     /**
 450      * Reports the type of this method handle.
 451      * Every invocation of this method handle via {@code invokeExact} must exactly match this type.


1492      * The reference {@code x} must be convertible to the first parameter
1493      * type of the target.
1494      * <p>
1495      * <em>Note:</em>  Because method handles are immutable, the target method handle
1496      * retains its original type and behavior.
1497      * <p>
1498      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
1499      * variable-arity method handle}, even if the original target method handle was.
1500      * @param x  the value to bind to the first argument of the target
1501      * @return a new method handle which prepends the given value to the incoming
1502      *         argument list, before calling the original method handle
1503      * @throws IllegalArgumentException if the target does not have a
1504      *         leading parameter type that is a reference type
1505      * @throws ClassCastException if {@code x} cannot be converted
1506      *         to the leading parameter type of the target
1507      * @see MethodHandles#insertArguments
1508      */
1509     public MethodHandle bindTo(Object x) {
1510         x = type.leadingReferenceParameter().cast(x);  // throw CCE if needed
1511         return bindArgumentL(0, x);






















































1512     }
1513 
1514     /**
1515      * Returns a string representation of the method handle,
1516      * starting with the string {@code "MethodHandle"} and
1517      * ending with the string representation of the method handle's type.
1518      * In other words, this method returns a string equal to the value of:
1519      * <blockquote><pre>{@code
1520      * "MethodHandle" + type().toString()
1521      * }</pre></blockquote>
1522      * <p>
1523      * (<em>Note:</em>  Future releases of this API may add further information
1524      * to the string representation.
1525      * Therefore, the present syntax should not be parsed by applications.)
1526      *
1527      * @return a string representation of the method handle
1528      */
1529     @Override
1530     public String toString() {
1531         if (DEBUG_METHOD_HANDLE_NAMES)  return "MethodHandle"+debugString();




  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 
  29 import jdk.internal.HotSpotIntrinsicCandidate;
  30 
  31 import java.lang.constant.ClassDesc;
  32 import java.lang.constant.Constable;
  33 import java.lang.constant.ConstantDesc;
  34 import java.lang.constant.DirectMethodHandleDesc;
  35 import java.lang.constant.MethodHandleDesc;
  36 import java.lang.constant.MethodTypeDesc;
  37 import java.util.Arrays;
  38 import java.util.Objects;
  39 import java.util.Optional;
  40 
  41 import static java.lang.invoke.MethodHandleInfo.*;
  42 import static java.lang.invoke.MethodHandleStatics.*;
  43 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  44 
  45 /**
  46  * A method handle is a typed, directly executable reference to an underlying method,
  47  * constructor, field, or similar low-level operation, with optional
  48  * transformations of arguments or return values.
  49  * These transformations are quite general, and include such patterns as
  50  * {@linkplain #asType conversion},
  51  * {@linkplain #bindTo insertion},
  52  * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
  53  * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
  54  *
  55  * <h1>Method handle contents</h1>
  56  * Method handles are dynamically and strongly typed according to their parameter and return types.
  57  * They are not distinguished by the name or the defining class of their underlying methods.
  58  * A method handle must be invoked using a symbolic type descriptor which matches
  59  * the method handle's own {@linkplain #type() type descriptor}.
  60  * <p>
  61  * Every method handle reports its type descriptor via the {@link #type() type} accessor.
  62  * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
  63  * whose structure is a series of classes, one of which is


 420  * The JVM imposes on all methods and constructors of any kind an absolute
 421  * limit of 255 stacked arguments.  This limit can appear more restrictive
 422  * in certain cases:
 423  * <ul>
 424  * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
 425  * <li>A non-static method consumes an extra argument for the object on which the method is called.
 426  * <li>A constructor consumes an extra argument for the object which is being constructed.
 427  * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
 428  *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
 429  * </ul>
 430  * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
 431  * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
 432  * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
 433  * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
 434  *
 435  * @see MethodType
 436  * @see MethodHandles
 437  * @author John Rose, JSR 292 EG
 438  * @since 1.7
 439  */
 440 public abstract class MethodHandle implements Constable {
 441 
 442     /**
 443      * Internal marker interface which distinguishes (to the Java compiler)
 444      * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
 445      */
 446     @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
 447     @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
 448     @interface PolymorphicSignature { }
 449 
 450     private final MethodType type;
 451     /*private*/ final LambdaForm form;
 452     // form is not private so that invokers can easily fetch it
 453     /*private*/ MethodHandle asTypeCache;
 454     // asTypeCache is not private so that invokers can easily fetch it
 455     /*non-public*/ byte customizationCount;
 456     // customizationCount should be accessible from invokers
 457 
 458     /**
 459      * Reports the type of this method handle.
 460      * Every invocation of this method handle via {@code invokeExact} must exactly match this type.


1501      * The reference {@code x} must be convertible to the first parameter
1502      * type of the target.
1503      * <p>
1504      * <em>Note:</em>  Because method handles are immutable, the target method handle
1505      * retains its original type and behavior.
1506      * <p>
1507      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
1508      * variable-arity method handle}, even if the original target method handle was.
1509      * @param x  the value to bind to the first argument of the target
1510      * @return a new method handle which prepends the given value to the incoming
1511      *         argument list, before calling the original method handle
1512      * @throws IllegalArgumentException if the target does not have a
1513      *         leading parameter type that is a reference type
1514      * @throws ClassCastException if {@code x} cannot be converted
1515      *         to the leading parameter type of the target
1516      * @see MethodHandles#insertArguments
1517      */
1518     public MethodHandle bindTo(Object x) {
1519         x = type.leadingReferenceParameter().cast(x);  // throw CCE if needed
1520         return bindArgumentL(0, x);
1521     }
1522 
1523     /**
1524      * Return a nominal descriptor for this instance, if one can be
1525      * constructed, or an empty {@link Optional} if one cannot be.
1526      *
1527      * @return An {@link Optional} containing the resulting nominal descriptor,
1528      * or an empty {@link Optional} if one cannot be constructed.
1529      * @since 12
1530      */
1531     @Override
1532     public Optional<MethodHandleDesc> describeConstable() {
1533         MethodHandleInfo info;
1534         ClassDesc owner;
1535         String name;
1536         MethodTypeDesc type;
1537         boolean isInterface;
1538         try {
1539             info = IMPL_LOOKUP.revealDirect(this);
1540             isInterface = info.getDeclaringClass().isInterface();
1541             owner = info.getDeclaringClass().describeConstable().orElseThrow();
1542             type = info.getMethodType().describeConstable().orElseThrow();
1543             name = info.getName();
1544         }
1545         catch (Exception e) {
1546             return Optional.empty();
1547         }
1548 
1549         switch (info.getReferenceKind()) {
1550             case REF_getField:
1551                 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.GETTER, owner, name, type.returnType()));
1552             case REF_putField:
1553                 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.SETTER, owner, name, type.parameterType(0)));
1554             case REF_getStatic:
1555                 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.STATIC_GETTER, owner, name, type.returnType()));
1556             case REF_putStatic:
1557                 return Optional.of(MethodHandleDesc.ofField(DirectMethodHandleDesc.Kind.STATIC_SETTER, owner, name, type.parameterType(0)));
1558             case REF_invokeVirtual:
1559                 return Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.VIRTUAL, owner, name, type));
1560             case REF_invokeStatic:
1561                 return isInterface ?
1562                         Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.INTERFACE_STATIC, owner, name, type)) :
1563                         Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.STATIC, owner, name, type));
1564             case REF_invokeSpecial:
1565                 return isInterface ?
1566                         Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.INTERFACE_SPECIAL, owner, name, type)) :
1567                         Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.SPECIAL, owner, name, type));
1568             case REF_invokeInterface:
1569                 return Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.INTERFACE_VIRTUAL, owner, name, type));
1570             case REF_newInvokeSpecial:
1571                 return Optional.of(MethodHandleDesc.ofMethod(DirectMethodHandleDesc.Kind.CONSTRUCTOR, owner, name, type));
1572             default:
1573                 return Optional.empty();
1574         }
1575     }
1576 
1577     /**
1578      * Returns a string representation of the method handle,
1579      * starting with the string {@code "MethodHandle"} and
1580      * ending with the string representation of the method handle's type.
1581      * In other words, this method returns a string equal to the value of:
1582      * <blockquote><pre>{@code
1583      * "MethodHandle" + type().toString()
1584      * }</pre></blockquote>
1585      * <p>
1586      * (<em>Note:</em>  Future releases of this API may add further information
1587      * to the string representation.
1588      * Therefore, the present syntax should not be parsed by applications.)
1589      *
1590      * @return a string representation of the method handle
1591      */
1592     @Override
1593     public String toString() {
1594         if (DEBUG_METHOD_HANDLE_NAMES)  return "MethodHandle"+debugString();


< prev index next >