rt/emul/compact/src/main/java/java/lang/invoke/MethodHandles.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 11:32:38 +0200
branchjdk8
changeset 1659 d279ddd06652
parent 1651 5c990ed353e9
permissions -rw-r--r--
1st parameter of bootstrap method - the Lookup - is correct
jaroslav@1646
     1
/*
jaroslav@1646
     2
 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1646
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1646
     4
 *
jaroslav@1646
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1646
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1646
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1646
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1646
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1646
    10
 *
jaroslav@1646
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1646
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1646
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1646
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1646
    15
 * accompanied this code).
jaroslav@1646
    16
 *
jaroslav@1646
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1646
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1646
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1646
    20
 *
jaroslav@1646
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1646
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1646
    23
 * questions.
jaroslav@1646
    24
 */
jaroslav@1646
    25
jaroslav@1646
    26
package java.lang.invoke;
jaroslav@1646
    27
jaroslav@1646
    28
import java.lang.reflect.*;
jaroslav@1646
    29
import java.util.List;
jaroslav@1646
    30
import java.util.ArrayList;
jaroslav@1646
    31
import java.util.Arrays;
jaroslav@1646
    32
jaroslav@1646
    33
import sun.invoke.util.ValueConversions;
jaroslav@1646
    34
import sun.invoke.util.VerifyAccess;
jaroslav@1646
    35
import sun.invoke.util.Wrapper;
jaroslav@1646
    36
import static java.lang.invoke.MethodHandleStatics.*;
jaroslav@1646
    37
import static java.lang.invoke.MethodHandleNatives.Constants.*;
jaroslav@1646
    38
import java.util.concurrent.ConcurrentHashMap;
jaroslav@1646
    39
jaroslav@1646
    40
/**
jaroslav@1646
    41
 * This class consists exclusively of static methods that operate on or return
jaroslav@1646
    42
 * method handles. They fall into several categories:
jaroslav@1646
    43
 * <ul>
jaroslav@1646
    44
 * <li>Lookup methods which help create method handles for methods and fields.
jaroslav@1646
    45
 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
jaroslav@1646
    46
 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
jaroslav@1646
    47
 * </ul>
jaroslav@1646
    48
 * <p>
jaroslav@1646
    49
 * @author John Rose, JSR 292 EG
jaroslav@1646
    50
 * @since 1.7
jaroslav@1646
    51
 */
jaroslav@1646
    52
