1 /*
  2  * Copyright (c) 2012, 2025, 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.io.Serializable;
 29 import java.util.Arrays;
 30 import java.lang.reflect.Array;
 31 import java.util.Objects;
 32 
 33 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
 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  * <p>Uses besides evaluation of lambda expressions and method references are
235  * unintended.  These linkage methods may change their unspecified behaviors at
236  * any time to better suit the Java language features they were designed to
237  * support, and such changes may impact unintended uses.  Unintended uses of
238  * these linkage methods may lead to resource leaks, or other unspecified
239  * negative effects.
240  *
241  * @implNote In the reference implementation, the classes implementing the created
242  * function objects are strongly reachable from the defining class loader of the
243  * caller, like classes and interfaces in Java source code.  This technique
244  * reduces heap memory use, but as a consequence, the implementation classes can
245  * be unloaded only if the caller class can be unloaded.  In particular, if the
246  * caller is a {@linkplain MethodHandles.Lookup.ClassOption#STRONG weak hidden
247  * class}, the implementation class, a strong hidden class, may not be unloaded
248  * even if the caller may be unloaded.
249  *
250  * @since 1.8
251  */
252 @AOTSafeClassInitializer
253 public final class LambdaMetafactory {
254 
255     private LambdaMetafactory() {}
256 
257     /** Flag for {@link #altMetafactory} indicating the lambda object
258      * must be serializable */
259     public static final int FLAG_SERIALIZABLE = 1 << 0;
260 
261     /**
262      * Flag for {@link #altMetafactory} indicating the lambda object implements
263      * other interfaces besides {@code Serializable}
264      */
265     public static final int FLAG_MARKERS = 1 << 1;
266 
267     /**
268      * Flag for alternate metafactories indicating the lambda object requires
269      * additional methods that invoke the {@code implementation}
270      */
271     public static final int FLAG_BRIDGES = 1 << 2;
272 
273     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
274     private static final MethodType[] EMPTY_MT_ARRAY = new MethodType[0];
275 
276     // LambdaMetafactory bootstrap methods are startup sensitive, and may be
277     // special cased in java.lang.invoke.BootstrapMethodInvoker to ensure
278     // methods are invoked with exact type information to avoid generating
279     // code for runtime checks. Take care any changes or additions here are
280     // reflected there as appropriate.
281 
282     /**
283      * Facilitates the creation of simple "function objects" that implement one
284      * or more interfaces by delegation to a provided {@link MethodHandle},
285      * after appropriate type adaptation and partial evaluation of arguments.
286      * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
287      * call sites, to support the <em>lambda expression</em> and <em>method
288      * reference expression</em> features of the Java Programming Language.
289      *
290      * <p>This is the standard, streamlined metafactory; additional flexibility
291      * is provided by {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}.
292      * A general description of the behavior of this method is provided
293      * {@link LambdaMetafactory above}.
294      *
295      * <p>When the target of the {@code CallSite} returned from this method is
296      * invoked, the resulting function objects are instances of a class which
297      * implements the interface named by the return type of {@code factoryType},
298      * declares a method with the name given by {@code interfaceMethodName} and the
299      * signature given by {@code interfaceMethodType}.  It may also override additional
300      * methods from {@code Object}.
301      *
302      * @param caller Represents a lookup context with the accessibility
303      *               privileges of the caller.  Specifically, the lookup context
304      *               must have {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess()
305      *               full privilege access}.
306      *               When used with {@code invokedynamic}, this is stacked
307      *               automatically by the VM.
308      * @param interfaceMethodName The name of the method to implement.  When used with
309      *                            {@code invokedynamic}, this is provided by the
310      *                            {@code NameAndType} of the {@code InvokeDynamic}
311      *                            structure and is stacked automatically by the VM.
312      * @param factoryType The expected signature of the {@code CallSite}.  The
313      *                    parameter types represent the types of capture variables;
314      *                    the return type is the interface to implement.   When
315      *                    used with {@code invokedynamic}, this is provided by
316      *                    the {@code NameAndType} of the {@code InvokeDynamic}
317      *                    structure and is stacked automatically by the VM.
318      * @param interfaceMethodType Signature and return type of method to be
319      *                            implemented by the function object.
320      * @param implementation A direct method handle describing the implementation
321      *                       method which should be called (with suitable adaptation
322      *                       of argument types and return types, and with captured
323      *                       arguments prepended to the invocation arguments) at
324      *                       invocation time.
325      * @param dynamicMethodType The signature and return type that should
326      *                          be enforced dynamically at invocation time.
327      *                          In simple use cases this is the same as
328      *                          {@code interfaceMethodType}.
329      * @return a CallSite whose target can be used to perform capture, generating
330      *         instances of the interface named by {@code factoryType}
331      * @throws LambdaConversionException If {@code caller} does not have full privilege
332      *         access, or if {@code interfaceMethodName} is not a valid JVM
333      *         method name, or if the return type of {@code factoryType} is not
334      *         an interface, or if {@code implementation} is not a direct method
335      *         handle referencing a method or constructor, or if the linkage
336      *         invariants are violated, as defined {@link LambdaMetafactory above}.
337      * @throws NullPointerException If any argument is {@code null}.
338      */
339     public static CallSite metafactory(MethodHandles.Lookup caller,
340                                        String interfaceMethodName,
341                                        MethodType factoryType,
342                                        MethodType interfaceMethodType,
343                                        MethodHandle implementation,
344                                        MethodType dynamicMethodType)
345             throws LambdaConversionException {
346         AbstractValidatingLambdaMetafactory mf;
347         mf = new InnerClassLambdaMetafactory(Objects.requireNonNull(caller),
348                                              Objects.requireNonNull(factoryType),
349                                              Objects.requireNonNull(interfaceMethodName),
350                                              Objects.requireNonNull(interfaceMethodType),
351                                              Objects.requireNonNull(implementation),
352                                              Objects.requireNonNull(dynamicMethodType),
353                                              false,
354                                              EMPTY_CLASS_ARRAY,
355                                              EMPTY_MT_ARRAY);
356         mf.validateMetafactoryArgs();
357         return mf.buildCallSite();
358     }
359 
360     /**
361      * Facilitates the creation of simple "function objects" that implement one
362      * or more interfaces by delegation to a provided {@link MethodHandle},
363      * after appropriate type adaptation and partial evaluation of arguments.
364      * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
365      * call sites, to support the <em>lambda expression</em> and <em>method
366      * reference expression</em> features of the Java Programming Language.
367      *
368      * <p>This is the general, more flexible metafactory; a streamlined version
369      * is provided by {@link #metafactory(java.lang.invoke.MethodHandles.Lookup,
370      * String, MethodType, MethodType, MethodHandle, MethodType)}.
371      * A general description of the behavior of this method is provided
372      * {@link LambdaMetafactory above}.
373      *
374      * <p>The argument list for this method includes three fixed parameters,
375      * corresponding to the parameters automatically stacked by the VM for the
376      * bootstrap method in an {@code invokedynamic} invocation, and an {@code Object[]}
377      * parameter that contains additional parameters.  The declared argument
378      * list for this method is:
379      *
380      * <pre>{@code
381      *  CallSite altMetafactory(MethodHandles.Lookup caller,
382      *                          String interfaceMethodName,
383      *                          MethodType factoryType,
384      *                          Object... args)
385      * }</pre>
386      *
387      * <p>but it behaves as if the argument list is as follows:
388      *
389      * <pre>{@code
390      *  CallSite altMetafactory(MethodHandles.Lookup caller,
391      *                          String interfaceMethodName,
392      *                          MethodType factoryType,
393      *                          MethodType interfaceMethodType,
394      *                          MethodHandle implementation,
395      *                          MethodType dynamicMethodType,
396      *                          int flags,
397      *                          int altInterfaceCount,        // IF flags has MARKERS set
398      *                          Class... altInterfaces,       // IF flags has MARKERS set
399      *                          int altMethodCount,           // IF flags has BRIDGES set
400      *                          MethodType... altMethods      // IF flags has BRIDGES set
401      *                          )
402      * }</pre>
403      *
404      * <p>Arguments that appear in the argument list for
405      * {@link #metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)}
406      * have the same specification as in that method.  The additional arguments
407      * are interpreted as follows:
408      * <ul>
409      *     <li>{@code flags} indicates additional options; this is a bitwise
410      *     OR of desired flags.  Defined flags are {@link #FLAG_BRIDGES},
411      *     {@link #FLAG_MARKERS}, and {@link #FLAG_SERIALIZABLE}.</li>
412      *     <li>{@code altInterfaceCount} is the number of additional interfaces
413      *     the function object should implement, and is present if and only if the
414      *     {@code FLAG_MARKERS} flag is set.</li>
415      *     <li>{@code altInterfaces} is a variable-length list of additional
416      *     interfaces to implement, whose length equals {@code altInterfaceCount},
417      *     and is present if and only if the {@code FLAG_MARKERS} flag is set.</li>
418      *     <li>{@code altMethodCount} is the number of additional method signatures
419      *     the function object should implement, and is present if and only if
420      *     the {@code FLAG_BRIDGES} flag is set.</li>
421      *     <li>{@code altMethods} is a variable-length list of additional
422      *     methods signatures to implement, whose length equals {@code altMethodCount},
423      *     and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li>
424      * </ul>
425      *
426      * <p>Each class named by {@code altInterfaces} is subject to the same
427      * restrictions as {@code Rd}, the return type of {@code factoryType},
428      * as described {@link LambdaMetafactory above}.  Each {@code MethodType}
429      * named by {@code altMethods} is subject to the same restrictions as
430      * {@code interfaceMethodType}, as described {@link LambdaMetafactory above}.
431      *
432      * <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects
433      * will implement {@code Serializable}, and will have a {@code writeReplace}
434      * method that returns an appropriate {@link SerializedLambda}.  The
435      * {@code caller} class must have an appropriate {@code $deserializeLambda$}
436      * method, as described in {@link SerializedLambda}.
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      */
487     public static CallSite altMetafactory(MethodHandles.Lookup caller,
488                                           String interfaceMethodName,
489                                           MethodType factoryType,
490                                           Object... args)
491             throws LambdaConversionException {
492         Objects.requireNonNull(caller);
493         Objects.requireNonNull(interfaceMethodName);
494         Objects.requireNonNull(factoryType);
495         Objects.requireNonNull(args);
496         int argIndex = 0;
497         MethodType interfaceMethodType = extractArg(args, argIndex++, MethodType.class);
498         MethodHandle implementation = extractArg(args, argIndex++, MethodHandle.class);
499         MethodType dynamicMethodType = extractArg(args, argIndex++, MethodType.class);
500         int flags = extractArg(args, argIndex++, Integer.class);
501         Class<?>[] altInterfaces = EMPTY_CLASS_ARRAY;
502         MethodType[] altMethods = EMPTY_MT_ARRAY;
503         if ((flags & FLAG_MARKERS) != 0) {
504             int altInterfaceCount = extractArg(args, argIndex++, Integer.class);
505             if (altInterfaceCount < 0) {
506                 throw new IllegalArgumentException("negative argument count");
507             }
508             if (altInterfaceCount > 0) {
509                 altInterfaces = extractArgs(args, argIndex, Class.class, altInterfaceCount);
510                 argIndex += altInterfaceCount;
511             }
512         }
513         if ((flags & FLAG_BRIDGES) != 0) {
514             int altMethodCount = extractArg(args, argIndex++, Integer.class);
515             if (altMethodCount < 0) {
516                 throw new IllegalArgumentException("negative argument count");
517             }
518             if (altMethodCount > 0) {
519                 altMethods = extractArgs(args, argIndex, MethodType.class, altMethodCount);
520                 argIndex += altMethodCount;
521             }
522         }
523         if (argIndex < args.length) {
524             throw new IllegalArgumentException("too many arguments");
525         }
526 
527         boolean isSerializable = ((flags & FLAG_SERIALIZABLE) != 0);
528         if (isSerializable) {
529             boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(factoryType.returnType());
530             for (Class<?> c : altInterfaces)
531                 foundSerializableSupertype |= Serializable.class.isAssignableFrom(c);
532             if (!foundSerializableSupertype) {
533                 altInterfaces = Arrays.copyOf(altInterfaces, altInterfaces.length + 1);
534                 altInterfaces[altInterfaces.length-1] = Serializable.class;
535             }
536         }
537 
538         AbstractValidatingLambdaMetafactory mf
539                 = new InnerClassLambdaMetafactory(caller,
540                                                   factoryType,
541                                                   interfaceMethodName,
542                                                   interfaceMethodType,
543                                                   implementation,
544                                                   dynamicMethodType,
545                                                   isSerializable,
546                                                   altInterfaces,
547                                                   altMethods);
548         mf.validateMetafactoryArgs();
549         return mf.buildCallSite();
550     }
551 
552     private static <T> T extractArg(Object[] args, int index, Class<T> type) {
553         if (index >= args.length) {
554             throw new IllegalArgumentException("missing argument");
555         }
556         Object result = Objects.requireNonNull(args[index]);
557         if (!type.isInstance(result)) {
558             throw new IllegalArgumentException("argument has wrong type");
559         }
560         return type.cast(result);
561     }
562 
563     private static <T> T[] extractArgs(Object[] args, int index, Class<T> type, int count) {
564         @SuppressWarnings("unchecked")
565         T[] result = (T[]) Array.newInstance(type, count);
566         for (int i = 0; i < count; i++) {
567             result[i] = extractArg(args, index + i, type);
568         }
569         return result;
570     }
571 
572 }