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