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