public class MethodHandles {
jaroslav@1646
    53
jaroslav@1646
    54
    private MethodHandles() { }  // do not instantiate
jaroslav@1646
    55
jaroslav@1646
    56
    private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
jaroslav@1646
    57
    static { MethodHandleImpl.initStatics(); }
jaroslav@1646
    58
    // See IMPL_LOOKUP below.
jaroslav@1646
    59
jaroslav@1646
    60
    //// Method handle creation from ordinary methods.
jaroslav@1646
    61
jaroslav@1646
    62
    /**
jaroslav@1646
    63
     * Returns a {@link Lookup lookup object} with
jaroslav@1646
    64
     * full capabilities to emulate all supported bytecode behaviors of the caller.
jaroslav@1646
    65
     * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
jaroslav@1646
    66
     * Factory methods on the lookup object can create
jaroslav@1646
    67
     * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
jaroslav@1646
    68
     * for any member that the caller has access to via bytecodes,
jaroslav@1646
    69
     * including protected and private fields and methods.
jaroslav@1646
    70
     * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
jaroslav@1646
    71
     * Do not store it in place where untrusted code can access it.
jaroslav@1646
    72
     * <p>
jaroslav@1646
    73
     * This method is caller sensitive, which means that it may return different
jaroslav@1646
    74
     * values to different callers.
jaroslav@1646
    75
     * <p>
jaroslav@1646
    76
     * For any given caller class {@code C}, the lookup object returned by this call
jaroslav@1646
    77
     * has equivalent capabilities to any lookup object
jaroslav@1646
    78
     * supplied by the JVM to the bootstrap method of an
jaroslav@1646
    79
     * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
jaroslav@1646
    80
     * executing in the same caller class {@code C}.
jaroslav@1646
    81
     * @return a lookup object for the caller of this method, with private access
jaroslav@1646
    82
     */
jaroslav@1651
    83
//    @CallerSensitive
jaroslav@1646
    84
    public static Lookup lookup() {
jaroslav@1651
    85
        throw new IllegalStateException("Implement me!");
jaroslav@1651
    86
//        return new Lookup(Reflection.getCallerClass());
jaroslav@1646
    87
    }
jaroslav@1646
    88
jaroslav@1646
    89
    /**
jaroslav@1646
    90
     * Returns a {@link Lookup lookup object} which is trusted minimally.
jaroslav@1646
    91
     * It can only be used to create method handles to
jaroslav@1646
    92
     * publicly accessible fields and methods.
jaroslav@1646
    93
     * <p>
jaroslav@1646
    94
     * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
jaroslav@1646
    95
     * of this lookup object will be {@link java.lang.Object}.
jaroslav@1646
    96
     *
jaroslav@1646
    97
     * <p style="font-size:smaller;">
jaroslav@1646
    98
     * <em>Discussion:</em>
jaroslav@1646
    99
     * The lookup class can be changed to any other class {@code C} using an expression of the form
jaroslav@1646
   100
     * {@link Lookup#in publicLookup().in(C.class)}.
jaroslav@1646
   101
     * Since all classes have equal access to public names,
jaroslav@1646
   102
     * such a change would confer no new access rights.
jaroslav@1646
   103
     * A public lookup object is always subject to
jaroslav@1646
   104
     * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
jaroslav@1646
   105
     * Also, it cannot access
jaroslav@1646
   106
     * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
jaroslav@1646
   107
     * @return a lookup object which is trusted minimally
jaroslav@1646
   108
     */
jaroslav@1646
   109
    public static Lookup publicLookup() {
jaroslav@1646
   110
        return Lookup.PUBLIC_LOOKUP;
jaroslav@1646
   111
    }
jaroslav@1646
   112
jaroslav@1646
   113
    /**
jaroslav@1646
   114
     * Performs an unchecked "crack" of a
jaroslav@1646
   115
     * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
jaroslav@1646
   116
     * The result is as if the user had obtained a lookup object capable enough
jaroslav@1646
   117
     * to crack the target method handle, called
jaroslav@1646
   118
     * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
jaroslav@1646
   119
     * on the target to obtain its symbolic reference, and then called
jaroslav@1646
   120
     * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
jaroslav@1646
   121
     * to resolve the symbolic reference to a member.
jaroslav@1646
   122
     * <p>
jaroslav@1646
   123
     * If there is a security manager, its {@code checkPermission} method
jaroslav@1646
   124
     * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
jaroslav@1646
   125
     * @param <T> the desired type of the result, either {@link Member} or a subtype
jaroslav@1646
   126
     * @param target a direct method handle to crack into symbolic reference components
jaroslav@1646
   127
     * @param expected a class object representing the desired result type {@code T}
jaroslav@1646
   128
     * @return a reference to the method, constructor, or field object
jaroslav@1646
   129
     * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
jaroslav@1646
   130
     * @exception NullPointerException if either argument is {@code null}
jaroslav@1646
   131
     * @exception IllegalArgumentException if the target is not a direct method handle
jaroslav@1646
   132
     * @exception ClassCastException if the member is not of the expected type
jaroslav@1646
   133
     * @since 1.8
jaroslav@1646
   134
     */
jaroslav@1646
   135
    public static <T extends Member> T
jaroslav@1646
   136
    reflectAs(Class<T> expected, MethodHandle target) {
jaroslav@1651
   137
//        SecurityManager smgr = System.getSecurityManager();
jaroslav@1651
   138
//        if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
jaroslav@1646
   139
        Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
jaroslav@1646
   140
        return lookup.revealDirect(target).reflectAs(expected, lookup);
jaroslav@1646
   141
    }
jaroslav@1646
   142
    // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
jaroslav@1651
   143
//    static final private java.security.Permission ACCESS_PERMISSION =
jaroslav@1651
   144
//        new ReflectPermission("suppressAccessChecks");
jaroslav@1659
   145
    
jaroslav@1659
   146
    static Lookup findFor(Class<?> clazz) {
jaroslav@1659
   147
        Object o = clazz;
jaroslav@1659
   148
        if (o instanceof Class) {
jaroslav@1659
   149
            return new Lookup(clazz, Lookup.ALL_MODES);
jaroslav@1659
   150
        }
jaroslav@1659
   151
        throw new IllegalArgumentException("Expecting class: " + o);
jaroslav@1659
   152
    }
jaroslav@1646
   153
jaroslav@1646
   154
    /**
jaroslav@1646
   155
     * A <em>lookup object</em> is a factory for creating method handles,
jaroslav@1646
   156
     * when the creation requires access checking.
jaroslav@1646
   157
     * Method handles do not perform
jaroslav@1646
   158
     * access checks when they are called, but rather when they are created.
jaroslav@1646
   159
     * Therefore, method handle access
jaroslav@1646
   160
     * restrictions must be enforced when a method handle is created.
jaroslav@1646
   161
     * The caller class against which those restrictions are enforced
jaroslav@1646
   162
     * is known as the {@linkplain #lookupClass lookup class}.
jaroslav@1646
   163
     * <p>
jaroslav@1646
   164
     * A lookup class which needs to create method handles will call
jaroslav@1646
   165
     * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
jaroslav@1646
   166
     * When the {@code Lookup} factory object is created, the identity of the lookup class is
jaroslav@1646
   167
     * determined, and securely stored in the {@code Lookup} object.
jaroslav@1646
   168
     * The lookup class (or its delegates) may then use factory methods
jaroslav@1646
   169
     * on the {@code Lookup} object to create method handles for access-checked members.
jaroslav@1646
   170
     * This includes all methods, constructors, and fields which are allowed to the lookup class,
jaroslav@1646
   171
     * even private ones.
jaroslav@1646
   172
     *
jaroslav@1646
   173
     * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
jaroslav@1646
   174
     * The factory methods on a {@code Lookup} object correspond to all major
jaroslav@1646
   175
     * use cases for methods, constructors, and fields.
jaroslav@1646
   176
     * Each method handle created by a factory method is the functional
jaroslav@1646
   177
     * equivalent of a particular <em>bytecode behavior</em>.
jaroslav@1646
   178
     * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
jaroslav@1646
   179
     * Here is a summary of the correspondence between these factory methods and
jaroslav@1646
   180
     * the behavior the resulting method handles:
jaroslav@1646
   181
     * <table border=1 cellpadding=5 summary="lookup method behaviors">
jaroslav@1646
   182
     * <tr>
jaroslav@1646
   183
     *     <th><a name="equiv"></a>lookup expression</th>
jaroslav@1646
   184
     *     <th>member</th>
jaroslav@1646
   185
     *     <th>bytecode behavior</th>
jaroslav@1646
   186
     * </tr>
jaroslav@1646
   187
     * <tr>
jaroslav@1646
   188
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
jaroslav@1646
   189
     *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
jaroslav@1646
   190
     * </tr>
jaroslav@1646
   191
     * <tr>
jaroslav@1646
   192
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
jaroslav@1646
   193
     *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
jaroslav@1646
   194
     * </tr>
jaroslav@1646
   195
     * <tr>
jaroslav@1646
   196
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
jaroslav@1646
   197
     *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
jaroslav@1646
   198
     * </tr>
jaroslav@1646
   199
     * <tr>
jaroslav@1646
   200
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
jaroslav@1646
   201
     *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
jaroslav@1646
   202
     * </tr>
jaroslav@1646
   203
     * <tr>
jaroslav@1646
   204
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
jaroslav@1646
   205
     *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
jaroslav@1646
   206
     * </tr>
jaroslav@1646
   207
     * <tr>
jaroslav@1646
   208
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
jaroslav@1646
   209
     *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
jaroslav@1646
   210
     * </tr>
jaroslav@1646
   211
     * <tr>
jaroslav@1646
   212
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
jaroslav@1646
   213
     *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
jaroslav@1646
   214
     * </tr>
jaroslav@1646
   215
     * <tr>
jaroslav@1646
   216
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
jaroslav@1646
   217
     *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
jaroslav@1646
   218
     * </tr>
jaroslav@1646
   219
     * <tr>
jaroslav@1646
   220
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
jaroslav@1646
   221
     *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
jaroslav@1646
   222
     * </tr>
jaroslav@1646
   223
     * <tr>
jaroslav@1646
   224
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
jaroslav@1646
   225
     *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
jaroslav@1646
   226
     * </tr>
jaroslav@1646
   227
     * <tr>
jaroslav@1646
   228
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
jaroslav@1646
   229
     *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
jaroslav@1646
   230
     * </tr>
jaroslav@1646
   231
     * <tr>
jaroslav@1646
   232
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
jaroslav@1646
   233
     *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
jaroslav@1646
   234
     * </tr>
jaroslav@1646
   235
     * <tr>
jaroslav@1646
   236
     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
jaroslav@1646
   237
     *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
jaroslav@1646
   238
     * </tr>
jaroslav@1646
   239
     * </table>
jaroslav@1646
   240
     *
jaroslav@1646
   241
     * Here, the type {@code C} is the class or interface being searched for a member,
jaroslav@1646
   242
     * documented as a parameter named {@code refc} in the lookup methods.
jaroslav@1646
   243
     * The method type {@code MT} is composed from the return type {@code T}
jaroslav@1646
   244
     * and the sequence of argument types {@code A*}.
jaroslav@1646
   245
     * The constructor also has a sequence of argument types {@code A*} and
jaroslav@1646
   246
     * is deemed to return the newly-created object of type {@code C}.
jaroslav@1646
   247
     * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
jaroslav@1646
   248
     * The formal parameter {@code this} stands for the self-reference of type {@code C};
jaroslav@1646
   249
     * if it is present, it is always the leading argument to the method handle invocation.
jaroslav@1646
   250
     * (In the case of some {@code protected} members, {@code this} may be
jaroslav@1646
   251
     * restricted in type to the lookup class; see below.)
jaroslav@1646
   252
     * The name {@code arg} stands for all the other method handle arguments.
jaroslav@1646
   253
     * In the code examples for the Core Reflection API, the name {@code thisOrNull}
jaroslav@1646
   254
     * stands for a null reference if the accessed method or field is static,
jaroslav@1646
   255
     * and {@code this} otherwise.
jaroslav@1646
   256
     * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
jaroslav@1646
   257
     * for reflective objects corresponding to the given members.
jaroslav@1646
   258
     * <p>
jaroslav@1646
   259
     * In cases where the given member is of variable arity (i.e., a method or constructor)
jaroslav@1646
   260
     * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
jaroslav@1646
   261
     * In all other cases, the returned method handle will be of fixed arity.
jaroslav@1646
   262
     * <p style="font-size:smaller;">
jaroslav@1646
   263
     * <em>Discussion:</em>
jaroslav@1646
   264
     * The equivalence between looked-up method handles and underlying
jaroslav@1646
   265
     * class members and bytecode behaviors
jaroslav@1646
   266
     * can break down in a few ways:
jaroslav@1646
   267
     * <ul style="font-size:smaller;">
jaroslav@1646
   268
     * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
jaroslav@1646
   269
     * the lookup can still succeed, even when there is no equivalent
jaroslav@1646
   270
     * Java expression or bytecoded constant.
jaroslav@1646
   271
     * <li>Likewise, if {@code T} or {@code MT}
jaroslav@1646
   272
     * is not symbolically accessible from the lookup class's loader,
jaroslav@1646
   273
     * the lookup can still succeed.
jaroslav@1646
   274
     * For example, lookups for {@code MethodHandle.invokeExact} and
jaroslav@1646
   275
     * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
jaroslav@1646
   276
     * <li>If there is a security manager installed, it can forbid the lookup
jaroslav@1646
   277
     * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
jaroslav@1646
   278
     * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
jaroslav@1646
   279
     * constant is not subject to security manager checks.
jaroslav@1646
   280
     * <li>If the looked-up method has a
jaroslav@1646
   281
     * <a href="MethodHandle.html#maxarity">very large arity</a>,
jaroslav@1646
   282
     * the method handle creation may fail, due to the method handle
jaroslav@1646
   283
     * type having too many parameters.
jaroslav@1646
   284
     * </ul>
jaroslav@1646
   285
     *
jaroslav@1646
   286
     * <h1><a name="access"></a>Access checking</h1>
jaroslav@1646
   287
     * Access checks are applied in the factory methods of {@code Lookup},
jaroslav@1646
   288
     * when a method handle is created.
jaroslav@1646
   289
     * This is a key difference from the Core Reflection API, since
jaroslav@1646
   290
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
jaroslav@1646
   291
     * performs access checking against every caller, on every call.
jaroslav@1646
   292
     * <p>
jaroslav@1646
   293
     * All access checks start from a {@code Lookup} object, which
jaroslav@1646
   294
     * compares its recorded lookup class against all requests to
jaroslav@1646
   295
     * create method handles.
jaroslav@1646
   296
     * A single {@code Lookup} object can be used to create any number
jaroslav@1646
   297
     * of access-checked method handles, all checked against a single
jaroslav@1646
   298
     * lookup class.
jaroslav@1646
   299
     * <p>
jaroslav@1646
   300
     * A {@code Lookup} object can be shared with other trusted code,
jaroslav@1646
   301
     * such as a metaobject protocol.
jaroslav@1646
   302
     * A shared {@code Lookup} object delegates the capability
jaroslav@1646
   303
     * to create method handles on private members of the lookup class.
jaroslav@1646
   304
     * Even if privileged code uses the {@code Lookup} object,
jaroslav@1646
   305
     * the access checking is confined to the privileges of the
jaroslav@1646
   306
     * original lookup class.
jaroslav@1646
   307
     * <p>
jaroslav@1646
   308
     * A lookup can fail, because
jaroslav@1646
   309
     * the containing class is not accessible to the lookup class, or
jaroslav@1646
   310
     * because the desired class member is missing, or because the
jaroslav@1646
   311
     * desired class member is not accessible to the lookup class, or
jaroslav@1646
   312
     * because the lookup object is not trusted enough to access the member.
jaroslav@1646
   313
     * In any of these cases, a {@code ReflectiveOperationException} will be
jaroslav@1646
   314
     * thrown from the attempted lookup.  The exact class will be one of
jaroslav@1646
   315
     * the following:
jaroslav@1646
   316
     * <ul>
jaroslav@1646
   317
     * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
jaroslav@1646
   318
     * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
jaroslav@1646
   319
     * <li>IllegalAccessException &mdash; if the member exists but an access check fails
jaroslav@1646
   320
     * </ul>
jaroslav@1646
   321
     * <p>
jaroslav@1646
   322
     * In general, the conditions under which a method handle may be
jaroslav@1646
   323
     * looked up for a method {@code M} are no more restrictive than the conditions
jaroslav@1646
   324
     * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
jaroslav@1646
   325
     * Where the JVM would raise exceptions like {@code NoSuchMethodError},
jaroslav@1646
   326
     * a method handle lookup will generally raise a corresponding
jaroslav@1646
   327
     * checked exception, such as {@code NoSuchMethodException}.
jaroslav@1646
   328
     * And the effect of invoking the method handle resulting from the lookup
jaroslav@1646
   329
     * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
jaroslav@1646
   330
     * to executing the compiled, verified, and resolved call to {@code M}.
jaroslav@1646
   331
     * The same point is true of fields and constructors.
jaroslav@1646
   332
     * <p style="font-size:smaller;">
jaroslav@1646
   333
     * <em>Discussion:</em>
jaroslav@1646
   334
     * Access checks only apply to named and reflected methods,
jaroslav@1646
   335
     * constructors, and fields.
jaroslav@1646
   336
     * Other method handle creation methods, such as
jaroslav@1646
   337
     * {@link MethodHandle#asType MethodHandle.asType},
jaroslav@1646
   338
     * do not require any access checks, and are used
jaroslav@1646
   339
     * independently of any {@code Lookup} object.
jaroslav@1646
   340
     * <p>
jaroslav@1646
   341
     * If the desired member is {@code protected}, the usual JVM rules apply,
jaroslav@1646
   342
     * including the requirement that the lookup class must be either be in the
jaroslav@1646
   343
     * same package as the desired member, or must inherit that member.
jaroslav@1646
   344
     * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
jaroslav@1646
   345
     * In addition, if the desired member is a non-static field or method
jaroslav@1646
   346
     * in a different package, the resulting method handle may only be applied
jaroslav@1646
   347
     * to objects of the lookup class or one of its subclasses.
jaroslav@1646
   348
     * This requirement is enforced by narrowing the type of the leading
jaroslav@1646
   349
     * {@code this} parameter from {@code C}
jaroslav@1646
   350
     * (which will necessarily be a superclass of the lookup class)
jaroslav@1646
   351
     * to the lookup class itself.
jaroslav@1646
   352
     * <p>
jaroslav@1646
   353
     * The JVM imposes a similar requirement on {@code invokespecial} instruction,
jaroslav@1646
   354
     * that the receiver argument must match both the resolved method <em>and</em>
jaroslav@1646
   355
     * the current class.  Again, this requirement is enforced by narrowing the
jaroslav@1646
   356
     * type of the leading parameter to the resulting method handle.
jaroslav@1646
   357
     * (See the Java Virtual Machine Specification, section 4.10.1.9.)
jaroslav@1646
   358
     * <p>
jaroslav@1646
   359
     * The JVM represents constructors and static initializer blocks as internal methods
jaroslav@1646
   360
     * with special names ({@code "<init>"} and {@code "<clinit>"}).
jaroslav@1646
   361
     * The internal syntax of invocation instructions allows them to refer to such internal
jaroslav@1646
   362
     * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
jaroslav@1646
   363
     * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
jaroslav@1646
   364
     * <p>
jaroslav@1646
   365
     * In some cases, access between nested classes is obtained by the Java compiler by creating
jaroslav@1646
   366
     * an wrapper method to access a private method of another class
jaroslav@1646
   367
     * in the same top-level declaration.
jaroslav@1646
   368
     * For example, a nested class {@code C.D}
jaroslav@1646
   369
     * can access private members within other related classes such as
jaroslav@1646
   370
     * {@code C}, {@code C.D.E}, or {@code C.B},
jaroslav@1646
   371
     * but the Java compiler may need to generate wrapper methods in
jaroslav@1646
   372
     * those related classes.  In such cases, a {@code Lookup} object on
jaroslav@1646
   373
     * {@code C.E} would be unable to those private members.
jaroslav@1646
   374
     * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
jaroslav@1646
   375
     * which can transform a lookup on {@code C.E} into one on any of those other
jaroslav@1646
   376
     * classes, without special elevation of privilege.
jaroslav@1646
   377
     * <p>
jaroslav@1646
   378
     * The accesses permitted to a given lookup object may be limited,
jaroslav@1646
   379
     * according to its set of {@link #lookupModes lookupModes},
jaroslav@1646
   380
     * to a subset of members normally accessible to the lookup class.
jaroslav@1646
   381
     * For example, the {@link MethodHandles#publicLookup publicLookup}
jaroslav@1646
   382
     * method produces a lookup object which is only allowed to access
jaroslav@1646
   383
     * public members in public classes.
jaroslav@1646
   384
     * The caller sensitive method {@link MethodHandles#lookup lookup}
jaroslav@1646
   385
     * produces a lookup object with full capabilities relative to
jaroslav@1646
   386
     * its caller class, to emulate all supported bytecode behaviors.
jaroslav@1646
   387
     * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
jaroslav@1646
   388
     * with fewer access modes than the original lookup object.
jaroslav@1646
   389
     *
jaroslav@1646
   390
     * <p style="font-size:smaller;">
jaroslav@1646
   391
     * <a name="privacc"></a>
jaroslav@1646
   392
     * <em>Discussion of private access:</em>
jaroslav@1646
   393
     * We say that a lookup has <em>private access</em>
jaroslav@1646
   394
     * if its {@linkplain #lookupModes lookup modes}
jaroslav@1646
   395
     * include the possibility of accessing {@code private} members.
jaroslav@1646
   396
     * As documented in the relevant methods elsewhere,
jaroslav@1646
   397
     * only lookups with private access possess the following capabilities:
jaroslav@1646
   398
     * <ul style="font-size:smaller;">
jaroslav@1646
   399
     * <li>access private fields, methods, and constructors of the lookup class
jaroslav@1646
   400
     * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
jaroslav@1646
   401
     *     such as {@code Class.forName}
jaroslav@1646
   402
     * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
jaroslav@1646
   403
     * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
jaroslav@1646
   404
     *     for classes accessible to the lookup class
jaroslav@1646
   405
     * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
jaroslav@1646
   406
     *     within the same package member
jaroslav@1646
   407
     * </ul>
jaroslav@1646
   408
     * <p style="font-size:smaller;">
jaroslav@1646
   409
     * Each of these permissions is a consequence of the fact that a lookup object
jaroslav@1646
   410
     * with private access can be securely traced back to an originating class,
jaroslav@1646
   411
     * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
jaroslav@1646
   412
     * can be reliably determined and emulated by method handles.
jaroslav@1646
   413
     *
jaroslav@1646
   414
     * <h1><a name="secmgr"></a>Security manager interactions</h1>
jaroslav@1646
   415
     * Although bytecode instructions can only refer to classes in
jaroslav@1646
   416
     * a related class loader, this API can search for methods in any
jaroslav@1646
   417
     * class, as long as a reference to its {@code Class} object is
jaroslav@1646
   418
     * available.  Such cross-loader references are also possible with the
jaroslav@1646
   419
     * Core Reflection API, and are impossible to bytecode instructions
jaroslav@1646
   420
     * such as {@code invokestatic} or {@code getfield}.
jaroslav@1646
   421
     * There is a {@linkplain java.lang.SecurityManager security manager API}
jaroslav@1646
   422
     * to allow applications to check such cross-loader references.
jaroslav@1646
   423
     * These checks apply to both the {@code MethodHandles.Lookup} API
jaroslav@1646
   424
     * and the Core Reflection API
jaroslav@1646
   425
     * (as found on {@link java.lang.Class Class}).
jaroslav@1646
   426
     * <p>
jaroslav@1646
   427
     * If a security manager is present, member lookups are subject to
jaroslav@1646
   428
     * additional checks.
jaroslav@1646
   429
     * From one to three calls are made to the security manager.
jaroslav@1646
   430
     * Any of these calls can refuse access by throwing a
jaroslav@1646
   431
     * {@link java.lang.SecurityException SecurityException}.
jaroslav@1646
   432
     * Define {@code smgr} as the security manager,
jaroslav@1646
   433
     * {@code lookc} as the lookup class of the current lookup object,
jaroslav@1646
   434
     * {@code refc} as the containing class in which the member
jaroslav@1646
   435
     * is being sought, and {@code defc} as the class in which the
jaroslav@1646
   436
     * member is actually defined.
jaroslav@1646
   437
     * The value {@code lookc} is defined as <em>not present</em>
jaroslav@1646
   438
     * if the current lookup object does not have
jaroslav@1646
   439
     * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
jaroslav@1646
   440
     * The calls are made according to the following rules:
jaroslav@1646
   441
     * <ul>
jaroslav@1646
   442
     * <li><b>Step 1:</b>
jaroslav@1646
   443
     *     If {@code lookc} is not present, or if its class loader is not
jaroslav@1646
   444
     *     the same as or an ancestor of the class loader of {@code refc},
jaroslav@1646
   445
     *     then {@link SecurityManager#checkPackageAccess
jaroslav@1646
   446
     *     smgr.checkPackageAccess(refcPkg)} is called,
jaroslav@1646
   447
     *     where {@code refcPkg} is the package of {@code refc}.
jaroslav@1646
   448
     * <li><b>Step 2:</b>
jaroslav@1646
   449
     *     If the retrieved member is not public and
jaroslav@1646
   450
     *     {@code lookc} is not present, then
jaroslav@1646
   451
     *     {@link SecurityManager#checkPermission smgr.checkPermission}
jaroslav@1646
   452
     *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
jaroslav@1646
   453
     * <li><b>Step 3:</b>
jaroslav@1646
   454
     *     If the retrieved member is not public,
jaroslav@1646
   455
     *     and if {@code lookc} is not present,
jaroslav@1646
   456
     *     and if {@code defc} and {@code refc} are different,
jaroslav@1646
   457
     *     then {@link SecurityManager#checkPackageAccess
jaroslav@1646
   458
     *     smgr.checkPackageAccess(defcPkg)} is called,
jaroslav@1646
   459
     *     where {@code defcPkg} is the package of {@code defc}.
jaroslav@1646
   460
     * </ul>
jaroslav@1646
   461
     * Security checks are performed after other access checks have passed.
jaroslav@1646
   462
     * Therefore, the above rules presuppose a member that is public,
jaroslav@1646
   463
     * or else that is being accessed from a lookup class that has
jaroslav@1646
   464
     * rights to access the member.
jaroslav@1646
   465
     *
jaroslav@1646
   466
     * <h1><a name="callsens"></a>Caller sensitive methods</h1>
jaroslav@1646
   467
     * A small number of Java methods have a special property called caller sensitivity.
jaroslav@1646
   468
     * A <em>caller-sensitive</em> method can behave differently depending on the
jaroslav@1646
   469
     * identity of its immediate caller.
jaroslav@1646
   470
     * <p>
jaroslav@1646
   471
     * If a method handle for a caller-sensitive method is requested,
jaroslav@1646
   472
     * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
jaroslav@1646
   473
     * but they take account of the lookup class in a special way.
jaroslav@1646
   474
     * The resulting method handle behaves as if it were called
jaroslav@1646
   475
     * from an instruction contained in the lookup class,
jaroslav@1646
   476
     * so that the caller-sensitive method detects the lookup class.
jaroslav@1646
   477
     * (By contrast, the invoker of the method handle is disregarded.)
jaroslav@1646
   478
     * Thus, in the case of caller-sensitive methods,
jaroslav@1646
   479
     * different lookup classes may give rise to
jaroslav@1646
   480
     * differently behaving method handles.
jaroslav@1646
   481
     * <p>
jaroslav@1646
   482
     * In cases where the lookup object is
jaroslav@1646
   483
     * {@link MethodHandles#publicLookup() publicLookup()},
jaroslav@1646
   484
     * or some other lookup object without
jaroslav@1646
   485
     * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
jaroslav@1646
   486
     * the lookup class is disregarded.
jaroslav@1646
   487
     * In such cases, no caller-sensitive method handle can be created,
jaroslav@1646
   488
     * access is forbidden, and the lookup fails with an
jaroslav@1646
   489
     * {@code IllegalAccessException}.
jaroslav@1646
   490
     * <p style="font-size:smaller;">
jaroslav@1646
   491
     * <em>Discussion:</em>
jaroslav@1646
   492
     * For example, the caller-sensitive method
jaroslav@1646
   493
     * {@link java.lang.Class#forName(String) Class.forName(x)}
jaroslav@1646
   494
     * can return varying classes or throw varying exceptions,
jaroslav@1646
   495
     * depending on the class loader of the class that calls it.
jaroslav@1646
   496
     * A public lookup of {@code Class.forName} will fail, because
jaroslav@1646
   497
     * there is no reasonable way to determine its bytecode behavior.
jaroslav@1646
   498
     * <p style="font-size:smaller;">
jaroslav@1646
   499
     * If an application caches method handles for broad sharing,
jaroslav@1646
   500
     * it should use {@code publicLookup()} to create them.
jaroslav@1646
   501
     * If there is a lookup of {@code Class.forName}, it will fail,
jaroslav@1646
   502
     * and the application must take appropriate action in that case.
jaroslav@1646
   503
     * It may be that a later lookup, perhaps during the invocation of a
jaroslav@1646
   504
     * bootstrap method, can incorporate the specific identity
jaroslav@1646
   505
     * of the caller, making the method accessible.
jaroslav@1646
   506
     * <p style="font-size:smaller;">
jaroslav@1646
   507
     * The function {@code MethodHandles.lookup} is caller sensitive
jaroslav@1646
   508
     * so that there can be a secure foundation for lookups.
jaroslav@1646
   509
     * Nearly all other methods in the JSR 292 API rely on lookup
jaroslav@1646
   510
     * objects to check access requests.
jaroslav@1646
   511
     */
jaroslav@1646
   512
    public static final
jaroslav@1646
   513
    class Lookup {
jaroslav@1646
   514
        /** The class on behalf of whom the lookup is being performed. */
jaroslav@1646
   515
        private final Class<?> lookupClass;
jaroslav@1646
   516
jaroslav@1646
   517
        /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
jaroslav@1646
   518
        private final int allowedModes;
jaroslav@1646
   519
jaroslav@1646
   520
        /** A single-bit mask representing {@code public} access,
jaroslav@1646
   521
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646
   522
         *  The value, {@code 0x01}, happens to be the same as the value of the
jaroslav@1646
   523
         *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
jaroslav@1646
   524
         */
jaroslav@1646
   525
        public static final int PUBLIC = Modifier.PUBLIC;
jaroslav@1646
   526
jaroslav@1646
   527
        /** A single-bit mask representing {@code private} access,
jaroslav@1646
   528
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646
   529
         *  The value, {@code 0x02}, happens to be the same as the value of the
jaroslav@1646
   530
         *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
jaroslav@1646
   531
         */
jaroslav@1646
   532
        public static final int PRIVATE = Modifier.PRIVATE;
jaroslav@1646
   533
jaroslav@1646
   534
        /** A single-bit mask representing {@code protected} access,
jaroslav@1646
   535
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646
   536
         *  The value, {@code 0x04}, happens to be the same as the value of the
jaroslav@1646
   537
         *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
jaroslav@1646
   538
         */
jaroslav@1646
   539
        public static final int PROTECTED = Modifier.PROTECTED;
jaroslav@1646
   540
jaroslav@1646
   541
        /** A single-bit mask representing {@code package} access (default access),
jaroslav@1646
   542
         *  which may contribute to the result of {@link #lookupModes lookupModes}.
jaroslav@1646
   543
         *  The value is {@code 0x08}, which does not correspond meaningfully to
jaroslav@1646
   544
         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
jaroslav@1646
   545
         */
jaroslav@1646
   546
        public static final int PACKAGE = Modifier.STATIC;
jaroslav@1646
   547
jaroslav@1646
   548
        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
jaroslav@1646
   549
        private static final int TRUSTED   = -1;
jaroslav@1646
   550
jaroslav@1646
   551
        private static int fixmods(int mods) {
jaroslav@1646
   552
            mods &= (ALL_MODES - PACKAGE);
jaroslav@1646
   553
            return (mods != 0) ? mods : PACKAGE;
jaroslav@1646
   554
        }
jaroslav@1646
   555
jaroslav@1646
   556
        /** Tells which class is performing the lookup.  It is this class against
jaroslav@1646
   557
         *  which checks are performed for visibility and access permissions.
jaroslav@1646
   558
         *  <p>
jaroslav@1646
   559
         *  The class implies a maximum level of access permission,
jaroslav@1646
   560
         *  but the permissions may be additionally limited by the bitmask
jaroslav@1646
   561
         *  {@link #lookupModes lookupModes}, which controls whether non-public members
jaroslav@1646
   562
         *  can be accessed.
jaroslav@1646
   563
         *  @return the lookup class, on behalf of which this lookup object finds members
jaroslav@1646
   564
         */
jaroslav@1646
   565
        public Class<?> lookupClass() {
jaroslav@1646
   566
            return lookupClass;
jaroslav@1646
   567
        }
jaroslav@1646
   568
jaroslav@1646
   569
        // This is just for calling out to MethodHandleImpl.
jaroslav@1646
   570
        private Class<?> lookupClassOrNull() {
jaroslav@1646
   571
            return (allowedModes == TRUSTED) ? null : lookupClass;
jaroslav@1646
   572
        }
jaroslav@1646
   573
jaroslav@1646
   574
        /** Tells which access-protection classes of members this lookup object can produce.
jaroslav@1646
   575
         *  The result is a bit-mask of the bits
jaroslav@1646
   576
         *  {@linkplain #PUBLIC PUBLIC (0x01)},
jaroslav@1646
   577
         *  {@linkplain #PRIVATE PRIVATE (0x02)},
jaroslav@1646
   578
         *  {@linkplain #PROTECTED PROTECTED (0x04)},
jaroslav@1646
   579
         *  and {@linkplain #PACKAGE PACKAGE (0x08)}.
jaroslav@1646
   580
         *  <p>
jaroslav@1646
   581
         *  A freshly-created lookup object
jaroslav@1646
   582
         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
jaroslav@1646
   583
         *  has all possible bits set, since the caller class can access all its own members.
jaroslav@1646
   584
         *  A lookup object on a new lookup class
jaroslav@1646
   585
         *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
jaroslav@1646
   586
         *  may have some mode bits set to zero.
jaroslav@1646
   587
         *  The purpose of this is to restrict access via the new lookup object,
jaroslav@1646
   588
         *  so that it can access only names which can be reached by the original
jaroslav@1646
   589
         *  lookup object, and also by the new lookup class.
jaroslav@1646
   590
         *  @return the lookup modes, which limit the kinds of access performed by this lookup object
jaroslav@1646
   591
         */
jaroslav@1646
   592
        public int lookupModes() {
jaroslav@1646
   593
            return allowedModes & ALL_MODES;
jaroslav@1646
   594
        }
jaroslav@1646
   595
jaroslav@1646
   596
        /** Embody the current class (the lookupClass) as a lookup class
jaroslav@1646
   597
         * for method handle creation.
jaroslav@1646
   598
         * Must be called by from a method in this package,
jaroslav@1646
   599
         * which in turn is called by a method not in this package.
jaroslav@1646
   600
         */
jaroslav@1646
   601
        Lookup(Class<?> lookupClass) {
jaroslav@1646
   602
            this(lookupClass, ALL_MODES);
jaroslav@1646
   603
            // make sure we haven't accidentally picked up a privileged class:
jaroslav@1646
   604
            checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
jaroslav@1646
   605
        }
jaroslav@1646
   606
jaroslav@1646
   607
        private Lookup(Class<?> lookupClass, int allowedModes) {
jaroslav@1646
   608
            this.lookupClass = lookupClass;
jaroslav@1646
   609
            this.allowedModes = allowedModes;
jaroslav@1646
   610
        }
jaroslav@1646
   611
jaroslav@1646
   612
        /**
jaroslav@1646
   613
         * Creates a lookup on the specified new lookup class.
jaroslav@1646
   614
         * The resulting object will report the specified
jaroslav@1646
   615
         * class as its own {@link #lookupClass lookupClass}.
jaroslav@1646
   616
         * <p>
jaroslav@1646
   617
         * However, the resulting {@code Lookup} object is guaranteed
jaroslav@1646
   618
         * to have no more access capabilities than the original.
jaroslav@1646
   619
         * In particular, access capabilities can be lost as follows:<ul>
jaroslav@1646
   620
         * <li>If the new lookup class differs from the old one,
jaroslav@1646
   621
         * protected members will not be accessible by virtue of inheritance.
jaroslav@1646
   622
         * (Protected members may continue to be accessible because of package sharing.)
jaroslav@1646
   623
         * <li>If the new lookup class is in a different package
jaroslav@1646
   624
         * than the old one, protected and default (package) members will not be accessible.
jaroslav@1646
   625
         * <li>If the new lookup class is not within the same package member
jaroslav@1646
   626
         * as the old one, private members will not be accessible.
jaroslav@1646
   627
         * <li>If the new lookup class is not accessible to the old lookup class,
jaroslav@1646
   628
         * then no members, not even public members, will be accessible.
jaroslav@1646
   629
         * (In all other cases, public members will continue to be accessible.)
jaroslav@1646
   630
         * </ul>
jaroslav@1646
   631
         *
jaroslav@1646
   632
         * @param requestedLookupClass the desired lookup class for the new lookup object
jaroslav@1646
   633
         * @return a lookup object which reports the desired lookup class
jaroslav@1646
   634
         * @throws NullPointerException if the argument is null
jaroslav@1646
   635
         */
jaroslav@1646
   636
        public Lookup in(Class<?> requestedLookupClass) {
jaroslav@1646
   637
            requestedLookupClass.getClass();  // null check
jaroslav@1646
   638
            if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
jaroslav@1646
   639
                return new Lookup(requestedLookupClass, ALL_MODES);
jaroslav@1646
   640
            if (requestedLookupClass == this.lookupClass)
jaroslav@1646
   641
                return this;  // keep same capabilities
jaroslav@1646
   642
            int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
jaroslav@1646
   643
            if ((newModes & PACKAGE) != 0
jaroslav@1646
   644
                && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
jaroslav@1646
   645
                newModes &= ~(PACKAGE|PRIVATE);
jaroslav@1646
   646
            }
jaroslav@1646
   647
            // Allow nestmate lookups to be created without special privilege:
jaroslav@1646
   648
            if ((newModes & PRIVATE) != 0
jaroslav@1646
   649
                && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
jaroslav@1646
   650
                newModes &= ~PRIVATE;
jaroslav@1646
   651
            }
jaroslav@1646
   652
            if ((newModes & PUBLIC) != 0
jaroslav@1646
   653
                && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
jaroslav@1646
   654
                // The requested class it not accessible from the lookup class.
jaroslav@1646
   655
                // No permissions.
jaroslav@1646
   656
                newModes = 0;
jaroslav@1646
   657
            }
jaroslav@1646
   658
            checkUnprivilegedlookupClass(requestedLookupClass, newModes);
jaroslav@1646
   659
            return new Lookup(requestedLookupClass, newModes);
jaroslav@1646
   660
        }
jaroslav@1646
   661
jaroslav@1646
   662
        // Make sure outer class is initialized first.
jaroslav@1646
   663
        static { IMPL_NAMES.getClass(); }
jaroslav@1646
   664
jaroslav@1646
   665
        /** Version of lookup which is trusted minimally.
jaroslav@1646
   666
         *  It can only be used to create method handles to
jaroslav@1646
   667
         *  publicly accessible members.
jaroslav@1646
   668
         */
jaroslav@1646
   669
        static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
jaroslav@1646
   670
jaroslav@1646
   671
        /** Package-private version of lookup which is trusted. */
jaroslav@1646
   672
        static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
jaroslav@1646
   673
jaroslav@1646
   674
        private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
jaroslav@1646
   675
            String name = lookupClass.getName();
jaroslav@1646
   676
            if (name.startsWith("java.lang.invoke."))
jaroslav@1646
   677
                throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
jaroslav@1646
   678
jaroslav@1646
   679
            // For caller-sensitive MethodHandles.lookup()
jaroslav@1646
   680
            // disallow lookup more restricted packages
jaroslav@1646
   681
            if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
jaroslav@1646
   682
                if (name.startsWith("java.") ||
jaroslav@1646
   683
                        (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
jaroslav@1646
   684
                    throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
jaroslav@1646
   685
                }
jaroslav@1646
   686
            }
jaroslav@1646
   687
        }
jaroslav@1646
   688
jaroslav@1646
   689
        /**
jaroslav@1646
   690
         * Displays the name of the class from which lookups are to be made.
jaroslav@1646
   691
         * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
jaroslav@1646
   692
         * If there are restrictions on the access permitted to this lookup,
jaroslav@1646
   693
         * this is indicated by adding a suffix to the class name, consisting
jaroslav@1646
   694
         * of a slash and a keyword.  The keyword represents the strongest
jaroslav@1646
   695
         * allowed access, and is chosen as follows:
jaroslav@1646
   696
         * <ul>
jaroslav@1646
   697
         * <li>If no access is allowed, the suffix is "/noaccess".
jaroslav@1646
   698
         * <li>If only public access is allowed, the suffix is "/public".
jaroslav@1646
   699
         * <li>If only public and package access are allowed, the suffix is "/package".
jaroslav@1646
   700
         * <li>If only public, package, and private access are allowed, the suffix is "/private".
jaroslav@1646
   701
         * </ul>
jaroslav@1646
   702
         * If none of the above cases apply, it is the case that full
jaroslav@1646
   703
         * access (public, package, private, and protected) is allowed.
jaroslav@1646
   704
         * In this case, no suffix is added.
jaroslav@1646
   705
         * This is true only of an object obtained originally from
jaroslav@1646
   706
         * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
jaroslav@1646
   707
         * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
jaroslav@1646
   708
         * always have restricted access, and will display a suffix.
jaroslav@1646
   709
         * <p>
jaroslav@1646
   710
         * (It may seem strange that protected access should be
jaroslav@1646
   711
         * stronger than private access.  Viewed independently from
jaroslav@1646
   712
         * package access, protected access is the first to be lost,
jaroslav@1646
   713
         * because it requires a direct subclass relationship between
jaroslav@1646
   714
         * caller and callee.)
jaroslav@1646
   715
         * @see #in
jaroslav@1646
   716
         */
jaroslav@1646
   717
        @Override
jaroslav@1646
   718
        public String toString() {
jaroslav@1646
   719
            String cname = lookupClass.getName();
jaroslav@1646
   720
            switch (allowedModes) {
jaroslav@1646
   721
            case 0:  // no privileges
jaroslav@1646
   722
                return cname + "/noaccess";
jaroslav@1646
   723
            case PUBLIC:
jaroslav@1646
   724
                return cname + "/public";
jaroslav@1646
   725
            case PUBLIC|PACKAGE:
jaroslav@1646
   726
                return cname + "/package";
jaroslav@1646
   727
            case ALL_MODES & ~PROTECTED:
jaroslav@1646
   728
                return cname + "/private";
jaroslav@1646
   729
            case ALL_MODES:
jaroslav@1646
   730
                return cname;
jaroslav@1646
   731
            case TRUSTED:
jaroslav@1646
   732
                return "/trusted";  // internal only; not exported
jaroslav@1646
   733
            default:  // Should not happen, but it's a bitfield...
jaroslav@1646
   734
                cname = cname + "/" + Integer.toHexString(allowedModes);
jaroslav@1646
   735
                assert(false) : cname;
jaroslav@1646
   736
                return cname;
jaroslav@1646
   737
            }
jaroslav@1646
   738
        }
jaroslav@1646
   739
jaroslav@1646
   740
        /**
jaroslav@1646
   741
         * Produces a method handle for a static method.
jaroslav@1646
   742
         * The type of the method handle will be that of the method.
jaroslav@1646
   743
         * (Since static methods do not take receivers, there is no
jaroslav@1646
   744
         * additional receiver argument inserted into the method handle type,
jaroslav@1646
   745
         * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
jaroslav@1646
   746
         * The method and all its argument types must be accessible to the lookup object.
jaroslav@1646
   747
         * <p>
jaroslav@1646
   748
         * The returned method handle will have
jaroslav@1646
   749
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
   750
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
   751
         * <p>
jaroslav@1646
   752
         * If the returned method handle is invoked, the method's class will
jaroslav@1646
   753
         * be initialized, if it has not already been initialized.
jaroslav@1646
   754
         * <p><b>Example:</b>
jaroslav@1646
   755
         * <blockquote><pre>{@code
jaroslav@1646
   756
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
   757
import static java.lang.invoke.MethodType.*;
jaroslav@1646
   758
...
jaroslav@1646
   759
MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
jaroslav@1646
   760
  "asList", methodType(List.class, Object[].class));
jaroslav@1646
   761
assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
jaroslav@1646
   762
         * }</pre></blockquote>
jaroslav@1646
   763
         * @param refc the class from which the method is accessed
jaroslav@1646
   764
         * @param name the name of the method
jaroslav@1646
   765
         * @param type the type of the method
jaroslav@1646
   766
         * @return the desired method handle
jaroslav@1646
   767
         * @throws NoSuchMethodException if the method does not exist
jaroslav@1646
   768
         * @throws IllegalAccessException if access checking fails,
jaroslav@1646
   769
         *                                or if the method is not {@code static},
jaroslav@1646
   770
         *                                or if the method's variable arity modifier bit
jaroslav@1646
   771
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
   772
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
   773
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
   774
         * @throws NullPointerException if any argument is null
jaroslav@1646
   775
         */
jaroslav@1646
   776
        public
jaroslav@1646
   777
        MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646
   778
            MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
jaroslav@1646
   779
            return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
jaroslav@1646
   780
        }
