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