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 /** Flag for {@link #altMetafactory} indicating the lambda object
274 * must be a {@code Quotable} object, inspectable using code reflection. */
275 public static final int FLAG_QUOTABLE = 1 << 3;
276
277 private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
278 private static final MethodType[] EMPTY_MT_ARRAY = new MethodType[0];
279
280 // LambdaMetafactory bootstrap methods are startup sensitive, and may be
281 // special cased in java.lang.invoke.BootstrapMethodInvoker to ensure
282 // methods are invoked with exact type information to avoid generating
283 // code for runtime checks. Take care any changes or additions here are
284 // reflected there as appropriate.
285
286 /**
287 * Facilitates the creation of simple "function objects" that implement one
288 * or more interfaces by delegation to a provided {@link MethodHandle},
289 * after appropriate type adaptation and partial evaluation of arguments.
290 * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
291 * call sites, to support the <em>lambda expression</em> and <em>method
292 * reference expression</em> features of the Java Programming Language.
293 *
294 * <p>This is the standard, streamlined metafactory; additional flexibility
295 * is provided by {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)}.
296 * A general description of the behavior of this method is provided
297 * {@link LambdaMetafactory above}.
298 *
299 * <p>When the target of the {@code CallSite} returned from this method is
300 * invoked, the resulting function objects are instances of a class which
301 * implements the interface named by the return type of {@code factoryType},
302 * declares a method with the name given by {@code interfaceMethodName} and the
303 * signature given by {@code interfaceMethodType}. It may also override additional
304 * methods from {@code Object}.
305 *
306 * @param caller Represents a lookup context with the accessibility
307 * privileges of the caller. Specifically, the lookup context
308 * must have {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess()
309 * full privilege access}.
310 * When used with {@code invokedynamic}, this is stacked
311 * automatically by the VM.
312 * @param interfaceMethodName The name of the method to implement. When used with
313 * {@code invokedynamic}, this is provided by the
314 * {@code NameAndType} of the {@code InvokeDynamic}
315 * structure and is stacked automatically by the VM.
316 * @param factoryType The expected signature of the {@code CallSite}. The
317 * parameter types represent the types of capture variables;
318 * the return type is the interface to implement. When
319 * used with {@code invokedynamic}, this is provided by
320 * the {@code NameAndType} of the {@code InvokeDynamic}
321 * structure and is stacked automatically by the VM.
322 * @param interfaceMethodType Signature and return type of method to be
323 * implemented by the function object.
324 * @param implementation A direct method handle describing the implementation
325 * method which should be called (with suitable adaptation
326 * of argument types and return types, and with captured
327 * arguments prepended to the invocation arguments) at
328 * invocation time.
329 * @param dynamicMethodType The signature and return type that should
330 * be enforced dynamically at invocation time.
331 * In simple use cases this is the same as
332 * {@code interfaceMethodType}.
333 * @return a CallSite whose target can be used to perform capture, generating
334 * instances of the interface named by {@code factoryType}
335 * @throws LambdaConversionException If {@code caller} does not have full privilege
336 * access, or if {@code interfaceMethodName} is not a valid JVM
337 * method name, or if the return type of {@code factoryType} is not
338 * an interface, or if {@code implementation} is not a direct method
339 * handle referencing a method or constructor, or if the linkage
340 * invariants are violated, as defined {@link LambdaMetafactory above}.
341 * @throws NullPointerException If any argument is {@code null}.
342 */
343 public static CallSite metafactory(MethodHandles.Lookup caller,
344 String interfaceMethodName,
345 MethodType factoryType,
346 MethodType interfaceMethodType,
347 MethodHandle implementation,
348 MethodType dynamicMethodType)
349 throws LambdaConversionException {
350 AbstractValidatingLambdaMetafactory mf;
351 mf = new InnerClassLambdaMetafactory(Objects.requireNonNull(caller),
352 Objects.requireNonNull(factoryType),
353 Objects.requireNonNull(interfaceMethodName),
354 Objects.requireNonNull(interfaceMethodType),
355 Objects.requireNonNull(implementation),
356 Objects.requireNonNull(dynamicMethodType),
357 false,
358 EMPTY_CLASS_ARRAY,
359 EMPTY_MT_ARRAY,
360 null);
361 mf.validateMetafactoryArgs();
362 return mf.buildCallSite();
363 }
364
365 /**
366 * Facilitates the creation of simple "function objects" that implement one
367 * or more interfaces by delegation to a provided {@link MethodHandle},
368 * after appropriate type adaptation and partial evaluation of arguments.
369 * Typically used as a <em>bootstrap method</em> for {@code invokedynamic}
370 * call sites, to support the <em>lambda expression</em> and <em>method
371 * reference expression</em> features of the Java Programming Language.
372 *
373 * <p>This is the general, more flexible metafactory; a streamlined version
374 * is provided by {@link #metafactory(java.lang.invoke.MethodHandles.Lookup,
375 * String, MethodType, MethodType, MethodHandle, MethodType)}.
376 * A general description of the behavior of this method is provided
377 * {@link LambdaMetafactory above}.
378 *
379 * <p>The argument list for this method includes three fixed parameters,
380 * corresponding to the parameters automatically stacked by the VM for the
381 * bootstrap method in an {@code invokedynamic} invocation, and an {@code Object[]}
382 * parameter that contains additional parameters. The declared argument
383 * list for this method is:
384 *
385 * <pre>{@code
386 * CallSite altMetafactory(MethodHandles.Lookup caller,
387 * String interfaceMethodName,
388 * MethodType factoryType,
389 * Object... args)
390 * }</pre>
391 *
392 * <p>but it behaves as if the argument list is as follows:
393 *
394 * <pre>{@code
395 * CallSite altMetafactory(MethodHandles.Lookup caller,
396 * String interfaceMethodName,
397 * MethodType factoryType,
398 * MethodType interfaceMethodType,
399 * MethodHandle implementation,
400 * MethodType dynamicMethodType,
401 * int flags,
402 * int altInterfaceCount, // IF flags has MARKERS set
403 * Class... altInterfaces, // IF flags has MARKERS set
404 * int altMethodCount, // IF flags has BRIDGES set
405 * MethodType... altMethods // IF flags has BRIDGES set
406 * MethodHandle quotableField // IF flags has QUOTABLE set
407 * )
408 * }</pre>
409 *
410 * <p>Arguments that appear in the argument list for
411 * {@link #metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)}
412 * have the same specification as in that method. The additional arguments
413 * are interpreted as follows:
414 * <ul>
415 * <li>{@code flags} indicates additional options; this is a bitwise
416 * OR of desired flags. Defined flags are {@link #FLAG_BRIDGES},
417 * {@link #FLAG_MARKERS}, and {@link #FLAG_SERIALIZABLE}.</li>
418 * <li>{@code altInterfaceCount} is the number of additional interfaces
419 * the function object should implement, and is present if and only if the
420 * {@code FLAG_MARKERS} flag is set.</li>
421 * <li>{@code altInterfaces} is a variable-length list of additional
422 * interfaces to implement, whose length equals {@code altInterfaceCount},
423 * and is present if and only if the {@code FLAG_MARKERS} flag is set.</li>
424 * <li>{@code altMethodCount} is the number of additional method signatures
425 * the function object should implement, and is present if and only if
426 * the {@code FLAG_BRIDGES} flag is set.</li>
427 * <li>{@code altMethods} is a variable-length list of additional
428 * methods signatures to implement, whose length equals {@code altMethodCount},
429 * and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li>
430 * <li>{@code quotableField} is a
431 * {@linkplain MethodHandles.Lookup#findGetter(Class, String, Class) getter} method handle
432 * that is used to retrieve the string representation of the quotable lambda's associated
433 * intermediate representation.</li>
434 * </ul>
435 *
436 * <p>Each class named by {@code altInterfaces} is subject to the same
437 * restrictions as {@code Rd}, the return type of {@code factoryType},
438 * as described {@link LambdaMetafactory above}. Each {@code MethodType}
439 * named by {@code altMethods} is subject to the same restrictions as
440 * {@code interfaceMethodType}, as described {@link LambdaMetafactory above}.
441 *
442 * <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects
443 * will implement {@code Serializable}, and will have a {@code writeReplace}
444 * method that returns an appropriate {@link SerializedLambda}. The
445 * {@code caller} class must have an appropriate {@code $deserializeLambda$}
446 * method, as described in {@link SerializedLambda}.
447 *
448 * <p>When FLAG_QUOTABLE is set in {@code flags}, the function objects
449 * will implement {@code Quotable}.
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 Objects.requireNonNull(caller);
506 Objects.requireNonNull(interfaceMethodName);
507 Objects.requireNonNull(factoryType);
508 Objects.requireNonNull(args);
509 int argIndex = 0;
510 MethodType interfaceMethodType = extractArg(args, argIndex++, MethodType.class);
511 MethodHandle implementation = extractArg(args, argIndex++, MethodHandle.class);
512 MethodType dynamicMethodType = extractArg(args, argIndex++, MethodType.class);
513 int flags = extractArg(args, argIndex++, Integer.class);
514 Class<?>[] altInterfaces = EMPTY_CLASS_ARRAY;
515 MethodType[] altMethods = EMPTY_MT_ARRAY;
516 // Getter that returns the op of a Quotable instance
517 MethodHandle quotableOpGetter = null;
518 if ((flags & FLAG_MARKERS) != 0) {
519 int altInterfaceCount = extractArg(args, argIndex++, Integer.class);
520 if (altInterfaceCount < 0) {
521 throw new IllegalArgumentException("negative argument count");
522 }
523 if (altInterfaceCount > 0) {
524 altInterfaces = extractArgs(args, argIndex, Class.class, altInterfaceCount);
525 argIndex += altInterfaceCount;
526 }
527 }
528 if ((flags & FLAG_BRIDGES) != 0) {
529 int altMethodCount = extractArg(args, argIndex++, Integer.class);
530 if (altMethodCount < 0) {
531 throw new IllegalArgumentException("negative argument count");
532 }
533 if (altMethodCount > 0) {
534 altMethods = extractArgs(args, argIndex, MethodType.class, altMethodCount);
535 argIndex += altMethodCount;
536 }
537 }
538 if ((flags & FLAG_QUOTABLE) != 0) {
539 quotableOpGetter = extractArg(args, argIndex++, MethodHandle.class);
540 altInterfaces = Arrays.copyOf(altInterfaces, altInterfaces.length + 1);
541 altInterfaces[altInterfaces.length-1] = InnerClassLambdaMetafactory.CodeReflectionSupport.QUOTABLE_CLASS;
542 }
543 if (argIndex < args.length) {
544 throw new IllegalArgumentException("too many arguments");
545 }
546
547 boolean isSerializable = ((flags & FLAG_SERIALIZABLE) != 0);
548 if (isSerializable) {
549 boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(factoryType.returnType());
550 for (Class<?> c : altInterfaces)
551 foundSerializableSupertype |= Serializable.class.isAssignableFrom(c);
552 if (!foundSerializableSupertype) {
553 altInterfaces = Arrays.copyOf(altInterfaces, altInterfaces.length + 1);
554 altInterfaces[altInterfaces.length-1] = Serializable.class;
555 }
556 }
557
558 AbstractValidatingLambdaMetafactory mf
559 = new InnerClassLambdaMetafactory(caller,
560 factoryType,
561 interfaceMethodName,
562 interfaceMethodType,
563 implementation,
564 dynamicMethodType,
565 isSerializable,
566 altInterfaces,
567 altMethods,
568 quotableOpGetter);
569 mf.validateMetafactoryArgs();
570 return mf.buildCallSite();
571 }
572
573 private static <T> T extractArg(Object[] args, int index, Class<T> type) {
574 if (index >= args.length) {
575 throw new IllegalArgumentException("missing argument");
576 }
577 Object result = Objects.requireNonNull(args[index]);
578 if (!type.isInstance(result)) {
579 throw new IllegalArgumentException("argument has wrong type");
580 }
581 return type.cast(result);
582 }
583
584 private static <T> T[] extractArgs(Object[] args, int index, Class<T> type, int count) {
585 @SuppressWarnings("unchecked")
586 T[] result = (T[]) Array.newInstance(type, count);
587 for (int i = 0; i < count; i++) {
588 result[i] = extractArg(args, index + i, type);
589 }
590 return result;
591 }
592
593 }