jaroslav@1646
   781
jaroslav@1646
   782
        /**
jaroslav@1646
   783
         * Produces a method handle for a virtual method.
jaroslav@1646
   784
         * The type of the method handle will be that of the method,
jaroslav@1646
   785
         * with the receiver type (usually {@code refc}) prepended.
jaroslav@1646
   786
         * The method and all its argument types must be accessible to the lookup object.
jaroslav@1646
   787
         * <p>
jaroslav@1646
   788
         * When called, the handle will treat the first argument as a receiver
jaroslav@1646
   789
         * and dispatch on the receiver's type to determine which method
jaroslav@1646
   790
         * implementation to enter.
jaroslav@1646
   791
         * (The dispatching action is identical with that performed by an
jaroslav@1646
   792
         * {@code invokevirtual} or {@code invokeinterface} instruction.)
jaroslav@1646
   793
         * <p>
jaroslav@1646
   794
         * The first argument will be of type {@code refc} if the lookup
jaroslav@1646
   795
         * class has full privileges to access the member.  Otherwise
jaroslav@1646
   796
         * the member must be {@code protected} and the first argument
jaroslav@1646
   797
         * will be restricted in type to the lookup class.
jaroslav@1646
   798
         * <p>
jaroslav@1646
   799
         * The returned method handle will have
jaroslav@1646
   800
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
   801
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
   802
         * <p>
jaroslav@1646
   803
         * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
jaroslav@1646
   804
         * instructions and method handles produced by {@code findVirtual},
jaroslav@1646
   805
         * if the class is {@code MethodHandle} and the name string is
jaroslav@1646
   806
         * {@code invokeExact} or {@code invoke}, the resulting
jaroslav@1646
   807
         * method handle is equivalent to one produced by
jaroslav@1646
   808
         * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
jaroslav@1646
   809
         * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
jaroslav@1646
   810
         * with the same {@code type} argument.
jaroslav@1646
   811
         *
jaroslav@1646
   812
         * <b>Example:</b>
jaroslav@1646
   813
         * <blockquote><pre>{@code
jaroslav@1646
   814
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
   815
import static java.lang.invoke.MethodType.*;
jaroslav@1646
   816
...
jaroslav@1646
   817
MethodHandle MH_concat = publicLookup().findVirtual(String.class,
jaroslav@1646
   818
  "concat", methodType(String.class, String.class));
jaroslav@1646
   819
MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
jaroslav@1646
   820
  "hashCode", methodType(int.class));
jaroslav@1646
   821
MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
jaroslav@1646
   822
  "hashCode", methodType(int.class));
jaroslav@1646
   823
assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
jaroslav@1646
   824
assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
jaroslav@1646
   825
assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
jaroslav@1646
   826
// interface method:
jaroslav@1646
   827
MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
jaroslav@1646
   828
  "subSequence", methodType(CharSequence.class, int.class, int.class));
jaroslav@1646
   829
assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
jaroslav@1646
   830
// constructor "internal method" must be accessed differently:
jaroslav@1646
   831
MethodType MT_newString = methodType(void.class); //()V for new String()
jaroslav@1646
   832
try { assertEquals("impossible", lookup()
jaroslav@1646
   833
        .findVirtual(String.class, "<init>", MT_newString));
jaroslav@1646
   834
 } catch (NoSuchMethodException ex) { } // OK
jaroslav@1646
   835
MethodHandle MH_newString = publicLookup()
jaroslav@1646
   836
  .findConstructor(String.class, MT_newString);
jaroslav@1646
   837
assertEquals("", (String) MH_newString.invokeExact());
jaroslav@1646
   838
         * }</pre></blockquote>
jaroslav@1646
   839
         *
jaroslav@1646
   840
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
   841
         * @param name the name of the method
jaroslav@1646
   842
         * @param type the type of the method, with the receiver argument omitted
jaroslav@1646
   843
         * @return the desired method handle
jaroslav@1646
   844
         * @throws NoSuchMethodException if the method does not exist
jaroslav@1646
   845
         * @throws IllegalAccessException if access checking fails,
jaroslav@1646
   846
         *                                or if the method is {@code static}
jaroslav@1646
   847
         *                                or if the method's variable arity modifier bit
jaroslav@1646
   848
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
   849
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
   850
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
   851
         * @throws NullPointerException if any argument is null
jaroslav@1646
   852
         */
jaroslav@1646
   853
        public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646
   854
            if (refc == MethodHandle.class) {
jaroslav@1646
   855
                MethodHandle mh = findVirtualForMH(name, type);
jaroslav@1646
   856
                if (mh != null)  return mh;
jaroslav@1646
   857
            }
jaroslav@1646
   858
            byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
jaroslav@1646
   859
            MemberName method = resolveOrFail(refKind, refc, name, type);
jaroslav@1646
   860
            return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
jaroslav@1646
   861
        }
jaroslav@1646
   862
        private MethodHandle findVirtualForMH(String name, MethodType type) {
jaroslav@1646
   863
            // these names require special lookups because of the implicit MethodType argument
jaroslav@1646
   864
            if ("invoke".equals(name))
jaroslav@1646
   865
                return invoker(type);
jaroslav@1646
   866
            if ("invokeExact".equals(name))
jaroslav@1646
   867
                return exactInvoker(type);
jaroslav@1646
   868
            assert(!MemberName.isMethodHandleInvokeName(name));
jaroslav@1646
   869
            return null;
jaroslav@1646
   870
        }
jaroslav@1646
   871
jaroslav@1646
   872
        /**
jaroslav@1646
   873
         * Produces a method handle which creates an object and initializes it, using
jaroslav@1646
   874
         * the constructor of the specified type.
jaroslav@1646
   875
         * The parameter types of the method handle will be those of the constructor,
jaroslav@1646
   876
         * while the return type will be a reference to the constructor's class.
jaroslav@1646
   877
         * The constructor and all its argument types must be accessible to the lookup object.
jaroslav@1646
   878
         * <p>
jaroslav@1646
   879
         * The requested type must have a return type of {@code void}.
jaroslav@1646
   880
         * (This is consistent with the JVM's treatment of constructor type descriptors.)
jaroslav@1646
   881
         * <p>
jaroslav@1646
   882
         * The returned method handle will have
jaroslav@1646
   883
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
   884
         * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
   885
         * <p>
jaroslav@1646
   886
         * If the returned method handle is invoked, the constructor's class will
jaroslav@1646
   887
         * be initialized, if it has not already been initialized.
jaroslav@1646
   888
         * <p><b>Example:</b>
jaroslav@1646
   889
         * <blockquote><pre>{@code
jaroslav@1646
   890
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
   891
import static java.lang.invoke.MethodType.*;
jaroslav@1646
   892
...
jaroslav@1646
   893
MethodHandle MH_newArrayList = publicLookup().findConstructor(
jaroslav@1646
   894
  ArrayList.class, methodType(void.class, Collection.class));
jaroslav@1646
   895
Collection orig = Arrays.asList("x", "y");
jaroslav@1646
   896
Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
jaroslav@1646
   897
assert(orig != copy);
jaroslav@1646
   898
assertEquals(orig, copy);
jaroslav@1646
   899
// a variable-arity constructor:
jaroslav@1646
   900
MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
jaroslav@1646
   901
  ProcessBuilder.class, methodType(void.class, String[].class));
jaroslav@1646
   902
ProcessBuilder pb = (ProcessBuilder)
jaroslav@1646
   903
  MH_newProcessBuilder.invoke("x", "y", "z");
jaroslav@1646
   904
assertEquals("[x, y, z]", pb.command().toString());
jaroslav@1646
   905
         * }</pre></blockquote>
jaroslav@1646
   906
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
   907
         * @param type the type of the method, with the receiver argument omitted, and a void return type
jaroslav@1646
   908
         * @return the desired method handle
jaroslav@1646
   909
         * @throws NoSuchMethodException if the constructor does not exist
jaroslav@1646
   910
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
   911
         *                                or if the method's variable arity modifier bit
jaroslav@1646
   912
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
   913
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
   914
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
   915
         * @throws NullPointerException if any argument is null
jaroslav@1646
   916
         */
jaroslav@1646
   917
        public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646
   918
            String name = "<init>";
jaroslav@1646
   919
            MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
jaroslav@1646
   920
            return getDirectConstructor(refc, ctor);
jaroslav@1646
   921
        }
jaroslav@1646
   922
jaroslav@1646
   923
        /**
jaroslav@1646
   924
         * Produces an early-bound method handle for a virtual method.
jaroslav@1646
   925
         * It will bypass checks for overriding methods on the receiver,
jaroslav@1646
   926
         * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
jaroslav@1646
   927
         * instruction from within the explicitly specified {@code specialCaller}.
jaroslav@1646
   928
         * The type of the method handle will be that of the method,
jaroslav@1646
   929
         * with a suitably restricted receiver type prepended.
jaroslav@1646
   930
         * (The receiver type will be {@code specialCaller} or a subtype.)
jaroslav@1646
   931
         * The method and all its argument types must be accessible
jaroslav@1646
   932
         * to the lookup object.
jaroslav@1646
   933
         * <p>
jaroslav@1646
   934
         * Before method resolution,
jaroslav@1646
   935
         * if the explicitly specified caller class is not identical with the
jaroslav@1646
   936
         * lookup class, or if this lookup object does not have
jaroslav@1646
   937
         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
jaroslav@1646
   938
         * privileges, the access fails.
jaroslav@1646
   939
         * <p>
jaroslav@1646
   940
         * The returned method handle will have
jaroslav@1646
   941
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
   942
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
   943
         * <p style="font-size:smaller;">
jaroslav@1646
   944
         * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
jaroslav@1646
   945
         * even though the {@code invokespecial} instruction can refer to them
jaroslav@1646
   946
         * in special circumstances.  Use {@link #findConstructor findConstructor}
jaroslav@1646
   947
         * to access instance initialization methods in a safe manner.)</em>
jaroslav@1646
   948
         * <p><b>Example:</b>
jaroslav@1646
   949
         * <blockquote><pre>{@code
jaroslav@1646
   950
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
   951
import static java.lang.invoke.MethodType.*;
jaroslav@1646
   952
...
jaroslav@1646
   953
static class Listie extends ArrayList {
jaroslav@1646
   954
  public String toString() { return "[wee Listie]"; }
jaroslav@1646
   955
  static Lookup lookup() { return MethodHandles.lookup(); }
jaroslav@1646
   956
}
jaroslav@1646
   957
...
jaroslav@1646
   958
// no access to constructor via invokeSpecial:
jaroslav@1646
   959
MethodHandle MH_newListie = Listie.lookup()
jaroslav@1646
   960
  .findConstructor(Listie.class, methodType(void.class));
jaroslav@1646
   961
Listie l = (Listie) MH_newListie.invokeExact();
jaroslav@1646
   962
try { assertEquals("impossible", Listie.lookup().findSpecial(
jaroslav@1646
   963
        Listie.class, "<init>", methodType(void.class), Listie.class));
jaroslav@1646
   964
 } catch (NoSuchMethodException ex) { } // OK
jaroslav@1646
   965
// access to super and self methods via invokeSpecial:
jaroslav@1646
   966
MethodHandle MH_super = Listie.lookup().findSpecial(
jaroslav@1646
   967
  ArrayList.class, "toString" , methodType(String.class), Listie.class);
jaroslav@1646
   968
MethodHandle MH_this = Listie.lookup().findSpecial(
jaroslav@1646
   969
  Listie.class, "toString" , methodType(String.class), Listie.class);
jaroslav@1646
   970
MethodHandle MH_duper = Listie.lookup().findSpecial(
jaroslav@1646
   971
  Object.class, "toString" , methodType(String.class), Listie.class);
jaroslav@1646
   972
assertEquals("[]", (String) MH_super.invokeExact(l));
jaroslav@1646
   973
assertEquals(""+l, (String) MH_this.invokeExact(l));
jaroslav@1646
   974
assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
jaroslav@1646
   975
try { assertEquals("inaccessible", Listie.lookup().findSpecial(
jaroslav@1646
   976
        String.class, "toString", methodType(String.class), Listie.class));
jaroslav@1646
   977
 } catch (IllegalAccessException ex) { } // OK
jaroslav@1646
   978
Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
jaroslav@1646
   979
assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
jaroslav@1646
   980
         * }</pre></blockquote>
jaroslav@1646
   981
         *
jaroslav@1646
   982
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
   983
         * @param name the name of the method (which must not be "&lt;init&gt;")
jaroslav@1646
   984
         * @param type the type of the method, with the receiver argument omitted
jaroslav@1646
   985
         * @param specialCaller the proposed calling class to perform the {@code invokespecial}
jaroslav@1646
   986
         * @return the desired method handle
jaroslav@1646
   987
         * @throws NoSuchMethodException if the method does not exist
jaroslav@1646
   988
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
   989
         *                                or if the method's variable arity modifier bit
jaroslav@1646
   990
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
   991
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
   992
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
   993
         * @throws NullPointerException if any argument is null
jaroslav@1646
   994
         */
jaroslav@1646
   995
        public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
jaroslav@1646
   996
                                        Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646
   997
            checkSpecialCaller(specialCaller);
jaroslav@1646
   998
            Lookup specialLookup = this.in(specialCaller);
jaroslav@1646
   999
            MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
jaroslav@1646
  1000
            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
jaroslav@1646
  1001
        }
jaroslav@1646
  1002
jaroslav@1646
  1003
        /**
jaroslav@1646
  1004
         * Produces a method handle giving read access to a non-static field.
jaroslav@1646
  1005
         * The type of the method handle will have a return type of the field's
jaroslav@1646
  1006
         * value type.
jaroslav@1646
  1007
         * The method handle's single argument will be the instance containing
jaroslav@1646
  1008
         * the field.
jaroslav@1646
  1009
         * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1010
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
  1011
         * @param name the field's name
jaroslav@1646
  1012
         * @param type the field's type
jaroslav@1646
  1013
         * @return a method handle which can load values from the field
jaroslav@1646
  1014
         * @throws NoSuchFieldException if the field does not exist
jaroslav@1646
  1015
         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
jaroslav@1646
  1016
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
  1017
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
  1018
         * @throws NullPointerException if any argument is null
jaroslav@1646
  1019
         */
jaroslav@1646
  1020
        public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646
  1021
            MemberName field = resolveOrFail(REF_getField, refc, name, type);
jaroslav@1646
  1022
            return getDirectField(REF_getField, refc, field);
jaroslav@1646
  1023
        }
jaroslav@1646
  1024
jaroslav@1646
  1025
        /**
jaroslav@1646
  1026
         * Produces a method handle giving write access to a non-static field.
jaroslav@1646
  1027
         * The type of the method handle will have a void return type.
jaroslav@1646
  1028
         * The method handle will take two arguments, the instance containing
jaroslav@1646
  1029
         * the field, and the value to be stored.
jaroslav@1646
  1030
         * The second argument will be of the field's value type.
jaroslav@1646
  1031
         * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1032
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
  1033
         * @param name the field's name
jaroslav@1646
  1034
         * @param type the field's type
jaroslav@1646
  1035
         * @return a method handle which can store values into the field
jaroslav@1646
  1036
         * @throws NoSuchFieldException if the field does not exist
jaroslav@1646
  1037
         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
jaroslav@1646
  1038
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
  1039
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
  1040
         * @throws NullPointerException if any argument is null
jaroslav@1646
  1041
         */
jaroslav@1646
  1042
        public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646
  1043
            MemberName field = resolveOrFail(REF_putField, refc, name, type);
jaroslav@1646
  1044
            return getDirectField(REF_putField, refc, field);
jaroslav@1646
  1045
        }
jaroslav@1646
  1046
jaroslav@1646
  1047
        /**
jaroslav@1646
  1048
         * Produces a method handle giving read access to a static field.
jaroslav@1646
  1049
         * The type of the method handle will have a return type of the field's
jaroslav@1646
  1050
         * value type.
jaroslav@1646
  1051
         * The method handle will take no arguments.
jaroslav@1646
  1052
         * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1053
         * <p>
jaroslav@1646
  1054
         * If the returned method handle is invoked, the field's class will
jaroslav@1646
  1055
         * be initialized, if it has not already been initialized.
jaroslav@1646
  1056
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
  1057
         * @param name the field's name
jaroslav@1646
  1058
         * @param type the field's type
jaroslav@1646
  1059
         * @return a method handle which can load values from the field
jaroslav@1646
  1060
         * @throws NoSuchFieldException if the field does not exist
jaroslav@1646
  1061
         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
jaroslav@1646
  1062
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
  1063
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
  1064
         * @throws NullPointerException if any argument is null
jaroslav@1646
  1065
         */
jaroslav@1646
  1066
        public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646
  1067
            MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
jaroslav@1646
  1068
            return getDirectField(REF_getStatic, refc, field);
jaroslav@1646
  1069
        }
jaroslav@1646
  1070
jaroslav@1646
  1071
        /**
jaroslav@1646
  1072
         * Produces a method handle giving write access to a static field.
jaroslav@1646
  1073
         * The type of the method handle will have a void return type.
jaroslav@1646
  1074
         * The method handle will take a single
jaroslav@1646
  1075
         * argument, of the field's value type, the value to be stored.
jaroslav@1646
  1076
         * Access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1077
         * <p>
jaroslav@1646
  1078
         * If the returned method handle is invoked, the field's class will
jaroslav@1646
  1079
         * be initialized, if it has not already been initialized.
jaroslav@1646
  1080
         * @param refc the class or interface from which the method is accessed
jaroslav@1646
  1081
         * @param name the field's name
jaroslav@1646
  1082
         * @param type the field's type
jaroslav@1646
  1083
         * @return a method handle which can store values into the field
jaroslav@1646
  1084
         * @throws NoSuchFieldException if the field does not exist
jaroslav@1646
  1085
         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
jaroslav@1646
  1086
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
  1087
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
  1088
         * @throws NullPointerException if any argument is null
jaroslav@1646
  1089
         */
jaroslav@1646
  1090
        public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646
  1091
            MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
jaroslav@1646
  1092
            return getDirectField(REF_putStatic, refc, field);
jaroslav@1646
  1093
        }
jaroslav@1646
  1094
