jaroslav@1646: /* jaroslav@1646: * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. jaroslav@1646: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1646: * jaroslav@1646: * This code is free software; you can redistribute it and/or modify it jaroslav@1646: * under the terms of the GNU General Public License version 2 only, as jaroslav@1646: * published by the Free Software Foundation. Oracle designates this jaroslav@1646: * particular file as subject to the "Classpath" exception as provided jaroslav@1646: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1646: * jaroslav@1646: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1646: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1646: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1646: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1646: * accompanied this code). jaroslav@1646: * jaroslav@1646: * You should have received a copy of the GNU General Public License version jaroslav@1646: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1646: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1646: * jaroslav@1646: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1646: * or visit www.oracle.com if you need additional information or have any jaroslav@1646: * questions. jaroslav@1646: */ jaroslav@1646: jaroslav@1646: package java.lang.invoke; jaroslav@1646: jaroslav@1646: import java.lang.reflect.*; jaroslav@1646: import java.util.List; jaroslav@1646: import java.util.ArrayList; jaroslav@1646: import java.util.Arrays; jaroslav@1646: jaroslav@1646: import sun.invoke.util.ValueConversions; jaroslav@1646: import sun.invoke.util.VerifyAccess; jaroslav@1646: import sun.invoke.util.Wrapper; jaroslav@1646: import sun.reflect.CallerSensitive; jaroslav@1646: import sun.reflect.Reflection; jaroslav@1646: import sun.reflect.misc.ReflectUtil; jaroslav@1646: import sun.security.util.SecurityConstants; jaroslav@1646: import static java.lang.invoke.MethodHandleStatics.*; jaroslav@1646: import static java.lang.invoke.MethodHandleNatives.Constants.*; jaroslav@1646: import java.util.concurrent.ConcurrentHashMap; jaroslav@1646: import sun.security.util.SecurityConstants; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * This class consists exclusively of static methods that operate on or return jaroslav@1646: * method handles. They fall into several categories: jaroslav@1646: *
jaroslav@1646: * @author John Rose, JSR 292 EG jaroslav@1646: * @since 1.7 jaroslav@1646: */ jaroslav@1646: public class MethodHandles { jaroslav@1646: jaroslav@1646: private MethodHandles() { } // do not instantiate jaroslav@1646: jaroslav@1646: private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); jaroslav@1646: static { MethodHandleImpl.initStatics(); } jaroslav@1646: // See IMPL_LOOKUP below. jaroslav@1646: jaroslav@1646: //// Method handle creation from ordinary methods. jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Returns a {@link Lookup lookup object} with jaroslav@1646: * full capabilities to emulate all supported bytecode behaviors of the caller. jaroslav@1646: * These capabilities include private access to the caller. jaroslav@1646: * Factory methods on the lookup object can create jaroslav@1646: * direct method handles jaroslav@1646: * for any member that the caller has access to via bytecodes, jaroslav@1646: * including protected and private fields and methods. jaroslav@1646: * This lookup object is a capability which may be delegated to trusted agents. jaroslav@1646: * Do not store it in place where untrusted code can access it. jaroslav@1646: *
jaroslav@1646: * This method is caller sensitive, which means that it may return different jaroslav@1646: * values to different callers. jaroslav@1646: *
jaroslav@1646: * For any given caller class {@code C}, the lookup object returned by this call jaroslav@1646: * has equivalent capabilities to any lookup object jaroslav@1646: * supplied by the JVM to the bootstrap method of an jaroslav@1646: * invokedynamic instruction jaroslav@1646: * executing in the same caller class {@code C}. jaroslav@1646: * @return a lookup object for the caller of this method, with private access jaroslav@1646: */ jaroslav@1646: @CallerSensitive jaroslav@1646: public static Lookup lookup() { jaroslav@1646: return new Lookup(Reflection.getCallerClass()); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Returns a {@link Lookup lookup object} which is trusted minimally. jaroslav@1646: * It can only be used to create method handles to jaroslav@1646: * publicly accessible fields and methods. jaroslav@1646: *
jaroslav@1646: * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class} jaroslav@1646: * of this lookup object will be {@link java.lang.Object}. jaroslav@1646: * jaroslav@1646: *
jaroslav@1646: * Discussion: jaroslav@1646: * The lookup class can be changed to any other class {@code C} using an expression of the form jaroslav@1646: * {@link Lookup#in publicLookup().in(C.class)}. jaroslav@1646: * Since all classes have equal access to public names, jaroslav@1646: * such a change would confer no new access rights. jaroslav@1646: * A public lookup object is always subject to jaroslav@1646: * security manager checks. jaroslav@1646: * Also, it cannot access jaroslav@1646: * caller sensitive methods. jaroslav@1646: * @return a lookup object which is trusted minimally jaroslav@1646: */ jaroslav@1646: public static Lookup publicLookup() { jaroslav@1646: return Lookup.PUBLIC_LOOKUP; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Performs an unchecked "crack" of a jaroslav@1646: * direct method handle. jaroslav@1646: * The result is as if the user had obtained a lookup object capable enough jaroslav@1646: * to crack the target method handle, called jaroslav@1646: * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} jaroslav@1646: * on the target to obtain its symbolic reference, and then called jaroslav@1646: * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} jaroslav@1646: * to resolve the symbolic reference to a member. jaroslav@1646: *
jaroslav@1646: * If there is a security manager, its {@code checkPermission} method
jaroslav@1646: * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
jaroslav@1646: * @param
jaroslav@1646: * A lookup class which needs to create method handles will call
jaroslav@1646: * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
jaroslav@1646: * When the {@code Lookup} factory object is created, the identity of the lookup class is
jaroslav@1646: * determined, and securely stored in the {@code Lookup} object.
jaroslav@1646: * The lookup class (or its delegates) may then use factory methods
jaroslav@1646: * on the {@code Lookup} object to create method handles for access-checked members.
jaroslav@1646: * This includes all methods, constructors, and fields which are allowed to the lookup class,
jaroslav@1646: * even private ones.
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * In cases where the given member is of variable arity (i.e., a method or constructor)
jaroslav@1646: * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
jaroslav@1646: * In all other cases, the returned method handle will be of fixed arity.
jaroslav@1646: *
jaroslav@1646: * Discussion:
jaroslav@1646: * The equivalence between looked-up method handles and underlying
jaroslav@1646: * class members and bytecode behaviors
jaroslav@1646: * can break down in a few ways:
jaroslav@1646: *
jaroslav@1646: * All access checks start from a {@code Lookup} object, which
jaroslav@1646: * compares its recorded lookup class against all requests to
jaroslav@1646: * create method handles.
jaroslav@1646: * A single {@code Lookup} object can be used to create any number
jaroslav@1646: * of access-checked method handles, all checked against a single
jaroslav@1646: * lookup class.
jaroslav@1646: *
jaroslav@1646: * A {@code Lookup} object can be shared with other trusted code,
jaroslav@1646: * such as a metaobject protocol.
jaroslav@1646: * A shared {@code Lookup} object delegates the capability
jaroslav@1646: * to create method handles on private members of the lookup class.
jaroslav@1646: * Even if privileged code uses the {@code Lookup} object,
jaroslav@1646: * the access checking is confined to the privileges of the
jaroslav@1646: * original lookup class.
jaroslav@1646: *
jaroslav@1646: * A lookup can fail, because
jaroslav@1646: * the containing class is not accessible to the lookup class, or
jaroslav@1646: * because the desired class member is missing, or because the
jaroslav@1646: * desired class member is not accessible to the lookup class, or
jaroslav@1646: * because the lookup object is not trusted enough to access the member.
jaroslav@1646: * In any of these cases, a {@code ReflectiveOperationException} will be
jaroslav@1646: * thrown from the attempted lookup. The exact class will be one of
jaroslav@1646: * the following:
jaroslav@1646: *
jaroslav@1646: * In general, the conditions under which a method handle may be
jaroslav@1646: * looked up for a method {@code M} are no more restrictive than the conditions
jaroslav@1646: * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
jaroslav@1646: * Where the JVM would raise exceptions like {@code NoSuchMethodError},
jaroslav@1646: * a method handle lookup will generally raise a corresponding
jaroslav@1646: * checked exception, such as {@code NoSuchMethodException}.
jaroslav@1646: * And the effect of invoking the method handle resulting from the lookup
jaroslav@1646: * is exactly equivalent
jaroslav@1646: * to executing the compiled, verified, and resolved call to {@code M}.
jaroslav@1646: * The same point is true of fields and constructors.
jaroslav@1646: *
jaroslav@1646: * Discussion:
jaroslav@1646: * Access checks only apply to named and reflected methods,
jaroslav@1646: * constructors, and fields.
jaroslav@1646: * Other method handle creation methods, such as
jaroslav@1646: * {@link MethodHandle#asType MethodHandle.asType},
jaroslav@1646: * do not require any access checks, and are used
jaroslav@1646: * independently of any {@code Lookup} object.
jaroslav@1646: *
jaroslav@1646: * If the desired member is {@code protected}, the usual JVM rules apply,
jaroslav@1646: * including the requirement that the lookup class must be either be in the
jaroslav@1646: * same package as the desired member, or must inherit that member.
jaroslav@1646: * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
jaroslav@1646: * In addition, if the desired member is a non-static field or method
jaroslav@1646: * in a different package, the resulting method handle may only be applied
jaroslav@1646: * to objects of the lookup class or one of its subclasses.
jaroslav@1646: * This requirement is enforced by narrowing the type of the leading
jaroslav@1646: * {@code this} parameter from {@code C}
jaroslav@1646: * (which will necessarily be a superclass of the lookup class)
jaroslav@1646: * to the lookup class itself.
jaroslav@1646: *
jaroslav@1646: * The JVM imposes a similar requirement on {@code invokespecial} instruction,
jaroslav@1646: * that the receiver argument must match both the resolved method and
jaroslav@1646: * the current class. Again, this requirement is enforced by narrowing the
jaroslav@1646: * type of the leading parameter to the resulting method handle.
jaroslav@1646: * (See the Java Virtual Machine Specification, section 4.10.1.9.)
jaroslav@1646: *
jaroslav@1646: * The JVM represents constructors and static initializer blocks as internal methods
jaroslav@1646: * with special names ({@code "
jaroslav@1646: * In some cases, access between nested classes is obtained by the Java compiler by creating
jaroslav@1646: * an wrapper method to access a private method of another class
jaroslav@1646: * in the same top-level declaration.
jaroslav@1646: * For example, a nested class {@code C.D}
jaroslav@1646: * can access private members within other related classes such as
jaroslav@1646: * {@code C}, {@code C.D.E}, or {@code C.B},
jaroslav@1646: * but the Java compiler may need to generate wrapper methods in
jaroslav@1646: * those related classes. In such cases, a {@code Lookup} object on
jaroslav@1646: * {@code C.E} would be unable to those private members.
jaroslav@1646: * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
jaroslav@1646: * which can transform a lookup on {@code C.E} into one on any of those other
jaroslav@1646: * classes, without special elevation of privilege.
jaroslav@1646: *
jaroslav@1646: * The accesses permitted to a given lookup object may be limited,
jaroslav@1646: * according to its set of {@link #lookupModes lookupModes},
jaroslav@1646: * to a subset of members normally accessible to the lookup class.
jaroslav@1646: * For example, the {@link MethodHandles#publicLookup publicLookup}
jaroslav@1646: * method produces a lookup object which is only allowed to access
jaroslav@1646: * public members in public classes.
jaroslav@1646: * The caller sensitive method {@link MethodHandles#lookup lookup}
jaroslav@1646: * produces a lookup object with full capabilities relative to
jaroslav@1646: * its caller class, to emulate all supported bytecode behaviors.
jaroslav@1646: * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
jaroslav@1646: * with fewer access modes than the original lookup object.
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * Discussion of private access:
jaroslav@1646: * We say that a lookup has private access
jaroslav@1646: * if its {@linkplain #lookupModes lookup modes}
jaroslav@1646: * include the possibility of accessing {@code private} members.
jaroslav@1646: * As documented in the relevant methods elsewhere,
jaroslav@1646: * only lookups with private access possess the following capabilities:
jaroslav@1646: *
jaroslav@1646: * Each of these permissions is a consequence of the fact that a lookup object
jaroslav@1646: * with private access can be securely traced back to an originating class,
jaroslav@1646: * whose bytecode behaviors and Java language access permissions
jaroslav@1646: * can be reliably determined and emulated by method handles.
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * If a security manager is present, member lookups are subject to
jaroslav@1646: * additional checks.
jaroslav@1646: * From one to three calls are made to the security manager.
jaroslav@1646: * Any of these calls can refuse access by throwing a
jaroslav@1646: * {@link java.lang.SecurityException SecurityException}.
jaroslav@1646: * Define {@code smgr} as the security manager,
jaroslav@1646: * {@code lookc} as the lookup class of the current lookup object,
jaroslav@1646: * {@code refc} as the containing class in which the member
jaroslav@1646: * is being sought, and {@code defc} as the class in which the
jaroslav@1646: * member is actually defined.
jaroslav@1646: * The value {@code lookc} is defined as not present
jaroslav@1646: * if the current lookup object does not have
jaroslav@1646: * private access.
jaroslav@1646: * The calls are made according to the following rules:
jaroslav@1646: *
jaroslav@1646: * If a method handle for a caller-sensitive method is requested,
jaroslav@1646: * the general rules for bytecode behaviors apply,
jaroslav@1646: * but they take account of the lookup class in a special way.
jaroslav@1646: * The resulting method handle behaves as if it were called
jaroslav@1646: * from an instruction contained in the lookup class,
jaroslav@1646: * so that the caller-sensitive method detects the lookup class.
jaroslav@1646: * (By contrast, the invoker of the method handle is disregarded.)
jaroslav@1646: * Thus, in the case of caller-sensitive methods,
jaroslav@1646: * different lookup classes may give rise to
jaroslav@1646: * differently behaving method handles.
jaroslav@1646: *
jaroslav@1646: * In cases where the lookup object is
jaroslav@1646: * {@link MethodHandles#publicLookup() publicLookup()},
jaroslav@1646: * or some other lookup object without
jaroslav@1646: * private access,
jaroslav@1646: * the lookup class is disregarded.
jaroslav@1646: * In such cases, no caller-sensitive method handle can be created,
jaroslav@1646: * access is forbidden, and the lookup fails with an
jaroslav@1646: * {@code IllegalAccessException}.
jaroslav@1646: *
jaroslav@1646: * Discussion:
jaroslav@1646: * For example, the caller-sensitive method
jaroslav@1646: * {@link java.lang.Class#forName(String) Class.forName(x)}
jaroslav@1646: * can return varying classes or throw varying exceptions,
jaroslav@1646: * depending on the class loader of the class that calls it.
jaroslav@1646: * A public lookup of {@code Class.forName} will fail, because
jaroslav@1646: * there is no reasonable way to determine its bytecode behavior.
jaroslav@1646: *
jaroslav@1646: * If an application caches method handles for broad sharing,
jaroslav@1646: * it should use {@code publicLookup()} to create them.
jaroslav@1646: * If there is a lookup of {@code Class.forName}, it will fail,
jaroslav@1646: * and the application must take appropriate action in that case.
jaroslav@1646: * It may be that a later lookup, perhaps during the invocation of a
jaroslav@1646: * bootstrap method, can incorporate the specific identity
jaroslav@1646: * of the caller, making the method accessible.
jaroslav@1646: *
jaroslav@1646: * The function {@code MethodHandles.lookup} is caller sensitive
jaroslav@1646: * so that there can be a secure foundation for lookups.
jaroslav@1646: * Nearly all other methods in the JSR 292 API rely on lookup
jaroslav@1646: * objects to check access requests.
jaroslav@1646: */
jaroslav@1646: public static final
jaroslav@1646: class Lookup {
jaroslav@1646: /** The class on behalf of whom the lookup is being performed. */
jaroslav@1646: private final Class> lookupClass;
jaroslav@1646:
jaroslav@1646: /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
jaroslav@1646: private final int allowedModes;
jaroslav@1646:
jaroslav@1646: /** A single-bit mask representing {@code public} access,
jaroslav@1646: * which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646: * The value, {@code 0x01}, happens to be the same as the value of the
jaroslav@1646: * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
jaroslav@1646: */
jaroslav@1646: public static final int PUBLIC = Modifier.PUBLIC;
jaroslav@1646:
jaroslav@1646: /** A single-bit mask representing {@code private} access,
jaroslav@1646: * which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646: * The value, {@code 0x02}, happens to be the same as the value of the
jaroslav@1646: * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
jaroslav@1646: */
jaroslav@1646: public static final int PRIVATE = Modifier.PRIVATE;
jaroslav@1646:
jaroslav@1646: /** A single-bit mask representing {@code protected} access,
jaroslav@1646: * which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646: * The value, {@code 0x04}, happens to be the same as the value of the
jaroslav@1646: * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
jaroslav@1646: */
jaroslav@1646: public static final int PROTECTED = Modifier.PROTECTED;
jaroslav@1646:
jaroslav@1646: /** A single-bit mask representing {@code package} access (default access),
jaroslav@1646: * which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646: * The value is {@code 0x08}, which does not correspond meaningfully to
jaroslav@1646: * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
jaroslav@1646: */
jaroslav@1646: public static final int PACKAGE = Modifier.STATIC;
jaroslav@1646:
jaroslav@1646: private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
jaroslav@1646: private static final int TRUSTED = -1;
jaroslav@1646:
jaroslav@1646: private static int fixmods(int mods) {
jaroslav@1646: mods &= (ALL_MODES - PACKAGE);
jaroslav@1646: return (mods != 0) ? mods : PACKAGE;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /** Tells which class is performing the lookup. It is this class against
jaroslav@1646: * which checks are performed for visibility and access permissions.
jaroslav@1646: *
jaroslav@1646: * The class implies a maximum level of access permission,
jaroslav@1646: * but the permissions may be additionally limited by the bitmask
jaroslav@1646: * {@link #lookupModes lookupModes}, which controls whether non-public members
jaroslav@1646: * can be accessed.
jaroslav@1646: * @return the lookup class, on behalf of which this lookup object finds members
jaroslav@1646: */
jaroslav@1646: public Class> lookupClass() {
jaroslav@1646: return lookupClass;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: // This is just for calling out to MethodHandleImpl.
jaroslav@1646: private Class> lookupClassOrNull() {
jaroslav@1646: return (allowedModes == TRUSTED) ? null : lookupClass;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /** Tells which access-protection classes of members this lookup object can produce.
jaroslav@1646: * The result is a bit-mask of the bits
jaroslav@1646: * {@linkplain #PUBLIC PUBLIC (0x01)},
jaroslav@1646: * {@linkplain #PRIVATE PRIVATE (0x02)},
jaroslav@1646: * {@linkplain #PROTECTED PROTECTED (0x04)},
jaroslav@1646: * and {@linkplain #PACKAGE PACKAGE (0x08)}.
jaroslav@1646: *
jaroslav@1646: * A freshly-created lookup object
jaroslav@1646: * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
jaroslav@1646: * has all possible bits set, since the caller class can access all its own members.
jaroslav@1646: * A lookup object on a new lookup class
jaroslav@1646: * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
jaroslav@1646: * may have some mode bits set to zero.
jaroslav@1646: * The purpose of this is to restrict access via the new lookup object,
jaroslav@1646: * so that it can access only names which can be reached by the original
jaroslav@1646: * lookup object, and also by the new lookup class.
jaroslav@1646: * @return the lookup modes, which limit the kinds of access performed by this lookup object
jaroslav@1646: */
jaroslav@1646: public int lookupModes() {
jaroslav@1646: return allowedModes & ALL_MODES;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /** Embody the current class (the lookupClass) as a lookup class
jaroslav@1646: * for method handle creation.
jaroslav@1646: * Must be called by from a method in this package,
jaroslav@1646: * which in turn is called by a method not in this package.
jaroslav@1646: */
jaroslav@1646: Lookup(Class> lookupClass) {
jaroslav@1646: this(lookupClass, ALL_MODES);
jaroslav@1646: // make sure we haven't accidentally picked up a privileged class:
jaroslav@1646: checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: private Lookup(Class> lookupClass, int allowedModes) {
jaroslav@1646: this.lookupClass = lookupClass;
jaroslav@1646: this.allowedModes = allowedModes;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Creates a lookup on the specified new lookup class.
jaroslav@1646: * The resulting object will report the specified
jaroslav@1646: * class as its own {@link #lookupClass lookupClass}.
jaroslav@1646: *
jaroslav@1646: * However, the resulting {@code Lookup} object is guaranteed
jaroslav@1646: * to have no more access capabilities than the original.
jaroslav@1646: * In particular, access capabilities can be lost as follows:
jaroslav@1646: * (It may seem strange that protected access should be
jaroslav@1646: * stronger than private access. Viewed independently from
jaroslav@1646: * package access, protected access is the first to be lost,
jaroslav@1646: * because it requires a direct subclass relationship between
jaroslav@1646: * caller and callee.)
jaroslav@1646: * @see #in
jaroslav@1646: */
jaroslav@1646: @Override
jaroslav@1646: public String toString() {
jaroslav@1646: String cname = lookupClass.getName();
jaroslav@1646: switch (allowedModes) {
jaroslav@1646: case 0: // no privileges
jaroslav@1646: return cname + "/noaccess";
jaroslav@1646: case PUBLIC:
jaroslav@1646: return cname + "/public";
jaroslav@1646: case PUBLIC|PACKAGE:
jaroslav@1646: return cname + "/package";
jaroslav@1646: case ALL_MODES & ~PROTECTED:
jaroslav@1646: return cname + "/private";
jaroslav@1646: case ALL_MODES:
jaroslav@1646: return cname;
jaroslav@1646: case TRUSTED:
jaroslav@1646: return "/trusted"; // internal only; not exported
jaroslav@1646: default: // Should not happen, but it's a bitfield...
jaroslav@1646: cname = cname + "/" + Integer.toHexString(allowedModes);
jaroslav@1646: assert(false) : cname;
jaroslav@1646: return cname;
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle for a static method.
jaroslav@1646: * The type of the method handle will be that of the method.
jaroslav@1646: * (Since static methods do not take receivers, there is no
jaroslav@1646: * additional receiver argument inserted into the method handle type,
jaroslav@1646: * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
jaroslav@1646: * The method and all its argument types must be accessible to the lookup object.
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: *
jaroslav@1646: * If the returned method handle is invoked, the method's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * Example:
jaroslav@1646: *
jaroslav@1646: * When called, the handle will treat the first argument as a receiver
jaroslav@1646: * and dispatch on the receiver's type to determine which method
jaroslav@1646: * implementation to enter.
jaroslav@1646: * (The dispatching action is identical with that performed by an
jaroslav@1646: * {@code invokevirtual} or {@code invokeinterface} instruction.)
jaroslav@1646: *
jaroslav@1646: * The first argument will be of type {@code refc} if the lookup
jaroslav@1646: * class has full privileges to access the member. Otherwise
jaroslav@1646: * the member must be {@code protected} and the first argument
jaroslav@1646: * will be restricted in type to the lookup class.
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: *
jaroslav@1646: * Because of the general equivalence between {@code invokevirtual}
jaroslav@1646: * instructions and method handles produced by {@code findVirtual},
jaroslav@1646: * if the class is {@code MethodHandle} and the name string is
jaroslav@1646: * {@code invokeExact} or {@code invoke}, the resulting
jaroslav@1646: * method handle is equivalent to one produced by
jaroslav@1646: * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
jaroslav@1646: * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
jaroslav@1646: * with the same {@code type} argument.
jaroslav@1646: *
jaroslav@1646: * Example:
jaroslav@1646: *
jaroslav@1646: * The requested type must have a return type of {@code void}.
jaroslav@1646: * (This is consistent with the JVM's treatment of constructor type descriptors.)
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: *
jaroslav@1646: * If the returned method handle is invoked, the constructor's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * Example:
jaroslav@1646: *
jaroslav@1646: * Before method resolution,
jaroslav@1646: * if the explicitly specified caller class is not identical with the
jaroslav@1646: * lookup class, or if this lookup object does not have
jaroslav@1646: * private access
jaroslav@1646: * privileges, the access fails.
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: *
jaroslav@1646: * (Note: JVM internal methods named {@code " Example:
jaroslav@1646: *
jaroslav@1646: * If the returned method handle is invoked, the field's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param name the field's name
jaroslav@1646: * @param type the field's type
jaroslav@1646: * @return a method handle which can load values from the field
jaroslav@1646: * @throws NoSuchFieldException if the field does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findStaticGetter(Class> refc, String name, Class> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646: MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
jaroslav@1646: return getDirectField(REF_getStatic, refc, field);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle giving write access to a static field.
jaroslav@1646: * The type of the method handle will have a void return type.
jaroslav@1646: * The method handle will take a single
jaroslav@1646: * argument, of the field's value type, the value to be stored.
jaroslav@1646: * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: *
jaroslav@1646: * If the returned method handle is invoked, the field's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param name the field's name
jaroslav@1646: * @param type the field's type
jaroslav@1646: * @return a method handle which can store values into the field
jaroslav@1646: * @throws NoSuchFieldException if the field does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findStaticSetter(Class> refc, String name, Class> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646: MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
jaroslav@1646: return getDirectField(REF_putStatic, refc, field);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces an early-bound method handle for a non-static method.
jaroslav@1646: * The receiver must have a supertype {@code defc} in which a method
jaroslav@1646: * of the given name and type is accessible to the lookup class.
jaroslav@1646: * The method and all its argument types must be accessible to the lookup object.
jaroslav@1646: * The type of the method handle will be that of the method,
jaroslav@1646: * without any insertion of an additional receiver parameter.
jaroslav@1646: * The given receiver will be bound into the method handle,
jaroslav@1646: * so that every call to the method handle will invoke the
jaroslav@1646: * requested method on the given receiver.
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the method's variable arity modifier bit ({@code 0x0080}) is set
jaroslav@1646: * and the trailing array argument is not the only argument.
jaroslav@1646: * (If the trailing array argument is the only argument,
jaroslav@1646: * the given receiver value will be bound to it.)
jaroslav@1646: *
jaroslav@1646: * This is equivalent to the following code:
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: *
jaroslav@1646: * If m is static, and
jaroslav@1646: * if the returned method handle is invoked, the method's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * @param m the reflected method
jaroslav@1646: * @return a method handle which can invoke the reflected method
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @throws NullPointerException if the argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle unreflect(Method m) throws IllegalAccessException {
jaroslav@1646: if (m.getDeclaringClass() == MethodHandle.class) {
jaroslav@1646: MethodHandle mh = unreflectForMH(m);
jaroslav@1646: if (mh != null) return mh;
jaroslav@1646: }
jaroslav@1646: MemberName method = new MemberName(m);
jaroslav@1646: byte refKind = method.getReferenceKind();
jaroslav@1646: if (refKind == REF_invokeSpecial)
jaroslav@1646: refKind = REF_invokeVirtual;
jaroslav@1646: assert(method.isMethod());
jaroslav@1646: Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
jaroslav@1646: return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
jaroslav@1646: }
jaroslav@1646: private MethodHandle unreflectForMH(Method m) {
jaroslav@1646: // these names require special lookups because they throw UnsupportedOperationException
jaroslav@1646: if (MemberName.isMethodHandleInvokeName(m.getName()))
jaroslav@1646: return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
jaroslav@1646: return null;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle for a reflected method.
jaroslav@1646: * It will bypass checks for overriding methods on the receiver,
jaroslav@1646: * as if called from an {@code invokespecial}
jaroslav@1646: * instruction from within the explicitly specified {@code specialCaller}.
jaroslav@1646: * The type of the method handle will be that of the method,
jaroslav@1646: * with a suitably restricted receiver type prepended.
jaroslav@1646: * (The receiver type will be {@code specialCaller} or a subtype.)
jaroslav@1646: * If the method's {@code accessible} flag is not set,
jaroslav@1646: * access checking is performed immediately on behalf of the lookup class,
jaroslav@1646: * as if {@code invokespecial} instruction were being linked.
jaroslav@1646: *
jaroslav@1646: * Before method resolution,
jaroslav@1646: * if the explicitly specified caller class is not identical with the
jaroslav@1646: * lookup class, or if this lookup object does not have
jaroslav@1646: * private access
jaroslav@1646: * privileges, the access fails.
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: * @param m the reflected method
jaroslav@1646: * @param specialCaller the class nominally calling the method
jaroslav@1646: * @return a method handle which can invoke the reflected method
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle unreflectSpecial(Method m, Class> specialCaller) throws IllegalAccessException {
jaroslav@1646: checkSpecialCaller(specialCaller);
jaroslav@1646: Lookup specialLookup = this.in(specialCaller);
jaroslav@1646: MemberName method = new MemberName(m, true);
jaroslav@1646: assert(method.isMethod());
jaroslav@1646: // ignore m.isAccessible: this is a new kind of access
jaroslav@1646: return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle for a reflected constructor.
jaroslav@1646: * The type of the method handle will be that of the constructor,
jaroslav@1646: * with the return type changed to the declaring class.
jaroslav@1646: * The method handle will perform a {@code newInstance} operation,
jaroslav@1646: * creating a new instance of the constructor's class on the
jaroslav@1646: * arguments passed to the method handle.
jaroslav@1646: *
jaroslav@1646: * If the constructor's {@code accessible} flag is not set,
jaroslav@1646: * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: *
jaroslav@1646: * The returned method handle will have
jaroslav@1646: * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646: * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646: *
jaroslav@1646: * If the returned method handle is invoked, the constructor's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * @param c the reflected constructor
jaroslav@1646: * @return a method handle which can invoke the reflected constructor
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @throws NullPointerException if the argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle unreflectConstructor(Constructor> c) throws IllegalAccessException {
jaroslav@1646: MemberName ctor = new MemberName(c);
jaroslav@1646: assert(ctor.isConstructor());
jaroslav@1646: Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
jaroslav@1646: return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle giving read access to a reflected field.
jaroslav@1646: * The type of the method handle will have a return type of the field's
jaroslav@1646: * value type.
jaroslav@1646: * If the field is static, the method handle will take no arguments.
jaroslav@1646: * Otherwise, its single argument will be the instance containing
jaroslav@1646: * the field.
jaroslav@1646: * If the field's {@code accessible} flag is not set,
jaroslav@1646: * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: *
jaroslav@1646: * If the field is static, and
jaroslav@1646: * if the returned method handle is invoked, the field's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * @param f the reflected field
jaroslav@1646: * @return a method handle which can load values from the reflected field
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * @throws NullPointerException if the argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
jaroslav@1646: return unreflectField(f, false);
jaroslav@1646: }
jaroslav@1646: private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
jaroslav@1646: MemberName field = new MemberName(f, isSetter);
jaroslav@1646: assert(isSetter
jaroslav@1646: ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
jaroslav@1646: : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
jaroslav@1646: Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
jaroslav@1646: return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle giving write access to a reflected field.
jaroslav@1646: * The type of the method handle will have a void return type.
jaroslav@1646: * If the field is static, the method handle will take a single
jaroslav@1646: * argument, of the field's value type, the value to be stored.
jaroslav@1646: * Otherwise, the two arguments will be the instance containing
jaroslav@1646: * the field, and the value to be stored.
jaroslav@1646: * If the field's {@code accessible} flag is not set,
jaroslav@1646: * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: *
jaroslav@1646: * If the field is static, and
jaroslav@1646: * if the returned method handle is invoked, the field's class will
jaroslav@1646: * be initialized, if it has not already been initialized.
jaroslav@1646: * @param f the reflected field
jaroslav@1646: * @return a method handle which can store values into the reflected field
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * @throws NullPointerException if the argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
jaroslav@1646: return unreflectField(f, true);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Cracks a direct method handle
jaroslav@1646: * created by this lookup object or a similar one.
jaroslav@1646: * Security and access checks are performed to ensure that this lookup object
jaroslav@1646: * is capable of reproducing the target method handle.
jaroslav@1646: * This means that the cracking may fail if target is a direct method handle
jaroslav@1646: * but was created by an unrelated lookup object.
jaroslav@1646: * This can happen if the method handle is caller sensitive
jaroslav@1646: * and was created by a lookup object for a different class.
jaroslav@1646: * @param target a direct method handle to crack into symbolic reference components
jaroslav@1646: * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
jaroslav@1646: * @exception NullPointerException if the target is {@code null}
jaroslav@1646: * @see MethodHandleInfo
jaroslav@1646: * @since 1.8
jaroslav@1646: */
jaroslav@1646: public MethodHandleInfo revealDirect(MethodHandle target) {
jaroslav@1646: MemberName member = target.internalMemberName();
jaroslav@1646: if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke()))
jaroslav@1646: throw newIllegalArgumentException("not a direct method handle");
jaroslav@1646: Class> defc = member.getDeclaringClass();
jaroslav@1646: byte refKind = member.getReferenceKind();
jaroslav@1646: assert(MethodHandleNatives.refKindIsValid(refKind));
jaroslav@1646: if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
jaroslav@1646: // Devirtualized method invocation is usually formally virtual.
jaroslav@1646: // To avoid creating extra MemberName objects for this common case,
jaroslav@1646: // we encode this extra degree of freedom using MH.isInvokeSpecial.
jaroslav@1646: refKind = REF_invokeVirtual;
jaroslav@1646: if (refKind == REF_invokeVirtual && defc.isInterface())
jaroslav@1646: // Symbolic reference is through interface but resolves to Object method (toString, etc.)
jaroslav@1646: refKind = REF_invokeInterface;
jaroslav@1646: // Check SM permissions and member access before cracking.
jaroslav@1646: try {
jaroslav@1646: checkAccess(refKind, defc, member);
jaroslav@1646: checkSecurityManager(defc, member);
jaroslav@1646: } catch (IllegalAccessException ex) {
jaroslav@1646: throw new IllegalArgumentException(ex);
jaroslav@1646: }
jaroslav@1646: if (allowedModes != TRUSTED && member.isCallerSensitive()) {
jaroslav@1646: Class> callerClass = target.internalCallerClass();
jaroslav@1646: if (!hasPrivateAccess() || callerClass != lookupClass())
jaroslav@1646: throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
jaroslav@1646: }
jaroslav@1646: // Produce the handle to the results.
jaroslav@1646: return new InfoFromMemberName(this, member, refKind);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /// Helper methods, all package-private.
jaroslav@1646:
jaroslav@1646: MemberName resolveOrFail(byte refKind, Class> refc, String name, Class> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646: checkSymbolicClass(refc); // do this before attempting to resolve
jaroslav@1646: name.getClass(); // NPE
jaroslav@1646: type.getClass(); // NPE
jaroslav@1646: return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
jaroslav@1646: NoSuchFieldException.class);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: MemberName resolveOrFail(byte refKind, Class> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646: checkSymbolicClass(refc); // do this before attempting to resolve
jaroslav@1646: name.getClass(); // NPE
jaroslav@1646: type.getClass(); // NPE
jaroslav@1646: checkMethodName(refKind, name); // NPE check on name
jaroslav@1646: return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
jaroslav@1646: NoSuchMethodException.class);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
jaroslav@1646: checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve
jaroslav@1646: member.getName().getClass(); // NPE
jaroslav@1646: member.getType().getClass(); // NPE
jaroslav@1646: return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
jaroslav@1646: ReflectiveOperationException.class);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: void checkSymbolicClass(Class> refc) throws IllegalAccessException {
jaroslav@1646: refc.getClass(); // NPE
jaroslav@1646: Class> caller = lookupClassOrNull();
jaroslav@1646: if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
jaroslav@1646: throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /** Check name for an illegal leading "<" character. */
jaroslav@1646: void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
jaroslav@1646: if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
jaroslav@1646: throw new NoSuchMethodException("illegal method name: "+name);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Find my trustable caller class if m is a caller sensitive method.
jaroslav@1646: * If this lookup object has private access, then the caller class is the lookupClass.
jaroslav@1646: * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
jaroslav@1646: */
jaroslav@1646: Class> findBoundCallerClass(MemberName m) throws IllegalAccessException {
jaroslav@1646: Class> callerClass = null;
jaroslav@1646: if (MethodHandleNatives.isCallerSensitive(m)) {
jaroslav@1646: // Only lookups with private access are allowed to resolve caller-sensitive methods
jaroslav@1646: if (hasPrivateAccess()) {
jaroslav@1646: callerClass = lookupClass;
jaroslav@1646: } else {
jaroslav@1646: throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646: return callerClass;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: private boolean hasPrivateAccess() {
jaroslav@1646: return (allowedModes & PRIVATE) != 0;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Perform necessary access checks.
jaroslav@1646: * Determines a trustable caller class to compare with refc, the symbolic reference class.
jaroslav@1646: * If this lookup object has private access, then the caller class is the lookupClass.
jaroslav@1646: */
jaroslav@1646: void checkSecurityManager(Class> refc, MemberName m) {
jaroslav@1646: SecurityManager smgr = System.getSecurityManager();
jaroslav@1646: if (smgr == null) return;
jaroslav@1646: if (allowedModes == TRUSTED) return;
jaroslav@1646:
jaroslav@1646: // Step 1:
jaroslav@1646: boolean fullPowerLookup = hasPrivateAccess();
jaroslav@1646: if (!fullPowerLookup ||
jaroslav@1646: !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
jaroslav@1646: ReflectUtil.checkPackageAccess(refc);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: // Step 2:
jaroslav@1646: if (m.isPublic()) return;
jaroslav@1646: if (!fullPowerLookup) {
jaroslav@1646: smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: // Step 3:
jaroslav@1646: Class> defc = m.getDeclaringClass();
jaroslav@1646: if (!fullPowerLookup && defc != refc) {
jaroslav@1646: ReflectUtil.checkPackageAccess(defc);
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: void checkMethod(byte refKind, Class> refc, MemberName m) throws IllegalAccessException {
jaroslav@1646: boolean wantStatic = (refKind == REF_invokeStatic);
jaroslav@1646: String message;
jaroslav@1646: if (m.isConstructor())
jaroslav@1646: message = "expected a method, not a constructor";
jaroslav@1646: else if (!m.isMethod())
jaroslav@1646: message = "expected a method";
jaroslav@1646: else if (wantStatic != m.isStatic())
jaroslav@1646: message = wantStatic ? "expected a static method" : "expected a non-static method";
jaroslav@1646: else
jaroslav@1646: { checkAccess(refKind, refc, m); return; }
jaroslav@1646: throw m.makeAccessException(message, this);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: void checkField(byte refKind, Class> refc, MemberName m) throws IllegalAccessException {
jaroslav@1646: boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
jaroslav@1646: String message;
jaroslav@1646: if (wantStatic != m.isStatic())
jaroslav@1646: message = wantStatic ? "expected a static field" : "expected a non-static field";
jaroslav@1646: else
jaroslav@1646: { checkAccess(refKind, refc, m); return; }
jaroslav@1646: throw m.makeAccessException(message, this);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /** Check public/protected/private bits on the symbolic reference class and its member. */
jaroslav@1646: void checkAccess(byte refKind, Class> refc, MemberName m) throws IllegalAccessException {
jaroslav@1646: assert(m.referenceKindIsConsistentWith(refKind) &&
jaroslav@1646: MethodHandleNatives.refKindIsValid(refKind) &&
jaroslav@1646: (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
jaroslav@1646: int allowedModes = this.allowedModes;
jaroslav@1646: if (allowedModes == TRUSTED) return;
jaroslav@1646: int mods = m.getModifiers();
jaroslav@1646: if (Modifier.isProtected(mods) &&
jaroslav@1646: refKind == REF_invokeVirtual &&
jaroslav@1646: m.getDeclaringClass() == Object.class &&
jaroslav@1646: m.getName().equals("clone") &&
jaroslav@1646: refc.isArray()) {
jaroslav@1646: // The JVM does this hack also.
jaroslav@1646: // (See ClassVerifier::verify_invoke_instructions
jaroslav@1646: // and LinkResolver::check_method_accessability.)
jaroslav@1646: // Because the JVM does not allow separate methods on array types,
jaroslav@1646: // there is no separate method for int[].clone.
jaroslav@1646: // All arrays simply inherit Object.clone.
jaroslav@1646: // But for access checking logic, we make Object.clone
jaroslav@1646: // (normally protected) appear to be public.
jaroslav@1646: // Later on, when the DirectMethodHandle is created,
jaroslav@1646: // its leading argument will be restricted to the
jaroslav@1646: // requested array type.
jaroslav@1646: // N.B. The return type is not adjusted, because
jaroslav@1646: // that is *not* the bytecode behavior.
jaroslav@1646: mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
jaroslav@1646: }
jaroslav@1646: if (Modifier.isFinal(mods) &&
jaroslav@1646: MethodHandleNatives.refKindIsSetter(refKind))
jaroslav@1646: throw m.makeAccessException("unexpected set of a final field", this);
jaroslav@1646: if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
jaroslav@1646: return; // common case
jaroslav@1646: int requestedModes = fixmods(mods); // adjust 0 => PACKAGE
jaroslav@1646: if ((requestedModes & allowedModes) != 0) {
jaroslav@1646: if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
jaroslav@1646: mods, lookupClass(), allowedModes))
jaroslav@1646: return;
jaroslav@1646: } else {
jaroslav@1646: // Protected members can also be checked as if they were package-private.
jaroslav@1646: if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
jaroslav@1646: && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
jaroslav@1646: return;
jaroslav@1646: }
jaroslav@1646: throw m.makeAccessException(accessFailedMessage(refc, m), this);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: String accessFailedMessage(Class> refc, MemberName m) {
jaroslav@1646: Class> defc = m.getDeclaringClass();
jaroslav@1646: int mods = m.getModifiers();
jaroslav@1646: // check the class first:
jaroslav@1646: boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
jaroslav@1646: (defc == refc ||
jaroslav@1646: Modifier.isPublic(refc.getModifiers())));
jaroslav@1646: if (!classOK && (allowedModes & PACKAGE) != 0) {
jaroslav@1646: classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
jaroslav@1646: (defc == refc ||
jaroslav@1646: VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
jaroslav@1646: }
jaroslav@1646: if (!classOK)
jaroslav@1646: return "class is not public";
jaroslav@1646: if (Modifier.isPublic(mods))
jaroslav@1646: return "access to public member failed"; // (how?)
jaroslav@1646: if (Modifier.isPrivate(mods))
jaroslav@1646: return "member is private";
jaroslav@1646: if (Modifier.isProtected(mods))
jaroslav@1646: return "member is protected";
jaroslav@1646: return "member is private to package";
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: private static final boolean ALLOW_NESTMATE_ACCESS = false;
jaroslav@1646:
jaroslav@1646: private void checkSpecialCaller(Class> specialCaller) throws IllegalAccessException {
jaroslav@1646: int allowedModes = this.allowedModes;
jaroslav@1646: if (allowedModes == TRUSTED) return;
jaroslav@1646: if (!hasPrivateAccess()
jaroslav@1646: || (specialCaller != lookupClass()
jaroslav@1646: && !(ALLOW_NESTMATE_ACCESS &&
jaroslav@1646: VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
jaroslav@1646: throw new MemberName(specialCaller).
jaroslav@1646: makeAccessException("no private access for invokespecial", this);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: private boolean restrictProtectedReceiver(MemberName method) {
jaroslav@1646: // The accessing class only has the right to use a protected member
jaroslav@1646: // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc.
jaroslav@1646: if (!method.isProtected() || method.isStatic()
jaroslav@1646: || allowedModes == TRUSTED
jaroslav@1646: || method.getDeclaringClass() == lookupClass()
jaroslav@1646: || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
jaroslav@1646: || (ALLOW_NESTMATE_ACCESS &&
jaroslav@1646: VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
jaroslav@1646: return false;
jaroslav@1646: return true;
jaroslav@1646: }
jaroslav@1646: private MethodHandle restrictReceiver(MemberName method, MethodHandle mh, Class> caller) throws IllegalAccessException {
jaroslav@1646: assert(!method.isStatic());
jaroslav@1646: // receiver type of mh is too wide; narrow to caller
jaroslav@1646: if (!method.getDeclaringClass().isAssignableFrom(caller)) {
jaroslav@1646: throw method.makeAccessException("caller class must be a subclass below the method", caller);
jaroslav@1646: }
jaroslav@1646: MethodType rawType = mh.type();
jaroslav@1646: if (rawType.parameterType(0) == caller) return mh;
jaroslav@1646: MethodType narrowType = rawType.changeParameterType(0, caller);
jaroslav@1646: return mh.viewAsType(narrowType);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /** Check access and get the requested method. */
jaroslav@1646: private MethodHandle getDirectMethod(byte refKind, Class> refc, MemberName method, Class> callerClass) throws IllegalAccessException {
jaroslav@1646: final boolean doRestrict = true;
jaroslav@1646: final boolean checkSecurity = true;
jaroslav@1646: return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
jaroslav@1646: }
jaroslav@1646: /** Check access and get the requested method, eliding receiver narrowing rules. */
jaroslav@1646: private MethodHandle getDirectMethodNoRestrict(byte refKind, Class> refc, MemberName method, Class> callerClass) throws IllegalAccessException {
jaroslav@1646: final boolean doRestrict = false;
jaroslav@1646: final boolean checkSecurity = true;
jaroslav@1646: return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
jaroslav@1646: }
jaroslav@1646: /** Check access and get the requested method, eliding security manager checks. */
jaroslav@1646: private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class> refc, MemberName method, Class> callerClass) throws IllegalAccessException {
jaroslav@1646: final boolean doRestrict = true;
jaroslav@1646: final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
jaroslav@1646: return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
jaroslav@1646: }
jaroslav@1646: /** Common code for all methods; do not call directly except from immediately above. */
jaroslav@1646: private MethodHandle getDirectMethodCommon(byte refKind, Class> refc, MemberName method,
jaroslav@1646: boolean checkSecurity,
jaroslav@1646: boolean doRestrict, Class> callerClass) throws IllegalAccessException {
jaroslav@1646: checkMethod(refKind, refc, method);
jaroslav@1646: // Optionally check with the security manager; this isn't needed for unreflect* calls.
jaroslav@1646: if (checkSecurity)
jaroslav@1646: checkSecurityManager(refc, method);
jaroslav@1646: assert(!method.isMethodHandleInvoke());
jaroslav@1646:
jaroslav@1646: Class> refcAsSuper;
jaroslav@1646: if (refKind == REF_invokeSpecial &&
jaroslav@1646: refc != lookupClass() &&
jaroslav@1646: !refc.isInterface() &&
jaroslav@1646: refc != (refcAsSuper = lookupClass().getSuperclass()) &&
jaroslav@1646: refc.isAssignableFrom(lookupClass())) {
jaroslav@1646: assert(!method.getName().equals("
jaroslav@1646: * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
jaroslav@1646: * the indicated {@code type}.
jaroslav@1646: * That is, if the target is exactly of the given {@code type}, it will behave
jaroslav@1646: * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
jaroslav@1646: * is used to convert the target to the required {@code type}.
jaroslav@1646: *
jaroslav@1646: * The type of the returned invoker will not be the given {@code type}, but rather
jaroslav@1646: * will have all parameters except the first {@code leadingArgCount}
jaroslav@1646: * replaced by a single array of type {@code Object[]}, which will be
jaroslav@1646: * the final parameter.
jaroslav@1646: *
jaroslav@1646: * Before invoking its target, the invoker will spread the final array, apply
jaroslav@1646: * reference casts as necessary, and unbox and widen primitive arguments.
jaroslav@1646: * If, when the invoker is called, the supplied array argument does
jaroslav@1646: * not have the correct number of elements, the invoker will throw
jaroslav@1646: * an {@link IllegalArgumentException} instead of invoking the target.
jaroslav@1646: *
jaroslav@1646: * This method is equivalent to the following code (though it may be more efficient):
jaroslav@1646: *
jaroslav@1646: * This method is equivalent to the following code (though it may be more efficient):
jaroslav@1646: * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * Discussion:
jaroslav@1646: * Invoker method handles can be useful when working with variable method handles
jaroslav@1646: * of unknown types.
jaroslav@1646: * For example, to emulate an {@code invokeExact} call to a variable method
jaroslav@1646: * handle {@code M}, extract its type {@code T},
jaroslav@1646: * look up the invoker method {@code X} for {@code T},
jaroslav@1646: * and call the invoker method, as {@code X.invoke(T, A...)}.
jaroslav@1646: * (It would not work to call {@code X.invokeExact}, since the type {@code T}
jaroslav@1646: * is unknown.)
jaroslav@1646: * If spreading, collecting, or other argument transformations are required,
jaroslav@1646: * they can be applied once to the invoker {@code X} and reused on many {@code M}
jaroslav@1646: * method handle values, as long as they are compatible with the type of {@code X}.
jaroslav@1646: *
jaroslav@1646: * (Note: The invoker method is not available via the Core Reflection API.
jaroslav@1646: * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
jaroslav@1646: * on the declared {@code invokeExact} or {@code invoke} method will raise an
jaroslav@1646: * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)
jaroslav@1646: *
jaroslav@1646: * This method throws no reflective or security exceptions.
jaroslav@1646: * @param type the desired target type
jaroslav@1646: * @return a method handle suitable for invoking any method handle of the given type
jaroslav@1646: * @throws IllegalArgumentException if the resulting method handle's type would have
jaroslav@1646: * too many parameters
jaroslav@1646: */
jaroslav@1646: static public
jaroslav@1646: MethodHandle exactInvoker(MethodType type) {
jaroslav@1646: return type.invokers().exactInvoker();
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a special invoker method handle which can be used to
jaroslav@1646: * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
jaroslav@1646: * The resulting invoker will have a type which is
jaroslav@1646: * exactly equal to the desired type, except that it will accept
jaroslav@1646: * an additional leading argument of type {@code MethodHandle}.
jaroslav@1646: *
jaroslav@1646: * Before invoking its target, if the target differs from the expected type,
jaroslav@1646: * the invoker will apply reference casts as
jaroslav@1646: * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
jaroslav@1646: * Similarly, the return value will be converted as necessary.
jaroslav@1646: * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
jaroslav@1646: * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
jaroslav@1646: *
jaroslav@1646: * This method is equivalent to the following code (though it may be more efficient):
jaroslav@1646: * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
jaroslav@1646: *
jaroslav@1646: * Discussion:
jaroslav@1646: * A {@linkplain MethodType#genericMethodType general method type} is one which
jaroslav@1646: * mentions only {@code Object} arguments and return values.
jaroslav@1646: * An invoker for such a type is capable of calling any method handle
jaroslav@1646: * of the same arity as the general type.
jaroslav@1646: *
jaroslav@1646: * (Note: The invoker method is not available via the Core Reflection API.
jaroslav@1646: * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
jaroslav@1646: * on the declared {@code invokeExact} or {@code invoke} method will raise an
jaroslav@1646: * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)
jaroslav@1646: *
jaroslav@1646: * This method throws no reflective or security exceptions.
jaroslav@1646: * @param type the desired target type
jaroslav@1646: * @return a method handle suitable for invoking any method handle convertible to the given type
jaroslav@1646: * @throws IllegalArgumentException if the resulting method handle's type would have
jaroslav@1646: * too many parameters
jaroslav@1646: */
jaroslav@1646: static public
jaroslav@1646: MethodHandle invoker(MethodType type) {
jaroslav@1646: return type.invokers().generalInvoker();
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: static /*non-public*/
jaroslav@1646: MethodHandle basicInvoker(MethodType type) {
jaroslav@1646: return type.form().basicInvoker();
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /// method handle modification (creation from other method handles)
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle which adapts the type of the
jaroslav@1646: * given method handle to a new type by pairwise argument and return type conversion.
jaroslav@1646: * The original type and new type must have the same number of arguments.
jaroslav@1646: * The resulting method handle is guaranteed to report a type
jaroslav@1646: * which is equal to the desired new type.
jaroslav@1646: *
jaroslav@1646: * If the original type and new type are equal, returns target.
jaroslav@1646: *
jaroslav@1646: * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
jaroslav@1646: * and some additional conversions are also applied if those conversions fail.
jaroslav@1646: * Given types T0, T1, one of the following conversions is applied
jaroslav@1646: * if possible, before or instead of any conversions done by {@code asType}:
jaroslav@1646: *
jaroslav@1646: * The given array controls the reordering.
jaroslav@1646: * Call {@code #I} the number of incoming parameters (the value
jaroslav@1646: * {@code newType.parameterCount()}, and call {@code #O} the number
jaroslav@1646: * of outgoing parameters (the value {@code target.type().parameterCount()}).
jaroslav@1646: * Then the length of the reordering array must be {@code #O},
jaroslav@1646: * and each element must be a non-negative number less than {@code #I}.
jaroslav@1646: * For every {@code N} less than {@code #O}, the {@code N}-th
jaroslav@1646: * outgoing argument will be taken from the {@code I}-th incoming
jaroslav@1646: * argument, where {@code I} is {@code reorder[N]}.
jaroslav@1646: *
jaroslav@1646: * No argument or return value conversions are applied.
jaroslav@1646: * The type of each incoming argument, as determined by {@code newType},
jaroslav@1646: * must be identical to the type of the corresponding outgoing parameter
jaroslav@1646: * or parameters in the target method handle.
jaroslav@1646: * The return type of {@code newType} must be identical to the return
jaroslav@1646: * type of the original target.
jaroslav@1646: *
jaroslav@1646: * The reordering array need not specify an actual permutation.
jaroslav@1646: * An incoming argument will be duplicated if its index appears
jaroslav@1646: * more than once in the array, and an incoming argument will be dropped
jaroslav@1646: * if its index does not appear in the array.
jaroslav@1646: * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
jaroslav@1646: * incoming arguments which are not mentioned in the reordering array
jaroslav@1646: * are may be any type, as determined only by {@code newType}.
jaroslav@1646: *
jaroslav@1646: * Before the method handle is returned, the passed-in value is converted to the requested type.
jaroslav@1646: * If the requested type is primitive, widening primitive conversions are attempted,
jaroslav@1646: * else reference conversions are attempted.
jaroslav@1646: * The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
jaroslav@1646: * @param type the return type of the desired method handle
jaroslav@1646: * @param value the value to return
jaroslav@1646: * @return a method handle of the given return type and no arguments, which always returns the given value
jaroslav@1646: * @throws NullPointerException if the {@code type} argument is null
jaroslav@1646: * @throws ClassCastException if the value cannot be converted to the required return type
jaroslav@1646: * @throws IllegalArgumentException if the given type is {@code void.class}
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle constant(Class> type, Object value) {
jaroslav@1646: if (type.isPrimitive()) {
jaroslav@1646: if (type == void.class)
jaroslav@1646: throw newIllegalArgumentException("void type");
jaroslav@1646: Wrapper w = Wrapper.forPrimitiveType(type);
jaroslav@1646: return insertArguments(identity(type), 0, w.convert(value, type));
jaroslav@1646: } else {
jaroslav@1646: return identity(type).bindTo(type.cast(value));
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle which returns its sole argument when invoked.
jaroslav@1646: * @param type the type of the sole parameter and return value of the desired method handle
jaroslav@1646: * @return a unary method handle which accepts and returns the given type
jaroslav@1646: * @throws NullPointerException if the argument is null
jaroslav@1646: * @throws IllegalArgumentException if the given type is {@code void.class}
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle identity(Class> type) {
jaroslav@1646: if (type == void.class)
jaroslav@1646: throw newIllegalArgumentException("void type");
jaroslav@1646: else if (type == Object.class)
jaroslav@1646: return ValueConversions.identity();
jaroslav@1646: else if (type.isPrimitive())
jaroslav@1646: return ValueConversions.identity(Wrapper.forPrimitiveType(type));
jaroslav@1646: else
jaroslav@1646: return MethodHandleImpl.makeReferenceIdentity(type);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Provides a target method handle with one or more bound arguments
jaroslav@1646: * in advance of the method handle's invocation.
jaroslav@1646: * The formal parameters to the target corresponding to the bound
jaroslav@1646: * arguments are called bound parameters.
jaroslav@1646: * Returns a new method handle which saves away the bound arguments.
jaroslav@1646: * When it is invoked, it receives arguments for any non-bound parameters,
jaroslav@1646: * binds the saved arguments to their corresponding parameters,
jaroslav@1646: * and calls the original target.
jaroslav@1646: *
jaroslav@1646: * The type of the new method handle will drop the types for the bound
jaroslav@1646: * parameters from the original target type, since the new method handle
jaroslav@1646: * will no longer require those arguments to be supplied by its callers.
jaroslav@1646: *
jaroslav@1646: * Each given argument object must match the corresponding bound parameter type.
jaroslav@1646: * If a bound parameter type is a primitive, the argument object
jaroslav@1646: * must be a wrapper, and will be unboxed to produce the primitive value.
jaroslav@1646: *
jaroslav@1646: * The {@code pos} argument selects which parameters are to be bound.
jaroslav@1646: * It may range between zero and N-L (inclusively),
jaroslav@1646: * where N is the arity of the target method handle
jaroslav@1646: * and L is the length of the values array.
jaroslav@1646: * @param target the method handle to invoke after the argument is inserted
jaroslav@1646: * @param pos where to insert the argument (zero for the first)
jaroslav@1646: * @param values the series of arguments to insert
jaroslav@1646: * @return a method handle which inserts an additional argument,
jaroslav@1646: * before calling the original method handle
jaroslav@1646: * @throws NullPointerException if the target or the {@code values} array is null
jaroslav@1646: * @see MethodHandle#bindTo
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
jaroslav@1646: int insCount = values.length;
jaroslav@1646: MethodType oldType = target.type();
jaroslav@1646: int outargs = oldType.parameterCount();
jaroslav@1646: int inargs = outargs - insCount;
jaroslav@1646: if (inargs < 0)
jaroslav@1646: throw newIllegalArgumentException("too many values to insert");
jaroslav@1646: if (pos < 0 || pos > inargs)
jaroslav@1646: throw newIllegalArgumentException("no argument type to append");
jaroslav@1646: MethodHandle result = target;
jaroslav@1646: for (int i = 0; i < insCount; i++) {
jaroslav@1646: Object value = values[i];
jaroslav@1646: Class> ptype = oldType.parameterType(pos+i);
jaroslav@1646: if (ptype.isPrimitive()) {
jaroslav@1646: char btype = 'I';
jaroslav@1646: Wrapper w = Wrapper.forPrimitiveType(ptype);
jaroslav@1646: switch (w) {
jaroslav@1646: case LONG: btype = 'J'; break;
jaroslav@1646: case FLOAT: btype = 'F'; break;
jaroslav@1646: case DOUBLE: btype = 'D'; break;
jaroslav@1646: }
jaroslav@1646: // perform unboxing and/or primitive conversion
jaroslav@1646: value = w.convert(value, ptype);
jaroslav@1646: result = result.bindArgument(pos, btype, value);
jaroslav@1646: continue;
jaroslav@1646: }
jaroslav@1646: value = ptype.cast(value); // throw CCE if needed
jaroslav@1646: if (pos == 0) {
jaroslav@1646: result = result.bindReceiver(value);
jaroslav@1646: } else {
jaroslav@1646: result = result.bindArgument(pos, 'L', value);
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646: return result;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle which will discard some dummy arguments
jaroslav@1646: * before calling some other specified target method handle.
jaroslav@1646: * The type of the new method handle will be the same as the target's type,
jaroslav@1646: * except it will also include the dummy argument types,
jaroslav@1646: * at some given position.
jaroslav@1646: *
jaroslav@1646: * The {@code pos} argument may range between zero and N,
jaroslav@1646: * where N is the arity of the target.
jaroslav@1646: * If {@code pos} is zero, the dummy arguments will precede
jaroslav@1646: * the target's real arguments; if {@code pos} is N
jaroslav@1646: * they will come after.
jaroslav@1646: *
jaroslav@1646: * Example:
jaroslav@1646: *
jaroslav@1646: * This method is also equivalent to the following code:
jaroslav@1646: *
jaroslav@1646: * The {@code pos} argument may range between zero and N,
jaroslav@1646: * where N is the arity of the target.
jaroslav@1646: * If {@code pos} is zero, the dummy arguments will precede
jaroslav@1646: * the target's real arguments; if {@code pos} is N
jaroslav@1646: * they will come after.
jaroslav@1646: *
jaroslav@1646: * Example:
jaroslav@1646: *
jaroslav@1646: * This method is also equivalent to the following code:
jaroslav@1646: *
jaroslav@1646: * The pre-processing is performed by one or more method handles,
jaroslav@1646: * specified in the elements of the {@code filters} array.
jaroslav@1646: * The first element of the filter array corresponds to the {@code pos}
jaroslav@1646: * argument of the target, and so on in sequence.
jaroslav@1646: *
jaroslav@1646: * Null arguments in the array are treated as identity functions,
jaroslav@1646: * and the corresponding arguments left unchanged.
jaroslav@1646: * (If there are no non-null elements in the array, the original target is returned.)
jaroslav@1646: * Each filter is applied to the corresponding argument of the adapter.
jaroslav@1646: *
jaroslav@1646: * If a filter {@code F} applies to the {@code N}th argument of
jaroslav@1646: * the target, then {@code F} must be a method handle which
jaroslav@1646: * takes exactly one argument. The type of {@code F}'s sole argument
jaroslav@1646: * replaces the corresponding argument type of the target
jaroslav@1646: * in the resulting adapted method handle.
jaroslav@1646: * The return type of {@code F} must be identical to the corresponding
jaroslav@1646: * parameter type of the target.
jaroslav@1646: *
jaroslav@1646: * It is an error if there are elements of {@code filters}
jaroslav@1646: * (null or not)
jaroslav@1646: * which do not correspond to argument positions in the target.
jaroslav@1646: * Example:
jaroslav@1646: * Here is pseudocode for the resulting adapter:
jaroslav@1646: *
jaroslav@1646: * If the filter returns a value, the target must accept that value as
jaroslav@1646: * its argument in position {@code pos}, preceded and/or followed by
jaroslav@1646: * any arguments not passed to the filter.
jaroslav@1646: * If the filter returns void, the target must accept all arguments
jaroslav@1646: * not passed to the filter.
jaroslav@1646: * No arguments are reordered, and a result returned from the filter
jaroslav@1646: * replaces (in order) the whole subsequence of arguments originally
jaroslav@1646: * passed to the adapter.
jaroslav@1646: *
jaroslav@1646: * The argument types (if any) of the filter
jaroslav@1646: * replace zero or one argument types of the target, at position {@code pos},
jaroslav@1646: * in the resulting adapted method handle.
jaroslav@1646: * The return type of the filter (if any) must be identical to the
jaroslav@1646: * argument type of the target at position {@code pos}, and that target argument
jaroslav@1646: * is supplied by the return value of the filter.
jaroslav@1646: *
jaroslav@1646: * In all cases, {@code pos} must be greater than or equal to zero, and
jaroslav@1646: * {@code pos} must also be less than or equal to the target's arity.
jaroslav@1646: * Example:
jaroslav@1646: * Here is pseudocode for the resulting adapter:
jaroslav@1646: *
jaroslav@1646: * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
jaroslav@1646: * one which first "folds" the affected arguments, and then drops them, in separate
jaroslav@1646: * steps as follows:
jaroslav@1646: *
jaroslav@1646: * If the target returns a value, the filter must accept that value as
jaroslav@1646: * its only argument.
jaroslav@1646: * If the target returns void, the filter must accept no arguments.
jaroslav@1646: *
jaroslav@1646: * The return type of the filter
jaroslav@1646: * replaces the return type of the target
jaroslav@1646: * in the resulting adapted method handle.
jaroslav@1646: * The argument type of the filter (if any) must be identical to the
jaroslav@1646: * return type of the target.
jaroslav@1646: * Example:
jaroslav@1646: * Here is pseudocode for the resulting adapter:
jaroslav@1646: *
jaroslav@1646: * The pre-processing is performed by {@code combiner}, a second method handle.
jaroslav@1646: * Of the arguments passed to the adapter, the first {@code N} arguments
jaroslav@1646: * are copied to the combiner, which is then called.
jaroslav@1646: * (Here, {@code N} is defined as the parameter count of the combiner.)
jaroslav@1646: * After this, control passes to the target, with any result
jaroslav@1646: * from the combiner inserted before the original {@code N} incoming
jaroslav@1646: * arguments.
jaroslav@1646: *
jaroslav@1646: * If the combiner returns a value, the first parameter type of the target
jaroslav@1646: * must be identical with the return type of the combiner, and the next
jaroslav@1646: * {@code N} parameter types of the target must exactly match the parameters
jaroslav@1646: * of the combiner.
jaroslav@1646: *
jaroslav@1646: * If the combiner has a void return, no result will be inserted,
jaroslav@1646: * and the first {@code N} parameter types of the target
jaroslav@1646: * must exactly match the parameters of the combiner.
jaroslav@1646: *
jaroslav@1646: * The resulting adapter is the same type as the target, except that the
jaroslav@1646: * first parameter type is dropped,
jaroslav@1646: * if it corresponds to the result of the combiner.
jaroslav@1646: *
jaroslav@1646: * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
jaroslav@1646: * that either the combiner or the target does not wish to receive.
jaroslav@1646: * If some of the incoming arguments are destined only for the combiner,
jaroslav@1646: * consider using {@link MethodHandle#asCollector asCollector} instead, since those
jaroslav@1646: * arguments will not need to be live on the stack on entry to the
jaroslav@1646: * target.)
jaroslav@1646: * Example:
jaroslav@1646: * Here is pseudocode for the resulting adapter:
jaroslav@1646: * Here is pseudocode for the resulting adapter:
jaroslav@1646: *
jaroslav@1646: * The target and handler must have the same corresponding
jaroslav@1646: * argument and return types, except that handler may omit trailing arguments
jaroslav@1646: * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
jaroslav@1646: * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
jaroslav@1646: * Here is pseudocode for the resulting adapter:
jaroslav@1646: *
jaroslav@1646: * The target and handler must return the same type, even if the handler
jaroslav@1646: * always throws. (This might happen, for instance, because the handler
jaroslav@1646: * is simulating a {@code finally} clause).
jaroslav@1646: * To create such a throwing handler, compose the handler creation logic
jaroslav@1646: * with {@link #throwException throwException},
jaroslav@1646: * in order to create a method handle of the correct return type.
jaroslav@1646: * @param target method handle to call
jaroslav@1646: * @param exType the type of exception which the handler will catch
jaroslav@1646: * @param handler method handle to call if a matching exception is thrown
jaroslav@1646: * @return method handle which incorporates the specified try/catch logic
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: * @throws IllegalArgumentException if {@code handler} does not accept
jaroslav@1646: * the given exception type, or if the method handle types do
jaroslav@1646: * not match in their return types and their
jaroslav@1646: * corresponding parameters
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle catchException(MethodHandle target,
jaroslav@1646: Class extends Throwable> exType,
jaroslav@1646: MethodHandle handler) {
jaroslav@1646: MethodType ttype = target.type();
jaroslav@1646: MethodType htype = handler.type();
jaroslav@1646: if (htype.parameterCount() < 1 ||
jaroslav@1646: !htype.parameterType(0).isAssignableFrom(exType))
jaroslav@1646: throw newIllegalArgumentException("handler does not accept exception type "+exType);
jaroslav@1646: if (htype.returnType() != ttype.returnType())
jaroslav@1646: throw misMatchedTypes("target and handler return types", ttype, htype);
jaroslav@1646: ListLookup Factory Methods
jaroslav@1646: * The factory methods on a {@code Lookup} object correspond to all major
jaroslav@1646: * use cases for methods, constructors, and fields.
jaroslav@1646: * Each method handle created by a factory method is the functional
jaroslav@1646: * equivalent of a particular bytecode behavior.
jaroslav@1646: * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
jaroslav@1646: * Here is a summary of the correspondence between these factory methods and
jaroslav@1646: * the behavior the resulting method handles:
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * Access checking
jaroslav@1646: * Access checks are applied in the factory methods of {@code Lookup},
jaroslav@1646: * when a method handle is created.
jaroslav@1646: * This is a key difference from the Core Reflection API, since
jaroslav@1646: * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
jaroslav@1646: * performs access checking against every caller, on every call.
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * Security manager interactions
jaroslav@1646: * Although bytecode instructions can only refer to classes in
jaroslav@1646: * a related class loader, this API can search for methods in any
jaroslav@1646: * class, as long as a reference to its {@code Class} object is
jaroslav@1646: * available. Such cross-loader references are also possible with the
jaroslav@1646: * Core Reflection API, and are impossible to bytecode instructions
jaroslav@1646: * such as {@code invokestatic} or {@code getfield}.
jaroslav@1646: * There is a {@linkplain java.lang.SecurityManager security manager API}
jaroslav@1646: * to allow applications to check such cross-loader references.
jaroslav@1646: * These checks apply to both the {@code MethodHandles.Lookup} API
jaroslav@1646: * and the Core Reflection API
jaroslav@1646: * (as found on {@link java.lang.Class Class}).
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * Security checks are performed after other access checks have passed.
jaroslav@1646: * Therefore, the above rules presuppose a member that is public,
jaroslav@1646: * or else that is being accessed from a lookup class that has
jaroslav@1646: * rights to access the member.
jaroslav@1646: *
jaroslav@1646: * Caller sensitive methods
jaroslav@1646: * A small number of Java methods have a special property called caller sensitivity.
jaroslav@1646: * A caller-sensitive method can behave differently depending on the
jaroslav@1646: * identity of its immediate caller.
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * @param requestedLookupClass the desired lookup class for the new lookup object
jaroslav@1646: * @return a lookup object which reports the desired lookup class
jaroslav@1646: * @throws NullPointerException if the argument is null
jaroslav@1646: */
jaroslav@1646: public Lookup in(Class> requestedLookupClass) {
jaroslav@1646: requestedLookupClass.getClass(); // null check
jaroslav@1646: if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all
jaroslav@1646: return new Lookup(requestedLookupClass, ALL_MODES);
jaroslav@1646: if (requestedLookupClass == this.lookupClass)
jaroslav@1646: return this; // keep same capabilities
jaroslav@1646: int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
jaroslav@1646: if ((newModes & PACKAGE) != 0
jaroslav@1646: && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
jaroslav@1646: newModes &= ~(PACKAGE|PRIVATE);
jaroslav@1646: }
jaroslav@1646: // Allow nestmate lookups to be created without special privilege:
jaroslav@1646: if ((newModes & PRIVATE) != 0
jaroslav@1646: && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
jaroslav@1646: newModes &= ~PRIVATE;
jaroslav@1646: }
jaroslav@1646: if ((newModes & PUBLIC) != 0
jaroslav@1646: && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
jaroslav@1646: // The requested class it not accessible from the lookup class.
jaroslav@1646: // No permissions.
jaroslav@1646: newModes = 0;
jaroslav@1646: }
jaroslav@1646: checkUnprivilegedlookupClass(requestedLookupClass, newModes);
jaroslav@1646: return new Lookup(requestedLookupClass, newModes);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: // Make sure outer class is initialized first.
jaroslav@1646: static { IMPL_NAMES.getClass(); }
jaroslav@1646:
jaroslav@1646: /** Version of lookup which is trusted minimally.
jaroslav@1646: * It can only be used to create method handles to
jaroslav@1646: * publicly accessible members.
jaroslav@1646: */
jaroslav@1646: static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
jaroslav@1646:
jaroslav@1646: /** Package-private version of lookup which is trusted. */
jaroslav@1646: static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
jaroslav@1646:
jaroslav@1646: private static void checkUnprivilegedlookupClass(Class> lookupClass, int allowedModes) {
jaroslav@1646: String name = lookupClass.getName();
jaroslav@1646: if (name.startsWith("java.lang.invoke."))
jaroslav@1646: throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
jaroslav@1646:
jaroslav@1646: // For caller-sensitive MethodHandles.lookup()
jaroslav@1646: // disallow lookup more restricted packages
jaroslav@1646: if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
jaroslav@1646: if (name.startsWith("java.") ||
jaroslav@1646: (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
jaroslav@1646: throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Displays the name of the class from which lookups are to be made.
jaroslav@1646: * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
jaroslav@1646: * If there are restrictions on the access permitted to this lookup,
jaroslav@1646: * this is indicated by adding a suffix to the class name, consisting
jaroslav@1646: * of a slash and a keyword. The keyword represents the strongest
jaroslav@1646: * allowed access, and is chosen as follows:
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * If none of the above cases apply, it is the case that full
jaroslav@1646: * access (public, package, private, and protected) is allowed.
jaroslav@1646: * In this case, no suffix is added.
jaroslav@1646: * This is true only of an object obtained originally from
jaroslav@1646: * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
jaroslav@1646: * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
jaroslav@1646: * always have restricted access, and will display a suffix.
jaroslav@1646: *
jaroslav@1646: * @param refc the class from which the method is accessed
jaroslav@1646: * @param name the name of the method
jaroslav@1646: * @param type the type of the method
jaroslav@1646: * @return the desired method handle
jaroslav@1646: * @throws NoSuchMethodException if the method does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails,
jaroslav@1646: * or if the method is not {@code static},
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public
jaroslav@1646: MethodHandle findStatic(Class> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646: MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
jaroslav@1646: return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle for a virtual method.
jaroslav@1646: * The type of the method handle will be that of the method,
jaroslav@1646: * with the receiver type (usually {@code refc}) prepended.
jaroslav@1646: * The method and all its argument types must be accessible to the lookup object.
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
jaroslav@1646: "asList", methodType(List.class, Object[].class));
jaroslav@1646: assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
jaroslav@1646: * }
jaroslav@1646: *
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param name the name of the method
jaroslav@1646: * @param type the type of the method, with the receiver argument omitted
jaroslav@1646: * @return the desired method handle
jaroslav@1646: * @throws NoSuchMethodException if the method does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails,
jaroslav@1646: * or if the method is {@code static}
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findVirtual(Class> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646: if (refc == MethodHandle.class) {
jaroslav@1646: MethodHandle mh = findVirtualForMH(name, type);
jaroslav@1646: if (mh != null) return mh;
jaroslav@1646: }
jaroslav@1646: byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
jaroslav@1646: MemberName method = resolveOrFail(refKind, refc, name, type);
jaroslav@1646: return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
jaroslav@1646: }
jaroslav@1646: private MethodHandle findVirtualForMH(String name, MethodType type) {
jaroslav@1646: // these names require special lookups because of the implicit MethodType argument
jaroslav@1646: if ("invoke".equals(name))
jaroslav@1646: return invoker(type);
jaroslav@1646: if ("invokeExact".equals(name))
jaroslav@1646: return exactInvoker(type);
jaroslav@1646: assert(!MemberName.isMethodHandleInvokeName(name));
jaroslav@1646: return null;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle which creates an object and initializes it, using
jaroslav@1646: * the constructor of the specified type.
jaroslav@1646: * The parameter types of the method handle will be those of the constructor,
jaroslav@1646: * while the return type will be a reference to the constructor's class.
jaroslav@1646: * The constructor and all its argument types must be accessible to the lookup object.
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle MH_concat = publicLookup().findVirtual(String.class,
jaroslav@1646: "concat", methodType(String.class, String.class));
jaroslav@1646: MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
jaroslav@1646: "hashCode", methodType(int.class));
jaroslav@1646: MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
jaroslav@1646: "hashCode", methodType(int.class));
jaroslav@1646: assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
jaroslav@1646: assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
jaroslav@1646: assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
jaroslav@1646: // interface method:
jaroslav@1646: MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
jaroslav@1646: "subSequence", methodType(CharSequence.class, int.class, int.class));
jaroslav@1646: assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
jaroslav@1646: // constructor "internal method" must be accessed differently:
jaroslav@1646: MethodType MT_newString = methodType(void.class); //()V for new String()
jaroslav@1646: try { assertEquals("impossible", lookup()
jaroslav@1646: .findVirtual(String.class, "
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param type the type of the method, with the receiver argument omitted, and a void return type
jaroslav@1646: * @return the desired method handle
jaroslav@1646: * @throws NoSuchMethodException if the constructor does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findConstructor(Class> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646: String name = "{@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle MH_newArrayList = publicLookup().findConstructor(
jaroslav@1646: ArrayList.class, methodType(void.class, Collection.class));
jaroslav@1646: Collection orig = Arrays.asList("x", "y");
jaroslav@1646: Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
jaroslav@1646: assert(orig != copy);
jaroslav@1646: assertEquals(orig, copy);
jaroslav@1646: // a variable-arity constructor:
jaroslav@1646: MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
jaroslav@1646: ProcessBuilder.class, methodType(void.class, String[].class));
jaroslav@1646: ProcessBuilder pb = (ProcessBuilder)
jaroslav@1646: MH_newProcessBuilder.invoke("x", "y", "z");
jaroslav@1646: assertEquals("[x, y, z]", pb.command().toString());
jaroslav@1646: * }
jaroslav@1646: *
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param name the name of the method (which must not be "<init>")
jaroslav@1646: * @param type the type of the method, with the receiver argument omitted
jaroslav@1646: * @param specialCaller the proposed calling class to perform the {@code invokespecial}
jaroslav@1646: * @return the desired method handle
jaroslav@1646: * @throws NoSuchMethodException if the method does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findSpecial(Class> refc, String name, MethodType type,
jaroslav@1646: Class> specialCaller) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646: checkSpecialCaller(specialCaller);
jaroslav@1646: Lookup specialLookup = this.in(specialCaller);
jaroslav@1646: MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
jaroslav@1646: return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle giving read access to a non-static field.
jaroslav@1646: * The type of the method handle will have a return type of the field's
jaroslav@1646: * value type.
jaroslav@1646: * The method handle's single argument will be the instance containing
jaroslav@1646: * the field.
jaroslav@1646: * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param name the field's name
jaroslav@1646: * @param type the field's type
jaroslav@1646: * @return a method handle which can load values from the field
jaroslav@1646: * @throws NoSuchFieldException if the field does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findGetter(Class> refc, String name, Class> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646: MemberName field = resolveOrFail(REF_getField, refc, name, type);
jaroslav@1646: return getDirectField(REF_getField, refc, field);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle giving write access to a non-static field.
jaroslav@1646: * The type of the method handle will have a void return type.
jaroslav@1646: * The method handle will take two arguments, the instance containing
jaroslav@1646: * the field, and the value to be stored.
jaroslav@1646: * The second argument will be of the field's value type.
jaroslav@1646: * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: * @param refc the class or interface from which the method is accessed
jaroslav@1646: * @param name the field's name
jaroslav@1646: * @param type the field's type
jaroslav@1646: * @return a method handle which can store values into the field
jaroslav@1646: * @throws NoSuchFieldException if the field does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: */
jaroslav@1646: public MethodHandle findSetter(Class> refc, String name, Class> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646: MemberName field = resolveOrFail(REF_putField, refc, name, type);
jaroslav@1646: return getDirectField(REF_putField, refc, field);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle giving read access to a static field.
jaroslav@1646: * The type of the method handle will have a return type of the field's
jaroslav@1646: * value type.
jaroslav@1646: * The method handle will take no arguments.
jaroslav@1646: * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: static class Listie extends ArrayList {
jaroslav@1646: public String toString() { return "[wee Listie]"; }
jaroslav@1646: static Lookup lookup() { return MethodHandles.lookup(); }
jaroslav@1646: }
jaroslav@1646: ...
jaroslav@1646: // no access to constructor via invokeSpecial:
jaroslav@1646: MethodHandle MH_newListie = Listie.lookup()
jaroslav@1646: .findConstructor(Listie.class, methodType(void.class));
jaroslav@1646: Listie l = (Listie) MH_newListie.invokeExact();
jaroslav@1646: try { assertEquals("impossible", Listie.lookup().findSpecial(
jaroslav@1646: Listie.class, "
jaroslav@1646: * where {@code defc} is either {@code receiver.getClass()} or a super
jaroslav@1646: * type of that class, in which the requested method is accessible
jaroslav@1646: * to the lookup class.
jaroslav@1646: * (Note that {@code bindTo} does not preserve variable arity.)
jaroslav@1646: * @param receiver the object from which the method is accessed
jaroslav@1646: * @param name the name of the method
jaroslav@1646: * @param type the type of the method, with the receiver argument omitted
jaroslav@1646: * @return the desired method handle
jaroslav@1646: * @throws NoSuchMethodException if the method does not exist
jaroslav@1646: * @throws IllegalAccessException if access checking fails
jaroslav@1646: * or if the method's variable arity modifier bit
jaroslav@1646: * is set and {@code asVarargsCollector} fails
jaroslav@1646: * @exception SecurityException if a security manager is present and it
jaroslav@1646: * refuses access
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: * @see MethodHandle#bindTo
jaroslav@1646: * @see #findVirtual
jaroslav@1646: */
jaroslav@1646: public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646: Class extends Object> refc = receiver.getClass(); // may get NPE
jaroslav@1646: MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
jaroslav@1646: MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
jaroslav@1646: return mh.bindReceiver(receiver).setVarargs(method);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Makes a direct method handle
jaroslav@1646: * to m, if the lookup class has permission.
jaroslav@1646: * If m is non-static, the receiver argument is treated as an initial argument.
jaroslav@1646: * If m is virtual, overriding is respected on every call.
jaroslav@1646: * Unlike the Core Reflection API, exceptions are not wrapped.
jaroslav@1646: * The type of the method handle will be that of the method,
jaroslav@1646: * with the receiver type prepended (but only if it is non-static).
jaroslav@1646: * If the method's {@code accessible} flag is not set,
jaroslav@1646: * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646: * If m is not public, do not share the resulting handle with untrusted parties.
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle mh0 = lookup().findVirtual(defc, name, type);
jaroslav@1646: MethodHandle mh1 = mh0.bindTo(receiver);
jaroslav@1646: MethodType mt1 = mh1.type();
jaroslav@1646: if (mh0.isVarargsCollector())
jaroslav@1646: mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
jaroslav@1646: return mh1;
jaroslav@1646: * }
jaroslav@1646: *
jaroslav@1646: *
jaroslav@1646: * This method throws no reflective or security exceptions.
jaroslav@1646: * @param type the desired target type
jaroslav@1646: * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
jaroslav@1646: * @return a method handle suitable for invoking any method handle of the given type
jaroslav@1646: * @throws NullPointerException if {@code type} is null
jaroslav@1646: * @throws IllegalArgumentException if {@code leadingArgCount} is not in
jaroslav@1646: * the range from 0 to {@code type.parameterCount()} inclusive,
jaroslav@1646: * or if the resulting method handle's type would have
jaroslav@1646: * too many parameters
jaroslav@1646: */
jaroslav@1646: static public
jaroslav@1646: MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
jaroslav@1646: if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
jaroslav@1646: throw new IllegalArgumentException("bad argument count "+leadingArgCount);
jaroslav@1646: return type.invokers().spreadInvoker(leadingArgCount);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a special invoker method handle which can be used to
jaroslav@1646: * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
jaroslav@1646: * The resulting invoker will have a type which is
jaroslav@1646: * exactly equal to the desired type, except that it will accept
jaroslav@1646: * an additional leading argument of type {@code MethodHandle}.
jaroslav@1646: * {@code
jaroslav@1646: MethodHandle invoker = MethodHandles.invoker(type);
jaroslav@1646: int spreadArgCount = type.parameterCount() - leadingArgCount;
jaroslav@1646: invoker = invoker.asSpreader(Object[].class, spreadArgCount);
jaroslav@1646: return invoker;
jaroslav@1646: * }
jaroslav@1646: *
jaroslav@1646: * @param target the method handle to invoke after arguments are retyped
jaroslav@1646: * @param newType the expected type of the new method handle
jaroslav@1646: * @return a method handle which delegates to the target after performing
jaroslav@1646: * any necessary argument conversions, and arranges for any
jaroslav@1646: * necessary return value conversions
jaroslav@1646: * @throws NullPointerException if either argument is null
jaroslav@1646: * @throws WrongMethodTypeException if the conversion cannot be made
jaroslav@1646: * @see MethodHandle#asType
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
jaroslav@1646: if (!target.type().isCastableTo(newType)) {
jaroslav@1646: throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType);
jaroslav@1646: }
jaroslav@1646: return MethodHandleImpl.makePairwiseConvert(target, newType, 2);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle which adapts the calling sequence of the
jaroslav@1646: * given method handle to a new type, by reordering the arguments.
jaroslav@1646: * The resulting method handle is guaranteed to report a type
jaroslav@1646: * which is equal to the desired new type.
jaroslav@1646: *
jaroslav@1646: * @param target the method handle to invoke after arguments are reordered
jaroslav@1646: * @param newType the expected type of the new method handle
jaroslav@1646: * @param reorder an index array which controls the reordering
jaroslav@1646: * @return a method handle which delegates to the target after it
jaroslav@1646: * drops unused arguments and moves and/or duplicates the other arguments
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: * @throws IllegalArgumentException if the index array length is not equal to
jaroslav@1646: * the arity of the target, or if any index array element
jaroslav@1646: * not a valid index for a parameter of {@code newType},
jaroslav@1646: * or if two corresponding parameter types in
jaroslav@1646: * {@code target.type()} and {@code newType} are not identical,
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
jaroslav@1646: checkReorder(reorder, newType, target.type());
jaroslav@1646: return target.permuteArguments(newType, reorder);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) {
jaroslav@1646: if (newType.returnType() != oldType.returnType())
jaroslav@1646: throw newIllegalArgumentException("return types do not match",
jaroslav@1646: oldType, newType);
jaroslav@1646: if (reorder.length == oldType.parameterCount()) {
jaroslav@1646: int limit = newType.parameterCount();
jaroslav@1646: boolean bad = false;
jaroslav@1646: for (int j = 0; j < reorder.length; j++) {
jaroslav@1646: int i = reorder[j];
jaroslav@1646: if (i < 0 || i >= limit) {
jaroslav@1646: bad = true; break;
jaroslav@1646: }
jaroslav@1646: Class> src = newType.parameterType(i);
jaroslav@1646: Class> dst = oldType.parameterType(j);
jaroslav@1646: if (src != dst)
jaroslav@1646: throw newIllegalArgumentException("parameter types do not match after reorder",
jaroslav@1646: oldType, newType);
jaroslav@1646: }
jaroslav@1646: if (!bad) return;
jaroslav@1646: }
jaroslav@1646: throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Produces a method handle of the requested return type which returns the given
jaroslav@1646: * constant value every time it is invoked.
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodType intfn1 = methodType(int.class, int.class);
jaroslav@1646: MethodType intfn2 = methodType(int.class, int.class, int.class);
jaroslav@1646: MethodHandle sub = ... (int x, int y) -> (x-y) ...;
jaroslav@1646: assert(sub.type().equals(intfn2));
jaroslav@1646: MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
jaroslav@1646: MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
jaroslav@1646: assert((int)rsub.invokeExact(1, 100) == 99);
jaroslav@1646: MethodHandle add = ... (int x, int y) -> (x+y) ...;
jaroslav@1646: assert(add.type().equals(intfn2));
jaroslav@1646: MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
jaroslav@1646: assert(twice.type().equals(intfn1));
jaroslav@1646: assert((int)twice.invokeExact(21) == 42);
jaroslav@1646: * }
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646: "concat", methodType(String.class, String.class));
jaroslav@1646: assertEquals("xy", (String) cat.invokeExact("x", "y"));
jaroslav@1646: MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
jaroslav@1646: MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
jaroslav@1646: assertEquals(bigType, d0.type());
jaroslav@1646: assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
jaroslav@1646: * }
jaroslav@1646: * @param target the method handle to invoke after the arguments are dropped
jaroslav@1646: * @param valueTypes the type(s) of the argument(s) to drop
jaroslav@1646: * @param pos position of first argument to drop (zero for the leftmost)
jaroslav@1646: * @return a method handle which drops arguments of the given types,
jaroslav@1646: * before calling the original method handle
jaroslav@1646: * @throws NullPointerException if the target is null,
jaroslav@1646: * or if the {@code valueTypes} list or any of its elements is null
jaroslav@1646: * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
jaroslav@1646: * or if {@code pos} is negative or greater than the arity of the target,
jaroslav@1646: * or if the new method handle's type would have too many parameters
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle dropArguments(MethodHandle target, int pos, List
jaroslav@1646: * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
jaroslav@1646: *
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646: "concat", methodType(String.class, String.class));
jaroslav@1646: assertEquals("xy", (String) cat.invokeExact("x", "y"));
jaroslav@1646: MethodHandle d0 = dropArguments(cat, 0, String.class);
jaroslav@1646: assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
jaroslav@1646: MethodHandle d1 = dropArguments(cat, 1, String.class);
jaroslav@1646: assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
jaroslav@1646: MethodHandle d2 = dropArguments(cat, 2, String.class);
jaroslav@1646: assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
jaroslav@1646: MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
jaroslav@1646: assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
jaroslav@1646: * }
jaroslav@1646: * @param target the method handle to invoke after the arguments are dropped
jaroslav@1646: * @param valueTypes the type(s) of the argument(s) to drop
jaroslav@1646: * @param pos position of first argument to drop (zero for the leftmost)
jaroslav@1646: * @return a method handle which drops arguments of the given types,
jaroslav@1646: * before calling the original method handle
jaroslav@1646: * @throws NullPointerException if the target is null,
jaroslav@1646: * or if the {@code valueTypes} array or any of its elements is null
jaroslav@1646: * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
jaroslav@1646: * or if {@code pos} is negative or greater than the arity of the target,
jaroslav@1646: * or if the new method handle's type would have
jaroslav@1646: * too many parameters
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle dropArguments(MethodHandle target, int pos, Class>... valueTypes) {
jaroslav@1646: return dropArguments(target, pos, Arrays.asList(valueTypes));
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Adapts a target method handle by pre-processing
jaroslav@1646: * one or more of its arguments, each with its own unary filter function,
jaroslav@1646: * and then calling the target with each pre-processed argument
jaroslav@1646: * replaced by the result of its corresponding filter function.
jaroslav@1646: *
jaroslav@1646: * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
jaroslav@1646: *
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646: "concat", methodType(String.class, String.class));
jaroslav@1646: MethodHandle upcase = lookup().findVirtual(String.class,
jaroslav@1646: "toUpperCase", methodType(String.class));
jaroslav@1646: assertEquals("xy", (String) cat.invokeExact("x", "y"));
jaroslav@1646: MethodHandle f0 = filterArguments(cat, 0, upcase);
jaroslav@1646: assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
jaroslav@1646: MethodHandle f1 = filterArguments(cat, 1, upcase);
jaroslav@1646: assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
jaroslav@1646: MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
jaroslav@1646: assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
jaroslav@1646: * }
jaroslav@1646: *
jaroslav@1646: * @param target the method handle to invoke after arguments are filtered
jaroslav@1646: * @param pos the position of the first argument to filter
jaroslav@1646: * @param filters method handles to call initially on filtered arguments
jaroslav@1646: * @return method handle which incorporates the specified argument filtering logic
jaroslav@1646: * @throws NullPointerException if the target is null
jaroslav@1646: * or if the {@code filters} array is null
jaroslav@1646: * @throws IllegalArgumentException if a non-null element of {@code filters}
jaroslav@1646: * does not match a corresponding argument type of target as described above,
jaroslav@1646: * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
jaroslav@1646: * or if the resulting method handle's type would have
jaroslav@1646: * too many parameters
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
jaroslav@1646: MethodType targetType = target.type();
jaroslav@1646: MethodHandle adapter = target;
jaroslav@1646: MethodType adapterType = null;
jaroslav@1646: assert((adapterType = targetType) != null);
jaroslav@1646: int maxPos = targetType.parameterCount();
jaroslav@1646: if (pos + filters.length > maxPos)
jaroslav@1646: throw newIllegalArgumentException("too many filters");
jaroslav@1646: int curPos = pos-1; // pre-incremented
jaroslav@1646: for (MethodHandle filter : filters) {
jaroslav@1646: curPos += 1;
jaroslav@1646: if (filter == null) continue; // ignore null elements of filters
jaroslav@1646: adapter = filterArgument(adapter, curPos, filter);
jaroslav@1646: assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null);
jaroslav@1646: }
jaroslav@1646: assert(adapterType.equals(adapter.type()));
jaroslav@1646: return adapter;
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /*non-public*/ static
jaroslav@1646: MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
jaroslav@1646: MethodType targetType = target.type();
jaroslav@1646: MethodType filterType = filter.type();
jaroslav@1646: if (filterType.parameterCount() != 1
jaroslav@1646: || filterType.returnType() != targetType.parameterType(pos))
jaroslav@1646: throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
jaroslav@1646: return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Adapts a target method handle by pre-processing
jaroslav@1646: * a sub-sequence of its arguments with a filter (another method handle).
jaroslav@1646: * The pre-processed arguments are replaced by the result (if any) of the
jaroslav@1646: * filter function.
jaroslav@1646: * The target is then called on the modified (usually shortened) argument list.
jaroslav@1646: * {@code
jaroslav@1646: * V target(P... p, A[i]... a[i], B... b);
jaroslav@1646: * A[i] filter[i](V[i]);
jaroslav@1646: * T adapter(P... p, V[i]... v[i], B... b) {
jaroslav@1646: * return target(p..., f[i](v[i])..., b...);
jaroslav@1646: * }
jaroslav@1646: * }
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle deepToString = publicLookup()
jaroslav@1646: .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1646:
jaroslav@1646: MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
jaroslav@1646: assertEquals("[strange]", (String) ts1.invokeExact("strange"));
jaroslav@1646:
jaroslav@1646: MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
jaroslav@1646: assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
jaroslav@1646:
jaroslav@1646: MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
jaroslav@1646: MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
jaroslav@1646: assertEquals("[top, [up, down], strange]",
jaroslav@1646: (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
jaroslav@1646:
jaroslav@1646: MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
jaroslav@1646: assertEquals("[top, [up, down], [strange]]",
jaroslav@1646: (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
jaroslav@1646:
jaroslav@1646: MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
jaroslav@1646: assertEquals("[top, [[up, down, strange], charm], bottom]",
jaroslav@1646: (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
jaroslav@1646: * }
jaroslav@1646: * {@code
jaroslav@1646: * T target(A...,V,C...);
jaroslav@1646: * V filter(B...);
jaroslav@1646: * T adapter(A... a,B... b,C... c) {
jaroslav@1646: * V v = filter(b...);
jaroslav@1646: * return target(a...,v,c...);
jaroslav@1646: * }
jaroslav@1646: * // and if the filter has no arguments:
jaroslav@1646: * T target2(A...,V,C...);
jaroslav@1646: * V filter2();
jaroslav@1646: * T adapter2(A... a,C... c) {
jaroslav@1646: * V v = filter2();
jaroslav@1646: * return target2(a...,v,c...);
jaroslav@1646: * }
jaroslav@1646: * // and if the filter has a void return:
jaroslav@1646: * T target3(A...,C...);
jaroslav@1646: * void filter3(B...);
jaroslav@1646: * void adapter3(A... a,B... b,C... c) {
jaroslav@1646: * filter3(b...);
jaroslav@1646: * return target3(a...,c...);
jaroslav@1646: * }
jaroslav@1646: * }
jaroslav@1646: * If the target method handle consumes no arguments besides than the result
jaroslav@1646: * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
jaroslav@1646: * is equivalent to {@code filterReturnValue(coll, mh)}.
jaroslav@1646: * If the filter method handle {@code coll} consumes one argument and produces
jaroslav@1646: * a non-void result, then {@code collectArguments(mh, N, coll)}
jaroslav@1646: * is equivalent to {@code filterArguments(mh, N, coll)}.
jaroslav@1646: * Other equivalences are possible but would require argument permutation.
jaroslav@1646: *
jaroslav@1646: * @param target the method handle to invoke after filtering the subsequence of arguments
jaroslav@1646: * @param pos the position of the first adapter argument to pass to the filter,
jaroslav@1646: * and/or the target argument which receives the result of the filter
jaroslav@1646: * @param filter method handle to call on the subsequence of arguments
jaroslav@1646: * @return method handle which incorporates the specified argument subsequence filtering logic
jaroslav@1646: * @throws NullPointerException if either argument is null
jaroslav@1646: * @throws IllegalArgumentException if the return type of {@code filter}
jaroslav@1646: * is non-void and is not the same as the {@code pos} argument of the target,
jaroslav@1646: * or if {@code pos} is not between 0 and the target's arity, inclusive,
jaroslav@1646: * or if the resulting method handle's type would have
jaroslav@1646: * too many parameters
jaroslav@1646: * @see MethodHandles#foldArguments
jaroslav@1646: * @see MethodHandles#filterArguments
jaroslav@1646: * @see MethodHandles#filterReturnValue
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
jaroslav@1646: MethodType targetType = target.type();
jaroslav@1646: MethodType filterType = filter.type();
jaroslav@1646: if (filterType.returnType() != void.class &&
jaroslav@1646: filterType.returnType() != targetType.parameterType(pos))
jaroslav@1646: throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
jaroslav@1646: return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Adapts a target method handle by post-processing
jaroslav@1646: * its return value (if any) with a filter (another method handle).
jaroslav@1646: * The result of the filter is returned from the adapter.
jaroslav@1646: * {@code
jaroslav@1646: * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
jaroslav@1646: * mh = MethodHandles.foldArguments(mh, coll); //step 1
jaroslav@1646: * }
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646: "concat", methodType(String.class, String.class));
jaroslav@1646: MethodHandle length = lookup().findVirtual(String.class,
jaroslav@1646: "length", methodType(int.class));
jaroslav@1646: System.out.println((String) cat.invokeExact("x", "y")); // xy
jaroslav@1646: MethodHandle f0 = filterReturnValue(cat, length);
jaroslav@1646: System.out.println((int) f0.invokeExact("x", "y")); // 2
jaroslav@1646: * }
jaroslav@1646: * @param target the method handle to invoke before filtering the return value
jaroslav@1646: * @param filter method handle to call on the return value
jaroslav@1646: * @return method handle which incorporates the specified return value filtering logic
jaroslav@1646: * @throws NullPointerException if either argument is null
jaroslav@1646: * @throws IllegalArgumentException if the argument list of {@code filter}
jaroslav@1646: * does not match the return type of target as described above
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
jaroslav@1646: MethodType targetType = target.type();
jaroslav@1646: MethodType filterType = filter.type();
jaroslav@1646: Class> rtype = targetType.returnType();
jaroslav@1646: int filterValues = filterType.parameterCount();
jaroslav@1646: if (filterValues == 0
jaroslav@1646: ? (rtype != void.class)
jaroslav@1646: : (rtype != filterType.parameterType(0)))
jaroslav@1646: throw newIllegalArgumentException("target and filter types do not match", target, filter);
jaroslav@1646: // result = fold( lambda(retval, arg...) { filter(retval) },
jaroslav@1646: // lambda( arg...) { target(arg...) } )
jaroslav@1646: return MethodHandleImpl.makeCollectArguments(filter, target, 0, false);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Adapts a target method handle by pre-processing
jaroslav@1646: * some of its arguments, and then calling the target with
jaroslav@1646: * the result of the pre-processing, inserted into the original
jaroslav@1646: * sequence of arguments.
jaroslav@1646: * {@code
jaroslav@1646: * V target(A...);
jaroslav@1646: * T filter(V);
jaroslav@1646: * T adapter(A... a) {
jaroslav@1646: * V v = target(a...);
jaroslav@1646: * return filter(v);
jaroslav@1646: * }
jaroslav@1646: * // and if the target has a void return:
jaroslav@1646: * void target2(A...);
jaroslav@1646: * T filter2();
jaroslav@1646: * T adapter2(A... a) {
jaroslav@1646: * target2(a...);
jaroslav@1646: * return filter2();
jaroslav@1646: * }
jaroslav@1646: * // and if the filter has a void return:
jaroslav@1646: * V target3(A...);
jaroslav@1646: * void filter3(V);
jaroslav@1646: * void adapter3(A... a) {
jaroslav@1646: * V v = target3(a...);
jaroslav@1646: * filter3(v);
jaroslav@1646: * }
jaroslav@1646: * }
jaroslav@1646: * {@code
jaroslav@1646: import static java.lang.invoke.MethodHandles.*;
jaroslav@1646: import static java.lang.invoke.MethodType.*;
jaroslav@1646: ...
jaroslav@1646: MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
jaroslav@1646: "println", methodType(void.class, String.class))
jaroslav@1646: .bindTo(System.out);
jaroslav@1646: MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646: "concat", methodType(String.class, String.class));
jaroslav@1646: assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
jaroslav@1646: MethodHandle catTrace = foldArguments(cat, trace);
jaroslav@1646: // also prints "boo":
jaroslav@1646: assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
jaroslav@1646: * }
jaroslav@1646: * @param target the method handle to invoke after arguments are combined
jaroslav@1646: * @param combiner method handle to call initially on the incoming arguments
jaroslav@1646: * @return method handle which incorporates the specified argument folding logic
jaroslav@1646: * @throws NullPointerException if either argument is null
jaroslav@1646: * @throws IllegalArgumentException if {@code combiner}'s return type
jaroslav@1646: * is non-void and not the same as the first argument type of
jaroslav@1646: * the target, or if the initial {@code N} argument types
jaroslav@1646: * of the target
jaroslav@1646: * (skipping one matching the {@code combiner}'s return type)
jaroslav@1646: * are not identical with the argument types of {@code combiner}
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
jaroslav@1646: int pos = 0;
jaroslav@1646: MethodType targetType = target.type();
jaroslav@1646: MethodType combinerType = combiner.type();
jaroslav@1646: int foldPos = pos;
jaroslav@1646: int foldArgs = combinerType.parameterCount();
jaroslav@1646: int foldVals = combinerType.returnType() == void.class ? 0 : 1;
jaroslav@1646: int afterInsertPos = foldPos + foldVals;
jaroslav@1646: boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
jaroslav@1646: if (ok && !(combinerType.parameterList()
jaroslav@1646: .equals(targetType.parameterList().subList(afterInsertPos,
jaroslav@1646: afterInsertPos + foldArgs))))
jaroslav@1646: ok = false;
jaroslav@1646: if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0)))
jaroslav@1646: ok = false;
jaroslav@1646: if (!ok)
jaroslav@1646: throw misMatchedTypes("target and combiner types", targetType, combinerType);
jaroslav@1646: MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos);
jaroslav@1646: return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true);
jaroslav@1646: }
jaroslav@1646:
jaroslav@1646: /**
jaroslav@1646: * Makes a method handle which adapts a target method handle,
jaroslav@1646: * by guarding it with a test, a boolean-valued method handle.
jaroslav@1646: * If the guard fails, a fallback handle is called instead.
jaroslav@1646: * All three method handles must have the same corresponding
jaroslav@1646: * argument and return types, except that the return type
jaroslav@1646: * of the test must be boolean, and the test is allowed
jaroslav@1646: * to have fewer arguments than the other two method handles.
jaroslav@1646: * {@code
jaroslav@1646: * // there are N arguments in A...
jaroslav@1646: * T target(V, A[N]..., B...);
jaroslav@1646: * V combiner(A...);
jaroslav@1646: * T adapter(A... a, B... b) {
jaroslav@1646: * V v = combiner(a...);
jaroslav@1646: * return target(v, a..., b...);
jaroslav@1646: * }
jaroslav@1646: * // and if the combiner has a void return:
jaroslav@1646: * T target2(A[N]..., B...);
jaroslav@1646: * void combiner2(A...);
jaroslav@1646: * T adapter2(A... a, B... b) {
jaroslav@1646: * combiner2(a...);
jaroslav@1646: * return target2(a..., b...);
jaroslav@1646: * }
jaroslav@1646: * }
jaroslav@1646: * Note that the test arguments ({@code a...} in the pseudocode) cannot
jaroslav@1646: * be modified by execution of the test, and so are passed unchanged
jaroslav@1646: * from the caller to the target or fallback as appropriate.
jaroslav@1646: * @param test method handle used for test, must return boolean
jaroslav@1646: * @param target method handle to call if test passes
jaroslav@1646: * @param fallback method handle to call if test fails
jaroslav@1646: * @return method handle which incorporates the specified if/then/else logic
jaroslav@1646: * @throws NullPointerException if any argument is null
jaroslav@1646: * @throws IllegalArgumentException if {@code test} does not return boolean,
jaroslav@1646: * or if all three method types do not match (with the return
jaroslav@1646: * type of {@code test} changed to match that of the target).
jaroslav@1646: */
jaroslav@1646: public static
jaroslav@1646: MethodHandle guardWithTest(MethodHandle test,
jaroslav@1646: MethodHandle target,
jaroslav@1646: MethodHandle fallback) {
jaroslav@1646: MethodType gtype = test.type();
jaroslav@1646: MethodType ttype = target.type();
jaroslav@1646: MethodType ftype = fallback.type();
jaroslav@1646: if (!ttype.equals(ftype))
jaroslav@1646: throw misMatchedTypes("target and fallback types", ttype, ftype);
jaroslav@1646: if (gtype.returnType() != boolean.class)
jaroslav@1646: throw newIllegalArgumentException("guard type is not a predicate "+gtype);
jaroslav@1646: List{@code
jaroslav@1646: * boolean test(A...);
jaroslav@1646: * T target(A...,B...);
jaroslav@1646: * T fallback(A...,B...);
jaroslav@1646: * T adapter(A... a,B... b) {
jaroslav@1646: * if (test(a...))
jaroslav@1646: * return target(a..., b...);
jaroslav@1646: * else
jaroslav@1646: * return fallback(a..., b...);
jaroslav@1646: * }
jaroslav@1646: * }
jaroslav@1646: * Note that the saved arguments ({@code a...} in the pseudocode) cannot
jaroslav@1646: * be modified by execution of the target, and so are passed unchanged
jaroslav@1646: * from the caller to the handler, if the handler is invoked.
jaroslav@1646: * {@code
jaroslav@1646: * T target(A..., B...);
jaroslav@1646: * T handler(ExType, A...);
jaroslav@1646: * T adapter(A... a, B... b) {
jaroslav@1646: * try {
jaroslav@1646: * return target(a..., b...);
jaroslav@1646: * } catch (ExType ex) {
jaroslav@1646: * return handler(ex, a...);
jaroslav@1646: * }
jaroslav@1646: * }
jaroslav@1646: * }