1 /*
  2  * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.invoke;
 27 
 28 import java.lang.reflect.code.Quotable;
 29 
 30 import java.io.Serializable;
 31 import java.util.Arrays;
 32 import java.lang.reflect.Array;
 33 import java.util.Objects;
 34 
 35 /**
 36  * <p>Methods to facilitate the creation of simple "function objects" that
 37  * implement one or more interfaces by delegation to a provided {@link MethodHandle},
 38  * possibly after type adaptation and partial evaluation of arguments.  These
 39  * methods are typically used as <em>bootstrap methods</em> for {@code invokedynamic}
 40  * call sites, to support the <em>lambda expression</em> and <em>method
 41  * reference expression</em> features of the Java Programming Language.
 42  *
 43  * <p>Indirect access to the behavior specified by the provided {@code MethodHandle}
 44  * proceeds in order through three phases:
 45  * <ul>
 46  *     <li><p><em>Linkage</em> occurs when the methods in this class are invoked.
 47  *     They take as arguments an interface to be implemented (typically a
 48  *     <em>functional interface</em>, one with a single abstract method), a
 49  *     name and signature of a method from that interface to be implemented, a
 50  *     {@linkplain MethodHandleInfo direct method handle} describing the desired
 51  *     implementation behavior for that method, and possibly other additional
 52  *     metadata, and produce a {@link CallSite} whose target can be used to
 53  *     create suitable function objects.
 54  *
 55  *     <p>Linkage may involve dynamically loading a new class that implements
 56  *     the target interface, or re-using a suitable existing class.
 57  *
 58  *     <p>The {@code CallSite} can be considered a "factory" for function
 59  *     objects and so these linkage methods are referred to as
 60  *     "metafactories".</li>
 61  *
 62  *     <li><p><em>Capture</em> occurs when the {@code CallSite}'s target is
 63  *     invoked, typically through an {@code invokedynamic} call site,
 64  *     producing a function object. This may occur many times for
 65  *     a single factory {@code CallSite}.
 66  *
 67  *     <p>If the behavior {@code MethodHandle} has additional parameters beyond
 68  *     those of the specified interface method, these are referred to as
 69  *     <em>captured parameters</em>, which must be provided as arguments to the
 70  *     {@code CallSite} target. The expected number and types of captured
 71  *     parameters are determined during linkage.
 72  *
 73  *     <p>Capture may involve allocation of a new function object, or may return
 74  *     a suitable existing function object. The identity of a function object
 75  *     produced by capture is unpredictable, and therefore identity-sensitive
 76  *     operations (such as reference equality, object locking, and {@code
 77  *     System.identityHashCode()}) may produce different results in different
 78  *     implementations, or even upon different invocations in the same
 79  *     implementation.</li>
 80  *
 81  *     <li><p><em>Invocation</em> occurs when an implemented interface method is
 82  *     invoked on a function object. This may occur many times for a single
 83  *     function object. The method referenced by the implementation
 84  *     {@code MethodHandle} is invoked, passing to it the captured arguments and
 85  *     the invocation arguments. The result of the method is returned.
 86  *     </li>
 87  * </ul>
 88  *
 89  * <p>It is sometimes useful to restrict the set of inputs or results permitted
 90  * at invocation.  For example, when the generic interface {@code Predicate<T>}
 91  * is parameterized as {@code Predicate<String>}, the input must be a
 92  * {@code String}, even though the method to implement allows any {@code Object}.
 93  * At linkage time, an additional {@link MethodType} parameter describes the
 94  * "dynamic" method type; on invocation, the arguments and eventual result
 95  * are checked against this {@code MethodType}.
 96  *
 97  * <p>This class provides two forms of linkage methods: a standard version
 98  * ({@link #metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)})
 99  * using an optimized protocol, and an alternate version
100  * {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}).
101  * The alternate version is a generalization of the standard version, providing
102  * additional control over the behavior of the generated function objects via
103  * flags and additional arguments.  The alternate version adds the ability to
104  * manage the following attributes of function objects:
105  *
106  * <ul>
107  *     <li><em>Multiple methods.</em>  It is sometimes useful to implement multiple
108  *     variations of the method signature, involving argument or return type
109  *     adaptation.  This occurs when multiple distinct VM signatures for a method
110  *     are logically considered to be the same method by the language.  The
111  *     flag {@code FLAG_BRIDGES} indicates that a list of additional
112  *     {@code MethodType}s will be provided, each of which will be implemented
113  *     by the resulting function object.  These methods will share the same
114  *     name and instantiated type.</li>
115  *
116  *     <li><em>Multiple interfaces.</em>  If needed, more than one interface
117  *     can be implemented by the function object.  (These additional interfaces
118  *     are typically marker interfaces with no methods.)  The flag {@code FLAG_MARKERS}
119  *     indicates that a list of additional interfaces will be provided, each of
120  *     which should be implemented by the resulting function object.</li>
121  *
122  *     <li><em>Serializability.</em>  The generated function objects do not
123  *     generally support serialization.  If desired, {@code FLAG_SERIALIZABLE}
124  *     can be used to indicate that the function objects should be serializable.
125  *     Serializable function objects will use, as their serialized form,
126  *     instances of the class {@code SerializedLambda}, which requires additional
127  *     assistance from the capturing class (the class described by the
128  *     {@link MethodHandles.Lookup} parameter {@code caller}); see
129  *     {@link SerializedLambda} for details.</li>
130  * </ul>
131  *
132  * <p>Assume the linkage arguments are as follows:
133  * <ul>
134  *      <li>{@code factoryType} (describing the {@code CallSite} signature) has
135  *      K parameters of types (D1..Dk) and return type Rd;</li>
136  *      <li>{@code interfaceMethodType} (describing the implemented method type) has N
137  *      parameters, of types (U1..Un) and return type Ru;</li>
138  *      <li>{@code implementation} (the {@code MethodHandle} providing the
139  *      implementation) has M parameters, of types (A1..Am) and return type Ra
140  *      (if the method describes an instance method, the method type of this
141  *      method handle already includes an extra first argument corresponding to
142  *      the receiver);</li>
143  *      <li>{@code dynamicMethodType} (allowing restrictions on invocation)
144  *      has N parameters, of types (T1..Tn) and return type Rt.</li>
145  * </ul>
146  *
147  * <p>Then the following linkage invariants must hold:
148  * <ul>
149  *     <li>{@code interfaceMethodType} and {@code dynamicMethodType} have the same
150  *     arity N, and for i=1..N, Ti and Ui are the same type, or Ti and Ui are
151  *     both reference types and Ti is a subtype of Ui</li>
152  *     <li>Either Rt and Ru are the same type, or both are reference types and
153  *     Rt is a subtype of Ru</li>
154  *     <li>K + N = M</li>
155  *     <li>For i=1..K, Di = Ai</li>
156  *     <li>For i=1..N, Ti is adaptable to Aj, where j=i+k</li>
157  *     <li>The return type Rt is void, or the return type Ra is not void and is
158  *     adaptable to Rt</li>
159  * </ul>
160  *
161  * <p>Further, at capture time, if {@code implementation} corresponds to an instance
162  * method, and there are any capture arguments ({@code K > 0}), then the first
163  * capture argument (corresponding to the receiver) must be non-null.
164  *
165  * <p>A type Q is considered adaptable to S as follows:
166  * <table class="striped">
167  *   <caption style="display:none">adaptable types</caption>
168  *   <thead>
169  *     <tr><th scope="col">Q</th><th scope="col">S</th><th scope="col">Link-time checks</th><th scope="col">Invocation-time checks</th></tr>
170  *   </thead>
171  *   <tbody>
172  *     <tr>
173  *         <th scope="row">Primitive</th><th scope="row">Primitive</th>
174  *         <td>Q can be converted to S via a primitive widening conversion</td>
175  *         <td>None</td>
176  *     </tr>
177  *     <tr>
178  *         <th scope="row">Primitive</th><th scope="row">Reference</th>
179  *         <td>S is a supertype of the Wrapper(Q)</td>
180  *         <td>Cast from Wrapper(Q) to S</td>
181  *     </tr>
182  *     <tr>
183  *         <th scope="row">Reference</th><th scope="row">Primitive</th>
184  *         <td>for parameter types: Q is a primitive wrapper and Primitive(Q)
185  *         can be widened to S
186  *         <br>for return types: If Q is a primitive wrapper, check that
187  *         Primitive(Q) can be widened to S</td>
188  *         <td>If Q is not a primitive wrapper, cast Q to the base Wrapper(S);
189  *         for example Number for numeric types</td>
190  *     </tr>
191  *     <tr>
192  *         <th scope="row">Reference</th><th scope="row">Reference</th>
193  *         <td>for parameter types: S is a supertype of Q
194  *         <br>for return types: none</td>
195  *         <td>Cast from Q to S</td>
196  *     </tr>
197  *   </tbody>
198  * </table>
199  *
200  * @apiNote These linkage methods are designed to support the evaluation
201  * of <em>lambda expressions</em> and <em>method references</em> in the Java
202  * Language.  For every lambda expressions or method reference in the source code,
203  * there is a target type which is a functional interface.  Evaluating a lambda
204  * expression produces an object of its target type. The recommended mechanism
205  * for evaluating lambda expressions is to desugar the lambda body to a method,
206  * invoke an invokedynamic call site whose static argument list describes the
207  * sole method of the functional interface and the desugared implementation
208  * method, and returns an object (the lambda object) that implements the target
209  * type. (For method references, the implementation method is simply the
210  * referenced method; no desugaring is needed.)
211  *
212  * <p>The argument list of the implementation method and the argument list of
213  * the interface method(s) may differ in several ways.  The implementation
214  * methods may have additional arguments to accommodate arguments captured by
215  * the lambda expression; there may also be differences resulting from permitted
216  * adaptations of arguments, such as casting, boxing, unboxing, and primitive
217  * widening. (Varargs adaptations are not handled by the metafactories; these are
218  * expected to be handled by the caller.)
219  *
220  * <p>Invokedynamic call sites have two argument lists: a static argument list
221  * and a dynamic argument list.  The static argument list is stored in the
222  * constant pool; the dynamic argument is pushed on the operand stack at capture
223  * time.  The bootstrap method has access to the entire static argument list
224  * (which in this case, includes information describing the implementation method,
225  * the target interface, and the target interface method(s)), as well as a
226  * method signature describing the number and static types (but not the values)
227  * of the dynamic arguments and the static return type of the invokedynamic site.
228  *
229  * <p>The implementation method is described with a direct method handle
230  * referencing a method or constructor. In theory, any method handle could be
231  * used, but this is not compatible with some implementation techniques and
232  * would complicate the work implementations must do.
233  *
234  * @since 1.8
235  */
236 public final class LambdaMetafactory {
237 
238     private LambdaMetafactory() {}
239 
240     /** Flag for {@link #altMetafactory} indicating the lambda object
241      * must be serializable */
242     public static final int FLAG_SERIALIZABLE = 1 << 0;
243 
244     /**
245      * Flag for {@link #altMetafactory} indicating the lambda object implements
246      * other interfaces besides {@code Serializable}
247      */
248     public static final int FLAG_MARKERS = 1 << 1;
249 
250     /**
251      * Flag for alternate metafactories indicating the lambda object requires
252      * additional methods that invoke the {@code implementation}
253      */
254     public static final int FLAG_BRIDGES = 1 << 2;
255 
256     /** Flag for {@link #altMetafactory} indicating the lambda object
257      * must be a {@code Quotable} object, inspectable using code reflection. */
258     public static final int FLAG_QUOTABLE = 1 << 3;
259 
260     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
261     private static final MethodType[] EMPTY_MT_ARRAY = new MethodType[0];
262 
263     // LambdaMetafactory bootstrap methods are startup sensitive, and may be
264     // special cased in java.lang.invoke.BootstrapMethodInvoker to ensure
265     // methods are invoked with exact type information to avoid generating
266     // code for runtime checks. Take care any changes or additions here are
267     // reflected there as appropriate.
268 
269     /**
270      * Facilitates the creation of simple "function objects" that implement one
271      * or more interfaces by delegation to a provided {@link MethodHandle},
272      * after appropriate type adaptation and partial evaluation of arguments.
273      * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
274      * call sites, to support the <em>lambda expression</em> and <em>method
275      * reference expression</em> features of the Java Programming Language.
276      *
277      * <p>This is the standard, streamlined metafactory; additional flexibility
278      * is provided by {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}.
279      * A general description of the behavior of this method is provided
280      * {@link LambdaMetafactory above}.
281      *
282      * <p>When the target of the {@code CallSite} returned from this method is
283      * invoked, the resulting function objects are instances of a class which
284      * implements the interface named by the return type of {@code factoryType},
285      * declares a method with the name given by {@code interfaceMethodName} and the
286      * signature given by {@code interfaceMethodType}.  It may also override additional
287      * methods from {@code Object}.
288      *
289      * @param caller Represents a lookup context with the accessibility
290      *               privileges of the caller.  Specifically, the lookup context
291      *               must have {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess()
292      *               full privilege access}.
293      *               When used with {@code invokedynamic}, this is stacked
294      *               automatically by the VM.
295      * @param interfaceMethodName The name of the method to implement.  When used with
296      *                            {@code invokedynamic}, this is provided by the
297      *                            {@code NameAndType} of the {@code InvokeDynamic}
298      *                            structure and is stacked automatically by the VM.
299      * @param factoryType The expected signature of the {@code CallSite}.  The
300      *                    parameter types represent the types of capture variables;
301      *                    the return type is the interface to implement.   When
302      *                    used with {@code invokedynamic}, this is provided by
303      *                    the {@code NameAndType} of the {@code InvokeDynamic}
304      *                    structure and is stacked automatically by the VM.
305      * @param interfaceMethodType Signature and return type of method to be
306      *                            implemented by the function object.
307      * @param implementation A direct method handle describing the implementation
308      *                       method which should be called (with suitable adaptation
309      *                       of argument types and return types, and with captured
310      *                       arguments prepended to the invocation arguments) at
311      *                       invocation time.
312      * @param dynamicMethodType The signature and return type that should
313      *                          be enforced dynamically at invocation time.
314      *                          In simple use cases this is the same as
315      *                          {@code interfaceMethodType}.
316      * @return a CallSite whose target can be used to perform capture, generating
317      *         instances of the interface named by {@code factoryType}
318      * @throws LambdaConversionException If {@code caller} does not have full privilege
319      *         access, or if {@code interfaceMethodName} is not a valid JVM
320      *         method name, or if the return type of {@code factoryType} is not
321      *         an interface, or if {@code implementation} is not a direct method
322      *         handle referencing a method or constructor, or if the linkage
323      *         invariants are violated, as defined {@link LambdaMetafactory above}.
324      * @throws NullPointerException If any argument is {@code null}.
325      * @throws SecurityException If a security manager is present, and it
326      *         <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
327      *         from {@code caller} to the package of {@code implementation}.
328      */
329     public static CallSite metafactory(MethodHandles.Lookup caller,
330                                        String interfaceMethodName,
331                                        MethodType factoryType,
332                                        MethodType interfaceMethodType,
333                                        MethodHandle implementation,
334                                        MethodType dynamicMethodType)
335             throws LambdaConversionException {
336         AbstractValidatingLambdaMetafactory mf;
337         mf = new InnerClassLambdaMetafactory(Objects.requireNonNull(caller),
338                                              Objects.requireNonNull(factoryType),
339                                              Objects.requireNonNull(interfaceMethodName),
340                                              Objects.requireNonNull(interfaceMethodType),
341                                              Objects.requireNonNull(implementation),
342                                              Objects.requireNonNull(dynamicMethodType),
343                                              false,
344                                              EMPTY_CLASS_ARRAY,
345                                              EMPTY_MT_ARRAY,
346                                  null);
347         mf.validateMetafactoryArgs();
348         return mf.buildCallSite();
349     }
350 
351     /**
352      * Facilitates the creation of simple "function objects" that implement one
353      * or more interfaces by delegation to a provided {@link MethodHandle},
354      * after appropriate type adaptation and partial evaluation of arguments.
355      * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
356      * call sites, to support the <em>lambda expression</em> and <em>method
357      * reference expression</em> features of the Java Programming Language.
358      *
359      * <p>This is the general, more flexible metafactory; a streamlined version
360      * is provided by {@link #metafactory(java.lang.invoke.MethodHandles.Lookup,
361      * String, MethodType, MethodType, MethodHandle, MethodType)}.
362      * A general description of the behavior of this method is provided
363      * {@link LambdaMetafactory above}.
364      *
365      * <p>The argument list for this method includes three fixed parameters,
366      * corresponding to the parameters automatically stacked by the VM for the
367      * bootstrap method in an {@code invokedynamic} invocation, and an {@code Object[]}
368      * parameter that contains additional parameters.  The declared argument
369      * list for this method is:
370      *
371      * <pre>{@code
372      *  CallSite altMetafactory(MethodHandles.Lookup caller,
373      *                          String interfaceMethodName,
374      *                          MethodType factoryType,
375      *                          Object... args)
376      * }</pre>
377      *
378      * <p>but it behaves as if the argument list is as follows:
379      *
380      * <pre>{@code
381      *  CallSite altMetafactory(MethodHandles.Lookup caller,
382      *                          String interfaceMethodName,
383      *                          MethodType factoryType,
384      *                          MethodType interfaceMethodType,
385      *                          MethodHandle implementation,
386      *                          MethodType dynamicMethodType,
387      *                          int flags,
388      *                          int altInterfaceCount,        // IF flags has MARKERS set
389      *                          Class... altInterfaces,       // IF flags has MARKERS set
390      *                          int altMethodCount,           // IF flags has BRIDGES set
391      *                          MethodType... altMethods      // IF flags has BRIDGES set
392      *                          MethodType reflectType        // IF flags has QUOTABLE set
393      *                          MethodHandle reflectField     // IF flags has QUOTABLE set
394      *                          )
395      * }</pre>
396      *
397      * <p>Arguments that appear in the argument list for
398      * {@link #metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)}
399      * have the same specification as in that method.  The additional arguments
400      * are interpreted as follows:
401      * <ul>
402      *     <li>{@code flags} indicates additional options; this is a bitwise
403      *     OR of desired flags.  Defined flags are {@link #FLAG_BRIDGES},
404      *     {@link #FLAG_MARKERS}, and {@link #FLAG_SERIALIZABLE}.</li>
405      *     <li>{@code altInterfaceCount} is the number of additional interfaces
406      *     the function object should implement, and is present if and only if the
407      *     {@code FLAG_MARKERS} flag is set.</li>
408      *     <li>{@code altInterfaces} is a variable-length list of additional
409      *     interfaces to implement, whose length equals {@code altInterfaceCount},
410      *     and is present if and only if the {@code FLAG_MARKERS} flag is set.</li>
411      *     <li>{@code altMethodCount} is the number of additional method signatures
412      *     the function object should implement, and is present if and only if
413      *     the {@code FLAG_BRIDGES} flag is set.</li>
414      *     <li>{@code altMethods} is a variable-length list of additional
415      *     methods signatures to implement, whose length equals {@code altMethodCount},
416      *     and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li>
417      *     <li>{@code quotableField} is a
418      *     {@linkplain MethodHandles.Lookup#findGetter(Class, String, Class) getter} method handle
419      *     that is used to retrieve the string representation of the quotable lambda's associated
420      *     intermediate representation.</li>
421      * </ul>
422      *
423      * <p>Each class named by {@code altInterfaces} is subject to the same
424      * restrictions as {@code Rd}, the return type of {@code factoryType},
425      * as described {@link LambdaMetafactory above}.  Each {@code MethodType}
426      * named by {@code altMethods} is subject to the same restrictions as
427      * {@code interfaceMethodType}, as described {@link LambdaMetafactory above}.
428      *
429      * <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects
430      * will implement {@code Serializable}, and will have a {@code writeReplace}
431      * method that returns an appropriate {@link SerializedLambda}.  The
432      * {@code caller} class must have an appropriate {@code $deserializeLambda$}
433      * method, as described in {@link SerializedLambda}.
434      *
435      * <p>When FLAG_QUOTABLE is set in {@code flags}, the function objects
436      * will implement {@code Quotable}.
437      *
438      * <p>When the target of the {@code CallSite} returned from this method is
439      * invoked, the resulting function objects are instances of a class with
440      * the following properties:
441      * <ul>
442      *     <li>The class implements the interface named by the return type
443      *     of {@code factoryType} and any interfaces named by {@code altInterfaces}</li>
444      *     <li>The class declares methods with the name given by {@code interfaceMethodName},
445      *     and the signature given by {@code interfaceMethodType} and additional signatures
446      *     given by {@code altMethods}</li>
447      *     <li>The class may override methods from {@code Object}, and may
448      *     implement methods related to serialization.</li>
449      * </ul>
450      *
451      * @param caller Represents a lookup context with the accessibility
452      *               privileges of the caller.  Specifically, the lookup context
453      *               must have {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess()
454      *               full privilege access}.
455      *               When used with {@code invokedynamic}, this is stacked
456      *               automatically by the VM.
457      * @param interfaceMethodName The name of the method to implement.  When used with
458      *                            {@code invokedynamic}, this is provided by the
459      *                            {@code NameAndType} of the {@code InvokeDynamic}
460      *                            structure and is stacked automatically by the VM.
461      * @param factoryType The expected signature of the {@code CallSite}.  The
462      *                    parameter types represent the types of capture variables;
463      *                    the return type is the interface to implement.   When
464      *                    used with {@code invokedynamic}, this is provided by
465      *                    the {@code NameAndType} of the {@code InvokeDynamic}
466      *                    structure and is stacked automatically by the VM.
467      * @param  args An array of {@code Object} containing the required
468      *              arguments {@code interfaceMethodType}, {@code implementation},
469      *              {@code dynamicMethodType}, {@code flags}, and any
470      *              optional arguments, as described above
471      * @return a CallSite whose target can be used to perform capture, generating
472      *         instances of the interface named by {@code factoryType}
473      * @throws LambdaConversionException If {@code caller} does not have full privilege
474      *         access, or if {@code interfaceMethodName} is not a valid JVM
475      *         method name, or if the return type of {@code factoryType} is not
476      *         an interface, or if any of {@code altInterfaces} is not an
477      *         interface, or if {@code implementation} is not a direct method
478      *         handle referencing a method or constructor, or if the linkage
479      *         invariants are violated, as defined {@link LambdaMetafactory above}.
480      * @throws NullPointerException If any argument, or any component of {@code args},
481      *         is {@code null}.
482      * @throws IllegalArgumentException If the number or types of the components
483      *         of {@code args} do not follow the above rules, or if
484      *         {@code altInterfaceCount} or {@code altMethodCount} are negative
485      *         integers.
486      * @throws SecurityException If a security manager is present, and it
487      *         <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
488      *         from {@code caller} to the package of {@code implementation}.
489      */
490     public static CallSite altMetafactory(MethodHandles.Lookup caller,
491                                           String interfaceMethodName,
492                                           MethodType factoryType,
493                                           Object... args)
494             throws LambdaConversionException {
495         Objects.requireNonNull(caller);
496         Objects.requireNonNull(interfaceMethodName);
497         Objects.requireNonNull(factoryType);
498         Objects.requireNonNull(args);
499         int argIndex = 0;
500         MethodType interfaceMethodType = extractArg(args, argIndex++, MethodType.class);
501         MethodHandle implementation = extractArg(args, argIndex++, MethodHandle.class);
502         MethodType dynamicMethodType = extractArg(args, argIndex++, MethodType.class);
503         int flags = extractArg(args, argIndex++, Integer.class);
504         Class<?>[] altInterfaces = EMPTY_CLASS_ARRAY;
505         MethodType[] altMethods = EMPTY_MT_ARRAY;
506         MethodHandle quotableField = null;
507         if ((flags & FLAG_MARKERS) != 0) {
508             int altInterfaceCount = extractArg(args, argIndex++, Integer.class);
509             if (altInterfaceCount < 0) {
510                 throw new IllegalArgumentException("negative argument count");
511             }
512             if (altInterfaceCount > 0) {
513                 altInterfaces = extractArgs(args, argIndex, Class.class, altInterfaceCount);
514                 argIndex += altInterfaceCount;
515             }
516         }
517         if ((flags & FLAG_BRIDGES) != 0) {
518             int altMethodCount = extractArg(args, argIndex++, Integer.class);
519             if (altMethodCount < 0) {
520                 throw new IllegalArgumentException("negative argument count");
521             }
522             if (altMethodCount > 0) {
523                 altMethods = extractArgs(args, argIndex, MethodType.class, altMethodCount);
524                 argIndex += altMethodCount;
525             }
526         }
527         if ((flags & FLAG_QUOTABLE) != 0) {
528             quotableField = extractArg(args, argIndex++, MethodHandle.class);
529             altInterfaces = Arrays.copyOf(altInterfaces, altInterfaces.length + 1);
530             altInterfaces[altInterfaces.length-1] = Quotable.class;
531         }
532         if (argIndex < args.length) {
533             throw new IllegalArgumentException("too many arguments");
534         }
535 
536         boolean isSerializable = ((flags & FLAG_SERIALIZABLE) != 0);
537         if (isSerializable) {
538             boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(factoryType.returnType());
539             for (Class<?> c : altInterfaces)
540                 foundSerializableSupertype |= Serializable.class.isAssignableFrom(c);
541             if (!foundSerializableSupertype) {
542                 altInterfaces = Arrays.copyOf(altInterfaces, altInterfaces.length + 1);
543                 altInterfaces[altInterfaces.length-1] = Serializable.class;
544             }
545         }
546 
547         AbstractValidatingLambdaMetafactory mf
548                 = new InnerClassLambdaMetafactory(caller,
549                                                   factoryType,
550                                                   interfaceMethodName,
551                                                   interfaceMethodType,
552                                                   implementation,
553                                                   dynamicMethodType,
554                                                   isSerializable,
555                                                   altInterfaces,
556                                                   altMethods,
557                                                   quotableField);
558         mf.validateMetafactoryArgs();
559         return mf.buildCallSite();
560     }
561 
562     private static <T> T extractArg(Object[] args, int index, Class<T> type) {
563         if (index >= args.length) {
564             throw new IllegalArgumentException("missing argument");
565         }
566         Object result = Objects.requireNonNull(args[index]);
567         if (!type.isInstance(result)) {
568             throw new IllegalArgumentException("argument has wrong type");
569         }
570         return type.cast(result);
571     }
572 
573     private static <T> T[] extractArgs(Object[] args, int index, Class<T> type, int count) {
574         @SuppressWarnings("unchecked")
575         T[] result = (T[]) Array.newInstance(type, count);
576         for (int i = 0; i < count; i++) {
577             result[i] = extractArg(args, index + i, type);
578         }
579         return result;
580     }
581 
582 }