jaroslav@1646
  1095
        /**
jaroslav@1646
  1096
         * Produces an early-bound method handle for a non-static method.
jaroslav@1646
  1097
         * The receiver must have a supertype {@code defc} in which a method
jaroslav@1646
  1098
         * of the given name and type is accessible to the lookup class.
jaroslav@1646
  1099
         * The method and all its argument types must be accessible to the lookup object.
jaroslav@1646
  1100
         * The type of the method handle will be that of the method,
jaroslav@1646
  1101
         * without any insertion of an additional receiver parameter.
jaroslav@1646
  1102
         * The given receiver will be bound into the method handle,
jaroslav@1646
  1103
         * so that every call to the method handle will invoke the
jaroslav@1646
  1104
         * requested method on the given receiver.
jaroslav@1646
  1105
         * <p>
jaroslav@1646
  1106
         * The returned method handle will have
jaroslav@1646
  1107
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
  1108
         * the method's variable arity modifier bit ({@code 0x0080}) is set
jaroslav@1646
  1109
         * <em>and</em> the trailing array argument is not the only argument.
jaroslav@1646
  1110
         * (If the trailing array argument is the only argument,
jaroslav@1646
  1111
         * the given receiver value will be bound to it.)
jaroslav@1646
  1112
         * <p>
jaroslav@1646
  1113
         * This is equivalent to the following code:
jaroslav@1646
  1114
         * <blockquote><pre>{@code
jaroslav@1646
  1115
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  1116
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  1117
...
jaroslav@1646
  1118
MethodHandle mh0 = lookup().findVirtual(defc, name, type);
jaroslav@1646
  1119
MethodHandle mh1 = mh0.bindTo(receiver);
jaroslav@1646
  1120
MethodType mt1 = mh1.type();
jaroslav@1646
  1121
if (mh0.isVarargsCollector())
jaroslav@1646
  1122
  mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
jaroslav@1646
  1123
return mh1;
jaroslav@1646
  1124
         * }</pre></blockquote>
jaroslav@1646
  1125
         * where {@code defc} is either {@code receiver.getClass()} or a super
jaroslav@1646
  1126
         * type of that class, in which the requested method is accessible
jaroslav@1646
  1127
         * to the lookup class.
jaroslav@1646
  1128
         * (Note that {@code bindTo} does not preserve variable arity.)
jaroslav@1646
  1129
         * @param receiver the object from which the method is accessed
jaroslav@1646
  1130
         * @param name the name of the method
jaroslav@1646
  1131
         * @param type the type of the method, with the receiver argument omitted
jaroslav@1646
  1132
         * @return the desired method handle
jaroslav@1646
  1133
         * @throws NoSuchMethodException if the method does not exist
jaroslav@1646
  1134
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
  1135
         *                                or if the method's variable arity modifier bit
jaroslav@1646
  1136
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
  1137
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
  1138
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
  1139
         * @throws NullPointerException if any argument is null
jaroslav@1646
  1140
         * @see MethodHandle#bindTo
jaroslav@1646
  1141
         * @see #findVirtual
jaroslav@1646
  1142
         */
jaroslav@1646
  1143
        public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646
  1144
            Class<? extends Object> refc = receiver.getClass(); // may get NPE
jaroslav@1646
  1145
            MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
jaroslav@1646
  1146
            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
jaroslav@1646
  1147
            return mh.bindReceiver(receiver).setVarargs(method);
jaroslav@1646
  1148
        }
jaroslav@1646
  1149
jaroslav@1646
  1150
        /**
jaroslav@1646
  1151
         * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
jaroslav@1646
  1152
         * to <i>m</i>, if the lookup class has permission.
jaroslav@1646
  1153
         * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
jaroslav@1646
  1154
         * If <i>m</i> is virtual, overriding is respected on every call.
jaroslav@1646
  1155
         * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
jaroslav@1646
  1156
         * The type of the method handle will be that of the method,
jaroslav@1646
  1157
         * with the receiver type prepended (but only if it is non-static).
jaroslav@1646
  1158
         * If the method's {@code accessible} flag is not set,
jaroslav@1646
  1159
         * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1160
         * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
jaroslav@1646
  1161
         * <p>
jaroslav@1646
  1162
         * The returned method handle will have
jaroslav@1646
  1163
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
  1164
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
  1165
         * <p>
jaroslav@1646
  1166
         * If <i>m</i> is static, and
jaroslav@1646
  1167
         * if the returned method handle is invoked, the method's class will
jaroslav@1646
  1168
         * be initialized, if it has not already been initialized.
jaroslav@1646
  1169
         * @param m the reflected method
jaroslav@1646
  1170
         * @return a method handle which can invoke the reflected method
jaroslav@1646
  1171
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
  1172
         *                                or if the method's variable arity modifier bit
jaroslav@1646
  1173
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
  1174
         * @throws NullPointerException if the argument is null
jaroslav@1646
  1175
         */
jaroslav@1646
  1176
        public MethodHandle unreflect(Method m) throws IllegalAccessException {
jaroslav@1646
  1177
            if (m.getDeclaringClass() == MethodHandle.class) {
jaroslav@1646
  1178
                MethodHandle mh = unreflectForMH(m);
jaroslav@1646
  1179
                if (mh != null)  return mh;
jaroslav@1646
  1180
            }
jaroslav@1646
  1181
            MemberName method = new MemberName(m);
jaroslav@1646
  1182
            byte refKind = method.getReferenceKind();
jaroslav@1646
  1183
            if (refKind == REF_invokeSpecial)
jaroslav@1646
  1184
                refKind = REF_invokeVirtual;
jaroslav@1646
  1185
            assert(method.isMethod());
jaroslav@1646
  1186
            Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
jaroslav@1646
  1187
            return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
jaroslav@1646
  1188
        }
jaroslav@1646
  1189
        private MethodHandle unreflectForMH(Method m) {
jaroslav@1646
  1190
            // these names require special lookups because they throw UnsupportedOperationException
jaroslav@1646
  1191
            if (MemberName.isMethodHandleInvokeName(m.getName()))
jaroslav@1646
  1192
                return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
jaroslav@1646
  1193
            return null;
jaroslav@1646
  1194
        }
jaroslav@1646
  1195
jaroslav@1646
  1196
        /**
jaroslav@1646
  1197
         * Produces a method handle for a reflected method.
jaroslav@1646
  1198
         * It will bypass checks for overriding methods on the receiver,
jaroslav@1646
  1199
         * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
jaroslav@1646
  1200
         * instruction from within the explicitly specified {@code specialCaller}.
jaroslav@1646
  1201
         * The type of the method handle will be that of the method,
jaroslav@1646
  1202
         * with a suitably restricted receiver type prepended.
jaroslav@1646
  1203
         * (The receiver type will be {@code specialCaller} or a subtype.)
jaroslav@1646
  1204
         * If the method's {@code accessible} flag is not set,
jaroslav@1646
  1205
         * access checking is performed immediately on behalf of the lookup class,
jaroslav@1646
  1206
         * as if {@code invokespecial} instruction were being linked.
jaroslav@1646
  1207
         * <p>
jaroslav@1646
  1208
         * Before method resolution,
jaroslav@1646
  1209
         * if the explicitly specified caller class is not identical with the
jaroslav@1646
  1210
         * lookup class, or if this lookup object does not have
jaroslav@1646
  1211
         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
jaroslav@1646
  1212
         * privileges, the access fails.
jaroslav@1646
  1213
         * <p>
jaroslav@1646
  1214
         * The returned method handle will have
jaroslav@1646
  1215
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
  1216
         * the method's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
  1217
         * @param m the reflected method
jaroslav@1646
  1218
         * @param specialCaller the class nominally calling the method
jaroslav@1646
  1219
         * @return a method handle which can invoke the reflected method
jaroslav@1646
  1220
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
  1221
         *                                or if the method's variable arity modifier bit
jaroslav@1646
  1222
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
  1223
         * @throws NullPointerException if any argument is null
jaroslav@1646
  1224
         */
jaroslav@1646
  1225
        public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
jaroslav@1646
  1226
            checkSpecialCaller(specialCaller);
jaroslav@1646
  1227
            Lookup specialLookup = this.in(specialCaller);
jaroslav@1646
  1228
            MemberName method = new MemberName(m, true);
jaroslav@1646
  1229
            assert(method.isMethod());
jaroslav@1646
  1230
            // ignore m.isAccessible:  this is a new kind of access
jaroslav@1646
  1231
            return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
jaroslav@1646
  1232
        }
jaroslav@1646
  1233
jaroslav@1646
  1234
        /**
jaroslav@1646
  1235
         * Produces a method handle for a reflected constructor.
jaroslav@1646
  1236
         * The type of the method handle will be that of the constructor,
jaroslav@1646
  1237
         * with the return type changed to the declaring class.
jaroslav@1646
  1238
         * The method handle will perform a {@code newInstance} operation,
jaroslav@1646
  1239
         * creating a new instance of the constructor's class on the
jaroslav@1646
  1240
         * arguments passed to the method handle.
jaroslav@1646
  1241
         * <p>
jaroslav@1646
  1242
         * If the constructor's {@code accessible} flag is not set,
jaroslav@1646
  1243
         * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1244
         * <p>
jaroslav@1646
  1245
         * The returned method handle will have
jaroslav@1646
  1246
         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
jaroslav@1646
  1247
         * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
jaroslav@1646
  1248
         * <p>
jaroslav@1646
  1249
         * If the returned method handle is invoked, the constructor's class will
jaroslav@1646
  1250
         * be initialized, if it has not already been initialized.
jaroslav@1646
  1251
         * @param c the reflected constructor
jaroslav@1646
  1252
         * @return a method handle which can invoke the reflected constructor
jaroslav@1646
  1253
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
  1254
         *                                or if the method's variable arity modifier bit
jaroslav@1646
  1255
         *                                is set and {@code asVarargsCollector} fails
jaroslav@1646
  1256
         * @throws NullPointerException if the argument is null
jaroslav@1646
  1257
         */
jaroslav@1646
  1258
        public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
jaroslav@1646
  1259
            MemberName ctor = new MemberName(c);
jaroslav@1646
  1260
            assert(ctor.isConstructor());
jaroslav@1646
  1261
            Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
jaroslav@1646
  1262
            return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
jaroslav@1646
  1263
        }
jaroslav@1646
  1264
jaroslav@1646
  1265
        /**
jaroslav@1646
  1266
         * Produces a method handle giving read access to a reflected field.
jaroslav@1646
  1267
         * The type of the method handle will have a return type of the field's
jaroslav@1646
  1268
         * value type.
jaroslav@1646
  1269
         * If the field is static, the method handle will take no arguments.
jaroslav@1646
  1270
         * Otherwise, its single argument will be the instance containing
jaroslav@1646
  1271
         * the field.
jaroslav@1646
  1272
         * If the field's {@code accessible} flag is not set,
jaroslav@1646
  1273
         * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1274
         * <p>
jaroslav@1646
  1275
         * If the field is static, and
jaroslav@1646
  1276
         * if the returned method handle is invoked, the field's class will
jaroslav@1646
  1277
         * be initialized, if it has not already been initialized.
jaroslav@1646
  1278
         * @param f the reflected field
jaroslav@1646
  1279
         * @return a method handle which can load values from the reflected field
jaroslav@1646
  1280
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
  1281
         * @throws NullPointerException if the argument is null
jaroslav@1646
  1282
         */
jaroslav@1646
  1283
        public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
jaroslav@1646
  1284
            return unreflectField(f, false);
jaroslav@1646
  1285
        }
jaroslav@1646
  1286
        private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
jaroslav@1646
  1287
            MemberName field = new MemberName(f, isSetter);
jaroslav@1646
  1288
            assert(isSetter
jaroslav@1646
  1289
                    ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
jaroslav@1646
  1290
                    : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
jaroslav@1646
  1291
            Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
jaroslav@1646
  1292
            return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
jaroslav@1646
  1293
        }
jaroslav@1646
  1294
jaroslav@1646
  1295
        /**
jaroslav@1646
  1296
         * Produces a method handle giving write access to a reflected field.
jaroslav@1646
  1297
         * The type of the method handle will have a void return type.
jaroslav@1646
  1298
         * If the field is static, the method handle will take a single
jaroslav@1646
  1299
         * argument, of the field's value type, the value to be stored.
jaroslav@1646
  1300
         * Otherwise, the two arguments will be the instance containing
jaroslav@1646
  1301
         * the field, and the value to be stored.
jaroslav@1646
  1302
         * If the field's {@code accessible} flag is not set,
jaroslav@1646
  1303
         * access checking is performed immediately on behalf of the lookup class.
jaroslav@1646
  1304
         * <p>
jaroslav@1646
  1305
         * If the field is static, and
jaroslav@1646
  1306
         * if the returned method handle is invoked, the field's class will
jaroslav@1646
  1307
         * be initialized, if it has not already been initialized.
jaroslav@1646
  1308
         * @param f the reflected field
jaroslav@1646
  1309
         * @return a method handle which can store values into the reflected field
jaroslav@1646
  1310
         * @throws IllegalAccessException if access checking fails
jaroslav@1646
  1311
         * @throws NullPointerException if the argument is null
jaroslav@1646
  1312
         */
jaroslav@1646
  1313
        public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
jaroslav@1646
  1314
            return unreflectField(f, true);
jaroslav@1646
  1315
        }
jaroslav@1646
  1316
jaroslav@1646
  1317
        /**
jaroslav@1646
  1318
         * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
jaroslav@1646
  1319
         * created by this lookup object or a similar one.
jaroslav@1646
  1320
         * Security and access checks are performed to ensure that this lookup object
jaroslav@1646
  1321
         * is capable of reproducing the target method handle.
jaroslav@1646
  1322
         * This means that the cracking may fail if target is a direct method handle
jaroslav@1646
  1323
         * but was created by an unrelated lookup object.
jaroslav@1646
  1324
         * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
jaroslav@1646
  1325
         * and was created by a lookup object for a different class.
jaroslav@1646
  1326
         * @param target a direct method handle to crack into symbolic reference components
jaroslav@1646
  1327
         * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
jaroslav@1646
  1328
         * @exception SecurityException if a security manager is present and it
jaroslav@1646
  1329
         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
jaroslav@1646
  1330
         * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
jaroslav@1646
  1331
         * @exception NullPointerException if the target is {@code null}
jaroslav@1646
  1332
         * @see MethodHandleInfo
jaroslav@1646
  1333
         * @since 1.8
jaroslav@1646
  1334
         */
jaroslav@1646
  1335
        public MethodHandleInfo revealDirect(MethodHandle target) {
jaroslav@1646
  1336
            MemberName member = target.internalMemberName();
jaroslav@1646
  1337
            if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke()))
jaroslav@1646
  1338
                throw newIllegalArgumentException("not a direct method handle");
jaroslav@1646
  1339
            Class<?> defc = member.getDeclaringClass();
jaroslav@1646
  1340
            byte refKind = member.getReferenceKind();
jaroslav@1646
  1341
            assert(MethodHandleNatives.refKindIsValid(refKind));
jaroslav@1646
  1342
            if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
jaroslav@1646
  1343
                // Devirtualized method invocation is usually formally virtual.
jaroslav@1646
  1344
                // To avoid creating extra MemberName objects for this common case,
jaroslav@1646
  1345
                // we encode this extra degree of freedom using MH.isInvokeSpecial.
jaroslav@1646
  1346
                refKind = REF_invokeVirtual;
jaroslav@1646
  1347
            if (refKind == REF_invokeVirtual && defc.isInterface())
jaroslav@1646
  1348
                // Symbolic reference is through interface but resolves to Object method (toString, etc.)
jaroslav@1646
  1349
                refKind = REF_invokeInterface;
jaroslav@1646
  1350
            // Check SM permissions and member access before cracking.
jaroslav@1646
  1351
            try {
jaroslav@1646
  1352
                checkAccess(refKind, defc, member);
jaroslav@1646
  1353
                checkSecurityManager(defc, member);
jaroslav@1646
  1354
            } catch (IllegalAccessException ex) {
jaroslav@1646
  1355
                throw new IllegalArgumentException(ex);
jaroslav@1646
  1356
            }
jaroslav@1646
  1357
            if (allowedModes != TRUSTED && member.isCallerSensitive()) {
jaroslav@1646
  1358
                Class<?> callerClass = target.internalCallerClass();
jaroslav@1646
  1359
                if (!hasPrivateAccess() || callerClass != lookupClass())
jaroslav@1646
  1360
                    throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
jaroslav@1646
  1361
            }
jaroslav@1646
  1362
            // Produce the handle to the results.
jaroslav@1646
  1363
            return new InfoFromMemberName(this, member, refKind);
jaroslav@1646
  1364
        }
jaroslav@1646
  1365
jaroslav@1646
  1366
        /// Helper methods, all package-private.
jaroslav@1646
  1367
jaroslav@1646
  1368
        MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
jaroslav@1646
  1369
            checkSymbolicClass(refc);  // do this before attempting to resolve
jaroslav@1646
  1370
            name.getClass();  // NPE
jaroslav@1646
  1371
            type.getClass();  // NPE
jaroslav@1646
  1372
            return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
jaroslav@1646
  1373
                                            NoSuchFieldException.class);
jaroslav@1646
  1374
        }
jaroslav@1646
  1375
jaroslav@1646
  1376
        MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
jaroslav@1646
  1377
            checkSymbolicClass(refc);  // do this before attempting to resolve
jaroslav@1646
  1378
            name.getClass();  // NPE
jaroslav@1646
  1379
            type.getClass();  // NPE
jaroslav@1646
  1380
            checkMethodName(refKind, name);  // NPE check on name
jaroslav@1646
  1381
            return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
jaroslav@1646
  1382
                                            NoSuchMethodException.class);
jaroslav@1646
  1383
        }
jaroslav@1646
  1384
jaroslav@1646
  1385
        MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
jaroslav@1646
  1386
            checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
jaroslav@1646
  1387
            member.getName().getClass();  // NPE
jaroslav@1646
  1388
            member.getType().getClass();  // NPE
jaroslav@1646
  1389
            return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
jaroslav@1646
  1390
                                            ReflectiveOperationException.class);
jaroslav@1646
  1391
        }
jaroslav@1646
  1392
jaroslav@1646
  1393
        void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
jaroslav@1646
  1394
            refc.getClass();  // NPE
jaroslav@1646
  1395
            Class<?> caller = lookupClassOrNull();
jaroslav@1646
  1396
            if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
jaroslav@1646
  1397
                throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this);
jaroslav@1646
  1398
        }
jaroslav@1646
  1399
jaroslav@1646
  1400
        /** Check name for an illegal leading "&lt;" character. */
jaroslav@1646
  1401
        void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
jaroslav@1646
  1402
            if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
jaroslav@1646
  1403
                throw new NoSuchMethodException("illegal method name: "+name);
jaroslav@1646
  1404
        }
jaroslav@1646
  1405
jaroslav@1646
  1406
jaroslav@1646
  1407
        /**
jaroslav@1646
  1408
         * Find my trustable caller class if m is a caller sensitive method.
jaroslav@1646
  1409
         * If this lookup object has private access, then the caller class is the lookupClass.
jaroslav@1646
  1410
         * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
jaroslav@1646
  1411
         */
jaroslav@1646
  1412
        Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
jaroslav@1646
  1413
            Class<?> callerClass = null;
jaroslav@1646
  1414
            if (MethodHandleNatives.isCallerSensitive(m)) {
jaroslav@1646
  1415
                // Only lookups with private access are allowed to resolve caller-sensitive methods
jaroslav@1646
  1416
                if (hasPrivateAccess()) {
jaroslav@1646
  1417
                    callerClass = lookupClass;
jaroslav@1646
  1418
                } else {
jaroslav@1646
  1419
                    throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
jaroslav@1646
  1420
                }
jaroslav@1646
  1421
            }
jaroslav@1646
  1422
            return callerClass;
jaroslav@1646
  1423
        }
jaroslav@1646
  1424
jaroslav@1646
  1425
        private boolean hasPrivateAccess() {
jaroslav@1646
  1426
            return (allowedModes & PRIVATE) != 0;
jaroslav@1646
  1427
        }
jaroslav@1646
  1428
jaroslav@1646
  1429
        /**
jaroslav@1646
  1430
         * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
jaroslav@1646
  1431
         * Determines a trustable caller class to compare with refc, the symbolic reference class.
jaroslav@1646
  1432
         * If this lookup object has private access, then the caller class is the lookupClass.
jaroslav@1646
  1433
         */
jaroslav@1646
  1434
        void checkSecurityManager(Class<?> refc, MemberName m) {
jaroslav@1651
  1435
//            SecurityManager smgr = System.getSecurityManager();
jaroslav@1651
  1436
//            if (smgr == null)  return;
jaroslav@1651
  1437
//            if (allowedModes == TRUSTED)  return;
jaroslav@1651
  1438
//
jaroslav@1651
  1439
//            // Step 1:
jaroslav@1651
  1440
//            boolean fullPowerLookup = hasPrivateAccess();
jaroslav@1651
  1441
//            if (!fullPowerLookup ||
jaroslav@1651
  1442
//                !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
jaroslav@1651
  1443
//                ReflectUtil.checkPackageAccess(refc);
jaroslav@1651
  1444
//            }
jaroslav@1651
  1445
//
jaroslav@1651
  1446
//            // Step 2:
jaroslav@1651
  1447
//            if (m.isPublic()) return;
jaroslav@1651
  1448
//            if (!fullPowerLookup) {
jaroslav@1651
  1449
//                smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
jaroslav@1651
  1450
//            }
jaroslav@1651
  1451
//
jaroslav@1651
  1452
//            // Step 3:
jaroslav@1651
  1453
//            Class<?> defc = m.getDeclaringClass();
jaroslav@1651
  1454
//            if (!fullPowerLookup && defc != refc) {
jaroslav@1651
  1455
//                ReflectUtil.checkPackageAccess(defc);
jaroslav@1651
  1456
//            }
jaroslav@1646
  1457
        }
jaroslav@1646
  1458
jaroslav@1646
  1459
        void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
jaroslav@1646
  1460
            boolean wantStatic = (refKind == REF_invokeStatic);
jaroslav@1646
  1461
            String message;
jaroslav@1646
  1462
            if (m.isConstructor())
jaroslav@1646
  1463
                message = "expected a method, not a constructor";
jaroslav@1646
  1464
            else if (!m.isMethod())
jaroslav@1646
  1465
                message = "expected a method";
jaroslav@1646
  1466
            else if (wantStatic != m.isStatic())
jaroslav@1646
  1467
                message = wantStatic ? "expected a static method" : "expected a non-static method";
jaroslav@1646
  1468
            else
jaroslav@1646
  1469
                { checkAccess(refKind, refc, m); return; }
jaroslav@1646
  1470
            throw m.makeAccessException(message, this);
jaroslav@1646
  1471
        }
jaroslav@1646
  1472
jaroslav@1646
  1473
        void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
jaroslav@1646
  1474
            boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
jaroslav@1646
  1475
            String message;
jaroslav@1646
  1476
            if (wantStatic != m.isStatic())
jaroslav@1646
  1477
                message = wantStatic ? "expected a static field" : "expected a non-static field";
jaroslav@1646
  1478
            else
jaroslav@1646
  1479
                { checkAccess(refKind, refc, m); return; }
jaroslav@1646
  1480
            throw m.makeAccessException(message, this);
jaroslav@1646
  1481
        }
jaroslav@1646
  1482
jaroslav@1646
  1483
        /** Check public/protected/private bits on the symbolic reference class and its member. */
jaroslav@1646
  1484
        void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
jaroslav@1646
  1485
            assert(m.referenceKindIsConsistentWith(refKind) &&
jaroslav@1646
  1486
                   MethodHandleNatives.refKindIsValid(refKind) &&
jaroslav@1646
  1487
                   (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
jaroslav@1646
  1488
            int allowedModes = this.allowedModes;
jaroslav@1646
  1489
            if (allowedModes == TRUSTED)  return;
jaroslav@1646
  1490
            int mods = m.getModifiers();
jaroslav@1646
  1491
            if (Modifier.isProtected(mods) &&
jaroslav@1646
  1492
                    refKind == REF_invokeVirtual &&
jaroslav@1646
  1493
                    m.getDeclaringClass() == Object.class &&
jaroslav@1646
  1494
                    m.getName().equals("clone") &&
jaroslav@1646
  1495
                    refc.isArray()) {
jaroslav@1646
  1496
                // The JVM does this hack also.
jaroslav@1646
  1497
                // (See ClassVerifier::verify_invoke_instructions
jaroslav@1646
  1498
                // and LinkResolver::check_method_accessability.)
jaroslav@1646
  1499
                // Because the JVM does not allow separate methods on array types,
jaroslav@1646
  1500
                // there is no separate method for int[].clone.
jaroslav@1646
  1501
                // All arrays simply inherit Object.clone.
jaroslav@1646
  1502
                // But for access checking logic, we make Object.clone
jaroslav@1646
  1503
                // (normally protected) appear to be public.
jaroslav@1646
  1504
                // Later on, when the DirectMethodHandle is created,
jaroslav@1646
  1505
                // its leading argument will be restricted to the
jaroslav@1646
  1506
                // requested array type.
jaroslav@1646
  1507
                // N.B. The return type is not adjusted, because
jaroslav@1646
  1508
                // that is *not* the bytecode behavior.
jaroslav@1646
  1509
                mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
jaroslav@1646
  1510
            }
jaroslav@1646
  1511
            if (Modifier.isFinal(mods) &&
jaroslav@1646
  1512
                    MethodHandleNatives.refKindIsSetter(refKind))
jaroslav@1646
  1513
                throw m.makeAccessException("unexpected set of a final field", this);
jaroslav@1646
  1514
            if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
jaroslav@1646
  1515
                return;  // common case
jaroslav@1646
  1516
            int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
jaroslav@1646
  1517
            if ((requestedModes & allowedModes) != 0) {
jaroslav@1646
  1518
                if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
jaroslav@1646
  1519
                                                    mods, lookupClass(), allowedModes))
jaroslav@1646
  1520
                    return;
jaroslav@1646
  1521
            } else {
jaroslav@1646
  1522
                // Protected members can also be checked as if they were package-private.
jaroslav@1646
  1523
                if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
jaroslav@1646
  1524
                        && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
jaroslav@1646
  1525
                    return;
jaroslav@1646
  1526
            }
jaroslav@1646
  1527
            throw m.makeAccessException(accessFailedMessage(refc, m), this);
jaroslav@1646
  1528
        }
jaroslav@1646
  1529
jaroslav@1646
  1530
        String accessFailedMessage(Class<?> refc, MemberName m) {
jaroslav@1646
  1531
            Class<?> defc = m.getDeclaringClass();
jaroslav@1646
  1532
            int mods = m.getModifiers();
jaroslav@1646
  1533
            // check the class first:
jaroslav@1646
  1534
            boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
jaroslav@1646
  1535
                               (defc == refc ||
jaroslav@1646
  1536
                                Modifier.isPublic(refc.getModifiers())));
jaroslav@1646
  1537
            if (!classOK && (allowedModes & PACKAGE) != 0) {
jaroslav@1646
  1538
                classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
jaroslav@1646
  1539
                           (defc == refc ||
jaroslav@1646
  1540
                            VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
jaroslav@1646
  1541
            }
jaroslav@1646
  1542
            if (!classOK)
jaroslav@1646
  1543
                return "class is not public";
jaroslav@1646
  1544
            if (Modifier.isPublic(mods))
jaroslav@1646
  1545
                return "access to public member failed";  // (how?)
jaroslav@1646
  1546
            if (Modifier.isPrivate(mods))
jaroslav@1646
  1547
                return "member is private";
jaroslav@1646
  1548
            if (Modifier.isProtected(mods))
jaroslav@1646
  1549
                return "member is protected";
jaroslav@1646
  1550
            return "member is private to package";
jaroslav@1646
  1551
        }
jaroslav@1646
  1552
jaroslav@1646
  1553
        private static final boolean ALLOW_NESTMATE_ACCESS = false;
jaroslav@1646
  1554
jaroslav@1646
  1555
        private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException {
jaroslav@1646
  1556
            int allowedModes = this.allowedModes;
jaroslav@1646
  1557
            if (allowedModes == TRUSTED)  return;
jaroslav@1646
  1558
            if (!hasPrivateAccess()
jaroslav@1646
  1559
                || (specialCaller != lookupClass()
jaroslav@1646
  1560
                    && !(ALLOW_NESTMATE_ACCESS &&
jaroslav@1646
  1561
                         VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
jaroslav@1646
  1562
                throw new MemberName(specialCaller).
jaroslav@1646
  1563
                    makeAccessException("no private access for invokespecial", this);
jaroslav@1646
  1564
        }
jaroslav@1646
  1565
jaroslav@1646
  1566
        private boolean restrictProtectedReceiver(MemberName method) {
jaroslav@1646
  1567
            // The accessing class only has the right to use a protected member
jaroslav@1646
  1568
            // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
jaroslav@1646
  1569
            if (!method.isProtected() || method.isStatic()
jaroslav@1646
  1570
                || allowedModes == TRUSTED
jaroslav@1646
  1571
                || method.getDeclaringClass() == lookupClass()
jaroslav@1646
  1572
                || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
jaroslav@1646
  1573
                || (ALLOW_NESTMATE_ACCESS &&
jaroslav@1646
  1574
                    VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
jaroslav@1646
  1575
                return false;
jaroslav@1646
  1576
            return true;
jaroslav@1646
  1577
        }
jaroslav@1646
  1578
        private MethodHandle restrictReceiver(MemberName method, MethodHandle mh, Class<?> caller) throws IllegalAccessException {
jaroslav@1646
  1579
            assert(!method.isStatic());
jaroslav@1646
  1580
            // receiver type of mh is too wide; narrow to caller
jaroslav@1646
  1581
            if (!method.getDeclaringClass().isAssignableFrom(caller)) {
jaroslav@1646
  1582
                throw method.makeAccessException("caller class must be a subclass below the method", caller);
jaroslav@1646
  1583
            }
jaroslav@1646
  1584
            MethodType rawType = mh.type();
jaroslav@1646
  1585
            if (rawType.parameterType(0) == caller)  return mh;
jaroslav@1646
  1586
            MethodType narrowType = rawType.changeParameterType(0, caller);
jaroslav@1646
  1587
            return mh.viewAsType(narrowType);
jaroslav@1646
  1588
        }
jaroslav@1646
  1589
jaroslav@1646
  1590
        /** Check access and get the requested method. */
jaroslav@1646
  1591
        private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
jaroslav@1646
  1592
            final boolean doRestrict    = true;
jaroslav@1646
  1593
            final boolean checkSecurity = true;
jaroslav@1646
  1594
            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
jaroslav@1646
  1595
        }
jaroslav@1646
  1596
        /** Check access and get the requested method, eliding receiver narrowing rules. */
jaroslav@1646
  1597
        private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
jaroslav@1646
  1598
            final boolean doRestrict    = false;
jaroslav@1646
  1599
            final boolean checkSecurity = true;
jaroslav@1646
  1600
            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
jaroslav@1646
  1601
        }
jaroslav@1646
  1602
        /** Check access and get the requested method, eliding security manager checks. */
jaroslav@1646
  1603
        private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
jaroslav@1646
  1604
            final boolean doRestrict    = true;
jaroslav@1646
  1605
            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
jaroslav@1646
  1606
            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
jaroslav@1646
  1607
        }
jaroslav@1646
  1608
        /** Common code for all methods; do not call directly except from immediately above. */
jaroslav@1646
  1609
        private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
jaroslav@1646
  1610
                                                   boolean checkSecurity,
jaroslav@1646
  1611
                                                   boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
jaroslav@1646
  1612
            checkMethod(refKind, refc, method);
jaroslav@1646
  1613
            // Optionally check with the security manager; this isn't needed for unreflect* calls.
jaroslav@1646
  1614
            if (checkSecurity)
jaroslav@1646
  1615
                checkSecurityManager(refc, method);
jaroslav@1646
  1616
            assert(!method.isMethodHandleInvoke());
jaroslav@1646
  1617
jaroslav@1646
  1618
            Class<?> refcAsSuper;
jaroslav@1646
  1619
            if (refKind == REF_invokeSpecial &&
jaroslav@1646
  1620
                refc != lookupClass() &&
jaroslav@1646
  1621
                !refc.isInterface() &&
jaroslav@1646
  1622
                refc != (refcAsSuper = lookupClass().getSuperclass()) &&
jaroslav@1646
  1623
                refc.isAssignableFrom(lookupClass())) {
jaroslav@1646
  1624
                assert(!method.getName().equals("<init>"));  // not this code path
jaroslav@1646
  1625
                // Per JVMS 6.5, desc. of invokespecial instruction:
jaroslav@1646
  1626
                // If the method is in a superclass of the LC,
jaroslav@1646
  1627
                // and if our original search was above LC.super,
jaroslav@1646
  1628
                // repeat the search (symbolic lookup) from LC.super.
jaroslav@1646
  1629
                // FIXME: MemberName.resolve should handle this instead.
jaroslav@1646
  1630
                MemberName m2 = new MemberName(refcAsSuper,
jaroslav@1646
  1631
                                               method.getName(),
jaroslav@1646
  1632
                                               method.getMethodType(),
jaroslav@1646
  1633
                                               REF_invokeSpecial);
jaroslav@1646
  1634
                m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
jaroslav@1646
  1635
                if (m2 == null)  throw new InternalError(method.toString());
jaroslav@1646
  1636
                method = m2;
jaroslav@1646
  1637
                refc = refcAsSuper;
jaroslav@1646
  1638
                // redo basic checks
jaroslav@1646
  1639
                checkMethod(refKind, refc, method);
jaroslav@1646
  1640
            }
jaroslav@1646
  1641
jaroslav@1646
  1642
            MethodHandle mh = DirectMethodHandle.make(refKind, refc, method);
jaroslav@1646
  1643
            mh = maybeBindCaller(method, mh, callerClass);
jaroslav@1646
  1644
            mh = mh.setVarargs(method);
jaroslav@1646
  1645
            // Optionally narrow the receiver argument to refc using restrictReceiver.
jaroslav@1646
  1646
            if (doRestrict &&
jaroslav@1646
  1647
                   (refKind == REF_invokeSpecial ||
jaroslav@1646
  1648
                       (MethodHandleNatives.refKindHasReceiver(refKind) &&
jaroslav@1646
  1649
                           restrictProtectedReceiver(method))))
jaroslav@1646
  1650
                mh = restrictReceiver(method, mh, lookupClass());
jaroslav@1646
  1651
            return mh;
jaroslav@1646
  1652
        }
jaroslav@1646
  1653
        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
jaroslav@1646
  1654
                                             Class<?> callerClass)
jaroslav@1646
  1655
                                             throws IllegalAccessException {
jaroslav@1646
  1656
            if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
jaroslav@1646
  1657
                return mh;
jaroslav@1646
  1658
            Class<?> hostClass = lookupClass;
jaroslav@1646
  1659
            if (!hasPrivateAccess())  // caller must have private access
jaroslav@1646
  1660
                hostClass = callerClass;  // callerClass came from a security manager style stack walk
jaroslav@1646
  1661
            MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
jaroslav@1646
  1662
            // Note: caller will apply varargs after this step happens.
jaroslav@1646
  1663
            return cbmh;
jaroslav@1646
  1664
        }
jaroslav@1646
  1665
        /** Check access and get the requested field. */
jaroslav@1646
  1666
        private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
jaroslav@1646
  1667
            final boolean checkSecurity = true;
jaroslav@1646
  1668
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
jaroslav@1646
  1669
        }
jaroslav@1646
  1670
        /** Check access and get the requested field, eliding security manager checks. */
jaroslav@1646
  1671
        private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
jaroslav@1646
  1672
            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
jaroslav@1646
  1673
            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
jaroslav@1646
  1674
        }
jaroslav@1646
  1675
        /** Common code for all fields; do not call directly except from immediately above. */
jaroslav@1646
  1676
        private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
jaroslav@1646
  1677
                                                  boolean checkSecurity) throws IllegalAccessException {
jaroslav@1646
  1678
            checkField(refKind, refc, field);
jaroslav@1646
  1679
            // Optionally check with the security manager; this isn't needed for unreflect* calls.
jaroslav@1646
  1680
            if (checkSecurity)
jaroslav@1646
  1681
                checkSecurityManager(refc, field);
jaroslav@1646
  1682
            MethodHandle mh = DirectMethodHandle.make(refc, field);
jaroslav@1646
  1683
            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
jaroslav@1646
  1684
                                    restrictProtectedReceiver(field));
jaroslav@1646
  1685
            if (doRestrict)
jaroslav@1646
  1686
                mh = restrictReceiver(field, mh, lookupClass());
jaroslav@1646
  1687
            return mh;
jaroslav@1646
  1688
        }
jaroslav@1646
  1689
        /** Check access and get the requested constructor. */
jaroslav@1646
  1690
        private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
jaroslav@1646
  1691
            final boolean checkSecurity = true;
jaroslav@1646
  1692
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
jaroslav@1646
  1693
        }
jaroslav@1646
  1694
        /** Check access and get the requested constructor, eliding security manager checks. */
jaroslav@1646
  1695
        private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
jaroslav@1646
  1696
            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
jaroslav@1646
  1697
            return getDirectConstructorCommon(refc, ctor, checkSecurity);
jaroslav@1646
  1698
        }
jaroslav@1646
  1699
        /** Common code for all constructors; do not call directly except from immediately above. */
jaroslav@1646
  1700
        private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
jaroslav@1646
  1701
                                                  boolean checkSecurity) throws IllegalAccessException {
jaroslav@1646
  1702
            assert(ctor.isConstructor());
jaroslav@1646
  1703
            checkAccess(REF_newInvokeSpecial, refc, ctor);
jaroslav@1646
  1704
            // Optionally check with the security manager; this isn't needed for unreflect* calls.
jaroslav@1646
  1705
            if (checkSecurity)
jaroslav@1646
  1706
                checkSecurityManager(refc, ctor);
jaroslav@1646
  1707
            assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
jaroslav@1646
  1708
            return DirectMethodHandle.make(ctor).setVarargs(ctor);
jaroslav@1646
  1709
        }
jaroslav@1646
  1710
jaroslav@1646
  1711
        /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
jaroslav@1646
  1712
         */
jaroslav@1646
  1713
        /*non-public*/
jaroslav@1646
  1714
        MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
jaroslav@1646
  1715
            if (!(type instanceof Class || type instanceof MethodType))
jaroslav@1646
  1716
                throw new InternalError("unresolved MemberName");
jaroslav@1646
  1717
            MemberName member = new MemberName(refKind, defc, name, type);
jaroslav@1646
  1718
            MethodHandle mh = LOOKASIDE_TABLE.get(member);
jaroslav@1646
  1719
            if (mh != null) {
jaroslav@1646
  1720
                checkSymbolicClass(defc);
jaroslav@1646
  1721
                return mh;
jaroslav@1646
  1722
            }
jaroslav@1646
  1723
            // Treat MethodHandle.invoke and invokeExact specially.
jaroslav@1646
  1724
            if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
jaroslav@1646
  1725
                mh = findVirtualForMH(member.getName(), member.getMethodType());
jaroslav@1646
  1726
                if (mh != null) {
jaroslav@1646
  1727
                    return mh;
jaroslav@1646
  1728
                }
jaroslav@1646
  1729
            }
jaroslav@1646
  1730
            MemberName resolved = resolveOrFail(refKind, member);
jaroslav@1646
  1731
            mh = getDirectMethodForConstant(refKind, defc, resolved);
jaroslav@1646
  1732
            if (mh instanceof DirectMethodHandle
jaroslav@1646
  1733
                    && canBeCached(refKind, defc, resolved)) {
jaroslav@1646
  1734
                MemberName key = mh.internalMemberName();
jaroslav@1646
  1735
                if (key != null) {
jaroslav@1646
  1736
                    key = key.asNormalOriginal();
jaroslav@1646
  1737
                }
jaroslav@1646
  1738
                if (member.equals(key)) {  // better safe than sorry
jaroslav@1646
  1739
                    LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
jaroslav@1646
  1740
                }
jaroslav@1646
  1741
            }
jaroslav@1646
  1742
            return mh;
jaroslav@1646
  1743
        }
jaroslav@1646
  1744
        private
jaroslav@1646
  1745
        boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
jaroslav@1646
  1746
            if (refKind == REF_invokeSpecial) {
jaroslav@1646
  1747
                return false;
jaroslav@1646
  1748
            }
jaroslav@1646
  1749
            if (!Modifier.isPublic(defc.getModifiers()) ||
jaroslav@1646
  1750
                    !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
jaroslav@1646
  1751
                    !member.isPublic() ||
jaroslav@1646
  1752
                    member.isCallerSensitive()) {
jaroslav@1646
  1753
                return false;
jaroslav@1646
  1754
            }
jaroslav@1646
  1755
            ClassLoader loader = defc.getClassLoader();
jaroslav@1651
  1756
//            if (!sun.misc.VM.isSystemDomainLoader(loader)) {
jaroslav@1651
  1757
//                ClassLoader sysl = ClassLoader.getSystemClassLoader();
jaroslav@1651
  1758
//                boolean found = false;
jaroslav@1651
  1759
//                while (sysl != null) {
jaroslav@1651
  1760
//                    if (loader == sysl) { found = true; break; }
jaroslav@1651
  1761
//                    sysl = sysl.getParent();
jaroslav@1651
  1762
//                }
jaroslav@1651
  1763
//                if (!found) {
jaroslav@1651
  1764
//                    return false;
jaroslav@1651
  1765
//                }
jaroslav@1651
  1766
//            }
jaroslav@1646
  1767
            try {
jaroslav@1646
  1768
                MemberName resolved2 = publicLookup().resolveOrFail(refKind,
jaroslav@1646
  1769
                    new MemberName(refKind, defc, member.getName(), member.getType()));
jaroslav@1646
  1770
                checkSecurityManager(defc, resolved2);
jaroslav@1646
  1771
            } catch (ReflectiveOperationException | SecurityException ex) {
jaroslav@1646
  1772
                return false;
jaroslav@1646
  1773
            }
jaroslav@1646
  1774
            return true;
jaroslav@1646
  1775
        }
jaroslav@1646
  1776
        private
jaroslav@1646
  1777
        MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
jaroslav@1646
  1778
                throws ReflectiveOperationException {
jaroslav@1646
  1779
            if (MethodHandleNatives.refKindIsField(refKind)) {
jaroslav@1646
  1780
                return getDirectFieldNoSecurityManager(refKind, defc, member);
jaroslav@1646
  1781
            } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
jaroslav@1646
  1782
                return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
jaroslav@1646
  1783
            } else if (refKind == REF_newInvokeSpecial) {
jaroslav@1646
  1784
                return getDirectConstructorNoSecurityManager(defc, member);
jaroslav@1646
  1785
            }
jaroslav@1646
  1786
            // oops
jaroslav@1646
  1787
            throw newIllegalArgumentException("bad MethodHandle constant #"+member);
jaroslav@1646
  1788
        }
jaroslav@1646
  1789
jaroslav@1646
  1790
        static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
jaroslav@1646
  1791
    }
jaroslav@1646
  1792
jaroslav@1646
  1793
    /**
jaroslav@1646
  1794
     * Produces a method handle giving read access to elements of an array.
jaroslav@1646
  1795
     * The type of the method handle will have a return type of the array's
jaroslav@1646
  1796
     * element type.  Its first argument will be the array type,
jaroslav@1646
  1797
     * and the second will be {@code int}.
jaroslav@1646
  1798
     * @param arrayClass an array type
jaroslav@1646
  1799
     * @return a method handle which can load values from the given array type
jaroslav@1646
  1800
     * @throws NullPointerException if the argument is null
jaroslav@1646
  1801
     * @throws  IllegalArgumentException if arrayClass is not an array type
jaroslav@1646
  1802
     */
jaroslav@1646
  1803
    public static
jaroslav@1646
  1804
    MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
jaroslav@1646
  1805
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
jaroslav@1646
  1806
    }
jaroslav@1646
  1807
jaroslav@1646
  1808
    /**
jaroslav@1646
  1809
     * Produces a method handle giving write access to elements of an array.
jaroslav@1646
  1810
     * The type of the method handle will have a void return type.
jaroslav@1646
  1811
     * Its last argument will be the array's element type.
jaroslav@1646
  1812
     * The first and second arguments will be the array type and int.
jaroslav@1646
  1813
     * @param arrayClass the class of an array
jaroslav@1646
  1814
     * @return a method handle which can store values into the array type
jaroslav@1646
  1815
     * @throws NullPointerException if the argument is null
jaroslav@1646
  1816
     * @throws IllegalArgumentException if arrayClass is not an array type
jaroslav@1646
  1817
     */
jaroslav@1646
  1818
    public static
jaroslav@1646
  1819
    MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
jaroslav@1646
  1820
        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
jaroslav@1646
  1821
    }
jaroslav@1646
  1822
jaroslav@1646
  1823
    /// method handle invocation (reflective style)
jaroslav@1646
  1824
jaroslav@1646
  1825
    /**
jaroslav@1646
  1826
     * Produces a method handle which will invoke any method handle of the
jaroslav@1646
  1827
     * given {@code type}, with a given number of trailing arguments replaced by
jaroslav@1646
  1828
     * a single trailing {@code Object[]} array.
jaroslav@1646
  1829
     * The resulting invoker will be a method handle with the following
jaroslav@1646
  1830
     * arguments:
jaroslav@1646
  1831
     * <ul>
jaroslav@1646
  1832
     * <li>a single {@code MethodHandle} target
jaroslav@1646
  1833
     * <li>zero or more leading values (counted by {@code leadingArgCount})
jaroslav@1646
  1834
     * <li>an {@code Object[]} array containing trailing arguments
jaroslav@1646
  1835
     * </ul>
jaroslav@1646
  1836
     * <p>
jaroslav@1646
  1837
     * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
jaroslav@1646
  1838
     * the indicated {@code type}.
jaroslav@1646
  1839
     * That is, if the target is exactly of the given {@code type}, it will behave
jaroslav@1646
  1840
     * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
jaroslav@1646
  1841
     * is used to convert the target to the required {@code type}.
jaroslav@1646
  1842
     * <p>
jaroslav@1646
  1843
     * The type of the returned invoker will not be the given {@code type}, but rather
jaroslav@1646
  1844
     * will have all parameters except the first {@code leadingArgCount}
jaroslav@1646
  1845
     * replaced by a single array of type {@code Object[]}, which will be
jaroslav@1646
  1846
     * the final parameter.
jaroslav@1646
  1847
     * <p>
jaroslav@1646
  1848
     * Before invoking its target, the invoker will spread the final array, apply
jaroslav@1646
  1849
     * reference casts as necessary, and unbox and widen primitive arguments.
jaroslav@1646
  1850
     * If, when the invoker is called, the supplied array argument does
jaroslav@1646
  1851
     * not have the correct number of elements, the invoker will throw
jaroslav@1646
  1852
     * an {@link IllegalArgumentException} instead of invoking the target.
jaroslav@1646
  1853
     * <p>
jaroslav@1646
  1854
     * This method is equivalent to the following code (though it may be more efficient):
jaroslav@1646
  1855
     * <blockquote><pre>{@code
jaroslav@1646
  1856
MethodHandle invoker = MethodHandles.invoker(type);
jaroslav@1646
  1857
int spreadArgCount = type.parameterCount() - leadingArgCount;
jaroslav@1646
  1858
invoker = invoker.asSpreader(Object[].class, spreadArgCount);
jaroslav@1646
  1859
return invoker;
jaroslav@1646
  1860
     * }</pre></blockquote>
jaroslav@1646
  1861
     * This method throws no reflective or security exceptions.
jaroslav@1646
  1862
     * @param type the desired target type
jaroslav@1646
  1863
     * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
jaroslav@1646
  1864
     * @return a method handle suitable for invoking any method handle of the given type
jaroslav@1646
  1865
     * @throws NullPointerException if {@code type} is null
jaroslav@1646
  1866
     * @throws IllegalArgumentException if {@code leadingArgCount} is not in
jaroslav@1646
  1867
     *                  the range from 0 to {@code type.parameterCount()} inclusive,
jaroslav@1646
  1868
     *                  or if the resulting method handle's type would have
jaroslav@1646
  1869
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
  1870
     */
jaroslav@1646
  1871
    static public
jaroslav@1646
  1872
    MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
jaroslav@1646
  1873
        if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
jaroslav@1646
  1874
            throw new IllegalArgumentException("bad argument count "+leadingArgCount);
jaroslav@1646
  1875
        return type.invokers().spreadInvoker(leadingArgCount);
jaroslav@1646
  1876
    }
jaroslav@1646
  1877
jaroslav@1646
  1878
    /**
jaroslav@1646
  1879
     * Produces a special <em>invoker method handle</em> which can be used to
jaroslav@1646
  1880
     * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
jaroslav@1646
  1881
     * The resulting invoker will have a type which is
jaroslav@1646
  1882
     * exactly equal to the desired type, except that it will accept
jaroslav@1646
  1883
     * an additional leading argument of type {@code MethodHandle}.
jaroslav@1646
  1884
     * <p>
jaroslav@1646
  1885
     * This method is equivalent to the following code (though it may be more efficient):
jaroslav@1646
  1886
     * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
jaroslav@1646
  1887
     *
jaroslav@1646
  1888
     * <p style="font-size:smaller;">
jaroslav@1646
  1889
     * <em>Discussion:</em>
jaroslav@1646
  1890
     * Invoker method handles can be useful when working with variable method handles
jaroslav@1646
  1891
     * of unknown types.
jaroslav@1646
  1892
     * For example, to emulate an {@code invokeExact} call to a variable method
jaroslav@1646
  1893
     * handle {@code M}, extract its type {@code T},
jaroslav@1646
  1894
     * look up the invoker method {@code X} for {@code T},
jaroslav@1646
  1895
     * and call the invoker method, as {@code X.invoke(T, A...)}.
jaroslav@1646
  1896
     * (It would not work to call {@code X.invokeExact}, since the type {@code T}
jaroslav@1646
  1897
     * is unknown.)
jaroslav@1646
  1898
     * If spreading, collecting, or other argument transformations are required,
jaroslav@1646
  1899
     * they can be applied once to the invoker {@code X} and reused on many {@code M}
jaroslav@1646
  1900
     * method handle values, as long as they are compatible with the type of {@code X}.
jaroslav@1646
  1901
     * <p style="font-size:smaller;">
jaroslav@1646
  1902
     * <em>(Note:  The invoker method is not available via the Core Reflection API.
jaroslav@1646
  1903
     * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
jaroslav@1646
  1904
     * on the declared {@code invokeExact} or {@code invoke} method will raise an
jaroslav@1646
  1905
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
jaroslav@1646
  1906
     * <p>
jaroslav@1646
  1907
     * This method throws no reflective or security exceptions.
jaroslav@1646
  1908
     * @param type the desired target type
jaroslav@1646
  1909
     * @return a method handle suitable for invoking any method handle of the given type
jaroslav@1646
  1910
     * @throws IllegalArgumentException if the resulting method handle's type would have
jaroslav@1646
  1911
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
  1912
     */
jaroslav@1646
  1913
    static public
jaroslav@1646
  1914
    MethodHandle exactInvoker(MethodType type) {
jaroslav@1646
  1915
        return type.invokers().exactInvoker();
jaroslav@1646
  1916
    }
jaroslav@1646
  1917
jaroslav@1646
  1918
    /**
jaroslav@1646
  1919
     * Produces a special <em>invoker method handle</em> which can be used to
jaroslav@1646
  1920
     * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
jaroslav@1646
  1921
     * The resulting invoker will have a type which is
jaroslav@1646
  1922
     * exactly equal to the desired type, except that it will accept
jaroslav@1646
  1923
     * an additional leading argument of type {@code MethodHandle}.
jaroslav@1646
  1924
     * <p>
jaroslav@1646
  1925
     * Before invoking its target, if the target differs from the expected type,
jaroslav@1646
  1926
     * the invoker will apply reference casts as
jaroslav@1646
  1927
     * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
jaroslav@1646
  1928
     * Similarly, the return value will be converted as necessary.
jaroslav@1646
  1929
     * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
jaroslav@1646
  1930
     * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
jaroslav@1646
  1931
     * <p>
jaroslav@1646
  1932
     * This method is equivalent to the following code (though it may be more efficient):
jaroslav@1646
  1933
     * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
jaroslav@1646
  1934
     * <p style="font-size:smaller;">
jaroslav@1646
  1935
     * <em>Discussion:</em>
jaroslav@1646
  1936
     * A {@linkplain MethodType#genericMethodType general method type} is one which
jaroslav@1646
  1937
     * mentions only {@code Object} arguments and return values.
jaroslav@1646
  1938
     * An invoker for such a type is capable of calling any method handle
jaroslav@1646
  1939
     * of the same arity as the general type.
jaroslav@1646
  1940
     * <p style="font-size:smaller;">
jaroslav@1646
  1941
     * <em>(Note:  The invoker method is not available via the Core Reflection API.
jaroslav@1646
  1942
     * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
jaroslav@1646
  1943
     * on the declared {@code invokeExact} or {@code invoke} method will raise an
jaroslav@1646
  1944
     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
jaroslav@1646
  1945
     * <p>
jaroslav@1646
  1946
     * This method throws no reflective or security exceptions.
jaroslav@1646
  1947
     * @param type the desired target type
jaroslav@1646
  1948
     * @return a method handle suitable for invoking any method handle convertible to the given type
jaroslav@1646
  1949
     * @throws IllegalArgumentException if the resulting method handle's type would have
jaroslav@1646
  1950
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
  1951
     */
jaroslav@1646
  1952
    static public
jaroslav@1646
  1953
    MethodHandle invoker(MethodType type) {
jaroslav@1646
  1954
        return type.invokers().generalInvoker();
jaroslav@1646
  1955
    }
jaroslav@1646
  1956
jaroslav@1646
  1957
    static /*non-public*/
jaroslav@1646
  1958
    MethodHandle basicInvoker(MethodType type) {
jaroslav@1646
  1959
        return type.form().basicInvoker();
jaroslav@1646
  1960
    }
jaroslav@1646
  1961
jaroslav@1646
  1962
     /// method handle modification (creation from other method handles)
jaroslav@1646
  1963
jaroslav@1646
  1964
    /**
jaroslav@1646
  1965
     * Produces a method handle which adapts the type of the
jaroslav@1646
  1966
     * given method handle to a new type by pairwise argument and return type conversion.
jaroslav@1646
  1967
     * The original type and new type must have the same number of arguments.
jaroslav@1646
  1968
     * The resulting method handle is guaranteed to report a type
jaroslav@1646
  1969
     * which is equal to the desired new type.
jaroslav@1646
  1970
     * <p>
jaroslav@1646
  1971
     * If the original type and new type are equal, returns target.
jaroslav@1646
  1972
     * <p>
jaroslav@1646
  1973
     * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
jaroslav@1646
  1974
     * and some additional conversions are also applied if those conversions fail.
jaroslav@1646
  1975
     * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
jaroslav@1646
  1976
     * if possible, before or instead of any conversions done by {@code asType}:
jaroslav@1646
  1977
     * <ul>
jaroslav@1646
  1978
     * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
jaroslav@1646
  1979
     *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
jaroslav@1646
  1980
     *     (This treatment of interfaces follows the usage of the bytecode verifier.)
jaroslav@1646
  1981
     * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
jaroslav@1646
  1982
     *     the boolean is converted to a byte value, 1 for true, 0 for false.
jaroslav@1646
  1983
     *     (This treatment follows the usage of the bytecode verifier.)
jaroslav@1646
  1984
     * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
jaroslav@1646
  1985
     *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
jaroslav@1646
  1986
     *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
jaroslav@1646
  1987
     * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
jaroslav@1646
  1988
     *     then a Java casting conversion (JLS 5.5) is applied.
jaroslav@1646
  1989
     *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
jaroslav@1646
  1990
     *     widening and/or narrowing.)
jaroslav@1646
  1991
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
jaroslav@1646
  1992
     *     conversion will be applied at runtime, possibly followed
jaroslav@1646
  1993
     *     by a Java casting conversion (JLS 5.5) on the primitive value,
jaroslav@1646
  1994
     *     possibly followed by a conversion from byte to boolean by testing
jaroslav@1646
  1995
     *     the low-order bit.
jaroslav@1646
  1996
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
jaroslav@1646
  1997
     *     and if the reference is null at runtime, a zero value is introduced.
jaroslav@1646
  1998
     * </ul>
jaroslav@1646
  1999
     * @param target the method handle to invoke after arguments are retyped
jaroslav@1646
  2000
     * @param newType the expected type of the new method handle
jaroslav@1646
  2001
     * @return a method handle which delegates to the target after performing
jaroslav@1646
  2002
     *           any necessary argument conversions, and arranges for any
jaroslav@1646
  2003
     *           necessary return value conversions
jaroslav@1646
  2004
     * @throws NullPointerException if either argument is null
jaroslav@1646
  2005
     * @throws WrongMethodTypeException if the conversion cannot be made
jaroslav@1646
  2006
     * @see MethodHandle#asType
jaroslav@1646
  2007
     */
jaroslav@1646
  2008
    public static
jaroslav@1646
  2009
    MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
jaroslav@1646
  2010
        if (!target.type().isCastableTo(newType)) {
jaroslav@1646
  2011
            throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType);
jaroslav@1646
  2012
        }
jaroslav@1646
  2013
        return MethodHandleImpl.makePairwiseConvert(target, newType, 2);
jaroslav@1646
  2014
    }
jaroslav@1646
  2015
jaroslav@1646
  2016
    /**
jaroslav@1646
  2017
     * Produces a method handle which adapts the calling sequence of the
jaroslav@1646
  2018
     * given method handle to a new type, by reordering the arguments.
jaroslav@1646
  2019
     * The resulting method handle is guaranteed to report a type
jaroslav@1646
  2020
     * which is equal to the desired new type.
jaroslav@1646
  2021
     * <p>
jaroslav@1646
  2022
     * The given array controls the reordering.
jaroslav@1646
  2023
     * Call {@code #I} the number of incoming parameters (the value
jaroslav@1646
  2024
     * {@code newType.parameterCount()}, and call {@code #O} the number
jaroslav@1646
  2025
     * of outgoing parameters (the value {@code target.type().parameterCount()}).
jaroslav@1646
  2026
     * Then the length of the reordering array must be {@code #O},
jaroslav@1646
  2027
     * and each element must be a non-negative number less than {@code #I}.
jaroslav@1646
  2028
     * For every {@code N} less than {@code #O}, the {@code N}-th
jaroslav@1646
  2029
     * outgoing argument will be taken from the {@code I}-th incoming
jaroslav@1646
  2030
     * argument, where {@code I} is {@code reorder[N]}.
jaroslav@1646
  2031
     * <p>
jaroslav@1646
  2032
     * No argument or return value conversions are applied.
jaroslav@1646
  2033
     * The type of each incoming argument, as determined by {@code newType},
jaroslav@1646
  2034
     * must be identical to the type of the corresponding outgoing parameter
jaroslav@1646
  2035
     * or parameters in the target method handle.
jaroslav@1646
  2036
     * The return type of {@code newType} must be identical to the return
jaroslav@1646
  2037
     * type of the original target.
jaroslav@1646
  2038
     * <p>
jaroslav@1646
  2039
     * The reordering array need not specify an actual permutation.
jaroslav@1646
  2040
     * An incoming argument will be duplicated if its index appears
jaroslav@1646
  2041
     * more than once in the array, and an incoming argument will be dropped
jaroslav@1646
  2042
     * if its index does not appear in the array.
jaroslav@1646
  2043
     * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
jaroslav@1646
  2044
     * incoming arguments which are not mentioned in the reordering array
jaroslav@1646
  2045
     * are may be any type, as determined only by {@code newType}.
jaroslav@1646
  2046
     * <blockquote><pre>{@code
jaroslav@1646
  2047
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2048
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2049
...
jaroslav@1646
  2050
MethodType intfn1 = methodType(int.class, int.class);
jaroslav@1646
  2051
MethodType intfn2 = methodType(int.class, int.class, int.class);
jaroslav@1646
  2052
MethodHandle sub = ... (int x, int y) -> (x-y) ...;
jaroslav@1646
  2053
assert(sub.type().equals(intfn2));
jaroslav@1646
  2054
MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
jaroslav@1646
  2055
MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
jaroslav@1646
  2056
assert((int)rsub.invokeExact(1, 100) == 99);
jaroslav@1646
  2057
MethodHandle add = ... (int x, int y) -> (x+y) ...;
jaroslav@1646
  2058
assert(add.type().equals(intfn2));
jaroslav@1646
  2059
MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
jaroslav@1646
  2060
assert(twice.type().equals(intfn1));
jaroslav@1646
  2061
assert((int)twice.invokeExact(21) == 42);
jaroslav@1646
  2062
     * }</pre></blockquote>
jaroslav@1646
  2063
     * @param target the method handle to invoke after arguments are reordered
jaroslav@1646
  2064
     * @param newType the expected type of the new method handle
jaroslav@1646
  2065
     * @param reorder an index array which controls the reordering
jaroslav@1646
  2066
     * @return a method handle which delegates to the target after it
jaroslav@1646
  2067
     *           drops unused arguments and moves and/or duplicates the other arguments
jaroslav@1646
  2068
     * @throws NullPointerException if any argument is null
jaroslav@1646
  2069
     * @throws IllegalArgumentException if the index array length is not equal to
jaroslav@1646
  2070
     *                  the arity of the target, or if any index array element
jaroslav@1646
  2071
     *                  not a valid index for a parameter of {@code newType},
jaroslav@1646
  2072
     *                  or if two corresponding parameter types in
jaroslav@1646
  2073
     *                  {@code target.type()} and {@code newType} are not identical,
jaroslav@1646
  2074
     */
jaroslav@1646
  2075
    public static
jaroslav@1646
  2076
    MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
jaroslav@1646
  2077
        checkReorder(reorder, newType, target.type());
jaroslav@1646
  2078
        return target.permuteArguments(newType, reorder);
jaroslav@1646
  2079
    }
jaroslav@1646
  2080
jaroslav@1646
  2081
    private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) {
jaroslav@1646
  2082
        if (newType.returnType() != oldType.returnType())
jaroslav@1646
  2083
            throw newIllegalArgumentException("return types do not match",
jaroslav@1646
  2084
                    oldType, newType);
jaroslav@1646
  2085
        if (reorder.length == oldType.parameterCount()) {
jaroslav@1646
  2086
            int limit = newType.parameterCount();
jaroslav@1646
  2087
            boolean bad = false;
jaroslav@1646
  2088
            for (int j = 0; j < reorder.length; j++) {
jaroslav@1646
  2089
                int i = reorder[j];
jaroslav@1646
  2090
                if (i < 0 || i >= limit) {
jaroslav@1646
  2091
                    bad = true; break;
jaroslav@1646
  2092
                }
jaroslav@1646
  2093
                Class<?> src = newType.parameterType(i);
jaroslav@1646
  2094
                Class<?> dst = oldType.parameterType(j);
jaroslav@1646
  2095
                if (src != dst)
jaroslav@1646
  2096
                    throw newIllegalArgumentException("parameter types do not match after reorder",
jaroslav@1646
  2097
                            oldType, newType);
jaroslav@1646
  2098
            }
jaroslav@1646
  2099
            if (!bad)  return;
jaroslav@1646
  2100
        }
jaroslav@1646
  2101
        throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
jaroslav@1646
  2102
    }
jaroslav@1646
  2103
jaroslav@1646
  2104
    /**
jaroslav@1646
  2105
     * Produces a method handle of the requested return type which returns the given
jaroslav@1646
  2106
     * constant value every time it is invoked.
jaroslav@1646
  2107
     * <p>
jaroslav@1646
  2108
     * Before the method handle is returned, the passed-in value is converted to the requested type.
jaroslav@1646
  2109
     * If the requested type is primitive, widening primitive conversions are attempted,
jaroslav@1646
  2110
     * else reference conversions are attempted.
jaroslav@1646
  2111
     * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
jaroslav@1646
  2112
     * @param type the return type of the desired method handle
jaroslav@1646
  2113
     * @param value the value to return
jaroslav@1646
  2114
     * @return a method handle of the given return type and no arguments, which always returns the given value
jaroslav@1646
  2115
     * @throws NullPointerException if the {@code type} argument is null
jaroslav@1646
  2116
     * @throws ClassCastException if the value cannot be converted to the required return type
jaroslav@1646
  2117
     * @throws IllegalArgumentException if the given type is {@code void.class}
jaroslav@1646
  2118
     */
jaroslav@1646
  2119
    public static
jaroslav@1646
  2120
    MethodHandle constant(Class<?> type, Object value) {
jaroslav@1646
  2121
        if (type.isPrimitive()) {
jaroslav@1646
  2122
            if (type == void.class)
jaroslav@1646
  2123
                throw newIllegalArgumentException("void type");
jaroslav@1646
  2124
            Wrapper w = Wrapper.forPrimitiveType(type);
jaroslav@1646
  2125
            return insertArguments(identity(type), 0, w.convert(value, type));
jaroslav@1646
  2126
        } else {
jaroslav@1646
  2127
            return identity(type).bindTo(type.cast(value));
jaroslav@1646
  2128
        }
jaroslav@1646
  2129
    }
jaroslav@1646
  2130
jaroslav@1646
  2131
    /**
jaroslav@1646
  2132
     * Produces a method handle which returns its sole argument when invoked.
jaroslav@1646
  2133
     * @param type the type of the sole parameter and return value of the desired method handle
jaroslav@1646
  2134
     * @return a unary method handle which accepts and returns the given type
jaroslav@1646
  2135
     * @throws NullPointerException if the argument is null
jaroslav@1646
  2136
     * @throws IllegalArgumentException if the given type is {@code void.class}
jaroslav@1646
  2137
     */
jaroslav@1646
  2138
    public static
jaroslav@1646
  2139
    MethodHandle identity(Class<?> type) {
jaroslav@1646
  2140
        if (type == void.class)
jaroslav@1646
  2141
            throw newIllegalArgumentException("void type");
jaroslav@1646
  2142
        else if (type == Object.class)
jaroslav@1646
  2143
            return ValueConversions.identity();
jaroslav@1646
  2144
        else if (type.isPrimitive())
jaroslav@1646
  2145
            return ValueConversions.identity(Wrapper.forPrimitiveType(type));
jaroslav@1646
  2146
        else
jaroslav@1646
  2147
            return MethodHandleImpl.makeReferenceIdentity(type);
jaroslav@1646
  2148
    }
jaroslav@1646
  2149
jaroslav@1646
  2150
    /**
jaroslav@1646
  2151
     * Provides a target method handle with one or more <em>bound arguments</em>
jaroslav@1646
  2152
     * in advance of the method handle's invocation.
jaroslav@1646
  2153
     * The formal parameters to the target corresponding to the bound
jaroslav@1646
  2154
     * arguments are called <em>bound parameters</em>.
jaroslav@1646
  2155
     * Returns a new method handle which saves away the bound arguments.
jaroslav@1646
  2156
     * When it is invoked, it receives arguments for any non-bound parameters,
jaroslav@1646
  2157
     * binds the saved arguments to their corresponding parameters,
jaroslav@1646
  2158
     * and calls the original target.
jaroslav@1646
  2159
     * <p>
jaroslav@1646
  2160
     * The type of the new method handle will drop the types for the bound
jaroslav@1646
  2161
     * parameters from the original target type, since the new method handle
jaroslav@1646
  2162
     * will no longer require those arguments to be supplied by its callers.
jaroslav@1646
  2163
     * <p>
jaroslav@1646
  2164
     * Each given argument object must match the corresponding bound parameter type.
jaroslav@1646
  2165
     * If a bound parameter type is a primitive, the argument object
jaroslav@1646
  2166
     * must be a wrapper, and will be unboxed to produce the primitive value.
jaroslav@1646
  2167
     * <p>
jaroslav@1646
  2168
     * The {@code pos} argument selects which parameters are to be bound.
jaroslav@1646
  2169
     * It may range between zero and <i>N-L</i> (inclusively),
jaroslav@1646
  2170
     * where <i>N</i> is the arity of the target method handle
jaroslav@1646
  2171
     * and <i>L</i> is the length of the values array.
jaroslav@1646
  2172
     * @param target the method handle to invoke after the argument is inserted
jaroslav@1646
  2173
     * @param pos where to insert the argument (zero for the first)
jaroslav@1646
  2174
     * @param values the series of arguments to insert
jaroslav@1646
  2175
     * @return a method handle which inserts an additional argument,
jaroslav@1646
  2176
     *         before calling the original method handle
jaroslav@1646
  2177
     * @throws NullPointerException if the target or the {@code values} array is null
jaroslav@1646
  2178
     * @see MethodHandle#bindTo
jaroslav@1646
  2179
     */
jaroslav@1646
  2180
    public static
jaroslav@1646
  2181
    MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
jaroslav@1646
  2182
        int insCount = values.length;
jaroslav@1646
  2183
        MethodType oldType = target.type();
jaroslav@1646
  2184
        int outargs = oldType.parameterCount();
jaroslav@1646
  2185
        int inargs  = outargs - insCount;
jaroslav@1646
  2186
        if (inargs < 0)
jaroslav@1646
  2187
            throw newIllegalArgumentException("too many values to insert");
jaroslav@1646
  2188
        if (pos < 0 || pos > inargs)
jaroslav@1646
  2189
            throw newIllegalArgumentException("no argument type to append");
jaroslav@1646
  2190
        MethodHandle result = target;
jaroslav@1646
  2191
        for (int i = 0; i < insCount; i++) {
jaroslav@1646
  2192
            Object value = values[i];
jaroslav@1646
  2193
            Class<?> ptype = oldType.parameterType(pos+i);
jaroslav@1646
  2194
            if (ptype.isPrimitive()) {
jaroslav@1646
  2195
                char btype = 'I';
jaroslav@1646
  2196
                Wrapper w = Wrapper.forPrimitiveType(ptype);
jaroslav@1646
  2197
                switch (w) {
jaroslav@1646
  2198
                case LONG:    btype = 'J'; break;
jaroslav@1646
  2199
                case FLOAT:   btype = 'F'; break;
jaroslav@1646
  2200
                case DOUBLE:  btype = 'D'; break;
jaroslav@1646
  2201
                }
jaroslav@1646
  2202
                // perform unboxing and/or primitive conversion
jaroslav@1646
  2203
                value = w.convert(value, ptype);
jaroslav@1646
  2204
                result = result.bindArgument(pos, btype, value);
jaroslav@1646
  2205
                continue;
jaroslav@1646
  2206
            }
jaroslav@1646
  2207
            value = ptype.cast(value);  // throw CCE if needed
jaroslav@1646
  2208
            if (pos == 0) {
jaroslav@1646
  2209
                result = result.bindReceiver(value);
jaroslav@1646
  2210
            } else {
jaroslav@1646
  2211
                result = result.bindArgument(pos, 'L', value);
jaroslav@1646
  2212
            }
jaroslav@1646
  2213
        }
jaroslav@1646
  2214
        return result;
jaroslav@1646
  2215
    }
jaroslav@1646
  2216
jaroslav@1646
  2217
    /**
jaroslav@1646
  2218
     * Produces a method handle which will discard some dummy arguments
jaroslav@1646
  2219
     * before calling some other specified <i>target</i> method handle.
jaroslav@1646
  2220
     * The type of the new method handle will be the same as the target's type,
jaroslav@1646
  2221
     * except it will also include the dummy argument types,
jaroslav@1646
  2222
     * at some given position.
jaroslav@1646
  2223
     * <p>
jaroslav@1646
  2224
     * The {@code pos} argument may range between zero and <i>N</i>,
jaroslav@1646
  2225
     * where <i>N</i> is the arity of the target.
jaroslav@1646
  2226
     * If {@code pos} is zero, the dummy arguments will precede
jaroslav@1646
  2227
     * the target's real arguments; if {@code pos} is <i>N</i>
jaroslav@1646
  2228
     * they will come after.
jaroslav@1646
  2229
     * <p>
jaroslav@1646
  2230
     * <b>Example:</b>
jaroslav@1646
  2231
     * <blockquote><pre>{@code
jaroslav@1646
  2232
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2233
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2234
...
jaroslav@1646
  2235
MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646
  2236
  "concat", methodType(String.class, String.class));
jaroslav@1646
  2237
assertEquals("xy", (String) cat.invokeExact("x", "y"));
jaroslav@1646
  2238
MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
jaroslav@1646
  2239
MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
jaroslav@1646
  2240
assertEquals(bigType, d0.type());
jaroslav@1646
  2241
assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
jaroslav@1646
  2242
     * }</pre></blockquote>
jaroslav@1646
  2243
     * <p>
jaroslav@1646
  2244
     * This method is also equivalent to the following code:
jaroslav@1646
  2245
     * <blockquote><pre>
jaroslav@1646
  2246
     * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
jaroslav@1646
  2247
     * </pre></blockquote>
jaroslav@1646
  2248
     * @param target the method handle to invoke after the arguments are dropped
jaroslav@1646
  2249
     * @param valueTypes the type(s) of the argument(s) to drop
jaroslav@1646
  2250
     * @param pos position of first argument to drop (zero for the leftmost)
jaroslav@1646
  2251
     * @return a method handle which drops arguments of the given types,
jaroslav@1646
  2252
     *         before calling the original method handle
jaroslav@1646
  2253
     * @throws NullPointerException if the target is null,
jaroslav@1646
  2254
     *                              or if the {@code valueTypes} list or any of its elements is null
jaroslav@1646
  2255
     * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
jaroslav@1646
  2256
     *                  or if {@code pos} is negative or greater than the arity of the target,
jaroslav@1646
  2257
     *                  or if the new method handle's type would have too many parameters
jaroslav@1646
  2258
     */
jaroslav@1646
  2259
    public static
jaroslav@1646
  2260
    MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
jaroslav@1646
  2261
        MethodType oldType = target.type();  // get NPE
jaroslav@1646
  2262
        int dropped = valueTypes.size();
jaroslav@1646
  2263
        MethodType.checkSlotCount(dropped);
jaroslav@1646
  2264
        if (dropped == 0)  return target;
jaroslav@1646
  2265
        int outargs = oldType.parameterCount();
jaroslav@1646
  2266
        int inargs  = outargs + dropped;
jaroslav@1646
  2267
        if (pos < 0 || pos >= inargs)
jaroslav@1646
  2268
            throw newIllegalArgumentException("no argument type to remove");
jaroslav@1646
  2269
        ArrayList<Class<?>> ptypes = new ArrayList<>(oldType.parameterList());
jaroslav@1646
  2270
        ptypes.addAll(pos, valueTypes);
jaroslav@1646
  2271
        MethodType newType = MethodType.methodType(oldType.returnType(), ptypes);
jaroslav@1646
  2272
        return target.dropArguments(newType, pos, dropped);
jaroslav@1646
  2273
    }
jaroslav@1646
  2274
jaroslav@1646
  2275
    /**
jaroslav@1646
  2276
     * Produces a method handle which will discard some dummy arguments
jaroslav@1646
  2277
     * before calling some other specified <i>target</i> method handle.
jaroslav@1646
  2278
     * The type of the new method handle will be the same as the target's type,
jaroslav@1646
  2279
     * except it will also include the dummy argument types,
jaroslav@1646
  2280
     * at some given position.
jaroslav@1646
  2281
     * <p>
jaroslav@1646
  2282
     * The {@code pos} argument may range between zero and <i>N</i>,
jaroslav@1646
  2283
     * where <i>N</i> is the arity of the target.
jaroslav@1646
  2284
     * If {@code pos} is zero, the dummy arguments will precede
jaroslav@1646
  2285
     * the target's real arguments; if {@code pos} is <i>N</i>
jaroslav@1646
  2286
     * they will come after.
jaroslav@1646
  2287
     * <p>
jaroslav@1646
  2288
     * <b>Example:</b>
jaroslav@1646
  2289
     * <blockquote><pre>{@code
jaroslav@1646
  2290
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2291
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2292
...
jaroslav@1646
  2293
MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646
  2294
  "concat", methodType(String.class, String.class));
jaroslav@1646
  2295
assertEquals("xy", (String) cat.invokeExact("x", "y"));
jaroslav@1646
  2296
MethodHandle d0 = dropArguments(cat, 0, String.class);
jaroslav@1646
  2297
assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
jaroslav@1646
  2298
MethodHandle d1 = dropArguments(cat, 1, String.class);
jaroslav@1646
  2299
assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
jaroslav@1646
  2300
MethodHandle d2 = dropArguments(cat, 2, String.class);
jaroslav@1646
  2301
assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
jaroslav@1646
  2302
MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
jaroslav@1646
  2303
assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
jaroslav@1646
  2304
     * }</pre></blockquote>
jaroslav@1646
  2305
     * <p>
jaroslav@1646
  2306
     * This method is also equivalent to the following code:
jaroslav@1646
  2307
     * <blockquote><pre>
jaroslav@1646
  2308
     * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
jaroslav@1646
  2309
     * </pre></blockquote>
jaroslav@1646
  2310
     * @param target the method handle to invoke after the arguments are dropped
jaroslav@1646
  2311
     * @param valueTypes the type(s) of the argument(s) to drop
jaroslav@1646
  2312
     * @param pos position of first argument to drop (zero for the leftmost)
jaroslav@1646
  2313
     * @return a method handle which drops arguments of the given types,
jaroslav@1646
  2314
     *         before calling the original method handle
jaroslav@1646
  2315
     * @throws NullPointerException if the target is null,
jaroslav@1646
  2316
     *                              or if the {@code valueTypes} array or any of its elements is null
jaroslav@1646
  2317
     * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
jaroslav@1646
  2318
     *                  or if {@code pos} is negative or greater than the arity of the target,
jaroslav@1646
  2319
     *                  or if the new method handle's type would have
jaroslav@1646
  2320
     *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
  2321
     */
jaroslav@1646
  2322
    public static
jaroslav@1646
  2323
    MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
jaroslav@1646
  2324
        return dropArguments(target, pos, Arrays.asList(valueTypes));
jaroslav@1646
  2325
    }
jaroslav@1646
  2326
jaroslav@1646
  2327
    /**
jaroslav@1646
  2328
     * Adapts a target method handle by pre-processing
jaroslav@1646
  2329
     * one or more of its arguments, each with its own unary filter function,
jaroslav@1646
  2330
     * and then calling the target with each pre-processed argument
jaroslav@1646
  2331
     * replaced by the result of its corresponding filter function.
jaroslav@1646
  2332
     * <p>
jaroslav@1646
  2333
     * The pre-processing is performed by one or more method handles,
jaroslav@1646
  2334
     * specified in the elements of the {@code filters} array.
jaroslav@1646
  2335
     * The first element of the filter array corresponds to the {@code pos}
jaroslav@1646
  2336
     * argument of the target, and so on in sequence.
jaroslav@1646
  2337
     * <p>
jaroslav@1646
  2338
     * Null arguments in the array are treated as identity functions,
jaroslav@1646
  2339
     * and the corresponding arguments left unchanged.
jaroslav@1646
  2340
     * (If there are no non-null elements in the array, the original target is returned.)
jaroslav@1646
  2341
     * Each filter is applied to the corresponding argument of the adapter.
jaroslav@1646
  2342
     * <p>
jaroslav@1646
  2343
     * If a filter {@code F} applies to the {@code N}th argument of
jaroslav@1646
  2344
     * the target, then {@code F} must be a method handle which
jaroslav@1646
  2345
     * takes exactly one argument.  The type of {@code F}'s sole argument
jaroslav@1646
  2346
     * replaces the corresponding argument type of the target
jaroslav@1646
  2347
     * in the resulting adapted method handle.
jaroslav@1646
  2348
     * The return type of {@code F} must be identical to the corresponding
jaroslav@1646
  2349
     * parameter type of the target.
jaroslav@1646
  2350
     * <p>
jaroslav@1646
  2351
     * It is an error if there are elements of {@code filters}
jaroslav@1646
  2352
     * (null or not)
jaroslav@1646
  2353
     * which do not correspond to argument positions in the target.
jaroslav@1646
  2354
     * <p><b>Example:</b>
jaroslav@1646
  2355
     * <blockquote><pre>{@code
jaroslav@1646
  2356
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2357
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2358
...
jaroslav@1646
  2359
MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646
  2360
  "concat", methodType(String.class, String.class));
jaroslav@1646
  2361
MethodHandle upcase = lookup().findVirtual(String.class,
jaroslav@1646
  2362
  "toUpperCase", methodType(String.class));
jaroslav@1646
  2363
assertEquals("xy", (String) cat.invokeExact("x", "y"));
jaroslav@1646
  2364
MethodHandle f0 = filterArguments(cat, 0, upcase);
jaroslav@1646
  2365
assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
jaroslav@1646
  2366
MethodHandle f1 = filterArguments(cat, 1, upcase);
jaroslav@1646
  2367
assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
jaroslav@1646
  2368
MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
jaroslav@1646
  2369
assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
jaroslav@1646
  2370
     * }</pre></blockquote>
jaroslav@1646
  2371
     * <p> Here is pseudocode for the resulting adapter:
jaroslav@1646
  2372
     * <blockquote><pre>{@code
jaroslav@1646
  2373
     * V target(P... p, A[i]... a[i], B... b);
jaroslav@1646
  2374
     * A[i] filter[i](V[i]);
jaroslav@1646
  2375
     * T adapter(P... p, V[i]... v[i], B... b) {
jaroslav@1646
  2376
     *   return target(p..., f[i](v[i])..., b...);
jaroslav@1646
  2377
     * }
jaroslav@1646
  2378
     * }</pre></blockquote>
jaroslav@1646
  2379
     *
jaroslav@1646
  2380
     * @param target the method handle to invoke after arguments are filtered
jaroslav@1646
  2381
     * @param pos the position of the first argument to filter
jaroslav@1646
  2382
     * @param filters method handles to call initially on filtered arguments
jaroslav@1646
  2383
     * @return method handle which incorporates the specified argument filtering logic
jaroslav@1646
  2384
     * @throws NullPointerException if the target is null
jaroslav@1646
  2385
     *                              or if the {@code filters} array is null
jaroslav@1646
  2386
     * @throws IllegalArgumentException if a non-null element of {@code filters}
jaroslav@1646
  2387
     *          does not match a corresponding argument type of target as described above,
jaroslav@1646
  2388
     *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
jaroslav@1646
  2389
     *          or if the resulting method handle's type would have
jaroslav@1646
  2390
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
  2391
     */
jaroslav@1646
  2392
    public static
jaroslav@1646
  2393
    MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
jaroslav@1646
  2394
        MethodType targetType = target.type();
jaroslav@1646
  2395
        MethodHandle adapter = target;
jaroslav@1646
  2396
        MethodType adapterType = null;
jaroslav@1646
  2397
        assert((adapterType = targetType) != null);
jaroslav@1646
  2398
        int maxPos = targetType.parameterCount();
jaroslav@1646
  2399
        if (pos + filters.length > maxPos)
jaroslav@1646
  2400
            throw newIllegalArgumentException("too many filters");
jaroslav@1646
  2401
        int curPos = pos-1;  // pre-incremented
jaroslav@1646
  2402
        for (MethodHandle filter : filters) {
jaroslav@1646
  2403
            curPos += 1;
jaroslav@1646
  2404
            if (filter == null)  continue;  // ignore null elements of filters
jaroslav@1646
  2405
            adapter = filterArgument(adapter, curPos, filter);
jaroslav@1646
  2406
            assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null);
jaroslav@1646
  2407
        }
jaroslav@1646
  2408
        assert(adapterType.equals(adapter.type()));
jaroslav@1646
  2409
        return adapter;
jaroslav@1646
  2410
    }
jaroslav@1646
  2411
jaroslav@1646
  2412
    /*non-public*/ static
jaroslav@1646
  2413
    MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
jaroslav@1646
  2414
        MethodType targetType = target.type();
jaroslav@1646
  2415
        MethodType filterType = filter.type();
jaroslav@1646
  2416
        if (filterType.parameterCount() != 1
jaroslav@1646
  2417
            || filterType.returnType() != targetType.parameterType(pos))
jaroslav@1646
  2418
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
jaroslav@1646
  2419
        return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
jaroslav@1646
  2420
    }
jaroslav@1646
  2421
jaroslav@1646
  2422
    /**
jaroslav@1646
  2423
     * Adapts a target method handle by pre-processing
jaroslav@1646
  2424
     * a sub-sequence of its arguments with a filter (another method handle).
jaroslav@1646
  2425
     * The pre-processed arguments are replaced by the result (if any) of the
jaroslav@1646
  2426
     * filter function.
jaroslav@1646
  2427
     * The target is then called on the modified (usually shortened) argument list.
jaroslav@1646
  2428
     * <p>
jaroslav@1646
  2429
     * If the filter returns a value, the target must accept that value as
jaroslav@1646
  2430
     * its argument in position {@code pos}, preceded and/or followed by
jaroslav@1646
  2431
     * any arguments not passed to the filter.
jaroslav@1646
  2432
     * If the filter returns void, the target must accept all arguments
jaroslav@1646
  2433
     * not passed to the filter.
jaroslav@1646
  2434
     * No arguments are reordered, and a result returned from the filter
jaroslav@1646
  2435
     * replaces (in order) the whole subsequence of arguments originally
jaroslav@1646
  2436
     * passed to the adapter.
jaroslav@1646
  2437
     * <p>
jaroslav@1646
  2438
     * The argument types (if any) of the filter
jaroslav@1646
  2439
     * replace zero or one argument types of the target, at position {@code pos},
jaroslav@1646
  2440
     * in the resulting adapted method handle.
jaroslav@1646
  2441
     * The return type of the filter (if any) must be identical to the
jaroslav@1646
  2442
     * argument type of the target at position {@code pos}, and that target argument
jaroslav@1646
  2443
     * is supplied by the return value of the filter.
jaroslav@1646
  2444
     * <p>
jaroslav@1646
  2445
     * In all cases, {@code pos} must be greater than or equal to zero, and
jaroslav@1646
  2446
     * {@code pos} must also be less than or equal to the target's arity.
jaroslav@1646
  2447
     * <p><b>Example:</b>
jaroslav@1646
  2448
     * <blockquote><pre>{@code
jaroslav@1646
  2449
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2450
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2451
...
jaroslav@1646
  2452
MethodHandle deepToString = publicLookup()
jaroslav@1646
  2453
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1646
  2454
jaroslav@1646
  2455
MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
jaroslav@1646
  2456
assertEquals("[strange]", (String) ts1.invokeExact("strange"));
jaroslav@1646
  2457
jaroslav@1646
  2458
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
jaroslav@1646
  2459
assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
jaroslav@1646
  2460
jaroslav@1646
  2461
MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
jaroslav@1646
  2462
MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
jaroslav@1646
  2463
assertEquals("[top, [up, down], strange]",
jaroslav@1646
  2464
             (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
jaroslav@1646
  2465
jaroslav@1646
  2466
MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
jaroslav@1646
  2467
assertEquals("[top, [up, down], [strange]]",
jaroslav@1646
  2468
             (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
jaroslav@1646
  2469
jaroslav@1646
  2470
MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
jaroslav@1646
  2471
assertEquals("[top, [[up, down, strange], charm], bottom]",
jaroslav@1646
  2472
             (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
jaroslav@1646
  2473
     * }</pre></blockquote>
jaroslav@1646
  2474
     * <p> Here is pseudocode for the resulting adapter:
jaroslav@1646
  2475
     * <blockquote><pre>{@code
jaroslav@1646
  2476
     * T target(A...,V,C...);
jaroslav@1646
  2477
     * V filter(B...);
jaroslav@1646
  2478
     * T adapter(A... a,B... b,C... c) {
jaroslav@1646
  2479
     *   V v = filter(b...);
jaroslav@1646
  2480
     *   return target(a...,v,c...);
jaroslav@1646
  2481
     * }
jaroslav@1646
  2482
     * // and if the filter has no arguments:
jaroslav@1646
  2483
     * T target2(A...,V,C...);
jaroslav@1646
  2484
     * V filter2();
jaroslav@1646
  2485
     * T adapter2(A... a,C... c) {
jaroslav@1646
  2486
     *   V v = filter2();
jaroslav@1646
  2487
     *   return target2(a...,v,c...);
jaroslav@1646
  2488
     * }
jaroslav@1646
  2489
     * // and if the filter has a void return:
jaroslav@1646
  2490
     * T target3(A...,C...);
jaroslav@1646
  2491
     * void filter3(B...);
jaroslav@1646
  2492
     * void adapter3(A... a,B... b,C... c) {
jaroslav@1646
  2493
     *   filter3(b...);
jaroslav@1646
  2494
     *   return target3(a...,c...);
jaroslav@1646
  2495
     * }
jaroslav@1646
  2496
     * }</pre></blockquote>
jaroslav@1646
  2497
     * <p>
jaroslav@1646
  2498
     * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
jaroslav@1646
  2499
     * one which first "folds" the affected arguments, and then drops them, in separate
jaroslav@1646
  2500
     * steps as follows:
jaroslav@1646
  2501
     * <blockquote><pre>{@code
jaroslav@1646
  2502
     * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
jaroslav@1646
  2503
     * mh = MethodHandles.foldArguments(mh, coll); //step 1
jaroslav@1646
  2504
     * }</pre></blockquote>
jaroslav@1646
  2505
     * If the target method handle consumes no arguments besides than the result
jaroslav@1646
  2506
     * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
jaroslav@1646
  2507
     * is equivalent to {@code filterReturnValue(coll, mh)}.
jaroslav@1646
  2508
     * If the filter method handle {@code coll} consumes one argument and produces
jaroslav@1646
  2509
     * a non-void result, then {@code collectArguments(mh, N, coll)}
jaroslav@1646
  2510
     * is equivalent to {@code filterArguments(mh, N, coll)}.
jaroslav@1646
  2511
     * Other equivalences are possible but would require argument permutation.
jaroslav@1646
  2512
     *
jaroslav@1646
  2513
     * @param target the method handle to invoke after filtering the subsequence of arguments
jaroslav@1646
  2514
     * @param pos the position of the first adapter argument to pass to the filter,
jaroslav@1646
  2515
     *            and/or the target argument which receives the result of the filter
jaroslav@1646
  2516
     * @param filter method handle to call on the subsequence of arguments
jaroslav@1646
  2517
     * @return method handle which incorporates the specified argument subsequence filtering logic
jaroslav@1646
  2518
     * @throws NullPointerException if either argument is null
jaroslav@1646
  2519
     * @throws IllegalArgumentException if the return type of {@code filter}
jaroslav@1646
  2520
     *          is non-void and is not the same as the {@code pos} argument of the target,
jaroslav@1646
  2521
     *          or if {@code pos} is not between 0 and the target's arity, inclusive,
jaroslav@1646
  2522
     *          or if the resulting method handle's type would have
jaroslav@1646
  2523
     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
  2524
     * @see MethodHandles#foldArguments
jaroslav@1646
  2525
     * @see MethodHandles#filterArguments
jaroslav@1646
  2526
     * @see MethodHandles#filterReturnValue
jaroslav@1646
  2527
     */
jaroslav@1646
  2528
    public static
jaroslav@1646
  2529
    MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
jaroslav@1646
  2530
        MethodType targetType = target.type();
jaroslav@1646
  2531
        MethodType filterType = filter.type();
jaroslav@1646
  2532
        if (filterType.returnType() != void.class &&
jaroslav@1646
  2533
            filterType.returnType() != targetType.parameterType(pos))
jaroslav@1646
  2534
            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
jaroslav@1646
  2535
        return MethodHandleImpl.makeCollectArguments(target, filter, pos, false);
jaroslav@1646
  2536
    }
jaroslav@1646
  2537
jaroslav@1646
  2538
    /**
jaroslav@1646
  2539
     * Adapts a target method handle by post-processing
jaroslav@1646
  2540
     * its return value (if any) with a filter (another method handle).
jaroslav@1646
  2541
     * The result of the filter is returned from the adapter.
jaroslav@1646
  2542
     * <p>
jaroslav@1646
  2543
     * If the target returns a value, the filter must accept that value as
jaroslav@1646
  2544
     * its only argument.
jaroslav@1646
  2545
     * If the target returns void, the filter must accept no arguments.
jaroslav@1646
  2546
     * <p>
jaroslav@1646
  2547
     * The return type of the filter
jaroslav@1646
  2548
     * replaces the return type of the target
jaroslav@1646
  2549
     * in the resulting adapted method handle.
jaroslav@1646
  2550
     * The argument type of the filter (if any) must be identical to the
jaroslav@1646
  2551
     * return type of the target.
jaroslav@1646
  2552
     * <p><b>Example:</b>
jaroslav@1646
  2553
     * <blockquote><pre>{@code
jaroslav@1646
  2554
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2555
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2556
...
jaroslav@1646
  2557
MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646
  2558
  "concat", methodType(String.class, String.class));
jaroslav@1646
  2559
MethodHandle length = lookup().findVirtual(String.class,
jaroslav@1646
  2560
  "length", methodType(int.class));
jaroslav@1646
  2561
System.out.println((String) cat.invokeExact("x", "y")); // xy
jaroslav@1646
  2562
MethodHandle f0 = filterReturnValue(cat, length);
jaroslav@1646
  2563
System.out.println((int) f0.invokeExact("x", "y")); // 2
jaroslav@1646
  2564
     * }</pre></blockquote>
jaroslav@1646
  2565
     * <p> Here is pseudocode for the resulting adapter:
jaroslav@1646
  2566
     * <blockquote><pre>{@code
jaroslav@1646
  2567
     * V target(A...);
jaroslav@1646
  2568
     * T filter(V);
jaroslav@1646
  2569
     * T adapter(A... a) {
jaroslav@1646
  2570
     *   V v = target(a...);
jaroslav@1646
  2571
     *   return filter(v);
jaroslav@1646
  2572
     * }
jaroslav@1646
  2573
     * // and if the target has a void return:
jaroslav@1646
  2574
     * void target2(A...);
jaroslav@1646
  2575
     * T filter2();
jaroslav@1646
  2576
     * T adapter2(A... a) {
jaroslav@1646
  2577
     *   target2(a...);
jaroslav@1646
  2578
     *   return filter2();
jaroslav@1646
  2579
     * }
jaroslav@1646
  2580
     * // and if the filter has a void return:
jaroslav@1646
  2581
     * V target3(A...);
jaroslav@1646
  2582
     * void filter3(V);
jaroslav@1646
  2583
     * void adapter3(A... a) {
jaroslav@1646
  2584
     *   V v = target3(a...);
jaroslav@1646
  2585
     *   filter3(v);
jaroslav@1646
  2586
     * }
jaroslav@1646
  2587
     * }</pre></blockquote>
jaroslav@1646
  2588
     * @param target the method handle to invoke before filtering the return value
jaroslav@1646
  2589
     * @param filter method handle to call on the return value
jaroslav@1646
  2590
     * @return method handle which incorporates the specified return value filtering logic
jaroslav@1646
  2591
     * @throws NullPointerException if either argument is null
jaroslav@1646
  2592
     * @throws IllegalArgumentException if the argument list of {@code filter}
jaroslav@1646
  2593
     *          does not match the return type of target as described above
jaroslav@1646
  2594
     */
jaroslav@1646
  2595
    public static
jaroslav@1646
  2596
    MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
jaroslav@1646
  2597
        MethodType targetType = target.type();
jaroslav@1646
  2598
        MethodType filterType = filter.type();
jaroslav@1646
  2599
        Class<?> rtype = targetType.returnType();
jaroslav@1646
  2600
        int filterValues = filterType.parameterCount();
jaroslav@1646
  2601
        if (filterValues == 0
jaroslav@1646
  2602
                ? (rtype != void.class)
jaroslav@1646
  2603
                : (rtype != filterType.parameterType(0)))
jaroslav@1646
  2604
            throw newIllegalArgumentException("target and filter types do not match", target, filter);
jaroslav@1646
  2605
        // result = fold( lambda(retval, arg...) { filter(retval) },
jaroslav@1646
  2606
        //                lambda(        arg...) { target(arg...) } )
jaroslav@1646
  2607
        return MethodHandleImpl.makeCollectArguments(filter, target, 0, false);
jaroslav@1646
  2608
    }
jaroslav@1646
  2609
jaroslav@1646
  2610
    /**
jaroslav@1646
  2611
     * Adapts a target method handle by pre-processing
jaroslav@1646
  2612
     * some of its arguments, and then calling the target with
jaroslav@1646
  2613
     * the result of the pre-processing, inserted into the original
jaroslav@1646
  2614
     * sequence of arguments.
jaroslav@1646
  2615
     * <p>
jaroslav@1646
  2616
     * The pre-processing is performed by {@code combiner}, a second method handle.
jaroslav@1646
  2617
     * Of the arguments passed to the adapter, the first {@code N} arguments
jaroslav@1646
  2618
     * are copied to the combiner, which is then called.
jaroslav@1646
  2619
     * (Here, {@code N} is defined as the parameter count of the combiner.)
jaroslav@1646
  2620
     * After this, control passes to the target, with any result
jaroslav@1646
  2621
     * from the combiner inserted before the original {@code N} incoming
jaroslav@1646
  2622
     * arguments.
jaroslav@1646
  2623
     * <p>
jaroslav@1646
  2624
     * If the combiner returns a value, the first parameter type of the target
jaroslav@1646
  2625
     * must be identical with the return type of the combiner, and the next
jaroslav@1646
  2626
     * {@code N} parameter types of the target must exactly match the parameters
jaroslav@1646
  2627
     * of the combiner.
jaroslav@1646
  2628
     * <p>
jaroslav@1646
  2629
     * If the combiner has a void return, no result will be inserted,
jaroslav@1646
  2630
     * and the first {@code N} parameter types of the target
jaroslav@1646
  2631
     * must exactly match the parameters of the combiner.
jaroslav@1646
  2632
     * <p>
jaroslav@1646
  2633
     * The resulting adapter is the same type as the target, except that the
jaroslav@1646
  2634
     * first parameter type is dropped,
jaroslav@1646
  2635
     * if it corresponds to the result of the combiner.
jaroslav@1646
  2636
     * <p>
jaroslav@1646
  2637
     * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
jaroslav@1646
  2638
     * that either the combiner or the target does not wish to receive.
jaroslav@1646
  2639
     * If some of the incoming arguments are destined only for the combiner,
jaroslav@1646
  2640
     * consider using {@link MethodHandle#asCollector asCollector} instead, since those
jaroslav@1646
  2641
     * arguments will not need to be live on the stack on entry to the
jaroslav@1646
  2642
     * target.)
jaroslav@1646
  2643
     * <p><b>Example:</b>
jaroslav@1646
  2644
     * <blockquote><pre>{@code
jaroslav@1646
  2645
import static java.lang.invoke.MethodHandles.*;
jaroslav@1646
  2646
import static java.lang.invoke.MethodType.*;
jaroslav@1646
  2647
...
jaroslav@1646
  2648
MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
jaroslav@1646
  2649
  "println", methodType(void.class, String.class))
jaroslav@1646
  2650
    .bindTo(System.out);
jaroslav@1646
  2651
MethodHandle cat = lookup().findVirtual(String.class,
jaroslav@1646
  2652
  "concat", methodType(String.class, String.class));
jaroslav@1646
  2653
assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
jaroslav@1646
  2654
MethodHandle catTrace = foldArguments(cat, trace);
jaroslav@1646
  2655
// also prints "boo":
jaroslav@1646
  2656
assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
jaroslav@1646
  2657
     * }</pre></blockquote>
jaroslav@1646
  2658
     * <p> Here is pseudocode for the resulting adapter:
jaroslav@1646
  2659
     * <blockquote><pre>{@code
jaroslav@1646
  2660
     * // there are N arguments in A...
jaroslav@1646
  2661
     * T target(V, A[N]..., B...);
jaroslav@1646
  2662
     * V combiner(A...);
jaroslav@1646
  2663
     * T adapter(A... a, B... b) {
jaroslav@1646
  2664
     *   V v = combiner(a...);
jaroslav@1646
  2665
     *   return target(v, a..., b...);
jaroslav@1646
  2666
     * }
jaroslav@1646
  2667
     * // and if the combiner has a void return:
jaroslav@1646
  2668
     * T target2(A[N]..., B...);
jaroslav@1646
  2669
     * void combiner2(A...);
jaroslav@1646
  2670
     * T adapter2(A... a, B... b) {
jaroslav@1646
  2671
     *   combiner2(a...);
jaroslav@1646
  2672
     *   return target2(a..., b...);
jaroslav@1646
  2673
     * }
jaroslav@1646
  2674
     * }</pre></blockquote>
jaroslav@1646
  2675
     * @param target the method handle to invoke after arguments are combined
jaroslav@1646
  2676
     * @param combiner method handle to call initially on the incoming arguments
jaroslav@1646
  2677
     * @return method handle which incorporates the specified argument folding logic
jaroslav@1646
  2678
     * @throws NullPointerException if either argument is null
jaroslav@1646
  2679
     * @throws IllegalArgumentException if {@code combiner}'s return type
jaroslav@1646
  2680
     *          is non-void and not the same as the first argument type of
jaroslav@1646
  2681
     *          the target, or if the initial {@code N} argument types
jaroslav@1646
  2682
     *          of the target
jaroslav@1646
  2683
     *          (skipping one matching the {@code combiner}'s return type)
jaroslav@1646
  2684
     *          are not identical with the argument types of {@code combiner}
jaroslav@1646
  2685
     */
jaroslav@1646
  2686
    public static
jaroslav@1646
  2687
    MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
jaroslav@1646
  2688
        int pos = 0;
jaroslav@1646
  2689
        MethodType targetType = target.type();
jaroslav@1646
  2690
        MethodType combinerType = combiner.type();
jaroslav@1646
  2691
        int foldPos = pos;
jaroslav@1646
  2692
        int foldArgs = combinerType.parameterCount();
jaroslav@1646
  2693
        int foldVals = combinerType.returnType() == void.class ? 0 : 1;
jaroslav@1646
  2694
        int afterInsertPos = foldPos + foldVals;
jaroslav@1646
  2695
        boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
jaroslav@1646
  2696
        if (ok && !(combinerType.parameterList()
jaroslav@1646
  2697
                    .equals(targetType.parameterList().subList(afterInsertPos,
jaroslav@1646
  2698
                                                               afterInsertPos + foldArgs))))
jaroslav@1646
  2699
            ok = false;
jaroslav@1646
  2700
        if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0)))
jaroslav@1646
  2701
            ok = false;
jaroslav@1646
  2702
        if (!ok)
jaroslav@1646
  2703
            throw misMatchedTypes("target and combiner types", targetType, combinerType);
jaroslav@1646
  2704
        MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos);
jaroslav@1646
  2705
        return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true);
jaroslav@1646
  2706
    }
jaroslav@1646
  2707
jaroslav@1646
  2708
    /**
jaroslav@1646
  2709
     * Makes a method handle which adapts a target method handle,
jaroslav@1646
  2710
     * by guarding it with a test, a boolean-valued method handle.
jaroslav@1646
  2711
     * If the guard fails, a fallback handle is called instead.
jaroslav@1646
  2712
     * All three method handles must have the same corresponding
jaroslav@1646
  2713
     * argument and return types, except that the return type
jaroslav@1646
  2714
     * of the test must be boolean, and the test is allowed
jaroslav@1646
  2715
     * to have fewer arguments than the other two method handles.
jaroslav@1646
  2716
     * <p> Here is pseudocode for the resulting adapter:
jaroslav@1646
  2717
     * <blockquote><pre>{@code
jaroslav@1646
  2718
     * boolean test(A...);
jaroslav@1646
  2719
     * T target(A...,B...);
jaroslav@1646
  2720
     * T fallback(A...,B...);
jaroslav@1646
  2721
     * T adapter(A... a,B... b) {
jaroslav@1646
  2722
     *   if (test(a...))
jaroslav@1646
  2723
     *     return target(a..., b...);
jaroslav@1646
  2724
     *   else
jaroslav@1646
  2725
     *     return fallback(a..., b...);
jaroslav@1646
  2726
     * }
jaroslav@1646
  2727
     * }</pre></blockquote>
jaroslav@1646
  2728
     * Note that the test arguments ({@code a...} in the pseudocode) cannot
jaroslav@1646
  2729
     * be modified by execution of the test, and so are passed unchanged
jaroslav@1646
  2730
     * from the caller to the target or fallback as appropriate.
jaroslav@1646
  2731
     * @param test method handle used for test, must return boolean
jaroslav@1646
  2732
     * @param target method handle to call if test passes
jaroslav@1646
  2733
     * @param fallback method handle to call if test fails
jaroslav@1646
  2734
     * @return method handle which incorporates the specified if/then/else logic
jaroslav@1646
  2735
     * @throws NullPointerException if any argument is null
jaroslav@1646
  2736
     * @throws IllegalArgumentException if {@code test} does not return boolean,
jaroslav@1646
  2737
     *          or if all three method types do not match (with the return
jaroslav@1646
  2738
     *          type of {@code test} changed to match that of the target).
jaroslav@1646
  2739
     */
jaroslav@1646
  2740
    public static
jaroslav@1646
  2741
    MethodHandle guardWithTest(MethodHandle test,
jaroslav@1646
  2742
                               MethodHandle target,
jaroslav@1646
  2743
                               MethodHandle fallback) {
jaroslav@1646
  2744
        MethodType gtype = test.type();
jaroslav@1646
  2745
        MethodType ttype = target.type();
jaroslav@1646
  2746
        MethodType ftype = fallback.type();
jaroslav@1646
  2747
        if (!ttype.equals(ftype))
jaroslav@1646
  2748
            throw misMatchedTypes("target and fallback types", ttype, ftype);
jaroslav@1646
  2749
        if (gtype.returnType() != boolean.class)
jaroslav@1646
  2750
            throw newIllegalArgumentException("guard type is not a predicate "+gtype);
jaroslav@1646
  2751
        List<Class<?>> targs = ttype.parameterList();
jaroslav@1646
  2752
        List<Class<?>> gargs = gtype.parameterList();
jaroslav@1646
  2753
        if (!targs.equals(gargs)) {
jaroslav@1646
  2754
            int gpc = gargs.size(), tpc = targs.size();
jaroslav@1646
  2755
            if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
jaroslav@1646
  2756
                throw misMatchedTypes("target and test types", ttype, gtype);
jaroslav@1646
  2757
            test = dropArguments(test, gpc, targs.subList(gpc, tpc));
jaroslav@1646
  2758
            gtype = test.type();
jaroslav@1646
  2759
        }
jaroslav@1646
  2760
        return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
jaroslav@1646
  2761
    }
jaroslav@1646
  2762
jaroslav@1646
  2763
    static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) {
jaroslav@1646
  2764
        return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
jaroslav@1646
  2765
    }
jaroslav@1646
  2766
jaroslav@1646
  2767
    /**
jaroslav@1646
  2768
     * Makes a method handle which adapts a target method handle,
jaroslav@1646
  2769
     * by running it inside an exception handler.
jaroslav@1646
  2770
     * If the target returns normally, the adapter returns that value.
jaroslav@1646
  2771
     * If an exception matching the specified type is thrown, the fallback
jaroslav@1646
  2772
     * handle is called instead on the exception, plus the original arguments.
jaroslav@1646
  2773
     * <p>
jaroslav@1646
  2774
     * The target and handler must have the same corresponding
jaroslav@1646
  2775
     * argument and return types, except that handler may omit trailing arguments
jaroslav@1646
  2776
     * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
jaroslav@1646
  2777
     * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
jaroslav@1646
  2778
     * <p> Here is pseudocode for the resulting adapter:
jaroslav@1646
  2779
     * <blockquote><pre>{@code
jaroslav@1646
  2780
     * T target(A..., B...);
jaroslav@1646
  2781
     * T handler(ExType, A...);
jaroslav@1646
  2782
     * T adapter(A... a, B... b) {
jaroslav@1646
  2783
     *   try {
jaroslav@1646
  2784
     *     return target(a..., b...);
jaroslav@1646
  2785
     *   } catch (ExType ex) {
jaroslav@1646
  2786
     *     return handler(ex, a...);
jaroslav@1646
  2787
     *   }
jaroslav@1646
  2788
     * }
jaroslav@1646
  2789
     * }</pre></blockquote>
jaroslav@1646
  2790
     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
jaroslav@1646
  2791
     * be modified by execution of the target, and so are passed unchanged
jaroslav@1646
  2792
     * from the caller to the handler, if the handler is invoked.
jaroslav@1646
  2793
     * <p>
jaroslav@1646
  2794
     * The target and handler must return the same type, even if the handler
jaroslav@1646
  2795
     * always throws.  (This might happen, for instance, because the handler
jaroslav@1646
  2796
     * is simulating a {@code finally} clause).
jaroslav@1646
  2797
     * To create such a throwing handler, compose the handler creation logic
jaroslav@1646
  2798
     * with {@link #throwException throwException},
jaroslav@1646
  2799
     * in order to create a method handle of the correct return type.
jaroslav@1646
  2800
     * @param target method handle to call
jaroslav@1646
  2801
     * @param exType the type of exception which the handler will catch
jaroslav@1646
  2802
     * @param handler method handle to call if a matching exception is thrown
jaroslav@1646
  2803
     * @return method handle which incorporates the specified try/catch logic
jaroslav@1646
  2804
     * @throws NullPointerException if any argument is null
jaroslav@1646
  2805
     * @throws IllegalArgumentException if {@code handler} does not accept
jaroslav@1646
  2806
     *          the given exception type, or if the method handle types do
jaroslav@1646
  2807
     *          not match in their return types and their
jaroslav@1646
  2808
     *          corresponding parameters
jaroslav@1646
  2809
     */
jaroslav@1646
  2810
    public static
jaroslav@1646
  2811
    MethodHandle catchException(MethodHandle target,
jaroslav@1646
  2812
                                Class<? extends Throwable> exType,
jaroslav@1646
  2813
                                MethodHandle handler) {
jaroslav@1646
  2814
        MethodType ttype = target.type();
jaroslav@1646
  2815
        MethodType htype = handler.type();
jaroslav@1646
  2816
        if (htype.parameterCount() < 1 ||
jaroslav@1646
  2817
            !htype.parameterType(0).isAssignableFrom(exType))
jaroslav@1646
  2818
            throw newIllegalArgumentException("handler does not accept exception type "+exType);
jaroslav@1646
  2819
        if (htype.returnType() != ttype.returnType())
jaroslav@1646
  2820
            throw misMatchedTypes("target and handler return types", ttype, htype);
jaroslav@1646
  2821
        List<Class<?>> targs = ttype.parameterList();
jaroslav@1646
  2822
        List<Class<?>> hargs = htype.parameterList();
jaroslav@1646
  2823
        hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
jaroslav@1646
  2824
        if (!targs.equals(hargs)) {
jaroslav@1646
  2825
            int hpc = hargs.size(), tpc = targs.size();
jaroslav@1646
  2826
            if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
jaroslav@1646
  2827
                throw misMatchedTypes("target and handler types", ttype, htype);
jaroslav@1646
  2828
            handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));
jaroslav@1646
  2829
            htype = handler.type();
jaroslav@1646
  2830
        }
jaroslav@1646
  2831
        return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
jaroslav@1646
  2832
    }
jaroslav@1646
  2833
jaroslav@1646
  2834
    /**
jaroslav@1646
  2835
     * Produces a method handle which will throw exceptions of the given {@code exType}.
jaroslav@1646
  2836
     * The method handle will accept a single argument of {@code exType},
jaroslav@1646
  2837
     * and immediately throw it as an exception.
jaroslav@1646
  2838
     * The method type will nominally specify a return of {@code returnType}.
jaroslav@1646
  2839
     * The return type may be anything convenient:  It doesn't matter to the
jaroslav@1646
  2840
     * method handle's behavior, since it will never return normally.
jaroslav@1646
  2841
     * @param returnType the return type of the desired method handle
jaroslav@1646
  2842
     * @param exType the parameter type of the desired method handle
jaroslav@1646
  2843
     * @return method handle which can throw the given exceptions
jaroslav@1646
  2844
     * @throws NullPointerException if either argument is null
jaroslav@1646
  2845
     */
jaroslav@1646
  2846
    public static
jaroslav@1646
  2847
    MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
jaroslav@1646
  2848
        if (!Throwable.class.isAssignableFrom(exType))
jaroslav@1646
  2849
            throw new ClassCastException(exType.getName());
jaroslav@1646
  2850
        return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
jaroslav@1646
  2851
    }
jaroslav@1646
  2852
}