1 /*
2 * Copyright (c) 2008, 2026, 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 jdk.internal.access.SharedSecrets;
29 import jdk.internal.misc.Unsafe;
30 import jdk.internal.misc.VM;
31 import jdk.internal.reflect.CallerSensitive;
32 import jdk.internal.reflect.CallerSensitiveAdapter;
33 import jdk.internal.reflect.Reflection;
34 import jdk.internal.util.ClassFileDumper;
35 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
36 import jdk.internal.vm.annotation.ForceInline;
37 import jdk.internal.vm.annotation.Stable;
38 import sun.invoke.util.ValueConversions;
39 import sun.invoke.util.VerifyAccess;
40 import sun.invoke.util.Wrapper;
41
42 import java.lang.classfile.ClassFile;
43 import java.lang.classfile.ClassModel;
44 import java.lang.constant.ClassDesc;
45 import java.lang.constant.ConstantDescs;
46 import java.lang.invoke.LambdaForm.BasicType;
47 import java.lang.invoke.MethodHandleImpl.Intrinsic;
48 import java.lang.reflect.Constructor;
49 import java.lang.reflect.Field;
50 import java.lang.reflect.Member;
51 import java.lang.reflect.Method;
52 import java.lang.reflect.Modifier;
53 import java.nio.ByteOrder;
54 import java.security.ProtectionDomain;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.BitSet;
58 import java.util.Comparator;
59 import java.util.Iterator;
60 import java.util.List;
61 import java.util.Objects;
62 import java.util.Set;
63 import java.util.concurrent.ConcurrentHashMap;
64 import java.util.stream.Stream;
65
66 import static java.lang.classfile.ClassFile.*;
67 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
68 import static java.lang.invoke.MethodHandleNatives.Constants.*;
69 import static java.lang.invoke.MethodHandleStatics.*;
70 import static java.lang.invoke.MethodType.methodType;
71
72 /**
73 * This class consists exclusively of static methods that operate on or return
74 * method handles. They fall into several categories:
75 * <ul>
76 * <li>Lookup methods which help create method handles for methods and fields.
77 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
78 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
79 * </ul>
80 * A lookup, combinator, or factory method will fail and throw an
81 * {@code IllegalArgumentException} if the created method handle's type
82 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
83 *
84 * @author John Rose, JSR 292 EG
85 * @since 1.7
86 */
87 @AOTSafeClassInitializer
88 public final class MethodHandles {
89
90 private MethodHandles() { } // do not instantiate
91
92 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
93
94 // See IMPL_LOOKUP below.
95
96 //--- Method handle creation from ordinary methods.
97
98 /**
99 * Returns a {@link Lookup lookup object} with
100 * full capabilities to emulate all supported bytecode behaviors of the caller.
101 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
102 * Factory methods on the lookup object can create
103 * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
104 * for any member that the caller has access to via bytecodes,
105 * including protected and private fields and methods.
106 * This lookup object is created by the original lookup class
107 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
108 * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
109 * Do not store it in place where untrusted code can access it.
110 * <p>
111 * This method is caller sensitive, which means that it may return different
112 * values to different callers.
113 * In cases where {@code MethodHandles.lookup} is called from a context where
114 * there is no caller frame on the stack (e.g. when called directly
115 * from a JNI attached thread), {@code IllegalCallerException} is thrown.
116 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
117 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
118 * to obtain a low-privileged lookup instead.
119 * @return a lookup object for the caller of this method, with
120 * {@linkplain Lookup#ORIGINAL original} and
121 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
122 * @throws IllegalCallerException if there is no caller frame on the stack.
123 */
124 @CallerSensitive
125 @ForceInline // to ensure Reflection.getCallerClass optimization
126 public static Lookup lookup() {
127 final Class<?> c = Reflection.getCallerClass();
128 if (c == null) {
129 throw new IllegalCallerException("no caller frame");
130 }
131 return new Lookup(c);
132 }
133
134 /**
135 * This lookup method is the alternate implementation of
136 * the lookup method with a leading caller class argument which is
137 * non-caller-sensitive. This method is only invoked by reflection
138 * and method handle.
139 */
140 @CallerSensitiveAdapter
141 private static Lookup lookup(Class<?> caller) {
142 if (caller.getClassLoader() == null) {
143 throw newInternalError("calling lookup() reflectively is not supported: "+caller);
144 }
145 return new Lookup(caller);
146 }
147
148 /**
149 * Returns a {@link Lookup lookup object} which is trusted minimally.
150 * The lookup has the {@code UNCONDITIONAL} mode.
151 * It can only be used to create method handles to public members of
152 * public classes in packages that are exported unconditionally.
153 * <p>
154 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
155 * of this lookup object will be {@link java.lang.Object}.
156 *
157 * @apiNote The use of Object is conventional, and because the lookup modes are
158 * limited, there is no special access provided to the internals of Object, its package
159 * or its module. This public lookup object or other lookup object with
160 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
161 * is not used to determine the lookup context.
162 *
163 * <p style="font-size:smaller;">
164 * <em>Discussion:</em>
165 * The lookup class can be changed to any other class {@code C} using an expression of the form
166 * {@link Lookup#in publicLookup().in(C.class)}.
167 * Also, it cannot access
168 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
169 * @return a lookup object which is trusted minimally
170 */
171 public static Lookup publicLookup() {
172 return Lookup.PUBLIC_LOOKUP;
173 }
174
175 /**
176 * Returns a {@link Lookup lookup} object on a target class to emulate all supported
177 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
178 * The returned lookup object can provide access to classes in modules and packages,
179 * and members of those classes, outside the normal rules of Java access control,
180 * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
181 * <p>
182 * A caller, specified as a {@code Lookup} object, in module {@code M1} is
183 * allowed to do deep reflection on module {@code M2} and package of the target class
184 * if and only if all of the following conditions are {@code true}:
185 * <ul>
186 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
187 * full privilege access}. Specifically:
188 * <ul>
189 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
190 * (This is because otherwise there would be no way to ensure the original lookup
191 * creator was a member of any particular module, and so any subsequent checks
192 * for readability and qualified exports would become ineffective.)
193 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
194 * (This is because an application intending to share intra-module access
195 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share
196 * deep reflection to its own module.)
197 * </ul>
198 * <li>The target class must be a proper class, not a primitive or array class.
199 * (Thus, {@code M2} is well-defined.)
200 * <li>If the caller module {@code M1} differs from
201 * the target module {@code M2} then both of the following must be true:
202 * <ul>
203 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
204 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
205 * containing the target class to at least {@code M1}.</li>
206 * </ul>
207 * </ul>
208 * <p>
209 * If any of the above checks is violated, this method fails with an
210 * exception.
211 * <p>
212 * Otherwise, if {@code M1} and {@code M2} are the same module, this method
213 * returns a {@code Lookup} on {@code targetClass} with
214 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
215 * with {@code null} previous lookup class.
216 * <p>
217 * Otherwise, {@code M1} and {@code M2} are two different modules. This method
218 * returns a {@code Lookup} on {@code targetClass} that records
219 * the lookup class of the caller as the new previous lookup class with
220 * {@code PRIVATE} access but no {@code MODULE} access.
221 * <p>
222 * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
223 *
224 * @apiNote The {@code Lookup} object returned by this method is allowed to
225 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
226 * of {@code targetClass}. Extreme caution should be taken when opening a package
227 * to another module as such defined classes have the same full privilege
228 * access as other members in {@code targetClass}'s module.
229 *
230 * @param targetClass the target class
231 * @param caller the caller lookup object
232 * @return a lookup object for the target class, with private access
233 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
234 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
235 * @throws IllegalAccessException if any of the other access checks specified above fails
236 * @since 9
237 * @see Lookup#dropLookupMode
238 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
239 */
240 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
241 if (caller.allowedModes == Lookup.TRUSTED) {
242 return new Lookup(targetClass);
243 }
244
245 if (targetClass.isPrimitive())
246 throw new IllegalArgumentException(targetClass + " is a primitive class");
247 if (targetClass.isArray())
248 throw new IllegalArgumentException(targetClass + " is an array class");
249 // Ensure that we can reason accurately about private and module access.
250 int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
251 if ((caller.lookupModes() & requireAccess) != requireAccess)
252 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
253
254 // previous lookup class is never set if it has MODULE access
255 assert caller.previousLookupClass() == null;
256
257 Class<?> callerClass = caller.lookupClass();
258 Module callerModule = callerClass.getModule(); // M1
259 Module targetModule = targetClass.getModule(); // M2
260 Class<?> newPreviousClass = null;
261 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
262
263 if (targetModule != callerModule) {
264 if (!callerModule.canRead(targetModule))
265 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
266 if (targetModule.isNamed()) {
267 String pn = targetClass.getPackageName();
268 assert !pn.isEmpty() : "unnamed package cannot be in named module";
269 if (!targetModule.isOpen(pn, callerModule))
270 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
271 }
272
273 // M2 != M1, set previous lookup class to M1 and drop MODULE access
274 newPreviousClass = callerClass;
275 newModes &= ~Lookup.MODULE;
276 }
277 return Lookup.newLookup(targetClass, newPreviousClass, newModes);
278 }
279
280 /**
281 * Returns the <em>class data</em> associated with the lookup class
282 * of the given {@code caller} lookup object, or {@code null}.
283 *
284 * <p> A hidden class with class data can be created by calling
285 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
286 * Lookup::defineHiddenClassWithClassData}.
287 * This method will cause the static class initializer of the lookup
288 * class of the given {@code caller} lookup object be executed if
289 * it has not been initialized.
290 *
291 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
292 * Lookup::defineHiddenClass} and non-hidden classes have no class data.
293 * {@code null} is returned if this method is called on the lookup object
294 * on these classes.
295 *
296 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
297 * must have {@linkplain Lookup#ORIGINAL original access}
298 * in order to retrieve the class data.
299 *
300 * @apiNote
301 * This method can be called as a bootstrap method for a dynamically computed
302 * constant. A framework can create a hidden class with class data, for
303 * example that can be {@code Class} or {@code MethodHandle} object.
304 * The class data is accessible only to the lookup object
305 * created by the original caller but inaccessible to other members
306 * in the same nest. If a framework passes security sensitive objects
307 * to a hidden class via class data, it is recommended to load the value
308 * of class data as a dynamically computed constant instead of storing
309 * the class data in private static field(s) which are accessible to
310 * other nestmates.
311 *
312 * @param <T> the type to cast the class data object to
313 * @param caller the lookup context describing the class performing the
314 * operation (normally stacked by the JVM)
315 * @param name must be {@link ConstantDescs#DEFAULT_NAME}
316 * ({@code "_"})
317 * @param type the type of the class data
318 * @return the value of the class data if present in the lookup class;
319 * otherwise {@code null}
320 * @throws IllegalArgumentException if name is not {@code "_"}
321 * @throws IllegalAccessException if the lookup context does not have
322 * {@linkplain Lookup#ORIGINAL original} access
323 * @throws ClassCastException if the class data cannot be converted to
324 * the given {@code type}
325 * @throws NullPointerException if {@code caller} or {@code type} argument
326 * is {@code null}
327 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
328 * @see MethodHandles#classDataAt(Lookup, String, Class, int)
329 * @since 16
330 * @jvms 5.5 Initialization
331 */
332 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
333 Objects.requireNonNull(caller);
334 Objects.requireNonNull(type);
335 if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
336 throw new IllegalArgumentException("name must be \"_\": " + name);
337 }
338
339 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) {
340 throw new IllegalAccessException(caller + " does not have ORIGINAL access");
341 }
342
343 Object classdata = classData(caller.lookupClass());
344 if (classdata == null) return null;
345
346 try {
347 return BootstrapMethodInvoker.widenAndCast(classdata, type);
348 } catch (RuntimeException|Error e) {
349 throw e; // let CCE and other runtime exceptions through
350 } catch (Throwable e) {
351 throw new InternalError(e);
352 }
353 }
354
355 /*
356 * Returns the class data set by the VM in the Class::classData field.
357 *
358 * This is also invoked by LambdaForms as it cannot use condy via
359 * MethodHandles::classData due to bootstrapping issue.
360 */
361 static Object classData(Class<?> c) {
362 UNSAFE.ensureClassInitialized(c);
363 return SharedSecrets.getJavaLangAccess().classData(c);
364 }
365
366 /**
367 * Returns the element at the specified index in the
368 * {@linkplain #classData(Lookup, String, Class) class data},
369 * if the class data associated with the lookup class
370 * of the given {@code caller} lookup object is a {@code List}.
371 * If the class data is not present in this lookup class, this method
372 * returns {@code null}.
373 *
374 * <p> A hidden class with class data can be created by calling
375 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
376 * Lookup::defineHiddenClassWithClassData}.
377 * This method will cause the static class initializer of the lookup
378 * class of the given {@code caller} lookup object be executed if
379 * it has not been initialized.
380 *
381 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
382 * Lookup::defineHiddenClass} and non-hidden classes have no class data.
383 * {@code null} is returned if this method is called on the lookup object
384 * on these classes.
385 *
386 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
387 * must have {@linkplain Lookup#ORIGINAL original access}
388 * in order to retrieve the class data.
389 *
390 * @apiNote
391 * This method can be called as a bootstrap method for a dynamically computed
392 * constant. A framework can create a hidden class with class data, for
393 * example that can be {@code List.of(o1, o2, o3....)} containing more than
394 * one object and use this method to load one element at a specific index.
395 * The class data is accessible only to the lookup object
396 * created by the original caller but inaccessible to other members
397 * in the same nest. If a framework passes security sensitive objects
398 * to a hidden class via class data, it is recommended to load the value
399 * of class data as a dynamically computed constant instead of storing
400 * the class data in private static field(s) which are accessible to other
401 * nestmates.
402 *
403 * @param <T> the type to cast the result object to
404 * @param caller the lookup context describing the class performing the
405 * operation (normally stacked by the JVM)
406 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
407 * ({@code "_"})
408 * @param type the type of the element at the given index in the class data
409 * @param index index of the element in the class data
410 * @return the element at the given index in the class data
411 * if the class data is present; otherwise {@code null}
412 * @throws IllegalArgumentException if name is not {@code "_"}
413 * @throws IllegalAccessException if the lookup context does not have
414 * {@linkplain Lookup#ORIGINAL original} access
415 * @throws ClassCastException if the class data cannot be converted to {@code List}
416 * or the element at the specified index cannot be converted to the given type
417 * @throws IndexOutOfBoundsException if the index is out of range
418 * @throws NullPointerException if {@code caller} or {@code type} argument is
419 * {@code null}; or if unboxing operation fails because
420 * the element at the given index is {@code null}
421 *
422 * @since 16
423 * @see #classData(Lookup, String, Class)
424 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
425 */
426 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
427 throws IllegalAccessException
428 {
429 @SuppressWarnings("unchecked")
430 List<Object> classdata = (List<Object>)classData(caller, name, List.class);
431 if (classdata == null) return null;
432
433 try {
434 Object element = classdata.get(index);
435 return BootstrapMethodInvoker.widenAndCast(element, type);
436 } catch (RuntimeException|Error e) {
437 throw e; // let specified exceptions and other runtime exceptions/errors through
438 } catch (Throwable e) {
439 throw new InternalError(e);
440 }
441 }
442
443 /**
444 * Performs an unchecked "crack" of a
445 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
446 * The result is as if the user had obtained a lookup object capable enough
447 * to crack the target method handle, called
448 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
449 * on the target to obtain its symbolic reference, and then called
450 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
451 * to resolve the symbolic reference to a member.
452 * @param <T> the desired type of the result, either {@link Member} or a subtype
453 * @param expected a class object representing the desired result type {@code T}
454 * @param target a direct method handle to crack into symbolic reference components
455 * @return a reference to the method, constructor, or field object
456 * @throws NullPointerException if either argument is {@code null}
457 * @throws IllegalArgumentException if the target is not a direct method handle
458 * @throws ClassCastException if the member is not of the expected type
459 * @since 1.8
460 */
461 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
462 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup
463 return lookup.revealDirect(target).reflectAs(expected, lookup);
464 }
465
466 /**
467 * A <em>lookup object</em> is a factory for creating method handles,
468 * when the creation requires access checking.
469 * Method handles do not perform
470 * access checks when they are called, but rather when they are created.
471 * Therefore, method handle access
472 * restrictions must be enforced when a method handle is created.
473 * The caller class against which those restrictions are enforced
474 * is known as the {@linkplain #lookupClass() lookup class}.
475 * <p>
476 * A lookup class which needs to create method handles will call
477 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
478 * When the {@code Lookup} factory object is created, the identity of the lookup class is
479 * determined, and securely stored in the {@code Lookup} object.
480 * The lookup class (or its delegates) may then use factory methods
481 * on the {@code Lookup} object to create method handles for access-checked members.
482 * This includes all methods, constructors, and fields which are allowed to the lookup class,
483 * even private ones.
484 *
485 * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
486 * The factory methods on a {@code Lookup} object correspond to all major
487 * use cases for methods, constructors, and fields.
488 * Each method handle created by a factory method is the functional
489 * equivalent of a particular <em>bytecode behavior</em>.
490 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
491 * the Java Virtual Machine Specification.)
492 * Here is a summary of the correspondence between these factory methods and
493 * the behavior of the resulting method handles:
494 * <table class="striped">
495 * <caption style="display:none">lookup method behaviors</caption>
496 * <thead>
497 * <tr>
498 * <th scope="col"><a id="equiv"></a>lookup expression</th>
499 * <th scope="col">member</th>
500 * <th scope="col">bytecode behavior</th>
501 * </tr>
502 * </thead>
503 * <tbody>
504 * <tr>
505 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
506 * <td>{@code FT f;}</td><td>{@code (FT) this.f;}</td>
507 * </tr>
508 * <tr>
509 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
510 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
511 * </tr>
512 * <tr>
513 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
514 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
515 * </tr>
516 * <tr>
517 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
518 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
519 * </tr>
520 * <tr>
521 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
522 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
523 * </tr>
524 * <tr>
525 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
526 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
527 * </tr>
528 * <tr>
529 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
530 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
531 * </tr>
532 * <tr>
533 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
534 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
535 * </tr>
536 * <tr>
537 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
538 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
539 * </tr>
540 * <tr>
541 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
542 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
543 * </tr>
544 * <tr>
545 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
546 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
547 * </tr>
548 * <tr>
549 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
550 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
551 * </tr>
552 * <tr>
553 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
554 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
555 * </tr>
556 * <tr>
557 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
558 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
559 * </tr>
560 * </tbody>
561 * </table>
562 *
563 * Here, the type {@code C} is the class or interface being searched for a member,
564 * documented as a parameter named {@code refc} in the lookup methods.
565 * The method type {@code MT} is composed from the return type {@code T}
566 * and the sequence of argument types {@code A*}.
567 * The constructor also has a sequence of argument types {@code A*} and
568 * is deemed to return the newly-created object of type {@code C}.
569 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
570 * The formal parameter {@code this} stands for the self-reference of type {@code C};
571 * if it is present, it is always the leading argument to the method handle invocation.
572 * (In the case of some {@code protected} members, {@code this} may be
573 * restricted in type to the lookup class; see below.)
574 * The name {@code arg} stands for all the other method handle arguments.
575 * In the code examples for the Core Reflection API, the name {@code thisOrNull}
576 * stands for a null reference if the accessed method or field is static,
577 * and {@code this} otherwise.
578 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
579 * for reflective objects corresponding to the given members declared in type {@code C}.
580 * <p>
581 * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
582 * as if by {@code ldc CONSTANT_Class}.
583 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
584 * <p>
585 * In cases where the given member is of variable arity (i.e., a method or constructor)
586 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
587 * In all other cases, the returned method handle will be of fixed arity.
588 * <p style="font-size:smaller;">
589 * <em>Discussion:</em>
590 * The equivalence between looked-up method handles and underlying
591 * class members and bytecode behaviors
592 * can break down in a few ways:
593 * <ul style="font-size:smaller;">
594 * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
595 * the lookup can still succeed, even when there is no equivalent
596 * Java expression or bytecoded constant.
597 * <li>Likewise, if {@code T} or {@code MT}
598 * is not symbolically accessible from the lookup class's loader,
599 * the lookup can still succeed.
600 * For example, lookups for {@code MethodHandle.invokeExact} and
601 * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
602 * <li>If the looked-up method has a
603 * <a href="MethodHandle.html#maxarity">very large arity</a>,
604 * the method handle creation may fail with an
605 * {@code IllegalArgumentException}, due to the method handle type having
606 * <a href="MethodHandle.html#maxarity">too many parameters.</a>
607 * </ul>
608 *
609 * <h2><a id="access"></a>Access checking</h2>
610 * Access checks are applied in the factory methods of {@code Lookup},
611 * when a method handle is created.
612 * This is a key difference from the Core Reflection API, since
613 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
614 * performs access checking against every caller, on every call.
615 * <p>
616 * All access checks start from a {@code Lookup} object, which
617 * compares its recorded lookup class against all requests to
618 * create method handles.
619 * A single {@code Lookup} object can be used to create any number
620 * of access-checked method handles, all checked against a single
621 * lookup class.
622 * <p>
623 * A {@code Lookup} object can be shared with other trusted code,
624 * such as a metaobject protocol.
625 * A shared {@code Lookup} object delegates the capability
626 * to create method handles on private members of the lookup class.
627 * Even if privileged code uses the {@code Lookup} object,
628 * the access checking is confined to the privileges of the
629 * original lookup class.
630 * <p>
631 * A lookup can fail, because
632 * the containing class is not accessible to the lookup class, or
633 * because the desired class member is missing, or because the
634 * desired class member is not accessible to the lookup class, or
635 * because the lookup object is not trusted enough to access the member.
636 * In the case of a field setter function on a {@code final} field,
637 * finality enforcement is treated as a kind of access control,
638 * and the lookup will fail, except in special cases of
639 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
640 * In any of these cases, a {@code ReflectiveOperationException} will be
641 * thrown from the attempted lookup. The exact class will be one of
642 * the following:
643 * <ul>
644 * <li>NoSuchMethodException — if a method is requested but does not exist
645 * <li>NoSuchFieldException — if a field is requested but does not exist
646 * <li>IllegalAccessException — if the member exists but an access check fails
647 * </ul>
648 * <p>
649 * In general, the conditions under which a method handle may be
650 * looked up for a method {@code M} are no more restrictive than the conditions
651 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
652 * Where the JVM would raise exceptions like {@code NoSuchMethodError},
653 * a method handle lookup will generally raise a corresponding
654 * checked exception, such as {@code NoSuchMethodException}.
655 * And the effect of invoking the method handle resulting from the lookup
656 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
657 * to executing the compiled, verified, and resolved call to {@code M}.
658 * The same point is true of fields and constructors.
659 * <p style="font-size:smaller;">
660 * <em>Discussion:</em>
661 * Access checks only apply to named and reflected methods,
662 * constructors, and fields.
663 * Other method handle creation methods, such as
664 * {@link MethodHandle#asType MethodHandle.asType},
665 * do not require any access checks, and are used
666 * independently of any {@code Lookup} object.
667 * <p>
668 * If the desired member is {@code protected}, the usual JVM rules apply,
669 * including the requirement that the lookup class must either be in the
670 * same package as the desired member, or must inherit that member.
671 * (See the Java Virtual Machine Specification, sections {@jvms
672 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
673 * In addition, if the desired member is a non-static field or method
674 * in a different package, the resulting method handle may only be applied
675 * to objects of the lookup class or one of its subclasses.
676 * This requirement is enforced by narrowing the type of the leading
677 * {@code this} parameter from {@code C}
678 * (which will necessarily be a superclass of the lookup class)
679 * to the lookup class itself.
680 * <p>
681 * The JVM imposes a similar requirement on {@code invokespecial} instruction,
682 * that the receiver argument must match both the resolved method <em>and</em>
683 * the current class. Again, this requirement is enforced by narrowing the
684 * type of the leading parameter to the resulting method handle.
685 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
686 * <p>
687 * The JVM represents constructors and static initializer blocks as internal methods
688 * with special names ({@value ConstantDescs#INIT_NAME} and {@value
689 * ConstantDescs#CLASS_INIT_NAME}).
690 * The internal syntax of invocation instructions allows them to refer to such internal
691 * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
692 * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
693 * <p>
694 * If the relationship between nested types is expressed directly through the
695 * {@code NestHost} and {@code NestMembers} attributes
696 * (see the Java Virtual Machine Specification, sections {@jvms
697 * 4.7.28} and {@jvms 4.7.29}),
698 * then the associated {@code Lookup} object provides direct access to
699 * the lookup class and all of its nestmates
700 * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
701 * Otherwise, access between nested classes is obtained by the Java compiler creating
702 * a wrapper method to access a private method of another class in the same nest.
703 * For example, a nested class {@code C.D}
704 * can access private members within other related classes such as
705 * {@code C}, {@code C.D.E}, or {@code C.B},
706 * but the Java compiler may need to generate wrapper methods in
707 * those related classes. In such cases, a {@code Lookup} object on
708 * {@code C.E} would be unable to access those private members.
709 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
710 * which can transform a lookup on {@code C.E} into one on any of those other
711 * classes, without special elevation of privilege.
712 * <p>
713 * The accesses permitted to a given lookup object may be limited,
714 * according to its set of {@link #lookupModes lookupModes},
715 * to a subset of members normally accessible to the lookup class.
716 * For example, the {@link MethodHandles#publicLookup publicLookup}
717 * method produces a lookup object which is only allowed to access
718 * public members in public classes of exported packages.
719 * The caller sensitive method {@link MethodHandles#lookup lookup}
720 * produces a lookup object with full capabilities relative to
721 * its caller class, to emulate all supported bytecode behaviors.
722 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
723 * with fewer access modes than the original lookup object.
724 *
725 * <p style="font-size:smaller;">
726 * <a id="privacc"></a>
727 * <em>Discussion of private and module access:</em>
728 * We say that a lookup has <em>private access</em>
729 * if its {@linkplain #lookupModes lookup modes}
730 * include the possibility of accessing {@code private} members
731 * (which includes the private members of nestmates).
732 * As documented in the relevant methods elsewhere,
733 * only lookups with private access possess the following capabilities:
734 * <ul style="font-size:smaller;">
735 * <li>access private fields, methods, and constructors of the lookup class and its nestmates
736 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
737 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
738 * within the same package member
739 * </ul>
740 * <p style="font-size:smaller;">
741 * Similarly, a lookup with module access ensures that the original lookup creator was
742 * a member in the same module as the lookup class.
743 * <p style="font-size:smaller;">
744 * Private and module access are independently determined modes; a lookup may have
745 * either or both or neither. A lookup which possesses both access modes is said to
746 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
747 * <p style="font-size:smaller;">
748 * A lookup with <em>original access</em> ensures that this lookup is created by
749 * the original lookup class and the bootstrap method invoked by the VM.
750 * Such a lookup with original access also has private and module access
751 * which has the following additional capability:
752 * <ul style="font-size:smaller;">
753 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
754 * such as {@code Class.forName}
755 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
756 * class data} associated with the lookup class</li>
757 * </ul>
758 * <p style="font-size:smaller;">
759 * Each of these permissions is a consequence of the fact that a lookup object
760 * with private access can be securely traced back to an originating class,
761 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
762 * can be reliably determined and emulated by method handles.
763 *
764 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
765 * When a lookup class in one module {@code M1} accesses a class in another module
766 * {@code M2}, extra access checking is performed beyond the access mode bits.
767 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
768 * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
769 * and when the type is in a package of {@code M2} that is exported to
770 * at least {@code M1}.
771 * <p>
772 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
773 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
774 * MethodHandles.privateLookupIn} methods.
775 * Teleporting across modules will always record the original lookup class as
776 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
777 * and drops {@link Lookup#MODULE MODULE} access.
778 * If the target class is in the same module as the lookup class {@code C},
779 * then the target class becomes the new lookup class
780 * and there is no change to the previous lookup class.
781 * If the target class is in a different module from {@code M1} ({@code C}'s module),
782 * {@code C} becomes the new previous lookup class
783 * and the target class becomes the new lookup class.
784 * In that case, if there was already a previous lookup class in {@code M0},
785 * and it differs from {@code M1} and {@code M2}, then the resulting lookup
786 * drops all privileges.
787 * For example,
788 * {@snippet lang="java" :
789 * Lookup lookup = MethodHandles.lookup(); // in class C
790 * Lookup lookup2 = lookup.in(D.class);
791 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
792 * }
793 * <p>
794 * The {@link #lookup()} factory method produces a {@code Lookup} object
795 * with {@code null} previous lookup class.
796 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
797 * to class {@code D} without elevation of privileges.
798 * If {@code C} and {@code D} are in the same module,
799 * {@code lookup2} records {@code D} as the new lookup class and keeps the
800 * same previous lookup class as the original {@code lookup}, or
801 * {@code null} if not present.
802 * <p>
803 * When a {@code Lookup} teleports from a class
804 * in one nest to another nest, {@code PRIVATE} access is dropped.
805 * When a {@code Lookup} teleports from a class in one package to
806 * another package, {@code PACKAGE} access is dropped.
807 * When a {@code Lookup} teleports from a class in one module to another module,
808 * {@code MODULE} access is dropped.
809 * Teleporting across modules drops the ability to access non-exported classes
810 * in both the module of the new lookup class and the module of the old lookup class
811 * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
812 * A {@code Lookup} can teleport back and forth to a class in the module of
813 * the lookup class and the module of the previous class lookup.
814 * Teleporting across modules can only decrease access but cannot increase it.
815 * Teleporting to some third module drops all accesses.
816 * <p>
817 * In the above example, if {@code C} and {@code D} are in different modules,
818 * {@code lookup2} records {@code D} as its lookup class and
819 * {@code C} as its previous lookup class and {@code lookup2} has only
820 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
821 * {@code C}'s module and {@code D}'s module.
822 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
823 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
824 * class {@code D} is recorded as its previous lookup class.
825 * <p>
826 * Teleporting across modules restricts access to the public types that
827 * both the lookup class and the previous lookup class can equally access
828 * (see below).
829 * <p>
830 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
831 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
832 * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
833 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
834 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
835 * to call {@code privateLookupIn}.
836 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
837 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn}
838 * produces a new {@code Lookup} on {@code T} with full capabilities.
839 * A {@code lookup} on {@code C} is also allowed
840 * to do deep reflection on {@code T} in another module {@code M2} if
841 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
842 * the package containing {@code T} to at least {@code M1}.
843 * {@code T} becomes the new lookup class and {@code C} becomes the new previous
844 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
845 * The resulting {@code Lookup} can be used to do member lookup or teleport
846 * to another lookup class by calling {@link #in Lookup::in}. But
847 * it cannot be used to obtain another private {@code Lookup} by calling
848 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
849 * because it has no {@code MODULE} access.
850 * <p>
851 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
852 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
853 * of {@code T}. Extreme caution should be taken when opening a package
854 * to another module as such defined classes have the same full privilege
855 * access as other members in {@code M2}.
856 *
857 * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
858 *
859 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
860 * allows cross-module access. The access checking is performed with respect
861 * to both the lookup class and the previous lookup class if present.
862 * <p>
863 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
864 * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
865 * exported unconditionally}.
866 * <p>
867 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
868 * the lookup with {@link #PUBLIC} mode can access all public types in modules
869 * that are readable to {@code M1} and the type is in a package that is exported
870 * at least to {@code M1}.
871 * <p>
872 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
873 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
874 * the intersection of all public types that are accessible to {@code M1}
875 * with all public types that are accessible to {@code M0}. {@code M0}
876 * reads {@code M1} and hence the set of accessible types includes:
877 *
878 * <ul>
879 * <li>unconditional-exported packages from {@code M1}</li>
880 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
881 * <li>
882 * unconditional-exported packages from a third module {@code M2}if both {@code M0}
883 * and {@code M1} read {@code M2}
884 * </li>
885 * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
886 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
887 * <li>
888 * qualified-exported packages from a third module {@code M2} to both {@code M0} and
889 * {@code M1} if both {@code M0} and {@code M1} read {@code M2}
890 * </li>
891 * </ul>
892 *
893 * <h2><a id="access-modes"></a>Access modes</h2>
894 *
895 * The table below shows the access modes of a {@code Lookup} produced by
896 * any of the following factory or transformation methods:
897 * <ul>
898 * <li>{@link #lookup() MethodHandles::lookup}</li>
899 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
900 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
901 * <li>{@link Lookup#in Lookup::in}</li>
902 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
903 * </ul>
904 *
905 * <table class="striped">
906 * <caption style="display:none">
907 * Access mode summary
908 * </caption>
909 * <thead>
910 * <tr>
911 * <th scope="col">Lookup object</th>
912 * <th style="text-align:center">original</th>
913 * <th style="text-align:center">protected</th>
914 * <th style="text-align:center">private</th>
915 * <th style="text-align:center">package</th>
916 * <th style="text-align:center">module</th>
917 * <th style="text-align:center">public</th>
918 * </tr>
919 * </thead>
920 * <tbody>
921 * <tr>
922 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
923 * <td style="text-align:center">ORI</td>
924 * <td style="text-align:center">PRO</td>
925 * <td style="text-align:center">PRI</td>
926 * <td style="text-align:center">PAC</td>
927 * <td style="text-align:center">MOD</td>
928 * <td style="text-align:center">1R</td>
929 * </tr>
930 * <tr>
931 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
932 * <td></td>
933 * <td></td>
934 * <td></td>
935 * <td style="text-align:center">PAC</td>
936 * <td style="text-align:center">MOD</td>
937 * <td style="text-align:center">1R</td>
938 * </tr>
939 * <tr>
940 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
941 * <td></td>
942 * <td></td>
943 * <td></td>
944 * <td></td>
945 * <td style="text-align:center">MOD</td>
946 * <td style="text-align:center">1R</td>
947 * </tr>
948 * <tr>
949 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
950 * <td></td>
951 * <td></td>
952 * <td></td>
953 * <td></td>
954 * <td></td>
955 * <td style="text-align:center">2R</td>
956 * </tr>
957 * <tr>
958 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
959 * <td></td>
960 * <td></td>
961 * <td></td>
962 * <td></td>
963 * <td></td>
964 * <td style="text-align:center">2R</td>
965 * </tr>
966 * <tr>
967 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
968 * <td></td>
969 * <td style="text-align:center">PRO</td>
970 * <td style="text-align:center">PRI</td>
971 * <td style="text-align:center">PAC</td>
972 * <td style="text-align:center">MOD</td>
973 * <td style="text-align:center">1R</td>
974 * </tr>
975 * <tr>
976 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
977 * <td></td>
978 * <td style="text-align:center">PRO</td>
979 * <td style="text-align:center">PRI</td>
980 * <td style="text-align:center">PAC</td>
981 * <td style="text-align:center">MOD</td>
982 * <td style="text-align:center">1R</td>
983 * </tr>
984 * <tr>
985 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
986 * <td></td>
987 * <td></td>
988 * <td></td>
989 * <td style="text-align:center">PAC</td>
990 * <td style="text-align:center">MOD</td>
991 * <td style="text-align:center">1R</td>
992 * </tr>
993 * <tr>
994 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
995 * <td></td>
996 * <td></td>
997 * <td></td>
998 * <td></td>
999 * <td style="text-align:center">MOD</td>
1000 * <td style="text-align:center">1R</td>
1001 * </tr>
1002 * <tr>
1003 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1004 * <td></td>
1005 * <td></td>
1006 * <td></td>
1007 * <td></td>
1008 * <td></td>
1009 * <td style="text-align:center">2R</td>
1010 * </tr>
1011 * <tr>
1012 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1013 * <td></td>
1014 * <td></td>
1015 * <td style="text-align:center">PRI</td>
1016 * <td style="text-align:center">PAC</td>
1017 * <td style="text-align:center">MOD</td>
1018 * <td style="text-align:center">1R</td>
1019 * </tr>
1020 * <tr>
1021 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1022 * <td></td>
1023 * <td></td>
1024 * <td></td>
1025 * <td style="text-align:center">PAC</td>
1026 * <td style="text-align:center">MOD</td>
1027 * <td style="text-align:center">1R</td>
1028 * </tr>
1029 * <tr>
1030 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1031 * <td></td>
1032 * <td></td>
1033 * <td></td>
1034 * <td></td>
1035 * <td style="text-align:center">MOD</td>
1036 * <td style="text-align:center">1R</td>
1037 * </tr>
1038 * <tr>
1039 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1040 * <td></td>
1041 * <td></td>
1042 * <td></td>
1043 * <td></td>
1044 * <td></td>
1045 * <td style="text-align:center">1R</td>
1046 * </tr>
1047 * <tr>
1048 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1049 * <td></td>
1050 * <td></td>
1051 * <td></td>
1052 * <td></td>
1053 * <td></td>
1054 * <td style="text-align:center">none</td>
1055 * <tr>
1056 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1057 * <td></td>
1058 * <td style="text-align:center">PRO</td>
1059 * <td style="text-align:center">PRI</td>
1060 * <td style="text-align:center">PAC</td>
1061 * <td></td>
1062 * <td style="text-align:center">2R</td>
1063 * </tr>
1064 * <tr>
1065 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1066 * <td></td>
1067 * <td style="text-align:center">PRO</td>
1068 * <td style="text-align:center">PRI</td>
1069 * <td style="text-align:center">PAC</td>
1070 * <td></td>
1071 * <td style="text-align:center">2R</td>
1072 * </tr>
1073 * <tr>
1074 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1075 * <td></td>
1076 * <td></td>
1077 * <td></td>
1078 * <td></td>
1079 * <td></td>
1080 * <td style="text-align:center">IAE</td>
1081 * </tr>
1082 * <tr>
1083 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1084 * <td></td>
1085 * <td></td>
1086 * <td></td>
1087 * <td style="text-align:center">PAC</td>
1088 * <td></td>
1089 * <td style="text-align:center">2R</td>
1090 * </tr>
1091 * <tr>
1092 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1093 * <td></td>
1094 * <td></td>
1095 * <td></td>
1096 * <td></td>
1097 * <td></td>
1098 * <td style="text-align:center">2R</td>
1099 * </tr>
1100 * <tr>
1101 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1102 * <td></td>
1103 * <td></td>
1104 * <td></td>
1105 * <td></td>
1106 * <td></td>
1107 * <td style="text-align:center">2R</td>
1108 * </tr>
1109 * <tr>
1110 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1111 * <td></td>
1112 * <td></td>
1113 * <td></td>
1114 * <td></td>
1115 * <td></td>
1116 * <td style="text-align:center">none</td>
1117 * </tr>
1118 * <tr>
1119 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1120 * <td></td>
1121 * <td></td>
1122 * <td style="text-align:center">PRI</td>
1123 * <td style="text-align:center">PAC</td>
1124 * <td></td>
1125 * <td style="text-align:center">2R</td>
1126 * </tr>
1127 * <tr>
1128 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1129 * <td></td>
1130 * <td></td>
1131 * <td></td>
1132 * <td style="text-align:center">PAC</td>
1133 * <td></td>
1134 * <td style="text-align:center">2R</td>
1135 * </tr>
1136 * <tr>
1137 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1138 * <td></td>
1139 * <td></td>
1140 * <td></td>
1141 * <td></td>
1142 * <td></td>
1143 * <td style="text-align:center">2R</td>
1144 * </tr>
1145 * <tr>
1146 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1147 * <td></td>
1148 * <td></td>
1149 * <td></td>
1150 * <td></td>
1151 * <td></td>
1152 * <td style="text-align:center">2R</td>
1153 * </tr>
1154 * <tr>
1155 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1156 * <td></td>
1157 * <td></td>
1158 * <td></td>
1159 * <td></td>
1160 * <td></td>
1161 * <td style="text-align:center">none</td>
1162 * </tr>
1163 * <tr>
1164 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1165 * <td></td>
1166 * <td></td>
1167 * <td style="text-align:center">PRI</td>
1168 * <td style="text-align:center">PAC</td>
1169 * <td style="text-align:center">MOD</td>
1170 * <td style="text-align:center">1R</td>
1171 * </tr>
1172 * <tr>
1173 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1174 * <td></td>
1175 * <td></td>
1176 * <td></td>
1177 * <td style="text-align:center">PAC</td>
1178 * <td style="text-align:center">MOD</td>
1179 * <td style="text-align:center">1R</td>
1180 * </tr>
1181 * <tr>
1182 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1183 * <td></td>
1184 * <td></td>
1185 * <td></td>
1186 * <td></td>
1187 * <td style="text-align:center">MOD</td>
1188 * <td style="text-align:center">1R</td>
1189 * </tr>
1190 * <tr>
1191 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1192 * <td></td>
1193 * <td></td>
1194 * <td></td>
1195 * <td></td>
1196 * <td></td>
1197 * <td style="text-align:center">1R</td>
1198 * </tr>
1199 * <tr>
1200 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1201 * <td></td>
1202 * <td></td>
1203 * <td></td>
1204 * <td></td>
1205 * <td></td>
1206 * <td style="text-align:center">none</td>
1207 * </tr>
1208 * <tr>
1209 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1210 * <td></td>
1211 * <td></td>
1212 * <td></td>
1213 * <td></td>
1214 * <td></td>
1215 * <td style="text-align:center">U</td>
1216 * </tr>
1217 * <tr>
1218 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1219 * <td></td>
1220 * <td></td>
1221 * <td></td>
1222 * <td></td>
1223 * <td></td>
1224 * <td style="text-align:center">U</td>
1225 * </tr>
1226 * <tr>
1227 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1228 * <td></td>
1229 * <td></td>
1230 * <td></td>
1231 * <td></td>
1232 * <td></td>
1233 * <td style="text-align:center">U</td>
1234 * </tr>
1235 * <tr>
1236 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1237 * <td></td>
1238 * <td></td>
1239 * <td></td>
1240 * <td></td>
1241 * <td></td>
1242 * <td style="text-align:center">none</td>
1243 * </tr>
1244 * <tr>
1245 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1246 * <td></td>
1247 * <td></td>
1248 * <td></td>
1249 * <td></td>
1250 * <td></td>
1251 * <td style="text-align:center">IAE</td>
1252 * </tr>
1253 * <tr>
1254 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1255 * <td></td>
1256 * <td></td>
1257 * <td></td>
1258 * <td></td>
1259 * <td></td>
1260 * <td style="text-align:center">none</td>
1261 * </tr>
1262 * </tbody>
1263 * </table>
1264 *
1265 * <p>
1266 * Notes:
1267 * <ul>
1268 * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1269 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1270 * is in module {@code M3}. {@code X} stands for class which is inaccessible
1271 * to the lookup. {@code ANY} stands for any of the example lookups.</li>
1272 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1273 * {@code PRO} indicates {@link #PROTECTED} bit set,
1274 * {@code PRI} indicates {@link #PRIVATE} bit set,
1275 * {@code PAC} indicates {@link #PACKAGE} bit set,
1276 * {@code MOD} indicates {@link #MODULE} bit set,
1277 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1278 * {@code U} indicates {@link #UNCONDITIONAL} bit set,
1279 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1280 * <li>Public access comes in three kinds:
1281 * <ul>
1282 * <li>unconditional ({@code U}): the lookup assumes readability.
1283 * The lookup has {@code null} previous lookup class.
1284 * <li>one-module-reads ({@code 1R}): the module access checking is
1285 * performed with respect to the lookup class. The lookup has {@code null}
1286 * previous lookup class.
1287 * <li>two-module-reads ({@code 2R}): the module access checking is
1288 * performed with respect to the lookup class and the previous lookup class.
1289 * The lookup has a non-null previous lookup class which is in a
1290 * different module from the current lookup class.
1291 * </ul>
1292 * <li>Any attempt to reach a third module loses all access.</li>
1293 * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1294 * all access modes are dropped.</li>
1295 * </ul>
1296 *
1297 * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1298 * A small number of Java methods have a special property called caller sensitivity.
1299 * A <em>caller-sensitive</em> method can behave differently depending on the
1300 * identity of its immediate caller.
1301 * <p>
1302 * If a method handle for a caller-sensitive method is requested,
1303 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1304 * but they take account of the lookup class in a special way.
1305 * The resulting method handle behaves as if it were called
1306 * from an instruction contained in the lookup class,
1307 * so that the caller-sensitive method detects the lookup class.
1308 * (By contrast, the invoker of the method handle is disregarded.)
1309 * Thus, in the case of caller-sensitive methods,
1310 * different lookup classes may give rise to
1311 * differently behaving method handles.
1312 * <p>
1313 * In cases where the lookup object is
1314 * {@link MethodHandles#publicLookup() publicLookup()},
1315 * or some other lookup object without the
1316 * {@linkplain #ORIGINAL original access},
1317 * the lookup class is disregarded.
1318 * In such cases, no caller-sensitive method handle can be created,
1319 * access is forbidden, and the lookup fails with an
1320 * {@code IllegalAccessException}.
1321 * <p style="font-size:smaller;">
1322 * <em>Discussion:</em>
1323 * For example, the caller-sensitive method
1324 * {@link java.lang.Class#forName(String) Class.forName(x)}
1325 * can return varying classes or throw varying exceptions,
1326 * depending on the class loader of the class that calls it.
1327 * A public lookup of {@code Class.forName} will fail, because
1328 * there is no reasonable way to determine its bytecode behavior.
1329 * <p style="font-size:smaller;">
1330 * If an application caches method handles for broad sharing,
1331 * it should use {@code publicLookup()} to create them.
1332 * If there is a lookup of {@code Class.forName}, it will fail,
1333 * and the application must take appropriate action in that case.
1334 * It may be that a later lookup, perhaps during the invocation of a
1335 * bootstrap method, can incorporate the specific identity
1336 * of the caller, making the method accessible.
1337 * <p style="font-size:smaller;">
1338 * The function {@code MethodHandles.lookup} is caller sensitive
1339 * so that there can be a secure foundation for lookups.
1340 * Nearly all other methods in the JSR 292 API rely on lookup
1341 * objects to check access requests.
1342 */
1343 public static final
1344 class Lookup {
1345 /** The class on behalf of whom the lookup is being performed. */
1346 private final Class<?> lookupClass;
1347
1348 /** previous lookup class */
1349 private final Class<?> prevLookupClass;
1350
1351 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1352 private final int allowedModes;
1353
1354 static {
1355 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1356 }
1357
1358 /** A single-bit mask representing {@code public} access,
1359 * which may contribute to the result of {@link #lookupModes lookupModes}.
1360 * The value, {@code 0x01}, happens to be the same as the value of the
1361 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1362 * <p>
1363 * A {@code Lookup} with this lookup mode performs cross-module access check
1364 * with respect to the {@linkplain #lookupClass() lookup class} and
1365 * {@linkplain #previousLookupClass() previous lookup class} if present.
1366 */
1367 public static final int PUBLIC = Modifier.PUBLIC;
1368
1369 /** A single-bit mask representing {@code private} access,
1370 * which may contribute to the result of {@link #lookupModes lookupModes}.
1371 * The value, {@code 0x02}, happens to be the same as the value of the
1372 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1373 */
1374 public static final int PRIVATE = Modifier.PRIVATE;
1375
1376 /** A single-bit mask representing {@code protected} access,
1377 * which may contribute to the result of {@link #lookupModes lookupModes}.
1378 * The value, {@code 0x04}, happens to be the same as the value of the
1379 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1380 */
1381 public static final int PROTECTED = Modifier.PROTECTED;
1382
1383 /** A single-bit mask representing {@code package} access (default access),
1384 * which may contribute to the result of {@link #lookupModes lookupModes}.
1385 * The value is {@code 0x08}, which does not correspond meaningfully to
1386 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1387 */
1388 public static final int PACKAGE = Modifier.STATIC;
1389
1390 /** A single-bit mask representing {@code module} access,
1391 * which may contribute to the result of {@link #lookupModes lookupModes}.
1392 * The value is {@code 0x10}, which does not correspond meaningfully to
1393 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1394 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1395 * with this lookup mode can access all public types in the module of the
1396 * lookup class and public types in packages exported by other modules
1397 * to the module of the lookup class.
1398 * <p>
1399 * If this lookup mode is set, the {@linkplain #previousLookupClass()
1400 * previous lookup class} is always {@code null}.
1401 *
1402 * @since 9
1403 */
1404 public static final int MODULE = PACKAGE << 1;
1405
1406 /** A single-bit mask representing {@code unconditional} access
1407 * which may contribute to the result of {@link #lookupModes lookupModes}.
1408 * The value is {@code 0x20}, which does not correspond meaningfully to
1409 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1410 * A {@code Lookup} with this lookup mode assumes {@linkplain
1411 * java.lang.Module#canRead(java.lang.Module) readability}.
1412 * This lookup mode can access all public members of public types
1413 * of all modules when the type is in a package that is {@link
1414 * java.lang.Module#isExported(String) exported unconditionally}.
1415 *
1416 * <p>
1417 * If this lookup mode is set, the {@linkplain #previousLookupClass()
1418 * previous lookup class} is always {@code null}.
1419 *
1420 * @since 9
1421 * @see #publicLookup()
1422 */
1423 public static final int UNCONDITIONAL = PACKAGE << 2;
1424
1425 /** A single-bit mask representing {@code original} access
1426 * which may contribute to the result of {@link #lookupModes lookupModes}.
1427 * The value is {@code 0x40}, which does not correspond meaningfully to
1428 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1429 *
1430 * <p>
1431 * If this lookup mode is set, the {@code Lookup} object must be
1432 * created by the original lookup class by calling
1433 * {@link MethodHandles#lookup()} method or by a bootstrap method
1434 * invoked by the VM. The {@code Lookup} object with this lookup
1435 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1436 *
1437 * @since 16
1438 */
1439 public static final int ORIGINAL = PACKAGE << 3;
1440
1441 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1442 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access
1443 private static final int TRUSTED = -1;
1444
1445 /*
1446 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1447 * Adjust 0 => PACKAGE
1448 */
1449 private static int fixmods(int mods) {
1450 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1451 if (Modifier.isPublic(mods))
1452 mods |= UNCONDITIONAL;
1453 return (mods != 0) ? mods : PACKAGE;
1454 }
1455
1456 /** Tells which class is performing the lookup. It is this class against
1457 * which checks are performed for visibility and access permissions.
1458 * <p>
1459 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1460 * access checks are performed against both the lookup class and the previous lookup class.
1461 * <p>
1462 * The class implies a maximum level of access permission,
1463 * but the permissions may be additionally limited by the bitmask
1464 * {@link #lookupModes lookupModes}, which controls whether non-public members
1465 * can be accessed.
1466 * @return the lookup class, on behalf of which this lookup object finds members
1467 * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1468 */
1469 public Class<?> lookupClass() {
1470 return lookupClass;
1471 }
1472
1473 /** Reports a lookup class in another module that this lookup object
1474 * was previously teleported from, or {@code null}.
1475 * <p>
1476 * A {@code Lookup} object produced by the factory methods, such as the
1477 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1478 * has {@code null} previous lookup class.
1479 * A {@code Lookup} object has a non-null previous lookup class
1480 * when this lookup was teleported from an old lookup class
1481 * in one module to a new lookup class in another module.
1482 *
1483 * @return the lookup class in another module that this lookup object was
1484 * previously teleported from, or {@code null}
1485 * @since 14
1486 * @see #in(Class)
1487 * @see MethodHandles#privateLookupIn(Class, Lookup)
1488 * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1489 */
1490 public Class<?> previousLookupClass() {
1491 return prevLookupClass;
1492 }
1493
1494 // This is just for calling out to MethodHandleImpl.
1495 private Class<?> lookupClassOrNull() {
1496 return (allowedModes == TRUSTED) ? null : lookupClass;
1497 }
1498
1499 /** Tells which access-protection classes of members this lookup object can produce.
1500 * The result is a bit-mask of the bits
1501 * {@linkplain #PUBLIC PUBLIC (0x01)},
1502 * {@linkplain #PRIVATE PRIVATE (0x02)},
1503 * {@linkplain #PROTECTED PROTECTED (0x04)},
1504 * {@linkplain #PACKAGE PACKAGE (0x08)},
1505 * {@linkplain #MODULE MODULE (0x10)},
1506 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1507 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1508 * <p>
1509 * A freshly-created lookup object
1510 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1511 * all possible bits set, except {@code UNCONDITIONAL}.
1512 * A lookup object on a new lookup class
1513 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1514 * may have some mode bits set to zero.
1515 * Mode bits can also be
1516 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1517 * Once cleared, mode bits cannot be restored from the downgraded lookup object.
1518 * The purpose of this is to restrict access via the new lookup object,
1519 * so that it can access only names which can be reached by the original
1520 * lookup object, and also by the new lookup class.
1521 * @return the lookup modes, which limit the kinds of access performed by this lookup object
1522 * @see #in
1523 * @see #dropLookupMode
1524 */
1525 public int lookupModes() {
1526 return allowedModes & ALL_MODES;
1527 }
1528
1529 /** Embody the current class (the lookupClass) as a lookup class
1530 * for method handle creation.
1531 * Must be called by from a method in this package,
1532 * which in turn is called by a method not in this package.
1533 */
1534 Lookup(Class<?> lookupClass) {
1535 this(lookupClass, null, FULL_POWER_MODES);
1536 }
1537
1538 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1539 assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1540 && prevLookupClass.getModule() != lookupClass.getModule());
1541 assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1542 this.lookupClass = lookupClass;
1543 this.prevLookupClass = prevLookupClass;
1544 this.allowedModes = allowedModes;
1545 }
1546
1547 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1548 // make sure we haven't accidentally picked up a privileged class:
1549 checkUnprivilegedlookupClass(lookupClass);
1550 return new Lookup(lookupClass, prevLookupClass, allowedModes);
1551 }
1552
1553 /**
1554 * Creates a lookup on the specified new lookup class.
1555 * The resulting object will report the specified
1556 * class as its own {@link #lookupClass() lookupClass}.
1557 *
1558 * <p>
1559 * However, the resulting {@code Lookup} object is guaranteed
1560 * to have no more access capabilities than the original.
1561 * In particular, access capabilities can be lost as follows:<ul>
1562 * <li>If the new lookup class is different from the old lookup class,
1563 * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1564 * <li>If the new lookup class is in a different module from the old one,
1565 * i.e. {@link #MODULE MODULE} access is lost.
1566 * <li>If the new lookup class is in a different package
1567 * than the old one, protected and default (package) members will not be accessible,
1568 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1569 * <li>If the new lookup class is not within the same package member
1570 * as the old one, private members will not be accessible, and protected members
1571 * will not be accessible by virtue of inheritance,
1572 * i.e. {@link #PRIVATE PRIVATE} access is lost.
1573 * (Protected members may continue to be accessible because of package sharing.)
1574 * <li>If the new lookup class is not
1575 * {@linkplain #accessClass(Class) accessible} to this lookup,
1576 * then no members, not even public members, will be accessible
1577 * i.e. all access modes are lost.
1578 * <li>If the new lookup class, the old lookup class and the previous lookup class
1579 * are all in different modules i.e. teleporting to a third module,
1580 * all access modes are lost.
1581 * </ul>
1582 * <p>
1583 * The new previous lookup class is chosen as follows:
1584 * <ul>
1585 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1586 * the new previous lookup class is {@code null}.
1587 * <li>If the new lookup class is in the same module as the old lookup class,
1588 * the new previous lookup class is the old previous lookup class.
1589 * <li>If the new lookup class is in a different module from the old lookup class,
1590 * the new previous lookup class is the old lookup class.
1591 *</ul>
1592 * <p>
1593 * The resulting lookup's capabilities for loading classes
1594 * (used during {@link #findClass} invocations)
1595 * are determined by the lookup class' loader,
1596 * which may change due to this operation.
1597 *
1598 * @param requestedLookupClass the desired lookup class for the new lookup object
1599 * @return a lookup object which reports the desired lookup class, or the same object
1600 * if there is no change
1601 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1602 * @throws NullPointerException if the argument is null
1603 *
1604 * @see #accessClass(Class)
1605 * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1606 */
1607 public Lookup in(Class<?> requestedLookupClass) {
1608 Objects.requireNonNull(requestedLookupClass);
1609 if (requestedLookupClass.isPrimitive())
1610 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1611 if (requestedLookupClass.isArray())
1612 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1613
1614 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all
1615 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1616 if (requestedLookupClass == this.lookupClass)
1617 return this; // keep same capabilities
1618 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1619 Module fromModule = this.lookupClass.getModule();
1620 Module targetModule = requestedLookupClass.getModule();
1621 Class<?> plc = this.previousLookupClass();
1622 if ((this.allowedModes & UNCONDITIONAL) != 0) {
1623 assert plc == null;
1624 newModes = UNCONDITIONAL;
1625 } else if (fromModule != targetModule) {
1626 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1627 // allow hopping back and forth between fromModule and plc's module
1628 // but not the third module
1629 newModes = 0;
1630 }
1631 // drop MODULE access
1632 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1633 // teleport from this lookup class
1634 plc = this.lookupClass;
1635 }
1636 if ((newModes & PACKAGE) != 0
1637 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1638 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1639 }
1640 // Allow nestmate lookups to be created without special privilege:
1641 if ((newModes & PRIVATE) != 0
1642 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1643 newModes &= ~(PRIVATE|PROTECTED);
1644 }
1645 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1646 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1647 // The requested class it not accessible from the lookup class.
1648 // No permissions.
1649 newModes = 0;
1650 }
1651 return newLookup(requestedLookupClass, plc, newModes);
1652 }
1653
1654 /**
1655 * Creates a lookup on the same lookup class which this lookup object
1656 * finds members, but with a lookup mode that has lost the given lookup mode.
1657 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1658 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1659 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1660 * {@link #UNCONDITIONAL UNCONDITIONAL}.
1661 *
1662 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1663 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1664 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1665 * lookup has no access.
1666 *
1667 * <p> If this lookup is not a public lookup, then the following applies
1668 * regardless of its {@linkplain #lookupModes() lookup modes}.
1669 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1670 * dropped and so the resulting lookup mode will never have these access
1671 * capabilities. When dropping {@code PACKAGE}
1672 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1673 * access. When dropping {@code MODULE} then the resulting lookup will not
1674 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1675 * When dropping {@code PUBLIC} then the resulting lookup has no access.
1676 *
1677 * @apiNote
1678 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1679 * delegate non-public access within the package of the lookup class without
1680 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1681 * A lookup with {@code MODULE} but not
1682 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1683 * the module of the lookup class without conferring package access.
1684 * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1685 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1686 * to public classes accessible to both the module of the lookup class
1687 * and the module of the previous lookup class.
1688 *
1689 * @param modeToDrop the lookup mode to drop
1690 * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1691 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1692 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1693 * or {@code UNCONDITIONAL}
1694 * @see MethodHandles#privateLookupIn
1695 * @since 9
1696 */
1697 public Lookup dropLookupMode(int modeToDrop) {
1698 int oldModes = lookupModes();
1699 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1700 switch (modeToDrop) {
1701 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1702 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1703 case PACKAGE: newModes &= ~(PRIVATE); break;
1704 case PROTECTED:
1705 case PRIVATE:
1706 case ORIGINAL:
1707 case UNCONDITIONAL: break;
1708 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1709 }
1710 if (newModes == oldModes) return this; // return self if no change
1711 return newLookup(lookupClass(), previousLookupClass(), newModes);
1712 }
1713
1714 /**
1715 * Creates and links a class or interface from {@code bytes}
1716 * with the same class loader and in the same runtime package and
1717 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1718 * {@linkplain #lookupClass() lookup class} as if calling
1719 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1720 * ClassLoader::defineClass}.
1721 *
1722 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1723 * {@link #PACKAGE PACKAGE} access as default (package) members will be
1724 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1725 * that the lookup object was created by a caller in the runtime package (or derived
1726 * from a lookup originally created by suitably privileged code to a target class in
1727 * the runtime package). </p>
1728 *
1729 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1730 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1731 * same package as the lookup class. </p>
1732 *
1733 * <p> This method does not run the class initializer. The class initializer may
1734 * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1735 * Specification</em>. </p>
1736 *
1737 * @param bytes the class bytes
1738 * @return the {@code Class} object for the class
1739 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1740 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1741 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1742 * than the lookup class or {@code bytes} is not a class or interface
1743 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1744 * @throws VerifyError if the newly created class cannot be verified
1745 * @throws LinkageError if the newly created class cannot be linked for any other reason
1746 * @throws NullPointerException if {@code bytes} is {@code null}
1747 * @since 9
1748 * @see MethodHandles#privateLookupIn
1749 * @see Lookup#dropLookupMode
1750 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1751 */
1752 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1753 if ((lookupModes() & PACKAGE) == 0)
1754 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1755 return makeClassDefiner(bytes.clone()).defineClass(false);
1756 }
1757
1758 /**
1759 * The set of class options that specify whether a hidden class created by
1760 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1761 * Lookup::defineHiddenClass} method is dynamically added as a new member
1762 * to the nest of a lookup class and/or whether a hidden class has
1763 * a strong relationship with the class loader marked as its defining loader.
1764 *
1765 * @since 15
1766 */
1767 public enum ClassOption {
1768 /**
1769 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1770 * of a lookup class as a nestmate.
1771 *
1772 * <p> A hidden nestmate class has access to the private members of all
1773 * classes and interfaces in the same nest.
1774 *
1775 * @see Class#getNestHost()
1776 */
1777 NESTMATE(NESTMATE_CLASS),
1778
1779 /**
1780 * Specifies that a hidden class has a <em>strong</em>
1781 * relationship with the class loader marked as its defining loader,
1782 * as a normal class or interface has with its own defining loader.
1783 * This means that the hidden class may be unloaded if and only if
1784 * its defining loader is not reachable and thus may be reclaimed
1785 * by a garbage collector (JLS {@jls 12.7}).
1786 *
1787 * <p> By default, a hidden class or interface may be unloaded
1788 * even if the class loader that is marked as its defining loader is
1789 * <a href="../ref/package-summary.html#reachability">reachable</a>.
1790
1791 *
1792 * @jls 12.7 Unloading of Classes and Interfaces
1793 */
1794 STRONG(STRONG_LOADER_LINK);
1795
1796 /* the flag value is used by VM at define class time */
1797 private final int flag;
1798 ClassOption(int flag) {
1799 this.flag = flag;
1800 }
1801
1802 static int optionsToFlag(ClassOption[] options) {
1803 int flags = 0;
1804 for (ClassOption cp : options) {
1805 if ((flags & cp.flag) != 0) {
1806 throw new IllegalArgumentException("Duplicate ClassOption " + cp);
1807 }
1808 flags |= cp.flag;
1809 }
1810 return flags;
1811 }
1812 }
1813
1814 /**
1815 * Creates a <em>hidden</em> class or interface from {@code bytes},
1816 * returning a {@code Lookup} on the newly created class or interface.
1817 *
1818 * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1819 * which either defines {@code C} directly or delegates to another class loader.
1820 * A class loader defines {@code C} directly by invoking
1821 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1822 * ClassLoader::defineClass}, which causes the Java Virtual Machine
1823 * to derive {@code C} from a purported representation in {@code class} file format.
1824 * In situations where use of a class loader is undesirable, a class or interface
1825 * {@code C} can be created by this method instead. This method is capable of
1826 * defining {@code C}, and thereby creating it, without invoking
1827 * {@code ClassLoader::defineClass}.
1828 * Instead, this method defines {@code C} as if by arranging for
1829 * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1830 * from a purported representation in {@code class} file format
1831 * using the following rules:
1832 *
1833 * <ol>
1834 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1835 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1836 * This level of access is needed to create {@code C} in the module
1837 * of the lookup class of this {@code Lookup}.</li>
1838 *
1839 * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1840 * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1841 * The major and minor version may differ from the {@code class} file version
1842 * of the lookup class of this {@code Lookup}.</li>
1843 *
1844 * <li> The value of {@code this_class} must be a valid index in the
1845 * {@code constant_pool} table, and the entry at that index must be a valid
1846 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1847 * encoded in internal form that is specified by this structure. {@code N} must
1848 * denote a class or interface in the same package as the lookup class.</li>
1849 *
1850 * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1851 * where {@code <suffix>} is an unqualified name.
1852 *
1853 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1854 * {@code bytes} with an additional entry in the {@code constant_pool} table,
1855 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1856 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1857 * refers to the new {@code CONSTANT_Utf8_info} structure.
1858 *
1859 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1860 *
1861 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1862 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1863 * with the following adjustments:
1864 * <ul>
1865 * <li> The constant indicated by {@code this_class} is permitted to specify a name
1866 * that includes a single {@code "."} character, even though this is not a valid
1867 * binary class or interface name in internal form.</li>
1868 *
1869 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1870 * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1871 *
1872 * <li> {@code C} is considered to have the same runtime
1873 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1874 * and {@linkplain java.security.ProtectionDomain protection domain}
1875 * as the lookup class of this {@code Lookup}.
1876 * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1877 * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1878 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1879 * <ul>
1880 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1881 * even though this is not a valid binary class or interface name.</li>
1882 * <li> {@link Class#descriptorString()} returns the string
1883 * {@code "L" + N + "." + <suffix> + ";"},
1884 * even though this is not a valid type descriptor name.</li>
1885 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1886 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1887 * </ul>
1888 * </ul>
1889 * </li>
1890 * </ol>
1891 *
1892 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1893 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1894 * <ul>
1895 * <li> During verification, whenever it is necessary to load the class named
1896 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1897 * made of any class loader.</li>
1898 *
1899 * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1900 * by {@code this_class}, the symbolic reference is considered to be resolved to
1901 * {@code C} and resolution always succeeds immediately.</li>
1902 * </ul>
1903 *
1904 * <p> If the {@code initialize} parameter is {@code true},
1905 * then {@code C} is initialized by the Java Virtual Machine.
1906 *
1907 * <p> The newly created class or interface {@code C} serves as the
1908 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
1909 * returned by this method. {@code C} is <em>hidden</em> in the sense that
1910 * no other class or interface can refer to {@code C} via a constant pool entry.
1911 * That is, a hidden class or interface cannot be named as a supertype, a field type,
1912 * a method parameter type, or a method return type by any other class.
1913 * This is because a hidden class or interface does not have a binary name, so
1914 * there is no internal form available to record in any class's constant pool.
1915 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1916 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1917 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
1918 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1919 * JVM Tool Interface</a>.
1920 *
1921 * <p> A class or interface created by
1922 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1923 * a class loader} has a strong relationship with that class loader.
1924 * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
1925 * that {@linkplain Class#getClassLoader() defined it}.
1926 * This means that a class created by a class loader may be unloaded if and
1927 * only if its defining loader is not reachable and thus may be reclaimed
1928 * by a garbage collector (JLS {@jls 12.7}).
1929 *
1930 * By default, however, a hidden class or interface may be unloaded even if
1931 * the class loader that is marked as its defining loader is
1932 * <a href="../ref/package-summary.html#reachability">reachable</a>.
1933 * This behavior is useful when a hidden class or interface serves multiple
1934 * classes defined by arbitrary class loaders. In other cases, a hidden
1935 * class or interface may be linked to a single class (or a small number of classes)
1936 * with the same defining loader as the hidden class or interface.
1937 * In such cases, where the hidden class or interface must be coterminous
1938 * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
1939 * option may be passed in {@code options}.
1940 * This arranges for a hidden class to have the same strong relationship
1941 * with the class loader marked as its defining loader,
1942 * as a normal class or interface has with its own defining loader.
1943 *
1944 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
1945 * may still prevent a hidden class or interface from being
1946 * unloaded by ensuring that the {@code Class} object is reachable.
1947 *
1948 * <p> The unloading characteristics are set for each hidden class when it is
1949 * defined, and cannot be changed later. An advantage of allowing hidden classes
1950 * to be unloaded independently of the class loader marked as their defining loader
1951 * is that a very large number of hidden classes may be created by an application.
1952 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
1953 * just as if normal classes were created by class loaders.
1954 *
1955 * <p> Classes and interfaces in a nest are allowed to have mutual access to
1956 * their private members. The nest relationship is determined by
1957 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
1958 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
1959 * By default, a hidden class belongs to a nest consisting only of itself
1960 * because a hidden class has no binary name.
1961 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
1962 * to create a hidden class or interface {@code C} as a member of a nest.
1963 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
1964 * in the {@code ClassFile} structure from which {@code C} was derived.
1965 * Instead, the following rules determine the nest host of {@code C}:
1966 * <ul>
1967 * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1968 * been determined, then let {@code H} be the nest host of the lookup class.
1969 * Otherwise, the nest host of the lookup class is determined using the
1970 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
1971 * <li>The nest host of {@code C} is determined to be {@code H},
1972 * the nest host of the lookup class.</li>
1973 * </ul>
1974 *
1975 * <p> A hidden class or interface may be serializable, but this requires a custom
1976 * serialization mechanism in order to ensure that instances are properly serialized
1977 * and deserialized. The default serialization mechanism supports only classes and
1978 * interfaces that are discoverable by their class name.
1979 *
1980 * @param bytes the bytes that make up the class data,
1981 * in the format of a valid {@code class} file as defined by
1982 * <cite>The Java Virtual Machine Specification</cite>.
1983 * @param initialize if {@code true} the class will be initialized.
1984 * @param options {@linkplain ClassOption class options}
1985 * @return the {@code Lookup} object on the hidden class,
1986 * with {@linkplain #ORIGINAL original} and
1987 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
1988 *
1989 * @throws IllegalAccessException if this {@code Lookup} does not have
1990 * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1991 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1992 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1993 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1994 * than the lookup class or {@code bytes} is not a class or interface
1995 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1996 * @throws IncompatibleClassChangeError if the class or interface named as
1997 * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1998 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1999 * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2000 * {@code C} is {@code C} itself
2001 * @throws VerifyError if the newly created class cannot be verified
2002 * @throws LinkageError if the newly created class cannot be linked for any other reason
2003 * @throws NullPointerException if any parameter is {@code null}
2004 *
2005 * @since 15
2006 * @see Class#isHidden()
2007 * @jvms 4.2.1 Binary Class and Interface Names
2008 * @jvms 4.2.2 Unqualified Names
2009 * @jvms 4.7.28 The {@code NestHost} Attribute
2010 * @jvms 4.7.29 The {@code NestMembers} Attribute
2011 * @jvms 5.4.3.1 Class and Interface Resolution
2012 * @jvms 5.4.4 Access Control
2013 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2014 * @jvms 5.4 Linking
2015 * @jvms 5.5 Initialization
2016 * @jls 12.7 Unloading of Classes and Interfaces
2017 */
2018 @SuppressWarnings("doclint:reference") // cross-module links
2019 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2020 throws IllegalAccessException
2021 {
2022 Objects.requireNonNull(bytes);
2023 int flags = ClassOption.optionsToFlag(options);
2024 if (!hasFullPrivilegeAccess()) {
2025 throw new IllegalAccessException(this + " does not have full privilege access");
2026 }
2027
2028 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize);
2029 }
2030
2031 /**
2032 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2033 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2034 * returning a {@code Lookup} on the newly created class or interface.
2035 *
2036 * <p> This method is equivalent to calling
2037 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2038 * as if the hidden class is injected with a private static final <i>unnamed</i>
2039 * field which is initialized with the given {@code classData} at
2040 * the first instruction of the class initializer.
2041 * The newly created class is linked by the Java Virtual Machine.
2042 *
2043 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2044 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2045 * methods can be used to retrieve the {@code classData}.
2046 *
2047 * @apiNote
2048 * A framework can create a hidden class with class data with one or more
2049 * objects and load the class data as dynamically-computed constant(s)
2050 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class)
2051 * Class data} is accessible only to the lookup object created by the newly
2052 * defined hidden class but inaccessible to other members in the same nest
2053 * (unlike private static fields that are accessible to nestmates).
2054 * Care should be taken w.r.t. mutability for example when passing
2055 * an array or other mutable structure through the class data.
2056 * Changing any value stored in the class data at runtime may lead to
2057 * unpredictable behavior.
2058 * If the class data is a {@code List}, it is good practice to make it
2059 * unmodifiable for example via {@link List#of List::of}.
2060 *
2061 * @param bytes the class bytes
2062 * @param classData pre-initialized class data
2063 * @param initialize if {@code true} the class will be initialized.
2064 * @param options {@linkplain ClassOption class options}
2065 * @return the {@code Lookup} object on the hidden class,
2066 * with {@linkplain #ORIGINAL original} and
2067 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2068 *
2069 * @throws IllegalAccessException if this {@code Lookup} does not have
2070 * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2071 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2072 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2073 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2074 * than the lookup class or {@code bytes} is not a class or interface
2075 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2076 * @throws IncompatibleClassChangeError if the class or interface named as
2077 * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2078 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2079 * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2080 * {@code C} is {@code C} itself
2081 * @throws VerifyError if the newly created class cannot be verified
2082 * @throws LinkageError if the newly created class cannot be linked for any other reason
2083 * @throws NullPointerException if any parameter is {@code null}
2084 *
2085 * @since 16
2086 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2087 * @see Class#isHidden()
2088 * @see MethodHandles#classData(Lookup, String, Class)
2089 * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2090 * @jvms 4.2.1 Binary Class and Interface Names
2091 * @jvms 4.2.2 Unqualified Names
2092 * @jvms 4.7.28 The {@code NestHost} Attribute
2093 * @jvms 4.7.29 The {@code NestMembers} Attribute
2094 * @jvms 5.4.3.1 Class and Interface Resolution
2095 * @jvms 5.4.4 Access Control
2096 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2097 * @jvms 5.4 Linking
2098 * @jvms 5.5 Initialization
2099 * @jls 12.7 Unloading of Classes and Interfaces
2100 */
2101 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2102 throws IllegalAccessException
2103 {
2104 Objects.requireNonNull(bytes);
2105 Objects.requireNonNull(classData);
2106
2107 int flags = ClassOption.optionsToFlag(options);
2108
2109 if (!hasFullPrivilegeAccess()) {
2110 throw new IllegalAccessException(this + " does not have full privilege access");
2111 }
2112
2113 return makeHiddenClassDefiner(bytes.clone(), false, flags)
2114 .defineClassAsLookup(initialize, classData);
2115 }
2116
2117 // A default dumper for writing class files passed to Lookup::defineClass
2118 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable,
2119 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2120 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2121 //
2122 // This default dumper does not dump hidden classes defined by LambdaMetafactory
2123 // and LambdaForms and method handle internals. They are dumped via
2124 // different ClassFileDumpers.
2125 private static ClassFileDumper defaultDumper() {
2126 return DEFAULT_DUMPER;
2127 }
2128
2129 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2130 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2131
2132 /**
2133 * This method checks the class file version and the structure of `this_class`.
2134 * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2135 * that is in the named package.
2136 *
2137 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2138 * or the class is not in the given package name.
2139 */
2140 static String validateAndFindInternalName(byte[] bytes, String pkgName) {
2141 int magic = readInt(bytes, 0);
2142 if (magic != ClassFile.MAGIC_NUMBER) {
2143 throw new ClassFormatError("Incompatible magic value: " + magic);
2144 }
2145 // We have to read major and minor this way as ClassFile API throws IAE
2146 // yet we want distinct ClassFormatError and UnsupportedClassVersionError
2147 int minor = readUnsignedShort(bytes, 4);
2148 int major = readUnsignedShort(bytes, 6);
2149
2150 if (!VM.isSupportedClassFileVersion(major, minor)) {
2151 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2152 }
2153
2154 String name;
2155 ClassDesc sym;
2156 int accessFlags;
2157 try {
2158 ClassModel cm = ClassFile.of().parse(bytes);
2159 var thisClass = cm.thisClass();
2160 name = thisClass.asInternalName();
2161 sym = thisClass.asSymbol();
2162 accessFlags = cm.flags().flagsMask();
2163 } catch (IllegalArgumentException e) {
2164 ClassFormatError cfe = new ClassFormatError();
2165 cfe.initCause(e);
2166 throw cfe;
2167 }
2168 // must be a class or interface
2169 if ((accessFlags & ACC_MODULE) != 0) {
2170 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2171 }
2172
2173 String pn = sym.packageName();
2174 if (!pn.equals(pkgName)) {
2175 throw newIllegalArgumentException(name + " not in same package as lookup class");
2176 }
2177
2178 return name;
2179 }
2180
2181 private static int readInt(byte[] bytes, int offset) {
2182 if ((offset + 4) > bytes.length) {
2183 throw new ClassFormatError("Invalid ClassFile structure");
2184 }
2185 return ((bytes[offset] & 0xFF) << 24)
2186 | ((bytes[offset + 1] & 0xFF) << 16)
2187 | ((bytes[offset + 2] & 0xFF) << 8)
2188 | (bytes[offset + 3] & 0xFF);
2189 }
2190
2191 private static int readUnsignedShort(byte[] bytes, int offset) {
2192 if ((offset+2) > bytes.length) {
2193 throw new ClassFormatError("Invalid ClassFile structure");
2194 }
2195 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2196 }
2197
2198 /*
2199 * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2200 * from the given bytes.
2201 *
2202 * Caller should make a defensive copy of the arguments if needed
2203 * before calling this factory method.
2204 *
2205 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2206 * {@code bytes} denotes a class in a different package than the lookup class
2207 */
2208 private ClassDefiner makeClassDefiner(byte[] bytes) {
2209 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName());
2210 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper());
2211 }
2212
2213 /**
2214 * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2215 * from the given bytes. No package name check on the given bytes.
2216 *
2217 * @param internalName internal name
2218 * @param bytes class bytes
2219 * @param dumper dumper to write the given bytes to the dumper's output directory
2220 * @return ClassDefiner that defines a normal class of the given bytes.
2221 */
2222 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) {
2223 // skip package name validation
2224 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper);
2225 }
2226
2227 /**
2228 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2229 * from the given bytes. The name must be in the same package as the lookup class.
2230 *
2231 * Caller should make a defensive copy of the arguments if needed
2232 * before calling this factory method.
2233 *
2234 * @param bytes class bytes
2235 * @param dumper dumper to write the given bytes to the dumper's output directory
2236 * @return ClassDefiner that defines a hidden class of the given bytes.
2237 *
2238 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2239 * {@code bytes} denotes a class in a different package than the lookup class
2240 */
2241 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2242 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName());
2243 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0);
2244 }
2245
2246 /**
2247 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2248 * from the given bytes and options.
2249 * The name must be in the same package as the lookup class.
2250 *
2251 * Caller should make a defensive copy of the arguments if needed
2252 * before calling this factory method.
2253 *
2254 * @param bytes class bytes
2255 * @param flags class option flag mask
2256 * @param accessVmAnnotations true to give the hidden class access to VM annotations
2257 * @return ClassDefiner that defines a hidden class of the given bytes and options
2258 *
2259 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2260 * {@code bytes} denotes a class in a different package than the lookup class
2261 */
2262 private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2263 boolean accessVmAnnotations,
2264 int flags) {
2265 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName());
2266 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags);
2267 }
2268
2269 /**
2270 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2271 * from the given bytes and the given options. No package name check on the given bytes.
2272 *
2273 * @param internalName internal name that specifies the prefix of the hidden class
2274 * @param bytes class bytes
2275 * @param dumper dumper to write the given bytes to the dumper's output directory
2276 * @return ClassDefiner that defines a hidden class of the given bytes and options.
2277 */
2278 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) {
2279 Objects.requireNonNull(dumper);
2280 // skip name and access flags validation
2281 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0);
2282 }
2283
2284 /**
2285 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2286 * from the given bytes and the given options. No package name check on the given bytes.
2287 *
2288 * @param internalName internal name that specifies the prefix of the hidden class
2289 * @param bytes class bytes
2290 * @param flags class options flag mask
2291 * @param dumper dumper to write the given bytes to the dumper's output directory
2292 * @return ClassDefiner that defines a hidden class of the given bytes and options.
2293 */
2294 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) {
2295 Objects.requireNonNull(dumper);
2296 // skip name and access flags validation
2297 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags);
2298 }
2299
2300 /**
2301 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2302 * from the given class file and options.
2303 *
2304 * @param internalName internal name
2305 * @param bytes Class byte array
2306 * @param flags class option flag mask
2307 * @param accessVmAnnotations true to give the hidden class access to VM annotations
2308 * @param dumper dumper to write the given bytes to the dumper's output directory
2309 */
2310 private ClassDefiner makeHiddenClassDefiner(String internalName,
2311 byte[] bytes,
2312 boolean accessVmAnnotations,
2313 ClassFileDumper dumper,
2314 int flags) {
2315 flags |= HIDDEN_CLASS;
2316 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2317 // jdk.internal.vm.annotations are permitted for classes
2318 // defined to boot loader and platform loader
2319 flags |= ACCESS_VM_ANNOTATIONS;
2320 }
2321
2322 return new ClassDefiner(this, internalName, bytes, flags, dumper);
2323 }
2324
2325 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) {
2326 ClassDefiner {
2327 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2328 }
2329
2330 Class<?> defineClass(boolean initialize) {
2331 return defineClass(initialize, null);
2332 }
2333
2334 Lookup defineClassAsLookup(boolean initialize) {
2335 Class<?> c = defineClass(initialize, null);
2336 return new Lookup(c, null, FULL_POWER_MODES);
2337 }
2338
2339 /**
2340 * Defines the class of the given bytes and the given classData.
2341 * If {@code initialize} parameter is true, then the class will be initialized.
2342 *
2343 * @param initialize true if the class to be initialized
2344 * @param classData classData or null
2345 * @return the class
2346 *
2347 * @throws LinkageError linkage error
2348 */
2349 Class<?> defineClass(boolean initialize, Object classData) {
2350 Class<?> lookupClass = lookup.lookupClass();
2351 ClassLoader loader = lookupClass.getClassLoader();
2352 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2353 Class<?> c = null;
2354 try {
2355 c = SharedSecrets.getJavaLangAccess()
2356 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData);
2357 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2358 return c;
2359 } finally {
2360 // dump the classfile for debugging
2361 if (dumper.isEnabled()) {
2362 String name = internalName();
2363 if (c != null) {
2364 dumper.dumpClass(name, c, bytes);
2365 } else {
2366 dumper.dumpFailedClass(name, bytes);
2367 }
2368 }
2369 }
2370 }
2371
2372 /**
2373 * Defines the class of the given bytes and the given classData.
2374 * If {@code initialize} parameter is true, then the class will be initialized.
2375 *
2376 * @param initialize true if the class to be initialized
2377 * @param classData classData or null
2378 * @return a Lookup for the defined class
2379 *
2380 * @throws LinkageError linkage error
2381 */
2382 Lookup defineClassAsLookup(boolean initialize, Object classData) {
2383 Class<?> c = defineClass(initialize, classData);
2384 return new Lookup(c, null, FULL_POWER_MODES);
2385 }
2386
2387 private boolean isNestmate() {
2388 return (classFlags & NESTMATE_CLASS) != 0;
2389 }
2390 }
2391
2392 private ProtectionDomain lookupClassProtectionDomain() {
2393 ProtectionDomain pd = cachedProtectionDomain;
2394 if (pd == null) {
2395 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2396 }
2397 return pd;
2398 }
2399
2400 // cached protection domain
2401 private volatile ProtectionDomain cachedProtectionDomain;
2402
2403 // Make sure outer class is initialized first.
2404 static { IMPL_NAMES.getClass(); }
2405
2406 /** Package-private version of lookup which is trusted. */
2407 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2408
2409 /** Version of lookup which is trusted minimally.
2410 * It can only be used to create method handles to publicly accessible
2411 * members in packages that are exported unconditionally.
2412 */
2413 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2414
2415 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2416 String name = lookupClass.getName();
2417 if (name.startsWith("java.lang.invoke."))
2418 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2419 }
2420
2421 /**
2422 * Displays the name of the class from which lookups are to be made,
2423 * followed by "/" and the name of the {@linkplain #previousLookupClass()
2424 * previous lookup class} if present.
2425 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2426 * If there are restrictions on the access permitted to this lookup,
2427 * this is indicated by adding a suffix to the class name, consisting
2428 * of a slash and a keyword. The keyword represents the strongest
2429 * allowed access, and is chosen as follows:
2430 * <ul>
2431 * <li>If no access is allowed, the suffix is "/noaccess".
2432 * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2433 * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2434 * <li>If only public and module access are allowed, the suffix is "/module".
2435 * <li>If public and package access are allowed, the suffix is "/package".
2436 * <li>If public, package, and private access are allowed, the suffix is "/private".
2437 * </ul>
2438 * If none of the above cases apply, it is the case that
2439 * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2440 * (public, module, package, private, and protected) is allowed.
2441 * In this case, no suffix is added.
2442 * This is true only of an object obtained originally from
2443 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2444 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2445 * always have restricted access, and will display a suffix.
2446 * <p>
2447 * (It may seem strange that protected access should be
2448 * stronger than private access. Viewed independently from
2449 * package access, protected access is the first to be lost,
2450 * because it requires a direct subclass relationship between
2451 * caller and callee.)
2452 * @see #in
2453 */
2454 @Override
2455 public String toString() {
2456 String cname = lookupClass.getName();
2457 if (prevLookupClass != null)
2458 cname += "/" + prevLookupClass.getName();
2459 switch (allowedModes) {
2460 case 0: // no privileges
2461 return cname + "/noaccess";
2462 case UNCONDITIONAL:
2463 return cname + "/publicLookup";
2464 case PUBLIC:
2465 return cname + "/public";
2466 case PUBLIC|MODULE:
2467 return cname + "/module";
2468 case PUBLIC|PACKAGE:
2469 case PUBLIC|MODULE|PACKAGE:
2470 return cname + "/package";
2471 case PUBLIC|PACKAGE|PRIVATE:
2472 case PUBLIC|MODULE|PACKAGE|PRIVATE:
2473 return cname + "/private";
2474 case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2475 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2476 case FULL_POWER_MODES:
2477 return cname;
2478 case TRUSTED:
2479 return "/trusted"; // internal only; not exported
2480 default: // Should not happen, but it's a bitfield...
2481 cname = cname + "/" + Integer.toHexString(allowedModes);
2482 assert(false) : cname;
2483 return cname;
2484 }
2485 }
2486
2487 /**
2488 * Produces a method handle for a static method.
2489 * The type of the method handle will be that of the method.
2490 * (Since static methods do not take receivers, there is no
2491 * additional receiver argument inserted into the method handle type,
2492 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2493 * The method and all its argument types must be accessible to the lookup object.
2494 * <p>
2495 * The returned method handle will have
2496 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2497 * the method's variable arity modifier bit ({@code 0x0080}) is set.
2498 * <p>
2499 * If the returned method handle is invoked, the method's class will
2500 * be initialized, if it has not already been initialized.
2501 * <p><b>Example:</b>
2502 * {@snippet lang="java" :
2503 import static java.lang.invoke.MethodHandles.*;
2504 import static java.lang.invoke.MethodType.*;
2505 ...
2506 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2507 "asList", methodType(List.class, Object[].class));
2508 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2509 * }
2510 * @param refc the class from which the method is accessed
2511 * @param name the name of the method
2512 * @param type the type of the method
2513 * @return the desired method handle
2514 * @throws NoSuchMethodException if the method does not exist
2515 * @throws IllegalAccessException if access checking fails,
2516 * or if the method is not {@code static},
2517 * or if the method's variable arity modifier bit
2518 * is set and {@code asVarargsCollector} fails
2519 * @throws NullPointerException if any argument is null
2520 */
2521 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2522 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2523 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2524 }
2525
2526 /**
2527 * Produces a method handle for a virtual method.
2528 * The type of the method handle will be that of the method,
2529 * with the receiver type (usually {@code refc}) prepended.
2530 * The method and all its argument types must be accessible to the lookup object.
2531 * <p>
2532 * When called, the handle will treat the first argument as a receiver
2533 * and, for non-private methods, dispatch on the receiver's type to determine which method
2534 * implementation to enter.
2535 * For private methods the named method in {@code refc} will be invoked on the receiver.
2536 * (The dispatching action is identical with that performed by an
2537 * {@code invokevirtual} or {@code invokeinterface} instruction.)
2538 * <p>
2539 * The first argument will be of type {@code refc} if the lookup
2540 * class has full privileges to access the member. Otherwise
2541 * the member must be {@code protected} and the first argument
2542 * will be restricted in type to the lookup class.
2543 * <p>
2544 * The returned method handle will have
2545 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2546 * the method's variable arity modifier bit ({@code 0x0080}) is set.
2547 * <p>
2548 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2549 * instructions and method handles produced by {@code findVirtual},
2550 * if the class is {@code MethodHandle} and the name string is
2551 * {@code invokeExact} or {@code invoke}, the resulting
2552 * method handle is equivalent to one produced by
2553 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2554 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2555 * with the same {@code type} argument.
2556 * <p>
2557 * If the class is {@code VarHandle} and the name string corresponds to
2558 * the name of a signature-polymorphic access mode method, the resulting
2559 * method handle is equivalent to one produced by
2560 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2561 * the access mode corresponding to the name string and with the same
2562 * {@code type} arguments.
2563 * <p>
2564 * <b>Example:</b>
2565 * {@snippet lang="java" :
2566 import static java.lang.invoke.MethodHandles.*;
2567 import static java.lang.invoke.MethodType.*;
2568 ...
2569 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2570 "concat", methodType(String.class, String.class));
2571 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2572 "hashCode", methodType(int.class));
2573 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2574 "hashCode", methodType(int.class));
2575 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2576 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2577 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2578 // interface method:
2579 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2580 "subSequence", methodType(CharSequence.class, int.class, int.class));
2581 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2582 // constructor "internal method" must be accessed differently:
2583 MethodType MT_newString = methodType(void.class); //()V for new String()
2584 try { assertEquals("impossible", lookup()
2585 .findVirtual(String.class, "<init>", MT_newString));
2586 } catch (NoSuchMethodException ex) { } // OK
2587 MethodHandle MH_newString = publicLookup()
2588 .findConstructor(String.class, MT_newString);
2589 assertEquals("", (String) MH_newString.invokeExact());
2590 * }
2591 *
2592 * @param refc the class or interface from which the method is accessed
2593 * @param name the name of the method
2594 * @param type the type of the method, with the receiver argument omitted
2595 * @return the desired method handle
2596 * @throws NoSuchMethodException if the method does not exist
2597 * @throws IllegalAccessException if access checking fails,
2598 * or if the method is {@code static},
2599 * or if the method's variable arity modifier bit
2600 * is set and {@code asVarargsCollector} fails
2601 * @throws NullPointerException if any argument is null
2602 */
2603 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2604 if (refc == MethodHandle.class) {
2605 MethodHandle mh = findVirtualForMH(name, type);
2606 if (mh != null) return mh;
2607 } else if (refc == VarHandle.class) {
2608 MethodHandle mh = findVirtualForVH(name, type);
2609 if (mh != null) return mh;
2610 }
2611 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2612 MemberName method = resolveOrFail(refKind, refc, name, type);
2613 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2614 }
2615 private MethodHandle findVirtualForMH(String name, MethodType type) {
2616 // these names require special lookups because of the implicit MethodType argument
2617 if ("invoke".equals(name))
2618 return invoker(type);
2619 if ("invokeExact".equals(name))
2620 return exactInvoker(type);
2621 assert(!MemberName.isMethodHandleInvokeName(name));
2622 return null;
2623 }
2624 private MethodHandle findVirtualForVH(String name, MethodType type) {
2625 try {
2626 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2627 } catch (IllegalArgumentException e) {
2628 return null;
2629 }
2630 }
2631
2632 /**
2633 * Produces a method handle which creates an object and initializes it, using
2634 * the constructor of the specified type.
2635 * The parameter types of the method handle will be those of the constructor,
2636 * while the return type will be a reference to the constructor's class.
2637 * The constructor and all its argument types must be accessible to the lookup object.
2638 * <p>
2639 * The requested type must have a return type of {@code void}.
2640 * (This is consistent with the JVM's treatment of constructor type descriptors.)
2641 * <p>
2642 * The returned method handle will have
2643 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2644 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2645 * <p>
2646 * If the returned method handle is invoked, the constructor's class will
2647 * be initialized, if it has not already been initialized.
2648 * <p><b>Example:</b>
2649 * {@snippet lang="java" :
2650 import static java.lang.invoke.MethodHandles.*;
2651 import static java.lang.invoke.MethodType.*;
2652 ...
2653 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2654 ArrayList.class, methodType(void.class, Collection.class));
2655 Collection orig = Arrays.asList("x", "y");
2656 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2657 assert(orig != copy);
2658 assertEquals(orig, copy);
2659 // a variable-arity constructor:
2660 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2661 ProcessBuilder.class, methodType(void.class, String[].class));
2662 ProcessBuilder pb = (ProcessBuilder)
2663 MH_newProcessBuilder.invoke("x", "y", "z");
2664 assertEquals("[x, y, z]", pb.command().toString());
2665 * }
2666 * @param refc the class or interface from which the method is accessed
2667 * @param type the type of the method, with the receiver argument omitted, and a void return type
2668 * @return the desired method handle
2669 * @throws NoSuchMethodException if the constructor does not exist
2670 * @throws IllegalAccessException if access checking fails
2671 * or if the method's variable arity modifier bit
2672 * is set and {@code asVarargsCollector} fails
2673 * @throws NullPointerException if any argument is null
2674 */
2675 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2676 if (refc.isArray()) {
2677 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2678 }
2679 String name = ConstantDescs.INIT_NAME;
2680 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2681 return getDirectConstructor(refc, ctor);
2682 }
2683
2684 /**
2685 * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2686 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2687 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2688 * and then determines whether the class is accessible to this lookup object.
2689 * <p>
2690 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2691 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2692 * of {@code '['} and followed by the element type as encoded in the
2693 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2694 * <p>
2695 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2696 * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2697 *
2698 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2699 * or the string representing an array class
2700 * @return the requested class.
2701 * @throws LinkageError if the linkage fails
2702 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2703 * @throws IllegalAccessException if the class is not accessible, using the allowed access
2704 * modes.
2705 * @throws NullPointerException if {@code targetName} is null
2706 * @since 9
2707 * @jvms 5.4.3.1 Class and Interface Resolution
2708 */
2709 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2710 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2711 return accessClass(targetClass);
2712 }
2713
2714 /**
2715 * Ensures that {@code targetClass} has been initialized. The class
2716 * to be initialized must be {@linkplain #accessClass accessible}
2717 * to this {@code Lookup} object. This method causes {@code targetClass}
2718 * to be initialized if it has not been already initialized,
2719 * as specified in JVMS {@jvms 5.5}.
2720 *
2721 * <p>
2722 * This method returns when {@code targetClass} is fully initialized, or
2723 * when {@code targetClass} is being initialized by the current thread.
2724 *
2725 * @param <T> the type of the class to be initialized
2726 * @param targetClass the class to be initialized
2727 * @return {@code targetClass} that has been initialized, or that is being
2728 * initialized by the current thread.
2729 *
2730 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2731 * or array class
2732 * @throws IllegalAccessException if {@code targetClass} is not
2733 * {@linkplain #accessClass accessible} to this lookup
2734 * @throws ExceptionInInitializerError if the class initialization provoked
2735 * by this method fails
2736 * @since 15
2737 * @jvms 5.5 Initialization
2738 */
2739 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2740 if (targetClass.isPrimitive())
2741 throw new IllegalArgumentException(targetClass + " is a primitive class");
2742 if (targetClass.isArray())
2743 throw new IllegalArgumentException(targetClass + " is an array class");
2744
2745 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2746 throw makeAccessException(targetClass);
2747 }
2748
2749 // ensure class initialization
2750 Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2751 return targetClass;
2752 }
2753
2754 /*
2755 * Returns IllegalAccessException due to access violation to the given targetClass.
2756 *
2757 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2758 * which verifies access to a class rather a member.
2759 */
2760 private IllegalAccessException makeAccessException(Class<?> targetClass) {
2761 String message = "access violation: "+ targetClass;
2762 if (this == MethodHandles.publicLookup()) {
2763 message += ", from public Lookup";
2764 } else {
2765 Module m = lookupClass().getModule();
2766 message += ", from " + lookupClass() + " (" + m + ")";
2767 if (prevLookupClass != null) {
2768 message += ", previous lookup " +
2769 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2770 }
2771 }
2772 return new IllegalAccessException(message);
2773 }
2774
2775 /**
2776 * Determines if a class can be accessed from the lookup context defined by
2777 * this {@code Lookup} object. The static initializer of the class is not run.
2778 * If {@code targetClass} is an array class, {@code targetClass} is accessible
2779 * if the element type of the array class is accessible. Otherwise,
2780 * {@code targetClass} is determined as accessible as follows.
2781 *
2782 * <p>
2783 * If {@code targetClass} is in the same module as the lookup class,
2784 * the lookup class is {@code LC} in module {@code M1} and
2785 * the previous lookup class is in module {@code M0} or
2786 * {@code null} if not present,
2787 * {@code targetClass} is accessible if and only if one of the following is true:
2788 * <ul>
2789 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2790 * {@code LC} or other class in the same nest of {@code LC}.</li>
2791 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2792 * in the same runtime package of {@code LC}.</li>
2793 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2794 * a public type in {@code M1}.</li>
2795 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2796 * a public type in a package exported by {@code M1} to at least {@code M0}
2797 * if the previous lookup class is present; otherwise, {@code targetClass}
2798 * is a public type in a package exported by {@code M1} unconditionally.</li>
2799 * </ul>
2800 *
2801 * <p>
2802 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2803 * can access public types in all modules when the type is in a package
2804 * that is exported unconditionally.
2805 * <p>
2806 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2807 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2808 * is inaccessible.
2809 * <p>
2810 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2811 * {@code M1} is the module containing {@code lookupClass} and
2812 * {@code M2} is the module containing {@code targetClass},
2813 * then {@code targetClass} is accessible if and only if
2814 * <ul>
2815 * <li>{@code M1} reads {@code M2}, and
2816 * <li>{@code targetClass} is public and in a package exported by
2817 * {@code M2} at least to {@code M1}.
2818 * </ul>
2819 * <p>
2820 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2821 * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2822 * containing the previous lookup class, then {@code targetClass} is accessible
2823 * if and only if one of the following is true:
2824 * <ul>
2825 * <li>{@code targetClass} is in {@code M0} and {@code M1}
2826 * {@linkplain Module#canRead(Module)} reads} {@code M0} and the type is
2827 * in a package that is exported to at least {@code M1}.
2828 * <li>{@code targetClass} is in {@code M1} and {@code M0}
2829 * {@linkplain Module#canRead(Module)} reads} {@code M1} and the type is
2830 * in a package that is exported to at least {@code M0}.
2831 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2832 * and {@code M1} reads {@code M2} and the type is in a package
2833 * that is exported to at least both {@code M0} and {@code M2}.
2834 * </ul>
2835 * <p>
2836 * Otherwise, {@code targetClass} is not accessible.
2837 *
2838 * @param <T> the type of the class to be access-checked
2839 * @param targetClass the class to be access-checked
2840 * @return {@code targetClass} that has been access-checked
2841 * @throws IllegalAccessException if the class is not accessible from the lookup class
2842 * and previous lookup class, if present, using the allowed access modes.
2843 * @throws NullPointerException if {@code targetClass} is {@code null}
2844 * @since 9
2845 * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2846 */
2847 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
2848 if (!isClassAccessible(targetClass)) {
2849 throw makeAccessException(targetClass);
2850 }
2851 return targetClass;
2852 }
2853
2854 /**
2855 * Produces an early-bound method handle for a virtual method.
2856 * It will bypass checks for overriding methods on the receiver,
2857 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2858 * instruction from within the explicitly specified {@code specialCaller}.
2859 * The type of the method handle will be that of the method,
2860 * with a suitably restricted receiver type prepended.
2861 * (The receiver type will be {@code specialCaller} or a subtype.)
2862 * The method and all its argument types must be accessible
2863 * to the lookup object.
2864 * <p>
2865 * Before method resolution,
2866 * if the explicitly specified caller class is not identical with the
2867 * lookup class, or if this lookup object does not have
2868 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2869 * privileges, the access fails.
2870 * <p>
2871 * The returned method handle will have
2872 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2873 * the method's variable arity modifier bit ({@code 0x0080}) is set.
2874 * <p style="font-size:smaller;">
2875 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME}
2876 * are not visible to this API,
2877 * even though the {@code invokespecial} instruction can refer to them
2878 * in special circumstances. Use {@link #findConstructor findConstructor}
2879 * to access instance initialization methods in a safe manner.)</em>
2880 * <p><b>Example:</b>
2881 * {@snippet lang="java" :
2882 import static java.lang.invoke.MethodHandles.*;
2883 import static java.lang.invoke.MethodType.*;
2884 ...
2885 static class Listie extends ArrayList {
2886 public String toString() { return "[wee Listie]"; }
2887 static Lookup lookup() { return MethodHandles.lookup(); }
2888 }
2889 ...
2890 // no access to constructor via invokeSpecial:
2891 MethodHandle MH_newListie = Listie.lookup()
2892 .findConstructor(Listie.class, methodType(void.class));
2893 Listie l = (Listie) MH_newListie.invokeExact();
2894 try { assertEquals("impossible", Listie.lookup().findSpecial(
2895 Listie.class, "<init>", methodType(void.class), Listie.class));
2896 } catch (NoSuchMethodException ex) { } // OK
2897 // access to super and self methods via invokeSpecial:
2898 MethodHandle MH_super = Listie.lookup().findSpecial(
2899 ArrayList.class, "toString" , methodType(String.class), Listie.class);
2900 MethodHandle MH_this = Listie.lookup().findSpecial(
2901 Listie.class, "toString" , methodType(String.class), Listie.class);
2902 MethodHandle MH_duper = Listie.lookup().findSpecial(
2903 Object.class, "toString" , methodType(String.class), Listie.class);
2904 assertEquals("[]", (String) MH_super.invokeExact(l));
2905 assertEquals(""+l, (String) MH_this.invokeExact(l));
2906 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2907 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2908 String.class, "toString", methodType(String.class), Listie.class));
2909 } catch (IllegalAccessException ex) { } // OK
2910 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2911 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2912 * }
2913 *
2914 * @param refc the class or interface from which the method is accessed
2915 * @param name the name of the method (which must not be "<init>")
2916 * @param type the type of the method, with the receiver argument omitted
2917 * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2918 * @return the desired method handle
2919 * @throws NoSuchMethodException if the method does not exist
2920 * @throws IllegalAccessException if access checking fails,
2921 * or if the method is {@code static},
2922 * or if the method's variable arity modifier bit
2923 * is set and {@code asVarargsCollector} fails
2924 * @throws NullPointerException if any argument is null
2925 */
2926 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
2927 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
2928 checkSpecialCaller(specialCaller, refc);
2929 Lookup specialLookup = this.in(specialCaller);
2930 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
2931 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
2932 }
2933
2934 /**
2935 * Produces a method handle giving read access to a non-static field.
2936 * The type of the method handle will have a return type of the field's
2937 * value type.
2938 * The method handle's single argument will be the instance containing
2939 * the field.
2940 * Access checking is performed immediately on behalf of the lookup class.
2941 * @param refc the class or interface from which the method is accessed
2942 * @param name the field's name
2943 * @param type the field's type
2944 * @return a method handle which can load values from the field
2945 * @throws NoSuchFieldException if the field does not exist
2946 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2947 * @throws NullPointerException if any argument is null
2948 * @see #findVarHandle(Class, String, Class)
2949 */
2950 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2951 MemberName field = resolveOrFail(REF_getField, refc, name, type);
2952 return getDirectField(REF_getField, refc, field);
2953 }
2954
2955 /**
2956 * Produces a method handle giving write access to a non-static field.
2957 * The type of the method handle will have a void return type.
2958 * The method handle will take two arguments, the instance containing
2959 * the field, and the value to be stored.
2960 * The second argument will be of the field's value type.
2961 * Access checking is performed immediately on behalf of the lookup class.
2962 * @param refc the class or interface from which the method is accessed
2963 * @param name the field's name
2964 * @param type the field's type
2965 * @return a method handle which can store values into the field
2966 * @throws NoSuchFieldException if the field does not exist
2967 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2968 * or {@code final}
2969 * @throws NullPointerException if any argument is null
2970 * @see #findVarHandle(Class, String, Class)
2971 */
2972 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2973 MemberName field = resolveOrFail(REF_putField, refc, name, type);
2974 return getDirectField(REF_putField, refc, field);
2975 }
2976
2977 /**
2978 * Produces a VarHandle giving access to a non-static field {@code name}
2979 * of type {@code type} declared in a class of type {@code recv}.
2980 * The VarHandle's variable type is {@code type} and it has one
2981 * coordinate type, {@code recv}.
2982 * <p>
2983 * Access checking is performed immediately on behalf of the lookup
2984 * class.
2985 * <p>
2986 * Certain access modes of the returned VarHandle are unsupported under
2987 * the following conditions:
2988 * <ul>
2989 * <li>if the field is declared {@code final}, then the write, atomic
2990 * update, numeric atomic update, and bitwise atomic update access
2991 * modes are unsupported.
2992 * <li>if the field type is anything other than {@code byte},
2993 * {@code short}, {@code char}, {@code int}, {@code long},
2994 * {@code float}, or {@code double} then numeric atomic update
2995 * access modes are unsupported.
2996 * <li>if the field type is anything other than {@code boolean},
2997 * {@code byte}, {@code short}, {@code char}, {@code int} or
2998 * {@code long} then bitwise atomic update access modes are
2999 * unsupported.
3000 * </ul>
3001 * <p>
3002 * If the field is declared {@code volatile} then the returned VarHandle
3003 * will override access to the field (effectively ignore the
3004 * {@code volatile} declaration) in accordance to its specified
3005 * access modes.
3006 * <p>
3007 * If the field type is {@code float} or {@code double} then numeric
3008 * and atomic update access modes compare values using their bitwise
3009 * representation (see {@link Float#floatToRawIntBits} and
3010 * {@link Double#doubleToRawLongBits}, respectively).
3011 * @apiNote
3012 * Bitwise comparison of {@code float} values or {@code double} values,
3013 * as performed by the numeric and atomic update access modes, differ
3014 * from the primitive {@code ==} operator and the {@link Float#equals}
3015 * and {@link Double#equals} methods, specifically with respect to
3016 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3017 * Care should be taken when performing a compare and set or a compare
3018 * and exchange operation with such values since the operation may
3019 * unexpectedly fail.
3020 * There are many possible NaN values that are considered to be
3021 * {@code NaN} in Java, although no IEEE 754 floating-point operation
3022 * provided by Java can distinguish between them. Operation failure can
3023 * occur if the expected or witness value is a NaN value and it is
3024 * transformed (perhaps in a platform specific manner) into another NaN
3025 * value, and thus has a different bitwise representation (see
3026 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3027 * details).
3028 * The values {@code -0.0} and {@code +0.0} have different bitwise
3029 * representations but are considered equal when using the primitive
3030 * {@code ==} operator. Operation failure can occur if, for example, a
3031 * numeric algorithm computes an expected value to be say {@code -0.0}
3032 * and previously computed the witness value to be say {@code +0.0}.
3033 * @param recv the receiver class, of type {@code R}, that declares the
3034 * non-static field
3035 * @param name the field's name
3036 * @param type the field's type, of type {@code T}
3037 * @return a VarHandle giving access to non-static fields.
3038 * @throws NoSuchFieldException if the field does not exist
3039 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3040 * @throws NullPointerException if any argument is null
3041 * @since 9
3042 */
3043 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3044 MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3045 MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3046 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3047 }
3048
3049 /**
3050 * Produces a method handle giving read access to a static field.
3051 * The type of the method handle will have a return type of the field's
3052 * value type.
3053 * The method handle will take no arguments.
3054 * Access checking is performed immediately on behalf of the lookup class.
3055 * <p>
3056 * If the returned method handle is invoked, the field's class will
3057 * be initialized, if it has not already been initialized.
3058 * @param refc the class or interface from which the method is accessed
3059 * @param name the field's name
3060 * @param type the field's type
3061 * @return a method handle which can load values from the field
3062 * @throws NoSuchFieldException if the field does not exist
3063 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3064 * @throws NullPointerException if any argument is null
3065 */
3066 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3067 MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3068 return getDirectField(REF_getStatic, refc, field);
3069 }
3070
3071 /**
3072 * Produces a method handle giving write access to a static field.
3073 * The type of the method handle will have a void return type.
3074 * The method handle will take a single
3075 * argument, of the field's value type, the value to be stored.
3076 * Access checking is performed immediately on behalf of the lookup class.
3077 * <p>
3078 * If the returned method handle is invoked, the field's class will
3079 * be initialized, if it has not already been initialized.
3080 * @param refc the class or interface from which the method is accessed
3081 * @param name the field's name
3082 * @param type the field's type
3083 * @return a method handle which can store values into the field
3084 * @throws NoSuchFieldException if the field does not exist
3085 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3086 * or is {@code final}
3087 * @throws NullPointerException if any argument is null
3088 */
3089 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3090 MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3091 return getDirectField(REF_putStatic, refc, field);
3092 }
3093
3094 /**
3095 * Produces a VarHandle giving access to a static field {@code name} of
3096 * type {@code type} declared in a class of type {@code decl}.
3097 * The VarHandle's variable type is {@code type} and it has no
3098 * coordinate types.
3099 * <p>
3100 * Access checking is performed immediately on behalf of the lookup
3101 * class.
3102 * <p>
3103 * If the returned VarHandle is operated on, the declaring class will be
3104 * initialized, if it has not already been initialized.
3105 * <p>
3106 * Certain access modes of the returned VarHandle are unsupported under
3107 * the following conditions:
3108 * <ul>
3109 * <li>if the field is declared {@code final}, then the write, atomic
3110 * update, numeric atomic update, and bitwise atomic update access
3111 * modes are unsupported.
3112 * <li>if the field type is anything other than {@code byte},
3113 * {@code short}, {@code char}, {@code int}, {@code long},
3114 * {@code float}, or {@code double}, then numeric atomic update
3115 * access modes are unsupported.
3116 * <li>if the field type is anything other than {@code boolean},
3117 * {@code byte}, {@code short}, {@code char}, {@code int} or
3118 * {@code long} then bitwise atomic update access modes are
3119 * unsupported.
3120 * </ul>
3121 * <p>
3122 * If the field is declared {@code volatile} then the returned VarHandle
3123 * will override access to the field (effectively ignore the
3124 * {@code volatile} declaration) in accordance to its specified
3125 * access modes.
3126 * <p>
3127 * If the field type is {@code float} or {@code double} then numeric
3128 * and atomic update access modes compare values using their bitwise
3129 * representation (see {@link Float#floatToRawIntBits} and
3130 * {@link Double#doubleToRawLongBits}, respectively).
3131 * @apiNote
3132 * Bitwise comparison of {@code float} values or {@code double} values,
3133 * as performed by the numeric and atomic update access modes, differ
3134 * from the primitive {@code ==} operator and the {@link Float#equals}
3135 * and {@link Double#equals} methods, specifically with respect to
3136 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3137 * Care should be taken when performing a compare and set or a compare
3138 * and exchange operation with such values since the operation may
3139 * unexpectedly fail.
3140 * There are many possible NaN values that are considered to be
3141 * {@code NaN} in Java, although no IEEE 754 floating-point operation
3142 * provided by Java can distinguish between them. Operation failure can
3143 * occur if the expected or witness value is a NaN value and it is
3144 * transformed (perhaps in a platform specific manner) into another NaN
3145 * value, and thus has a different bitwise representation (see
3146 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3147 * details).
3148 * The values {@code -0.0} and {@code +0.0} have different bitwise
3149 * representations but are considered equal when using the primitive
3150 * {@code ==} operator. Operation failure can occur if, for example, a
3151 * numeric algorithm computes an expected value to be say {@code -0.0}
3152 * and previously computed the witness value to be say {@code +0.0}.
3153 * @param decl the class that declares the static field
3154 * @param name the field's name
3155 * @param type the field's type, of type {@code T}
3156 * @return a VarHandle giving access to a static field
3157 * @throws NoSuchFieldException if the field does not exist
3158 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3159 * @throws NullPointerException if any argument is null
3160 * @since 9
3161 */
3162 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3163 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3164 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3165 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3166 }
3167
3168 /**
3169 * Produces an early-bound method handle for a non-static method.
3170 * The receiver must have a supertype {@code defc} in which a method
3171 * of the given name and type is accessible to the lookup class.
3172 * The method and all its argument types must be accessible to the lookup object.
3173 * The type of the method handle will be that of the method,
3174 * without any insertion of an additional receiver parameter.
3175 * The given receiver will be bound into the method handle,
3176 * so that every call to the method handle will invoke the
3177 * requested method on the given receiver.
3178 * <p>
3179 * The returned method handle will have
3180 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3181 * the method's variable arity modifier bit ({@code 0x0080}) is set
3182 * <em>and</em> the trailing array argument is not the only argument.
3183 * (If the trailing array argument is the only argument,
3184 * the given receiver value will be bound to it.)
3185 * <p>
3186 * This is almost equivalent to the following code, with some differences noted below:
3187 * {@snippet lang="java" :
3188 import static java.lang.invoke.MethodHandles.*;
3189 import static java.lang.invoke.MethodType.*;
3190 ...
3191 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3192 MethodHandle mh1 = mh0.bindTo(receiver);
3193 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3194 return mh1;
3195 * }
3196 * where {@code defc} is either {@code receiver.getClass()} or a super
3197 * type of that class, in which the requested method is accessible
3198 * to the lookup class.
3199 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3200 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3201 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3202 * the receiver is restricted by {@code findVirtual} to the lookup class.)
3203 * @param receiver the object from which the method is accessed
3204 * @param name the name of the method
3205 * @param type the type of the method, with the receiver argument omitted
3206 * @return the desired method handle
3207 * @throws NoSuchMethodException if the method does not exist
3208 * @throws IllegalAccessException if access checking fails
3209 * or if the method's variable arity modifier bit
3210 * is set and {@code asVarargsCollector} fails
3211 * @throws NullPointerException if any argument is null
3212 * @see MethodHandle#bindTo
3213 * @see #findVirtual
3214 */
3215 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3216 Class<? extends Object> refc = receiver.getClass(); // may get NPE
3217 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3218 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3219 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3220 throw new IllegalAccessException("The restricted defining class " +
3221 mh.type().leadingReferenceParameter().getName() +
3222 " is not assignable from receiver class " +
3223 receiver.getClass().getName());
3224 }
3225 return mh.bindArgumentL(0, receiver).setVarargs(method);
3226 }
3227
3228 /**
3229 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3230 * to <i>m</i>, if the lookup class has permission.
3231 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3232 * If <i>m</i> is virtual, overriding is respected on every call.
3233 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3234 * The type of the method handle will be that of the method,
3235 * with the receiver type prepended (but only if it is non-static).
3236 * If the method's {@code accessible} flag is not set,
3237 * access checking is performed immediately on behalf of the lookup class.
3238 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3239 * <p>
3240 * The returned method handle will have
3241 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3242 * the method's variable arity modifier bit ({@code 0x0080}) is set.
3243 * <p>
3244 * If <i>m</i> is static, and
3245 * if the returned method handle is invoked, the method's class will
3246 * be initialized, if it has not already been initialized.
3247 * @param m the reflected method
3248 * @return a method handle which can invoke the reflected method
3249 * @throws IllegalAccessException if access checking fails
3250 * or if the method's variable arity modifier bit
3251 * is set and {@code asVarargsCollector} fails
3252 * @throws NullPointerException if the argument is null
3253 */
3254 public MethodHandle unreflect(Method m) throws IllegalAccessException {
3255 if (m.getDeclaringClass() == MethodHandle.class) {
3256 MethodHandle mh = unreflectForMH(m);
3257 if (mh != null) return mh;
3258 }
3259 if (m.getDeclaringClass() == VarHandle.class) {
3260 MethodHandle mh = unreflectForVH(m);
3261 if (mh != null) return mh;
3262 }
3263 MemberName method = new MemberName(m);
3264 byte refKind = method.getReferenceKind();
3265 if (refKind == REF_invokeSpecial)
3266 refKind = REF_invokeVirtual;
3267 assert(method.isMethod());
3268 @SuppressWarnings("deprecation")
3269 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3270 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3271 }
3272 private MethodHandle unreflectForMH(Method m) {
3273 // these names require special lookups because they throw UnsupportedOperationException
3274 if (MemberName.isMethodHandleInvokeName(m.getName()))
3275 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3276 return null;
3277 }
3278 private MethodHandle unreflectForVH(Method m) {
3279 // these names require special lookups because they throw UnsupportedOperationException
3280 if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3281 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3282 return null;
3283 }
3284
3285 /**
3286 * Produces a method handle for a reflected method.
3287 * It will bypass checks for overriding methods on the receiver,
3288 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3289 * instruction from within the explicitly specified {@code specialCaller}.
3290 * The type of the method handle will be that of the method,
3291 * with a suitably restricted receiver type prepended.
3292 * (The receiver type will be {@code specialCaller} or a subtype.)
3293 * If the method's {@code accessible} flag is not set,
3294 * access checking is performed immediately on behalf of the lookup class,
3295 * as if {@code invokespecial} instruction were being linked.
3296 * <p>
3297 * Before method resolution,
3298 * if the explicitly specified caller class is not identical with the
3299 * lookup class, or if this lookup object does not have
3300 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3301 * privileges, the access fails.
3302 * <p>
3303 * The returned method handle will have
3304 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3305 * the method's variable arity modifier bit ({@code 0x0080}) is set.
3306 * @param m the reflected method
3307 * @param specialCaller the class nominally calling the method
3308 * @return a method handle which can invoke the reflected method
3309 * @throws IllegalAccessException if access checking fails,
3310 * or if the method is {@code static},
3311 * or if the method's variable arity modifier bit
3312 * is set and {@code asVarargsCollector} fails
3313 * @throws NullPointerException if any argument is null
3314 */
3315 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3316 checkSpecialCaller(specialCaller, m.getDeclaringClass());
3317 Lookup specialLookup = this.in(specialCaller);
3318 MemberName method = new MemberName(m, true);
3319 assert(method.isMethod());
3320 // ignore m.isAccessible: this is a new kind of access
3321 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3322 }
3323
3324 /**
3325 * Produces a method handle for a reflected constructor.
3326 * The type of the method handle will be that of the constructor,
3327 * with the return type changed to the declaring class.
3328 * The method handle will perform a {@code newInstance} operation,
3329 * creating a new instance of the constructor's class on the
3330 * arguments passed to the method handle.
3331 * <p>
3332 * If the constructor's {@code accessible} flag is not set,
3333 * access checking is performed immediately on behalf of the lookup class.
3334 * <p>
3335 * The returned method handle will have
3336 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3337 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3338 * <p>
3339 * If the returned method handle is invoked, the constructor's class will
3340 * be initialized, if it has not already been initialized.
3341 * @param c the reflected constructor
3342 * @return a method handle which can invoke the reflected constructor
3343 * @throws IllegalAccessException if access checking fails
3344 * or if the method's variable arity modifier bit
3345 * is set and {@code asVarargsCollector} fails
3346 * @throws NullPointerException if the argument is null
3347 */
3348 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3349 MemberName ctor = new MemberName(c);
3350 assert(ctor.isConstructor());
3351 @SuppressWarnings("deprecation")
3352 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3353 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor);
3354 }
3355
3356 /*
3357 * Produces a method handle that is capable of creating instances of the given class
3358 * and instantiated by the given constructor.
3359 *
3360 * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3361 */
3362 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3363 MemberName ctor = new MemberName(c);
3364 assert(ctor.isConstructor() && constructorInSuperclass(decl, c));
3365 checkAccess(REF_newInvokeSpecial, decl, ctor);
3366 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
3367 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3368 }
3369
3370 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3371 if (decl == ctor.getDeclaringClass())
3372 return true;
3373
3374 Class<?> cl = decl;
3375 while ((cl = cl.getSuperclass()) != null) {
3376 if (cl == ctor.getDeclaringClass()) {
3377 return true;
3378 }
3379 }
3380 return false;
3381 }
3382
3383 /**
3384 * Produces a method handle giving read access to a reflected field.
3385 * The type of the method handle will have a return type of the field's
3386 * value type.
3387 * If the field is {@code static}, the method handle will take no arguments.
3388 * Otherwise, its single argument will be the instance containing
3389 * the field.
3390 * If the {@code Field} object's {@code accessible} flag is not set,
3391 * access checking is performed immediately on behalf of the lookup class.
3392 * <p>
3393 * If the field is static, and
3394 * if the returned method handle is invoked, the field's class will
3395 * be initialized, if it has not already been initialized.
3396 * @param f the reflected field
3397 * @return a method handle which can load values from the reflected field
3398 * @throws IllegalAccessException if access checking fails
3399 * @throws NullPointerException if the argument is null
3400 */
3401 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3402 return unreflectField(f, false);
3403 }
3404
3405 /**
3406 * Produces a method handle giving write access to a reflected field.
3407 * The type of the method handle will have a void return type.
3408 * If the field is {@code static}, the method handle will take a single
3409 * argument, of the field's value type, the value to be stored.
3410 * Otherwise, the two arguments will be the instance containing
3411 * the field, and the value to be stored.
3412 * If the {@code Field} object's {@code accessible} flag is not set,
3413 * access checking is performed immediately on behalf of the lookup class.
3414 * <p>
3415 * If the field is {@code final}, write access will not be
3416 * allowed and access checking will fail, except under certain
3417 * narrow circumstances documented for {@link Field#set Field.set}.
3418 * A method handle is returned only if a corresponding call to
3419 * the {@code Field} object's {@code set} method could return
3420 * normally. In particular, fields which are both {@code static}
3421 * and {@code final} may never be set.
3422 * <p>
3423 * If the field is {@code static}, and
3424 * if the returned method handle is invoked, the field's class will
3425 * be initialized, if it has not already been initialized.
3426 * @param f the reflected field
3427 * @return a method handle which can store values into the reflected field
3428 * @throws IllegalAccessException if access checking fails,
3429 * or if the field is {@code final} and write access
3430 * is not enabled on the {@code Field} object
3431 * @throws NullPointerException if the argument is null
3432 * @see <a href="{@docRoot}/java.base/java/lang/reflect/doc-files/MutationMethods.html">Mutation methods</a>
3433 */
3434 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3435 return unreflectField(f, true);
3436 }
3437
3438 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3439 @SuppressWarnings("deprecation")
3440 boolean isAccessible = f.isAccessible();
3441 MemberName field = new MemberName(f, isSetter);
3442 if (isSetter && field.isFinal()) {
3443 if (field.isTrustedFinalField()) {
3444 String msg = field.isStatic() ? "static final field has no write access"
3445 : "final field has no write access";
3446 throw field.makeAccessException(msg, this);
3447 }
3448 // check if write access to final field allowed
3449 if (!field.isStatic() && isAccessible) {
3450 SharedSecrets.getJavaLangReflectAccess().checkAllowedToUnreflectFinalSetter(lookupClass, f);
3451 }
3452 }
3453 assert(isSetter
3454 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3455 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3456 Lookup lookup = isAccessible ? IMPL_LOOKUP : this;
3457 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field);
3458 }
3459
3460 /**
3461 * Produces a VarHandle giving access to a reflected field {@code f}
3462 * of type {@code T} declared in a class of type {@code R}.
3463 * The VarHandle's variable type is {@code T}.
3464 * If the field is non-static the VarHandle has one coordinate type,
3465 * {@code R}. Otherwise, the field is static, and the VarHandle has no
3466 * coordinate types.
3467 * <p>
3468 * Access checking is performed immediately on behalf of the lookup
3469 * class, regardless of the value of the field's {@code accessible}
3470 * flag.
3471 * <p>
3472 * If the field is static, and if the returned VarHandle is operated
3473 * on, the field's declaring class will be initialized, if it has not
3474 * already been initialized.
3475 * <p>
3476 * Certain access modes of the returned VarHandle are unsupported under
3477 * the following conditions:
3478 * <ul>
3479 * <li>if the field is declared {@code final}, then the write, atomic
3480 * update, numeric atomic update, and bitwise atomic update access
3481 * modes are unsupported.
3482 * <li>if the field type is anything other than {@code byte},
3483 * {@code short}, {@code char}, {@code int}, {@code long},
3484 * {@code float}, or {@code double} then numeric atomic update
3485 * access modes are unsupported.
3486 * <li>if the field type is anything other than {@code boolean},
3487 * {@code byte}, {@code short}, {@code char}, {@code int} or
3488 * {@code long} then bitwise atomic update access modes are
3489 * unsupported.
3490 * </ul>
3491 * <p>
3492 * If the field is declared {@code volatile} then the returned VarHandle
3493 * will override access to the field (effectively ignore the
3494 * {@code volatile} declaration) in accordance to its specified
3495 * access modes.
3496 * <p>
3497 * If the field type is {@code float} or {@code double} then numeric
3498 * and atomic update access modes compare values using their bitwise
3499 * representation (see {@link Float#floatToRawIntBits} and
3500 * {@link Double#doubleToRawLongBits}, respectively).
3501 * @apiNote
3502 * Bitwise comparison of {@code float} values or {@code double} values,
3503 * as performed by the numeric and atomic update access modes, differ
3504 * from the primitive {@code ==} operator and the {@link Float#equals}
3505 * and {@link Double#equals} methods, specifically with respect to
3506 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3507 * Care should be taken when performing a compare and set or a compare
3508 * and exchange operation with such values since the operation may
3509 * unexpectedly fail.
3510 * There are many possible NaN values that are considered to be
3511 * {@code NaN} in Java, although no IEEE 754 floating-point operation
3512 * provided by Java can distinguish between them. Operation failure can
3513 * occur if the expected or witness value is a NaN value and it is
3514 * transformed (perhaps in a platform specific manner) into another NaN
3515 * value, and thus has a different bitwise representation (see
3516 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3517 * details).
3518 * The values {@code -0.0} and {@code +0.0} have different bitwise
3519 * representations but are considered equal when using the primitive
3520 * {@code ==} operator. Operation failure can occur if, for example, a
3521 * numeric algorithm computes an expected value to be say {@code -0.0}
3522 * and previously computed the witness value to be say {@code +0.0}.
3523 * @param f the reflected field, with a field of type {@code T}, and
3524 * a declaring class of type {@code R}
3525 * @return a VarHandle giving access to non-static fields or a static
3526 * field
3527 * @throws IllegalAccessException if access checking fails
3528 * @throws NullPointerException if the argument is null
3529 * @since 9
3530 */
3531 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3532 MemberName getField = new MemberName(f, false);
3533 MemberName putField = new MemberName(f, true);
3534 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(),
3535 f.getDeclaringClass(), getField, putField);
3536 }
3537
3538 /**
3539 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3540 * created by this lookup object or a similar one.
3541 * Security and access checks are performed to ensure that this lookup object
3542 * is capable of reproducing the target method handle.
3543 * This means that the cracking may fail if target is a direct method handle
3544 * but was created by an unrelated lookup object.
3545 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3546 * and was created by a lookup object for a different class.
3547 * @param target a direct method handle to crack into symbolic reference components
3548 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3549 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3550 * @throws NullPointerException if the target is {@code null}
3551 * @see MethodHandleInfo
3552 * @since 1.8
3553 */
3554 public MethodHandleInfo revealDirect(MethodHandle target) {
3555 if (!target.isCrackable()) {
3556 throw newIllegalArgumentException("not a direct method handle");
3557 }
3558 MemberName member = target.internalMemberName();
3559 Class<?> defc = member.getDeclaringClass();
3560 byte refKind = member.getReferenceKind();
3561 assert(MethodHandleNatives.refKindIsValid(refKind));
3562 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3563 // Devirtualized method invocation is usually formally virtual.
3564 // To avoid creating extra MemberName objects for this common case,
3565 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3566 refKind = REF_invokeVirtual;
3567 if (refKind == REF_invokeVirtual && defc.isInterface())
3568 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3569 refKind = REF_invokeInterface;
3570 // Check member access before cracking.
3571 try {
3572 checkAccess(refKind, defc, member);
3573 } catch (IllegalAccessException ex) {
3574 throw new IllegalArgumentException(ex);
3575 }
3576 if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3577 Class<?> callerClass = target.internalCallerClass();
3578 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3579 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3580 }
3581 // Produce the handle to the results.
3582 return new InfoFromMemberName(this, member, refKind);
3583 }
3584
3585 //--- Helper methods, all package-private.
3586
3587 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3588 checkSymbolicClass(refc); // do this before attempting to resolve
3589 Objects.requireNonNull(name);
3590 Objects.requireNonNull(type);
3591 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3592 NoSuchFieldException.class);
3593 }
3594
3595 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3596 checkSymbolicClass(refc); // do this before attempting to resolve
3597 Objects.requireNonNull(type);
3598 checkMethodName(refKind, name); // implicit null-check of name
3599 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3600 NoSuchMethodException.class);
3601 }
3602
3603 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3604 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve
3605 Objects.requireNonNull(member.getName());
3606 Objects.requireNonNull(member.getType());
3607 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3608 ReflectiveOperationException.class);
3609 }
3610
3611 MemberName resolveOrNull(byte refKind, MemberName member) {
3612 // do this before attempting to resolve
3613 if (!isClassAccessible(member.getDeclaringClass())) {
3614 return null;
3615 }
3616 Objects.requireNonNull(member.getName());
3617 Objects.requireNonNull(member.getType());
3618 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3619 }
3620
3621 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3622 // do this before attempting to resolve
3623 if (!isClassAccessible(refc)) {
3624 return null;
3625 }
3626 Objects.requireNonNull(type);
3627 // implicit null-check of name
3628 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3629 return null;
3630 }
3631 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3632 }
3633
3634 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3635 if (!isClassAccessible(refc)) {
3636 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3637 }
3638 }
3639
3640 boolean isClassAccessible(Class<?> refc) {
3641 Objects.requireNonNull(refc);
3642 Class<?> caller = lookupClassOrNull();
3643 Class<?> type = refc;
3644 while (type.isArray()) {
3645 type = type.getComponentType();
3646 }
3647 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3648 }
3649
3650 /** Check name for an illegal leading "<" character. */
3651 void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3652 if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3653 throw new NoSuchMethodException("illegal method name: "+name);
3654 }
3655
3656 /**
3657 * Find my trustable caller class if m is a caller sensitive method.
3658 * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3659 * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3660 */
3661 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3662 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3663 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3664 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3665 }
3666 return this;
3667 }
3668
3669 /**
3670 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3671 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3672 *
3673 * @deprecated This method was originally designed to test {@code PRIVATE} access
3674 * that implies full privilege access but {@code MODULE} access has since become
3675 * independent of {@code PRIVATE} access. It is recommended to call
3676 * {@link #hasFullPrivilegeAccess()} instead.
3677 * @since 9
3678 */
3679 @Deprecated(since="14")
3680 public boolean hasPrivateAccess() {
3681 return hasFullPrivilegeAccess();
3682 }
3683
3684 /**
3685 * Returns {@code true} if this lookup has <em>full privilege access</em>,
3686 * i.e. {@code PRIVATE} and {@code MODULE} access.
3687 * A {@code Lookup} object must have full privilege access in order to
3688 * access all members that are allowed to the
3689 * {@linkplain #lookupClass() lookup class}.
3690 *
3691 * @return {@code true} if this lookup has full privilege access.
3692 * @since 14
3693 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3694 */
3695 public boolean hasFullPrivilegeAccess() {
3696 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3697 }
3698
3699 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3700 boolean wantStatic = (refKind == REF_invokeStatic);
3701 String message;
3702 if (m.isConstructor())
3703 message = "expected a method, not a constructor";
3704 else if (!m.isMethod())
3705 message = "expected a method";
3706 else if (wantStatic != m.isStatic())
3707 message = wantStatic ? "expected a static method" : "expected a non-static method";
3708 else
3709 { checkAccess(refKind, refc, m); return; }
3710 throw m.makeAccessException(message, this);
3711 }
3712
3713 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3714 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3715 String message;
3716 if (wantStatic != m.isStatic())
3717 message = wantStatic ? "expected a static field" : "expected a non-static field";
3718 else
3719 { checkAccess(refKind, refc, m); return; }
3720 throw m.makeAccessException(message, this);
3721 }
3722
3723 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3724 return Modifier.isProtected(m.getModifiers()) &&
3725 refKind == REF_invokeVirtual &&
3726 m.getDeclaringClass() == Object.class &&
3727 m.getName().equals("clone") &&
3728 refc.isArray();
3729 }
3730
3731 /** Check public/protected/private bits on the symbolic reference class and its member. */
3732 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3733 assert(m.referenceKindIsConsistentWith(refKind) &&
3734 MethodHandleNatives.refKindIsValid(refKind) &&
3735 (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3736 int allowedModes = this.allowedModes;
3737 if (allowedModes == TRUSTED) return;
3738 int mods = m.getModifiers();
3739 if (isArrayClone(refKind, refc, m)) {
3740 // The JVM does this hack also.
3741 // (See ClassVerifier::verify_invoke_instructions
3742 // and LinkResolver::check_method_accessability.)
3743 // Because the JVM does not allow separate methods on array types,
3744 // there is no separate method for int[].clone.
3745 // All arrays simply inherit Object.clone.
3746 // But for access checking logic, we make Object.clone
3747 // (normally protected) appear to be public.
3748 // Later on, when the DirectMethodHandle is created,
3749 // its leading argument will be restricted to the
3750 // requested array type.
3751 // N.B. The return type is not adjusted, because
3752 // that is *not* the bytecode behavior.
3753 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3754 }
3755 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3756 // cannot "new" a protected ctor in a different package
3757 mods ^= Modifier.PROTECTED;
3758 }
3759 if (Modifier.isFinal(mods) &&
3760 MethodHandleNatives.refKindIsSetter(refKind))
3761 throw m.makeAccessException("unexpected set of a final field", this);
3762 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE
3763 if ((requestedModes & allowedModes) != 0) {
3764 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3765 mods, lookupClass(), previousLookupClass(), allowedModes))
3766 return;
3767 } else {
3768 // Protected members can also be checked as if they were package-private.
3769 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3770 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3771 return;
3772 }
3773 throw m.makeAccessException(accessFailedMessage(refc, m), this);
3774 }
3775
3776 String accessFailedMessage(Class<?> refc, MemberName m) {
3777 Class<?> defc = m.getDeclaringClass();
3778 int mods = m.getModifiers();
3779 // check the class first:
3780 boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3781 (defc == refc ||
3782 Modifier.isPublic(refc.getModifiers())));
3783 if (!classOK && (allowedModes & PACKAGE) != 0) {
3784 // ignore previous lookup class to check if default package access
3785 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3786 (defc == refc ||
3787 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3788 }
3789 if (!classOK)
3790 return "class is not public";
3791 if (Modifier.isPublic(mods))
3792 return "access to public member failed"; // (how?, module not readable?)
3793 if (Modifier.isPrivate(mods))
3794 return "member is private";
3795 if (Modifier.isProtected(mods))
3796 return "member is protected";
3797 return "member is private to package";
3798 }
3799
3800 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3801 int allowedModes = this.allowedModes;
3802 if (allowedModes == TRUSTED) return;
3803 if ((lookupModes() & PRIVATE) == 0
3804 || (specialCaller != lookupClass()
3805 // ensure non-abstract methods in superinterfaces can be special-invoked
3806 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3807 throw new MemberName(specialCaller).
3808 makeAccessException("no private access for invokespecial", this);
3809 }
3810
3811 private boolean restrictProtectedReceiver(MemberName method) {
3812 // The accessing class only has the right to use a protected member
3813 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc.
3814 if (!method.isProtected() || method.isStatic()
3815 || allowedModes == TRUSTED
3816 || method.getDeclaringClass() == lookupClass()
3817 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3818 return false;
3819 return true;
3820 }
3821 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3822 assert(!method.isStatic());
3823 // receiver type of mh is too wide; narrow to caller
3824 if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3825 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3826 }
3827 MethodType rawType = mh.type();
3828 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3829 MethodType narrowType = rawType.changeParameterType(0, caller);
3830 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness
3831 assert(mh.viewAsTypeChecks(narrowType, true));
3832 return mh.copyWith(narrowType, mh.form);
3833 }
3834
3835 /** Check access and get the requested method. */
3836 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3837 final boolean doRestrict = true;
3838 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup);
3839 }
3840 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3841 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3842 final boolean doRestrict = false;
3843 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup);
3844 }
3845 /** Common code for all methods; do not call directly except from immediately above. */
3846 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3847 boolean doRestrict,
3848 Lookup boundCaller) throws IllegalAccessException {
3849 checkMethod(refKind, refc, method);
3850 assert(!method.isMethodHandleInvoke());
3851
3852 if (refKind == REF_invokeSpecial &&
3853 refc != lookupClass() &&
3854 !refc.isInterface() && !lookupClass().isInterface() &&
3855 refc != lookupClass().getSuperclass() &&
3856 refc.isAssignableFrom(lookupClass())) {
3857 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path
3858
3859 // Per JVMS 6.5, desc. of invokespecial instruction:
3860 // If the method is in a superclass of the LC,
3861 // and if our original search was above LC.super,
3862 // repeat the search (symbolic lookup) from LC.super
3863 // and continue with the direct superclass of that class,
3864 // and so forth, until a match is found or no further superclasses exist.
3865 // FIXME: MemberName.resolve should handle this instead.
3866 Class<?> refcAsSuper = lookupClass();
3867 MemberName m2;
3868 do {
3869 refcAsSuper = refcAsSuper.getSuperclass();
3870 m2 = new MemberName(refcAsSuper,
3871 method.getName(),
3872 method.getMethodType(),
3873 REF_invokeSpecial);
3874 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
3875 } while (m2 == null && // no method is found yet
3876 refc != refcAsSuper); // search up to refc
3877 if (m2 == null) throw new InternalError(method.toString());
3878 method = m2;
3879 refc = refcAsSuper;
3880 // redo basic checks
3881 checkMethod(refKind, refc, method);
3882 }
3883 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
3884 MethodHandle mh = dmh;
3885 // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
3886 if ((doRestrict && refKind == REF_invokeSpecial) ||
3887 (MethodHandleNatives.refKindHasReceiver(refKind) &&
3888 restrictProtectedReceiver(method) &&
3889 // All arrays simply inherit the protected Object.clone method.
3890 // The leading argument is already restricted to the requested
3891 // array type (not the lookup class).
3892 !isArrayClone(refKind, refc, method))) {
3893 mh = restrictReceiver(method, dmh, lookupClass());
3894 }
3895 mh = maybeBindCaller(method, mh, boundCaller);
3896 mh = mh.setVarargs(method);
3897 return mh;
3898 }
3899 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
3900 throws IllegalAccessException {
3901 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
3902 return mh;
3903
3904 // boundCaller must have full privilege access.
3905 // It should have been checked by findBoundCallerLookup. Safe to check this again.
3906 if ((boundCaller.lookupModes() & ORIGINAL) == 0)
3907 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3908
3909 assert boundCaller.hasFullPrivilegeAccess();
3910
3911 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
3912 // Note: caller will apply varargs after this step happens.
3913 return cbmh;
3914 }
3915
3916 /** Check access and get the requested field. */
3917 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3918 return getDirectFieldCommon(refKind, refc, field);
3919 }
3920 /** Common code for all fields; do not call directly except from immediately above. */
3921 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3922 checkField(refKind, refc, field);
3923 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
3924 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
3925 restrictProtectedReceiver(field));
3926 if (doRestrict)
3927 return restrictReceiver(field, dmh, lookupClass());
3928 return dmh;
3929 }
3930 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
3931 Class<?> refc, MemberName getField, MemberName putField)
3932 throws IllegalAccessException {
3933 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField);
3934 }
3935 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
3936 Class<?> refc, MemberName getField,
3937 MemberName putField) throws IllegalAccessException {
3938 assert getField.isStatic() == putField.isStatic();
3939 assert getField.isGetter() && putField.isSetter();
3940 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
3941 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
3942
3943 checkField(getRefKind, refc, getField);
3944
3945 if (!putField.isFinal()) {
3946 // A VarHandle does not support updates to final fields, any
3947 // such VarHandle to a final field will be read-only and
3948 // therefore the following write-based accessibility checks are
3949 // only required for non-final fields
3950 checkField(putRefKind, refc, putField);
3951 }
3952
3953 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3954 restrictProtectedReceiver(getField));
3955 if (doRestrict) {
3956 assert !getField.isStatic();
3957 // receiver type of VarHandle is too wide; narrow to caller
3958 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3959 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3960 }
3961 refc = lookupClass();
3962 }
3963 return VarHandles.makeFieldHandle(getField, refc,
3964 this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
3965 }
3966 /** Check access and get the requested constructor. */
3967 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3968 return getDirectConstructorCommon(refc, ctor);
3969 }
3970 /** Common code for all constructors; do not call directly except from immediately above. */
3971 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3972 assert(ctor.isConstructor());
3973 checkAccess(REF_newInvokeSpecial, refc, ctor);
3974 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
3975 return DirectMethodHandle.make(ctor).setVarargs(ctor);
3976 }
3977
3978 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
3979 */
3980 /*non-public*/
3981 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
3982 throws ReflectiveOperationException {
3983 if (!(type instanceof Class || type instanceof MethodType))
3984 throw new InternalError("unresolved MemberName");
3985 MemberName member = new MemberName(refKind, defc, name, type);
3986 MethodHandle mh = LOOKASIDE_TABLE.get(member);
3987 if (mh != null) {
3988 checkSymbolicClass(defc);
3989 return mh;
3990 }
3991 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
3992 // Treat MethodHandle.invoke and invokeExact specially.
3993 mh = findVirtualForMH(member.getName(), member.getMethodType());
3994 if (mh != null) {
3995 return mh;
3996 }
3997 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
3998 // Treat signature-polymorphic methods on VarHandle specially.
3999 mh = findVirtualForVH(member.getName(), member.getMethodType());
4000 if (mh != null) {
4001 return mh;
4002 }
4003 }
4004 MemberName resolved = resolveOrFail(refKind, member);
4005 mh = getDirectMethodForConstant(refKind, defc, resolved);
4006 if (mh instanceof DirectMethodHandle dmh
4007 && canBeCached(refKind, defc, resolved)) {
4008 MemberName key = mh.internalMemberName();
4009 if (key != null) {
4010 key = key.asNormalOriginal();
4011 }
4012 if (member.equals(key)) { // better safe than sorry
4013 LOOKASIDE_TABLE.put(key, dmh);
4014 }
4015 }
4016 return mh;
4017 }
4018 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4019 if (refKind == REF_invokeSpecial) {
4020 return false;
4021 }
4022 if (!Modifier.isPublic(defc.getModifiers()) ||
4023 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4024 !member.isPublic() ||
4025 member.isCallerSensitive()) {
4026 return false;
4027 }
4028 ClassLoader loader = defc.getClassLoader();
4029 if (loader != null) {
4030 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4031 boolean found = false;
4032 while (sysl != null) {
4033 if (loader == sysl) { found = true; break; }
4034 sysl = sysl.getParent();
4035 }
4036 if (!found) {
4037 return false;
4038 }
4039 }
4040 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4041 new MemberName(refKind, defc, member.getName(), member.getType()));
4042 if (resolved2 == null) {
4043 return false;
4044 }
4045 return true;
4046 }
4047 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4048 throws ReflectiveOperationException {
4049 if (MethodHandleNatives.refKindIsField(refKind)) {
4050 return getDirectField(refKind, defc, member);
4051 } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4052 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member));
4053 } else if (refKind == REF_newInvokeSpecial) {
4054 return getDirectConstructor(defc, member);
4055 }
4056 // oops
4057 throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4058 }
4059
4060 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4061 }
4062
4063 /**
4064 * Produces a method handle constructing arrays of a desired type,
4065 * as if by the {@code anewarray} bytecode.
4066 * The return type of the method handle will be the array type.
4067 * The type of its sole argument will be {@code int}, which specifies the size of the array.
4068 *
4069 * <p> If the returned method handle is invoked with a negative
4070 * array size, a {@code NegativeArraySizeException} will be thrown.
4071 *
4072 * @param arrayClass an array type
4073 * @return a method handle which can create arrays of the given type
4074 * @throws NullPointerException if the argument is {@code null}
4075 * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4076 * @see java.lang.reflect.Array#newInstance(Class, int)
4077 * @jvms 6.5 {@code anewarray} Instruction
4078 * @since 9
4079 */
4080 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4081 if (!arrayClass.isArray()) {
4082 throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4083 }
4084 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4085 bindTo(arrayClass.getComponentType());
4086 return ani.asType(ani.type().changeReturnType(arrayClass));
4087 }
4088
4089 /**
4090 * Produces a method handle returning the length of an array,
4091 * as if by the {@code arraylength} bytecode.
4092 * The type of the method handle will have {@code int} as return type,
4093 * and its sole argument will be the array type.
4094 *
4095 * <p> If the returned method handle is invoked with a {@code null}
4096 * array reference, a {@code NullPointerException} will be thrown.
4097 *
4098 * @param arrayClass an array type
4099 * @return a method handle which can retrieve the length of an array of the given array type
4100 * @throws NullPointerException if the argument is {@code null}
4101 * @throws IllegalArgumentException if arrayClass is not an array type
4102 * @jvms 6.5 {@code arraylength} Instruction
4103 * @since 9
4104 */
4105 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4106 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4107 }
4108
4109 /**
4110 * Produces a method handle giving read access to elements of an array,
4111 * as if by the {@code aaload} bytecode.
4112 * The type of the method handle will have a return type of the array's
4113 * element type. Its first argument will be the array type,
4114 * and the second will be {@code int}.
4115 *
4116 * <p> When the returned method handle is invoked,
4117 * the array reference and array index are checked.
4118 * A {@code NullPointerException} will be thrown if the array reference
4119 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4120 * thrown if the index is negative or if it is greater than or equal to
4121 * the length of the array.
4122 *
4123 * @param arrayClass an array type
4124 * @return a method handle which can load values from the given array type
4125 * @throws NullPointerException if the argument is null
4126 * @throws IllegalArgumentException if arrayClass is not an array type
4127 * @jvms 6.5 {@code aaload} Instruction
4128 */
4129 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4130 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4131 }
4132
4133 /**
4134 * Produces a method handle giving write access to elements of an array,
4135 * as if by the {@code astore} bytecode.
4136 * The type of the method handle will have a void return type.
4137 * Its last argument will be the array's element type.
4138 * The first and second arguments will be the array type and int.
4139 *
4140 * <p> When the returned method handle is invoked,
4141 * the array reference and array index are checked.
4142 * A {@code NullPointerException} will be thrown if the array reference
4143 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4144 * thrown if the index is negative or if it is greater than or equal to
4145 * the length of the array.
4146 *
4147 * @param arrayClass the class of an array
4148 * @return a method handle which can store values into the array type
4149 * @throws NullPointerException if the argument is null
4150 * @throws IllegalArgumentException if arrayClass is not an array type
4151 * @jvms 6.5 {@code aastore} Instruction
4152 */
4153 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4154 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4155 }
4156
4157 /**
4158 * Produces a VarHandle giving access to elements of an array of type
4159 * {@code arrayClass}. The VarHandle's variable type is the component type
4160 * of {@code arrayClass} and the list of coordinate types is
4161 * {@code (arrayClass, int)}, where the {@code int} coordinate type
4162 * corresponds to an argument that is an index into an array.
4163 * <p>
4164 * Certain access modes of the returned VarHandle are unsupported under
4165 * the following conditions:
4166 * <ul>
4167 * <li>if the component type is anything other than {@code byte},
4168 * {@code short}, {@code char}, {@code int}, {@code long},
4169 * {@code float}, or {@code double} then numeric atomic update access
4170 * modes are unsupported.
4171 * <li>if the component type is anything other than {@code boolean},
4172 * {@code byte}, {@code short}, {@code char}, {@code int} or
4173 * {@code long} then bitwise atomic update access modes are
4174 * unsupported.
4175 * </ul>
4176 * <p>
4177 * If the component type is {@code float} or {@code double} then numeric
4178 * and atomic update access modes compare values using their bitwise
4179 * representation (see {@link Float#floatToRawIntBits} and
4180 * {@link Double#doubleToRawLongBits}, respectively).
4181 *
4182 * <p> When the returned {@code VarHandle} is invoked,
4183 * the array reference and array index are checked.
4184 * A {@code NullPointerException} will be thrown if the array reference
4185 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4186 * thrown if the index is negative or if it is greater than or equal to
4187 * the length of the array.
4188 *
4189 * @apiNote
4190 * Bitwise comparison of {@code float} values or {@code double} values,
4191 * as performed by the numeric and atomic update access modes, differ
4192 * from the primitive {@code ==} operator and the {@link Float#equals}
4193 * and {@link Double#equals} methods, specifically with respect to
4194 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4195 * Care should be taken when performing a compare and set or a compare
4196 * and exchange operation with such values since the operation may
4197 * unexpectedly fail.
4198 * There are many possible NaN values that are considered to be
4199 * {@code NaN} in Java, although no IEEE 754 floating-point operation
4200 * provided by Java can distinguish between them. Operation failure can
4201 * occur if the expected or witness value is a NaN value and it is
4202 * transformed (perhaps in a platform specific manner) into another NaN
4203 * value, and thus has a different bitwise representation (see
4204 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4205 * details).
4206 * The values {@code -0.0} and {@code +0.0} have different bitwise
4207 * representations but are considered equal when using the primitive
4208 * {@code ==} operator. Operation failure can occur if, for example, a
4209 * numeric algorithm computes an expected value to be say {@code -0.0}
4210 * and previously computed the witness value to be say {@code +0.0}.
4211 * @param arrayClass the class of an array, of type {@code T[]}
4212 * @return a VarHandle giving access to elements of an array
4213 * @throws NullPointerException if the arrayClass is null
4214 * @throws IllegalArgumentException if arrayClass is not an array type
4215 * @since 9
4216 */
4217 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4218 return VarHandles.makeArrayElementHandle(arrayClass);
4219 }
4220
4221 /**
4222 * Produces a VarHandle giving access to elements of a {@code byte[]} array
4223 * viewed as if it were a different primitive array type, such as
4224 * {@code int[]} or {@code long[]}.
4225 * The VarHandle's variable type is the component type of
4226 * {@code viewArrayClass} and the list of coordinate types is
4227 * {@code (byte[], int)}, where the {@code int} coordinate type
4228 * corresponds to an argument that is an index into a {@code byte[]} array.
4229 * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4230 * array, composing bytes to or from a value of the component type of
4231 * {@code viewArrayClass} according to the given endianness.
4232 * <p>
4233 * The supported component types (variables types) are {@code short},
4234 * {@code char}, {@code int}, {@code long}, {@code float} and
4235 * {@code double}.
4236 * <p>
4237 * Access of bytes at a given index will result in an
4238 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4239 * or greater than the {@code byte[]} array length minus the size (in bytes)
4240 * of {@code T}.
4241 * <p>
4242 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set}
4243 * access modes are supported by the returned var handle. For all other access modes, an
4244 * {@link UnsupportedOperationException} will be thrown.
4245 *
4246 * @apiNote if access modes other than plain access are required, clients should
4247 * consider using off-heap memory through
4248 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or
4249 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments},
4250 * or memory segments backed by a
4251 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}},
4252 * for which stronger alignment guarantees can be made.
4253 *
4254 * @param viewArrayClass the view array class, with a component type of
4255 * type {@code T}
4256 * @param byteOrder the endianness of the view array elements, as
4257 * stored in the underlying {@code byte} array
4258 * @return a VarHandle giving access to elements of a {@code byte[]} array
4259 * viewed as if elements corresponding to the components type of the view
4260 * array class
4261 * @throws NullPointerException if viewArrayClass or byteOrder is null
4262 * @throws IllegalArgumentException if viewArrayClass is not an array type
4263 * @throws UnsupportedOperationException if the component type of
4264 * viewArrayClass is not supported as a variable type
4265 * @since 9
4266 */
4267 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4268 ByteOrder byteOrder) throws IllegalArgumentException {
4269 Objects.requireNonNull(byteOrder);
4270 return VarHandles.byteArrayViewHandle(viewArrayClass,
4271 byteOrder == ByteOrder.BIG_ENDIAN);
4272 }
4273
4274 /**
4275 * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4276 * viewed as if it were an array of elements of a different primitive
4277 * component type to that of {@code byte}, such as {@code int[]} or
4278 * {@code long[]}.
4279 * The VarHandle's variable type is the component type of
4280 * {@code viewArrayClass} and the list of coordinate types is
4281 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4282 * corresponds to an argument that is an index into a {@code byte[]} array.
4283 * The returned VarHandle accesses bytes at an index in a
4284 * {@code ByteBuffer}, composing bytes to or from a value of the component
4285 * type of {@code viewArrayClass} according to the given endianness.
4286 * <p>
4287 * The supported component types (variables types) are {@code short},
4288 * {@code char}, {@code int}, {@code long}, {@code float} and
4289 * {@code double}.
4290 * <p>
4291 * Access will result in a {@code ReadOnlyBufferException} for anything
4292 * other than the read access modes if the {@code ByteBuffer} is read-only.
4293 * <p>
4294 * Access of bytes at a given index will result in an
4295 * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4296 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4297 * {@code T}.
4298 * <p>
4299 * For heap byte buffers, access is always unaligned. As a result, only the plain
4300 * {@linkplain VarHandle.AccessMode#GET get}
4301 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the
4302 * returned var handle. For all other access modes, an {@link IllegalStateException}
4303 * will be thrown.
4304 * <p>
4305 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T},
4306 * with respect to the underlying memory address, {@code A} say, associated
4307 * with the {@code ByteBuffer} and index.
4308 * If access is misaligned then access for anything other than the
4309 * {@code get} and {@code set} access modes will result in an
4310 * {@code IllegalStateException}. In such cases atomic access is only
4311 * guaranteed with respect to the largest power of two that divides the GCD
4312 * of {@code A} and the size (in bytes) of {@code T}.
4313 * If access is aligned then following access modes are supported and are
4314 * guaranteed to support atomic access:
4315 * <ul>
4316 * <li>read write access modes for all {@code T}. Access modes {@code get}
4317 * and {@code set} for {@code long} and {@code double} are supported but
4318 * have no atomicity guarantee, as described in Section {@jls 17.7} of
4319 * <cite>The Java Language Specification</cite>.
4320 * <li>atomic update access modes for {@code int}, {@code long},
4321 * {@code float} or {@code double}.
4322 * (Future major platform releases of the JDK may support additional
4323 * types for certain currently unsupported access modes.)
4324 * <li>numeric atomic update access modes for {@code int} and {@code long}.
4325 * (Future major platform releases of the JDK may support additional
4326 * numeric types for certain currently unsupported access modes.)
4327 * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4328 * (Future major platform releases of the JDK may support additional
4329 * numeric types for certain currently unsupported access modes.)
4330 * </ul>
4331 * <p>
4332 * Misaligned access, and therefore atomicity guarantees, may be determined
4333 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4334 * {@code index}, {@code T} and its corresponding boxed type,
4335 * {@code T_BOX}, as follows:
4336 * <pre>{@code
4337 * int sizeOfT = T_BOX.BYTES; // size in bytes of T
4338 * ByteBuffer bb = ...
4339 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4340 * boolean isMisaligned = misalignedAtIndex != 0;
4341 * }</pre>
4342 * <p>
4343 * If the variable type is {@code float} or {@code double} then atomic
4344 * update access modes compare values using their bitwise representation
4345 * (see {@link Float#floatToRawIntBits} and
4346 * {@link Double#doubleToRawLongBits}, respectively).
4347 * @param viewArrayClass the view array class, with a component type of
4348 * type {@code T}
4349 * @param byteOrder the endianness of the view array elements, as
4350 * stored in the underlying {@code ByteBuffer} (Note this overrides the
4351 * endianness of a {@code ByteBuffer})
4352 * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4353 * viewed as if elements corresponding to the components type of the view
4354 * array class
4355 * @throws NullPointerException if viewArrayClass or byteOrder is null
4356 * @throws IllegalArgumentException if viewArrayClass is not an array type
4357 * @throws UnsupportedOperationException if the component type of
4358 * viewArrayClass is not supported as a variable type
4359 * @since 9
4360 */
4361 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4362 ByteOrder byteOrder) throws IllegalArgumentException {
4363 Objects.requireNonNull(byteOrder);
4364 return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4365 byteOrder == ByteOrder.BIG_ENDIAN);
4366 }
4367
4368
4369 //--- method handle invocation (reflective style)
4370
4371 /**
4372 * Produces a method handle which will invoke any method handle of the
4373 * given {@code type}, with a given number of trailing arguments replaced by
4374 * a single trailing {@code Object[]} array.
4375 * The resulting invoker will be a method handle with the following
4376 * arguments:
4377 * <ul>
4378 * <li>a single {@code MethodHandle} target
4379 * <li>zero or more leading values (counted by {@code leadingArgCount})
4380 * <li>an {@code Object[]} array containing trailing arguments
4381 * </ul>
4382 * <p>
4383 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4384 * the indicated {@code type}.
4385 * That is, if the target is exactly of the given {@code type}, it will behave
4386 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4387 * is used to convert the target to the required {@code type}.
4388 * <p>
4389 * The type of the returned invoker will not be the given {@code type}, but rather
4390 * will have all parameters except the first {@code leadingArgCount}
4391 * replaced by a single array of type {@code Object[]}, which will be
4392 * the final parameter.
4393 * <p>
4394 * Before invoking its target, the invoker will spread the final array, apply
4395 * reference casts as necessary, and unbox and widen primitive arguments.
4396 * If, when the invoker is called, the supplied array argument does
4397 * not have the correct number of elements, the invoker will throw
4398 * an {@link IllegalArgumentException} instead of invoking the target.
4399 * <p>
4400 * This method is equivalent to the following code (though it may be more efficient):
4401 * {@snippet lang="java" :
4402 MethodHandle invoker = MethodHandles.invoker(type);
4403 int spreadArgCount = type.parameterCount() - leadingArgCount;
4404 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4405 return invoker;
4406 * }
4407 * This method throws no reflective exceptions.
4408 * @param type the desired target type
4409 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4410 * @return a method handle suitable for invoking any method handle of the given type
4411 * @throws NullPointerException if {@code type} is null
4412 * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4413 * the range from 0 to {@code type.parameterCount()} inclusive,
4414 * or if the resulting method handle's type would have
4415 * <a href="MethodHandle.html#maxarity">too many parameters</a>
4416 */
4417 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4418 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4419 throw newIllegalArgumentException("bad argument count", leadingArgCount);
4420 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4421 return type.invokers().spreadInvoker(leadingArgCount);
4422 }
4423
4424 /**
4425 * Produces a special <em>invoker method handle</em> which can be used to
4426 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4427 * The resulting invoker will have a type which is
4428 * exactly equal to the desired type, except that it will accept
4429 * an additional leading argument of type {@code MethodHandle}.
4430 * <p>
4431 * This method is equivalent to the following code (though it may be more efficient):
4432 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4433 *
4434 * <p style="font-size:smaller;">
4435 * <em>Discussion:</em>
4436 * Invoker method handles can be useful when working with variable method handles
4437 * of unknown types.
4438 * For example, to emulate an {@code invokeExact} call to a variable method
4439 * handle {@code M}, extract its type {@code T},
4440 * look up the invoker method {@code X} for {@code T},
4441 * and call the invoker method, as {@code X.invoke(T, A...)}.
4442 * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4443 * is unknown.)
4444 * If spreading, collecting, or other argument transformations are required,
4445 * they can be applied once to the invoker {@code X} and reused on many {@code M}
4446 * method handle values, as long as they are compatible with the type of {@code X}.
4447 * <p style="font-size:smaller;">
4448 * <em>(Note: The invoker method is not available via the Core Reflection API.
4449 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4450 * on the declared {@code invokeExact} or {@code invoke} method will raise an
4451 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4452 * <p>
4453 * This method throws no reflective exceptions.
4454 * @param type the desired target type
4455 * @return a method handle suitable for invoking any method handle of the given type
4456 * @throws IllegalArgumentException if the resulting method handle's type would have
4457 * <a href="MethodHandle.html#maxarity">too many parameters</a>
4458 */
4459 public static MethodHandle exactInvoker(MethodType type) {
4460 return type.invokers().exactInvoker();
4461 }
4462
4463 /**
4464 * Produces a special <em>invoker method handle</em> which can be used to
4465 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4466 * The resulting invoker will have a type which is
4467 * exactly equal to the desired type, except that it will accept
4468 * an additional leading argument of type {@code MethodHandle}.
4469 * <p>
4470 * Before invoking its target, if the target differs from the expected type,
4471 * the invoker will apply reference casts as
4472 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4473 * Similarly, the return value will be converted as necessary.
4474 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4475 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4476 * <p>
4477 * This method is equivalent to the following code (though it may be more efficient):
4478 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4479 * <p style="font-size:smaller;">
4480 * <em>Discussion:</em>
4481 * A {@linkplain MethodType#genericMethodType general method type} is one which
4482 * mentions only {@code Object} arguments and return values.
4483 * An invoker for such a type is capable of calling any method handle
4484 * of the same arity as the general type.
4485 * <p style="font-size:smaller;">
4486 * <em>(Note: The invoker method is not available via the Core Reflection API.
4487 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4488 * on the declared {@code invokeExact} or {@code invoke} method will raise an
4489 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4490 * <p>
4491 * This method throws no reflective exceptions.
4492 * @param type the desired target type
4493 * @return a method handle suitable for invoking any method handle convertible to the given type
4494 * @throws IllegalArgumentException if the resulting method handle's type would have
4495 * <a href="MethodHandle.html#maxarity">too many parameters</a>
4496 */
4497 public static MethodHandle invoker(MethodType type) {
4498 return type.invokers().genericInvoker();
4499 }
4500
4501 /**
4502 * Produces a special <em>invoker method handle</em> which can be used to
4503 * invoke a signature-polymorphic access mode method on any VarHandle whose
4504 * associated access mode type is compatible with the given type.
4505 * The resulting invoker will have a type which is exactly equal to the
4506 * desired given type, except that it will accept an additional leading
4507 * argument of type {@code VarHandle}.
4508 *
4509 * @param accessMode the VarHandle access mode
4510 * @param type the desired target type
4511 * @return a method handle suitable for invoking an access mode method of
4512 * any VarHandle whose access mode type is of the given type.
4513 * @since 9
4514 */
4515 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4516 return type.invokers().varHandleMethodExactInvoker(accessMode);
4517 }
4518
4519 /**
4520 * Produces a special <em>invoker method handle</em> which can be used to
4521 * invoke a signature-polymorphic access mode method on any VarHandle whose
4522 * associated access mode type is compatible with the given type.
4523 * The resulting invoker will have a type which is exactly equal to the
4524 * desired given type, except that it will accept an additional leading
4525 * argument of type {@code VarHandle}.
4526 * <p>
4527 * Before invoking its target, if the access mode type differs from the
4528 * desired given type, the invoker will apply reference casts as necessary
4529 * and box, unbox, or widen primitive values, as if by
4530 * {@link MethodHandle#asType asType}. Similarly, the return value will be
4531 * converted as necessary.
4532 * <p>
4533 * This method is equivalent to the following code (though it may be more
4534 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4535 *
4536 * @param accessMode the VarHandle access mode
4537 * @param type the desired target type
4538 * @return a method handle suitable for invoking an access mode method of
4539 * any VarHandle whose access mode type is convertible to the given
4540 * type.
4541 * @since 9
4542 */
4543 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4544 return type.invokers().varHandleMethodInvoker(accessMode);
4545 }
4546
4547 /*non-public*/
4548 static MethodHandle basicInvoker(MethodType type) {
4549 return type.invokers().basicInvoker();
4550 }
4551
4552 //--- method handle modification (creation from other method handles)
4553
4554 /**
4555 * Produces a method handle which adapts the type of the
4556 * given method handle to a new type by pairwise argument and return type conversion.
4557 * The original type and new type must have the same number of arguments.
4558 * The resulting method handle is guaranteed to report a type
4559 * which is equal to the desired new type.
4560 * <p>
4561 * If the original type and new type are equal, returns target.
4562 * <p>
4563 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4564 * and some additional conversions are also applied if those conversions fail.
4565 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4566 * if possible, before or instead of any conversions done by {@code asType}:
4567 * <ul>
4568 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4569 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4570 * (This treatment of interfaces follows the usage of the bytecode verifier.)
4571 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4572 * the boolean is converted to a byte value, 1 for true, 0 for false.
4573 * (This treatment follows the usage of the bytecode verifier.)
4574 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4575 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4576 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4577 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4578 * then a Java casting conversion (JLS {@jls 5.5}) is applied.
4579 * (Specifically, <em>T0</em> will convert to <em>T1</em> by
4580 * widening and/or narrowing.)
4581 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4582 * conversion will be applied at runtime, possibly followed
4583 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4584 * possibly followed by a conversion from byte to boolean by testing
4585 * the low-order bit.
4586 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4587 * and if the reference is null at runtime, a zero value is introduced.
4588 * </ul>
4589 * @param target the method handle to invoke after arguments are retyped
4590 * @param newType the expected type of the new method handle
4591 * @return a method handle which delegates to the target after performing
4592 * any necessary argument conversions, and arranges for any
4593 * necessary return value conversions
4594 * @throws NullPointerException if either argument is null
4595 * @throws WrongMethodTypeException if the conversion cannot be made
4596 * @see MethodHandle#asType
4597 */
4598 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4599 explicitCastArgumentsChecks(target, newType);
4600 // use the asTypeCache when possible:
4601 MethodType oldType = target.type();
4602 if (oldType == newType) return target;
4603 if (oldType.explicitCastEquivalentToAsType(newType)) {
4604 return target.asFixedArity().asType(newType);
4605 }
4606 return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4607 }
4608
4609 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4610 if (target.type().parameterCount() != newType.parameterCount()) {
4611 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4612 }
4613 }
4614
4615 /**
4616 * Produces a method handle which adapts the calling sequence of the
4617 * given method handle to a new type, by reordering the arguments.
4618 * The resulting method handle is guaranteed to report a type
4619 * which is equal to the desired new type.
4620 * <p>
4621 * The given array controls the reordering.
4622 * Call {@code #I} the number of incoming parameters (the value
4623 * {@code newType.parameterCount()}, and call {@code #O} the number
4624 * of outgoing parameters (the value {@code target.type().parameterCount()}).
4625 * Then the length of the reordering array must be {@code #O},
4626 * and each element must be a non-negative number less than {@code #I}.
4627 * For every {@code N} less than {@code #O}, the {@code N}-th
4628 * outgoing argument will be taken from the {@code I}-th incoming
4629 * argument, where {@code I} is {@code reorder[N]}.
4630 * <p>
4631 * No argument or return value conversions are applied.
4632 * The type of each incoming argument, as determined by {@code newType},
4633 * must be identical to the type of the corresponding outgoing parameter
4634 * or parameters in the target method handle.
4635 * The return type of {@code newType} must be identical to the return
4636 * type of the original target.
4637 * <p>
4638 * The reordering array need not specify an actual permutation.
4639 * An incoming argument will be duplicated if its index appears
4640 * more than once in the array, and an incoming argument will be dropped
4641 * if its index does not appear in the array.
4642 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4643 * incoming arguments which are not mentioned in the reordering array
4644 * may be of any type, as determined only by {@code newType}.
4645 * {@snippet lang="java" :
4646 import static java.lang.invoke.MethodHandles.*;
4647 import static java.lang.invoke.MethodType.*;
4648 ...
4649 MethodType intfn1 = methodType(int.class, int.class);
4650 MethodType intfn2 = methodType(int.class, int.class, int.class);
4651 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4652 assert(sub.type().equals(intfn2));
4653 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4654 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4655 assert((int)rsub.invokeExact(1, 100) == 99);
4656 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4657 assert(add.type().equals(intfn2));
4658 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4659 assert(twice.type().equals(intfn1));
4660 assert((int)twice.invokeExact(21) == 42);
4661 * }
4662 * <p>
4663 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4664 * variable-arity method handle}, even if the original target method handle was.
4665 * @param target the method handle to invoke after arguments are reordered
4666 * @param newType the expected type of the new method handle
4667 * @param reorder an index array which controls the reordering
4668 * @return a method handle which delegates to the target after it
4669 * drops unused arguments and moves and/or duplicates the other arguments
4670 * @throws NullPointerException if any argument is null
4671 * @throws IllegalArgumentException if the index array length is not equal to
4672 * the arity of the target, or if any index array element
4673 * not a valid index for a parameter of {@code newType},
4674 * or if two corresponding parameter types in
4675 * {@code target.type()} and {@code newType} are not identical,
4676 */
4677 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4678 reorder = reorder.clone(); // get a private copy
4679 MethodType oldType = target.type();
4680 permuteArgumentChecks(reorder, newType, oldType);
4681 // first detect dropped arguments and handle them separately
4682 int[] originalReorder = reorder;
4683 BoundMethodHandle result = target.rebind();
4684 LambdaForm form = result.form;
4685 int newArity = newType.parameterCount();
4686 // Normalize the reordering into a real permutation,
4687 // by removing duplicates and adding dropped elements.
4688 // This somewhat improves lambda form caching, as well
4689 // as simplifying the transform by breaking it up into steps.
4690 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4691 if (ddIdx > 0) {
4692 // We found a duplicated entry at reorder[ddIdx].
4693 // Example: (x,y,z)->asList(x,y,z)
4694 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4695 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4696 // The starred element corresponds to the argument
4697 // deleted by the dupArgumentForm transform.
4698 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4699 boolean killFirst = false;
4700 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4701 // Set killFirst if the dup is larger than an intervening position.
4702 // This will remove at least one inversion from the permutation.
4703 if (dupVal > val) killFirst = true;
4704 }
4705 if (!killFirst) {
4706 srcPos = dstPos;
4707 dstPos = ddIdx;
4708 }
4709 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4710 assert (reorder[srcPos] == reorder[dstPos]);
4711 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4712 // contract the reordering by removing the element at dstPos
4713 int tailPos = dstPos + 1;
4714 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4715 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4716 } else {
4717 int dropVal = ~ddIdx, insPos = 0;
4718 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4719 // Find first element of reorder larger than dropVal.
4720 // This is where we will insert the dropVal.
4721 insPos += 1;
4722 }
4723 Class<?> ptype = newType.parameterType(dropVal);
4724 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4725 oldType = oldType.insertParameterTypes(insPos, ptype);
4726 // expand the reordering by inserting an element at insPos
4727 int tailPos = insPos + 1;
4728 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4729 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4730 reorder[insPos] = dropVal;
4731 }
4732 assert (permuteArgumentChecks(reorder, newType, oldType));
4733 }
4734 assert (reorder.length == newArity); // a perfect permutation
4735 // Note: This may cache too many distinct LFs. Consider backing off to varargs code.
4736 form = form.editor().permuteArgumentsForm(1, reorder);
4737 if (newType == result.type() && form == result.internalForm())
4738 return result;
4739 return result.copyWith(newType, form);
4740 }
4741
4742 /**
4743 * Return an indication of any duplicate or omission in reorder.
4744 * If the reorder contains a duplicate entry, return the index of the second occurrence.
4745 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4746 * Otherwise, return zero.
4747 * If an element not in [0..newArity-1] is encountered, return reorder.length.
4748 */
4749 private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4750 final int BIT_LIMIT = 63; // max number of bits in bit mask
4751 if (newArity < BIT_LIMIT) {
4752 long mask = 0;
4753 for (int i = 0; i < reorder.length; i++) {
4754 int arg = reorder[i];
4755 if (arg >= newArity) {
4756 return reorder.length;
4757 }
4758 long bit = 1L << arg;
4759 if ((mask & bit) != 0) {
4760 return i; // >0 indicates a dup
4761 }
4762 mask |= bit;
4763 }
4764 if (mask == (1L << newArity) - 1) {
4765 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4766 return 0;
4767 }
4768 // find first zero
4769 long zeroBit = Long.lowestOneBit(~mask);
4770 int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4771 assert(zeroPos <= newArity);
4772 if (zeroPos == newArity) {
4773 return 0;
4774 }
4775 return ~zeroPos;
4776 } else {
4777 // same algorithm, different bit set
4778 BitSet mask = new BitSet(newArity);
4779 for (int i = 0; i < reorder.length; i++) {
4780 int arg = reorder[i];
4781 if (arg >= newArity) {
4782 return reorder.length;
4783 }
4784 if (mask.get(arg)) {
4785 return i; // >0 indicates a dup
4786 }
4787 mask.set(arg);
4788 }
4789 int zeroPos = mask.nextClearBit(0);
4790 assert(zeroPos <= newArity);
4791 if (zeroPos == newArity) {
4792 return 0;
4793 }
4794 return ~zeroPos;
4795 }
4796 }
4797
4798 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4799 if (newType.returnType() != oldType.returnType())
4800 throw newIllegalArgumentException("return types do not match",
4801 oldType, newType);
4802 if (reorder.length != oldType.parameterCount())
4803 throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
4804 oldType, Arrays.toString(reorder));
4805
4806 int limit = newType.parameterCount();
4807 for (int j = 0; j < reorder.length; j++) {
4808 int i = reorder[j];
4809 if (i < 0 || i >= limit) {
4810 throw newIllegalArgumentException("index is out of bounds for new type",
4811 i, newType);
4812 }
4813 Class<?> src = newType.parameterType(i);
4814 Class<?> dst = oldType.parameterType(j);
4815 if (src != dst)
4816 throw newIllegalArgumentException("parameter types do not match after reorder",
4817 oldType, newType);
4818 }
4819 return true;
4820 }
4821
4822 /**
4823 * Produces a method handle of the requested return type which returns the given
4824 * constant value every time it is invoked.
4825 * <p>
4826 * Before the method handle is returned, the passed-in value is converted to the requested type.
4827 * If the requested type is primitive, widening primitive conversions are attempted,
4828 * else reference conversions are attempted.
4829 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)},
4830 * for reference types. For all types it is equivalent to
4831 * {@code insertArguments(identity(type), 0, value)}.
4832 * @param type the return type of the desired method handle
4833 * @param value the value to return
4834 * @return a method handle of the given return type and no arguments, which always returns the given value
4835 * @throws NullPointerException if the {@code type} argument is null
4836 * @throws ClassCastException if the value cannot be converted to the required return type
4837 * @throws IllegalArgumentException if the given type is {@code void.class}
4838 */
4839 public static MethodHandle constant(Class<?> type, Object value) {
4840 if (Objects.requireNonNull(type) == void.class)
4841 throw newIllegalArgumentException("void type");
4842 return MethodHandleImpl.makeConstantReturning(type, value);
4843 }
4844
4845 /**
4846 * Produces a method handle which returns its sole argument when invoked.
4847 * @param type the type of the sole parameter and return value of the desired method handle
4848 * @return a unary method handle which accepts and returns the given type
4849 * @throws NullPointerException if the argument is null
4850 * @throws IllegalArgumentException if the given type is {@code void.class}
4851 */
4852 public static MethodHandle identity(Class<?> type) {
4853 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
4854 int pos = btw.ordinal();
4855 MethodHandle ident = IDENTITY_MHS[pos];
4856 if (ident == null) {
4857 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
4858 }
4859 if (ident.type().returnType() == type)
4860 return ident;
4861 // something like identity(Foo.class); do not bother to intern these
4862 assert (btw == Wrapper.OBJECT);
4863 return makeIdentity(type);
4864 }
4865
4866 /**
4867 * Produces a constant method handle of the requested return type which
4868 * returns the default value for that type every time it is invoked.
4869 * The resulting constant method handle will have no side effects.
4870 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
4871 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
4872 * since {@code explicitCastArguments} converts {@code null} to default values.
4873 * @param type the expected return type of the desired method handle
4874 * @return a constant method handle that takes no arguments
4875 * and returns the default value of the given type (or void, if the type is void)
4876 * @throws NullPointerException if the argument is null
4877 * @see MethodHandles#constant
4878 * @see MethodHandles#empty
4879 * @see MethodHandles#explicitCastArguments
4880 * @since 9
4881 */
4882 public static MethodHandle zero(Class<?> type) {
4883 Objects.requireNonNull(type);
4884 return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type))
4885 : MethodHandleImpl.makeConstantReturning(type, null);
4886 }
4887
4888 private static MethodHandle identityOrVoid(Class<?> type) {
4889 return type == void.class ? zero(type) : identity(type);
4890 }
4891
4892 /**
4893 * Produces a method handle of the requested type which ignores any arguments, does nothing,
4894 * and returns a suitable default depending on the return type.
4895 * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
4896 * <p>The returned method handle is equivalent to
4897 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
4898 *
4899 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
4900 * {@code guardWithTest(pred, target, empty(target.type())}.
4901 * @param type the type of the desired method handle
4902 * @return a constant method handle of the given type, which returns a default value of the given return type
4903 * @throws NullPointerException if the argument is null
4904 * @see MethodHandles#zero(Class)
4905 * @see MethodHandles#constant
4906 * @since 9
4907 */
4908 public static MethodHandle empty(MethodType type) {
4909 Objects.requireNonNull(type);
4910 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
4911 }
4912
4913 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
4914 private static MethodHandle makeIdentity(Class<?> ptype) {
4915 MethodType mtype = methodType(ptype, ptype); // throws IAE for void
4916 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
4917 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
4918 }
4919
4920 private static MethodHandle primitiveZero(Wrapper w) {
4921 assert w != Wrapper.OBJECT : w;
4922 int pos = w.ordinal();
4923 MethodHandle mh = PRIMITIVE_ZERO_MHS[pos];
4924 if (mh == null) {
4925 mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w));
4926 }
4927 assert (mh.type().returnType() == w.primitiveType()) : mh;
4928 return mh;
4929 }
4930
4931 private static MethodHandle makePrimitiveZero(Wrapper w) {
4932 if (w == Wrapper.VOID) {
4933 var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized
4934 return SimpleMethodHandle.make(MethodType.methodType(void.class), lf);
4935 } else {
4936 return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero());
4937 }
4938 }
4939
4940 private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT];
4941
4942 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
4943 // Simulate a CAS, to avoid racy duplication of results.
4944 MethodHandle prev = cache[pos];
4945 if (prev != null) return prev;
4946 return cache[pos] = value;
4947 }
4948
4949 /**
4950 * Provides a target method handle with one or more <em>bound arguments</em>
4951 * in advance of the method handle's invocation.
4952 * The formal parameters to the target corresponding to the bound
4953 * arguments are called <em>bound parameters</em>.
4954 * Returns a new method handle which saves away the bound arguments.
4955 * When it is invoked, it receives arguments for any non-bound parameters,
4956 * binds the saved arguments to their corresponding parameters,
4957 * and calls the original target.
4958 * <p>
4959 * The type of the new method handle will drop the types for the bound
4960 * parameters from the original target type, since the new method handle
4961 * will no longer require those arguments to be supplied by its callers.
4962 * <p>
4963 * Each given argument object must match the corresponding bound parameter type.
4964 * If a bound parameter type is a primitive, the argument object
4965 * must be a wrapper, and will be unboxed to produce the primitive value.
4966 * <p>
4967 * The {@code pos} argument selects which parameters are to be bound.
4968 * It may range between zero and <i>N-L</i> (inclusively),
4969 * where <i>N</i> is the arity of the target method handle
4970 * and <i>L</i> is the length of the values array.
4971 * <p>
4972 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4973 * variable-arity method handle}, even if the original target method handle was.
4974 * @param target the method handle to invoke after the argument is inserted
4975 * @param pos where to insert the argument (zero for the first)
4976 * @param values the series of arguments to insert
4977 * @return a method handle which inserts an additional argument,
4978 * before calling the original method handle
4979 * @throws NullPointerException if the target or the {@code values} array is null
4980 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
4981 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
4982 * is the length of the values array.
4983 * @throws ClassCastException if an argument does not match the corresponding bound parameter
4984 * type.
4985 * @see MethodHandle#bindTo
4986 */
4987 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
4988 int insCount = values.length;
4989 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
4990 if (insCount == 0) return target;
4991 BoundMethodHandle result = target.rebind();
4992 for (int i = 0; i < insCount; i++) {
4993 Object value = values[i];
4994 Class<?> ptype = ptypes[pos+i];
4995 if (ptype.isPrimitive()) {
4996 result = insertArgumentPrimitive(result, pos, ptype, value);
4997 } else {
4998 value = ptype.cast(value); // throw CCE if needed
4999 result = result.bindArgumentL(pos, value);
5000 }
5001 }
5002 return result;
5003 }
5004
5005 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5006 Class<?> ptype, Object value) {
5007 Wrapper w = Wrapper.forPrimitiveType(ptype);
5008 // perform unboxing and/or primitive conversion
5009 value = w.convert(value, ptype);
5010 return switch (w) {
5011 case INT -> result.bindArgumentI(pos, (int) value);
5012 case LONG -> result.bindArgumentJ(pos, (long) value);
5013 case FLOAT -> result.bindArgumentF(pos, (float) value);
5014 case DOUBLE -> result.bindArgumentD(pos, (double) value);
5015 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5016 };
5017 }
5018
5019 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5020 MethodType oldType = target.type();
5021 int outargs = oldType.parameterCount();
5022 int inargs = outargs - insCount;
5023 if (inargs < 0)
5024 throw newIllegalArgumentException("too many values to insert");
5025 if (pos < 0 || pos > inargs)
5026 throw newIllegalArgumentException("no argument type to append");
5027 return oldType.ptypes();
5028 }
5029
5030 /**
5031 * Produces a method handle which will discard some dummy arguments
5032 * before calling some other specified <i>target</i> method handle.
5033 * The type of the new method handle will be the same as the target's type,
5034 * except it will also include the dummy argument types,
5035 * at some given position.
5036 * <p>
5037 * The {@code pos} argument may range between zero and <i>N</i>,
5038 * where <i>N</i> is the arity of the target.
5039 * If {@code pos} is zero, the dummy arguments will precede
5040 * the target's real arguments; if {@code pos} is <i>N</i>
5041 * they will come after.
5042 * <p>
5043 * <b>Example:</b>
5044 * {@snippet lang="java" :
5045 import static java.lang.invoke.MethodHandles.*;
5046 import static java.lang.invoke.MethodType.*;
5047 ...
5048 MethodHandle cat = lookup().findVirtual(String.class,
5049 "concat", methodType(String.class, String.class));
5050 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5051 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5052 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5053 assertEquals(bigType, d0.type());
5054 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5055 * }
5056 * <p>
5057 * This method is also equivalent to the following code:
5058 * <blockquote><pre>
5059 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5060 * </pre></blockquote>
5061 * @param target the method handle to invoke after the arguments are dropped
5062 * @param pos position of first argument to drop (zero for the leftmost)
5063 * @param valueTypes the type(s) of the argument(s) to drop
5064 * @return a method handle which drops arguments of the given types,
5065 * before calling the original method handle
5066 * @throws NullPointerException if the target is null,
5067 * or if the {@code valueTypes} list or any of its elements is null
5068 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5069 * or if {@code pos} is negative or greater than the arity of the target,
5070 * or if the new method handle's type would have too many parameters
5071 */
5072 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5073 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5074 }
5075
5076 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5077 MethodType oldType = target.type(); // get NPE
5078 int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5079 MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5080 if (dropped == 0) return target;
5081 BoundMethodHandle result = target.rebind();
5082 LambdaForm lform = result.form;
5083 int insertFormArg = 1 + pos;
5084 for (Class<?> ptype : valueTypes) {
5085 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5086 }
5087 result = result.copyWith(newType, lform);
5088 return result;
5089 }
5090
5091 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5092 int dropped = valueTypes.length;
5093 MethodType.checkSlotCount(dropped);
5094 int outargs = oldType.parameterCount();
5095 int inargs = outargs + dropped;
5096 if (pos < 0 || pos > outargs)
5097 throw newIllegalArgumentException("no argument type to remove"
5098 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5099 );
5100 return dropped;
5101 }
5102
5103 /**
5104 * Produces a method handle which will discard some dummy arguments
5105 * before calling some other specified <i>target</i> method handle.
5106 * The type of the new method handle will be the same as the target's type,
5107 * except it will also include the dummy argument types,
5108 * at some given position.
5109 * <p>
5110 * The {@code pos} argument may range between zero and <i>N</i>,
5111 * where <i>N</i> is the arity of the target.
5112 * If {@code pos} is zero, the dummy arguments will precede
5113 * the target's real arguments; if {@code pos} is <i>N</i>
5114 * they will come after.
5115 * @apiNote
5116 * {@snippet lang="java" :
5117 import static java.lang.invoke.MethodHandles.*;
5118 import static java.lang.invoke.MethodType.*;
5119 ...
5120 MethodHandle cat = lookup().findVirtual(String.class,
5121 "concat", methodType(String.class, String.class));
5122 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5123 MethodHandle d0 = dropArguments(cat, 0, String.class);
5124 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5125 MethodHandle d1 = dropArguments(cat, 1, String.class);
5126 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5127 MethodHandle d2 = dropArguments(cat, 2, String.class);
5128 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5129 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5130 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5131 * }
5132 * <p>
5133 * This method is also equivalent to the following code:
5134 * <blockquote><pre>
5135 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5136 * </pre></blockquote>
5137 * @param target the method handle to invoke after the arguments are dropped
5138 * @param pos position of first argument to drop (zero for the leftmost)
5139 * @param valueTypes the type(s) of the argument(s) to drop
5140 * @return a method handle which drops arguments of the given types,
5141 * before calling the original method handle
5142 * @throws NullPointerException if the target is null,
5143 * or if the {@code valueTypes} array or any of its elements is null
5144 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5145 * or if {@code pos} is negative or greater than the arity of the target,
5146 * or if the new method handle's type would have
5147 * <a href="MethodHandle.html#maxarity">too many parameters</a>
5148 */
5149 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5150 return dropArgumentsTrusted(target, pos, valueTypes.clone());
5151 }
5152
5153 /* Convenience overloads for trusting internal low-arity call-sites */
5154 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5155 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5156 }
5157 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5158 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5159 }
5160
5161 // private version which allows caller some freedom with error handling
5162 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5163 boolean nullOnFailure) {
5164 Class<?>[] oldTypes = target.type().ptypes();
5165 int match = oldTypes.length;
5166 if (skip != 0) {
5167 if (skip < 0 || skip > match) {
5168 throw newIllegalArgumentException("illegal skip", skip, target);
5169 }
5170 oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5171 match -= skip;
5172 }
5173 Class<?>[] addTypes = newTypes;
5174 int add = addTypes.length;
5175 if (pos != 0) {
5176 if (pos < 0 || pos > add) {
5177 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5178 }
5179 addTypes = Arrays.copyOfRange(addTypes, pos, add);
5180 add -= pos;
5181 assert(addTypes.length == add);
5182 }
5183 // Do not add types which already match the existing arguments.
5184 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5185 if (nullOnFailure) {
5186 return null;
5187 }
5188 throw newIllegalArgumentException("argument lists do not match",
5189 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5190 }
5191 addTypes = Arrays.copyOfRange(addTypes, match, add);
5192 add -= match;
5193 assert(addTypes.length == add);
5194 // newTypes: ( P*[pos], M*[match], A*[add] )
5195 // target: ( S*[skip], M*[match] )
5196 MethodHandle adapter = target;
5197 if (add > 0) {
5198 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5199 }
5200 // adapter: (S*[skip], M*[match], A*[add] )
5201 if (pos > 0) {
5202 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5203 }
5204 // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5205 return adapter;
5206 }
5207
5208 /**
5209 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5210 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5211 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5212 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5213 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5214 * {@link #dropArguments(MethodHandle, int, Class[])}.
5215 * <p>
5216 * The resulting handle will have the same return type as the target handle.
5217 * <p>
5218 * In more formal terms, assume these two type lists:<ul>
5219 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5220 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5221 * {@code newTypes}.
5222 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5223 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5224 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5225 * sub-list.
5226 * </ul>
5227 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5228 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5229 * {@link #dropArguments(MethodHandle, int, Class[])}.
5230 *
5231 * @apiNote
5232 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5233 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5234 * {@snippet lang="java" :
5235 import static java.lang.invoke.MethodHandles.*;
5236 import static java.lang.invoke.MethodType.*;
5237 ...
5238 ...
5239 MethodHandle h0 = constant(boolean.class, true);
5240 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5241 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5242 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5243 if (h1.type().parameterCount() < h2.type().parameterCount())
5244 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1
5245 else
5246 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2
5247 MethodHandle h3 = guardWithTest(h0, h1, h2);
5248 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5249 * }
5250 * @param target the method handle to adapt
5251 * @param skip number of targets parameters to disregard (they will be unchanged)
5252 * @param newTypes the list of types to match {@code target}'s parameter type list to
5253 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5254 * @return a possibly adapted method handle
5255 * @throws NullPointerException if either argument is null
5256 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5257 * or if {@code skip} is negative or greater than the arity of the target,
5258 * or if {@code pos} is negative or greater than the newTypes list size,
5259 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5260 * {@code pos}.
5261 * @since 9
5262 */
5263 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5264 Objects.requireNonNull(target);
5265 Objects.requireNonNull(newTypes);
5266 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5267 }
5268
5269 /**
5270 * Drop the return value of the target handle (if any).
5271 * The returned method handle will have a {@code void} return type.
5272 *
5273 * @param target the method handle to adapt
5274 * @return a possibly adapted method handle
5275 * @throws NullPointerException if {@code target} is null
5276 * @since 16
5277 */
5278 public static MethodHandle dropReturn(MethodHandle target) {
5279 Objects.requireNonNull(target);
5280 MethodType oldType = target.type();
5281 Class<?> oldReturnType = oldType.returnType();
5282 if (oldReturnType == void.class)
5283 return target;
5284 MethodType newType = oldType.changeReturnType(void.class);
5285 BoundMethodHandle result = target.rebind();
5286 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5287 result = result.copyWith(newType, lform);
5288 return result;
5289 }
5290
5291 /**
5292 * Adapts a target method handle by pre-processing
5293 * one or more of its arguments, each with its own unary filter function,
5294 * and then calling the target with each pre-processed argument
5295 * replaced by the result of its corresponding filter function.
5296 * <p>
5297 * The pre-processing is performed by one or more method handles,
5298 * specified in the elements of the {@code filters} array.
5299 * The first element of the filter array corresponds to the {@code pos}
5300 * argument of the target, and so on in sequence.
5301 * The filter functions are invoked in left to right order.
5302 * <p>
5303 * Null arguments in the array are treated as identity functions,
5304 * and the corresponding arguments left unchanged.
5305 * (If there are no non-null elements in the array, the original target is returned.)
5306 * Each filter is applied to the corresponding argument of the adapter.
5307 * <p>
5308 * If a filter {@code F} applies to the {@code N}th argument of
5309 * the target, then {@code F} must be a method handle which
5310 * takes exactly one argument. The type of {@code F}'s sole argument
5311 * replaces the corresponding argument type of the target
5312 * in the resulting adapted method handle.
5313 * The return type of {@code F} must be identical to the corresponding
5314 * parameter type of the target.
5315 * <p>
5316 * It is an error if there are elements of {@code filters}
5317 * (null or not)
5318 * which do not correspond to argument positions in the target.
5319 * <p><b>Example:</b>
5320 * {@snippet lang="java" :
5321 import static java.lang.invoke.MethodHandles.*;
5322 import static java.lang.invoke.MethodType.*;
5323 ...
5324 MethodHandle cat = lookup().findVirtual(String.class,
5325 "concat", methodType(String.class, String.class));
5326 MethodHandle upcase = lookup().findVirtual(String.class,
5327 "toUpperCase", methodType(String.class));
5328 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5329 MethodHandle f0 = filterArguments(cat, 0, upcase);
5330 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5331 MethodHandle f1 = filterArguments(cat, 1, upcase);
5332 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5333 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5334 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5335 * }
5336 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5337 * denotes the return type of both the {@code target} and resulting adapter.
5338 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5339 * of the parameters and arguments that precede and follow the filter position
5340 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5341 * values of the filtered parameters and arguments; they also represent the
5342 * return types of the {@code filter[i]} handles. The latter accept arguments
5343 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5344 * the resulting adapter.
5345 * {@snippet lang="java" :
5346 * T target(P... p, A[i]... a[i], B... b);
5347 * A[i] filter[i](V[i]);
5348 * T adapter(P... p, V[i]... v[i], B... b) {
5349 * return target(p..., filter[i](v[i])..., b...);
5350 * }
5351 * }
5352 * <p>
5353 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5354 * variable-arity method handle}, even if the original target method handle was.
5355 *
5356 * @param target the method handle to invoke after arguments are filtered
5357 * @param pos the position of the first argument to filter
5358 * @param filters method handles to call initially on filtered arguments
5359 * @return method handle which incorporates the specified argument filtering logic
5360 * @throws NullPointerException if the target is null
5361 * or if the {@code filters} array is null
5362 * @throws IllegalArgumentException if a non-null element of {@code filters}
5363 * does not match a corresponding argument type of target as described above,
5364 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5365 * or if the resulting method handle's type would have
5366 * <a href="MethodHandle.html#maxarity">too many parameters</a>
5367 */
5368 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5369 // In method types arguments start at index 0, while the LF
5370 // editor have the MH receiver at position 0 - adjust appropriately.
5371 final int MH_RECEIVER_OFFSET = 1;
5372 filterArgumentsCheckArity(target, pos, filters);
5373 MethodHandle adapter = target;
5374
5375 // keep track of currently matched filters, as to optimize repeated filters
5376 int index = 0;
5377 int[] positions = new int[filters.length];
5378 MethodHandle filter = null;
5379
5380 // process filters in reverse order so that the invocation of
5381 // the resulting adapter will invoke the filters in left-to-right order
5382 for (int i = filters.length - 1; i >= 0; --i) {
5383 MethodHandle newFilter = filters[i];
5384 if (newFilter == null) continue; // ignore null elements of filters
5385
5386 // flush changes on update
5387 if (filter != newFilter) {
5388 if (filter != null) {
5389 if (index > 1) {
5390 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5391 } else {
5392 adapter = filterArgument(adapter, positions[0] - 1, filter);
5393 }
5394 }
5395 filter = newFilter;
5396 index = 0;
5397 }
5398
5399 filterArgumentChecks(target, pos + i, newFilter);
5400 positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5401 }
5402 if (index > 1) {
5403 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5404 } else if (index == 1) {
5405 adapter = filterArgument(adapter, positions[0] - 1, filter);
5406 }
5407 return adapter;
5408 }
5409
5410 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5411 MethodType targetType = adapter.type();
5412 MethodType filterType = filter.type();
5413 BoundMethodHandle result = adapter.rebind();
5414 Class<?> newParamType = filterType.parameterType(0);
5415
5416 Class<?>[] ptypes = targetType.ptypes().clone();
5417 for (int pos : positions) {
5418 ptypes[pos - 1] = newParamType;
5419 }
5420 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5421
5422 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5423 return result.copyWithExtendL(newType, lform, filter);
5424 }
5425
5426 /*non-public*/
5427 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5428 filterArgumentChecks(target, pos, filter);
5429 MethodType targetType = target.type();
5430 MethodType filterType = filter.type();
5431 BoundMethodHandle result = target.rebind();
5432 Class<?> newParamType = filterType.parameterType(0);
5433 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5434 MethodType newType = targetType.changeParameterType(pos, newParamType);
5435 result = result.copyWithExtendL(newType, lform, filter);
5436 return result;
5437 }
5438
5439 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5440 MethodType targetType = target.type();
5441 int maxPos = targetType.parameterCount();
5442 if (pos + filters.length > maxPos)
5443 throw newIllegalArgumentException("too many filters");
5444 }
5445
5446 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5447 MethodType targetType = target.type();
5448 MethodType filterType = filter.type();
5449 if (filterType.parameterCount() != 1
5450 || filterType.returnType() != targetType.parameterType(pos))
5451 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5452 }
5453
5454 /**
5455 * Adapts a target method handle by pre-processing
5456 * a sub-sequence of its arguments with a filter (another method handle).
5457 * The pre-processed arguments are replaced by the result (if any) of the
5458 * filter function.
5459 * The target is then called on the modified (usually shortened) argument list.
5460 * <p>
5461 * If the filter returns a value, the target must accept that value as
5462 * its argument in position {@code pos}, preceded and/or followed by
5463 * any arguments not passed to the filter.
5464 * If the filter returns void, the target must accept all arguments
5465 * not passed to the filter.
5466 * No arguments are reordered, and a result returned from the filter
5467 * replaces (in order) the whole subsequence of arguments originally
5468 * passed to the adapter.
5469 * <p>
5470 * The argument types (if any) of the filter
5471 * replace zero or one argument types of the target, at position {@code pos},
5472 * in the resulting adapted method handle.
5473 * The return type of the filter (if any) must be identical to the
5474 * argument type of the target at position {@code pos}, and that target argument
5475 * is supplied by the return value of the filter.
5476 * <p>
5477 * In all cases, {@code pos} must be greater than or equal to zero, and
5478 * {@code pos} must also be less than or equal to the target's arity.
5479 * <p><b>Example:</b>
5480 * {@snippet lang="java" :
5481 import static java.lang.invoke.MethodHandles.*;
5482 import static java.lang.invoke.MethodType.*;
5483 ...
5484 MethodHandle deepToString = publicLookup()
5485 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5486
5487 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5488 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5489
5490 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5491 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5492
5493 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5494 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5495 assertEquals("[top, [up, down], strange]",
5496 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5497
5498 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5499 assertEquals("[top, [up, down], [strange]]",
5500 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5501
5502 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5503 assertEquals("[top, [[up, down, strange], charm], bottom]",
5504 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5505 * }
5506 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5507 * represents the return type of the {@code target} and resulting adapter.
5508 * {@code V}/{@code v} stand for the return type and value of the
5509 * {@code filter}, which are also found in the signature and arguments of
5510 * the {@code target}, respectively, unless {@code V} is {@code void}.
5511 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5512 * and values preceding and following the collection position, {@code pos},
5513 * in the {@code target}'s signature. They also turn up in the resulting
5514 * adapter's signature and arguments, where they surround
5515 * {@code B}/{@code b}, which represent the parameter types and arguments
5516 * to the {@code filter} (if any).
5517 * {@snippet lang="java" :
5518 * T target(A...,V,C...);
5519 * V filter(B...);
5520 * T adapter(A... a,B... b,C... c) {
5521 * V v = filter(b...);
5522 * return target(a...,v,c...);
5523 * }
5524 * // and if the filter has no arguments:
5525 * T target2(A...,V,C...);
5526 * V filter2();
5527 * T adapter2(A... a,C... c) {
5528 * V v = filter2();
5529 * return target2(a...,v,c...);
5530 * }
5531 * // and if the filter has a void return:
5532 * T target3(A...,C...);
5533 * void filter3(B...);
5534 * T adapter3(A... a,B... b,C... c) {
5535 * filter3(b...);
5536 * return target3(a...,c...);
5537 * }
5538 * }
5539 * <p>
5540 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5541 * one which first "folds" the affected arguments, and then drops them, in separate
5542 * steps as follows:
5543 * {@snippet lang="java" :
5544 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5545 * mh = MethodHandles.foldArguments(mh, coll); //step 1
5546 * }
5547 * If the target method handle consumes no arguments besides than the result
5548 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5549 * is equivalent to {@code filterReturnValue(coll, mh)}.
5550 * If the filter method handle {@code coll} consumes one argument and produces
5551 * a non-void result, then {@code collectArguments(mh, N, coll)}
5552 * is equivalent to {@code filterArguments(mh, N, coll)}.
5553 * Other equivalences are possible but would require argument permutation.
5554 * <p>
5555 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5556 * variable-arity method handle}, even if the original target method handle was.
5557 *
5558 * @param target the method handle to invoke after filtering the subsequence of arguments
5559 * @param pos the position of the first adapter argument to pass to the filter,
5560 * and/or the target argument which receives the result of the filter
5561 * @param filter method handle to call on the subsequence of arguments
5562 * @return method handle which incorporates the specified argument subsequence filtering logic
5563 * @throws NullPointerException if either argument is null
5564 * @throws IllegalArgumentException if the return type of {@code filter}
5565 * is non-void and is not the same as the {@code pos} argument of the target,
5566 * or if {@code pos} is not between 0 and the target's arity, inclusive,
5567 * or if the resulting method handle's type would have
5568 * <a href="MethodHandle.html#maxarity">too many parameters</a>
5569 * @see MethodHandles#foldArguments
5570 * @see MethodHandles#filterArguments
5571 * @see MethodHandles#filterReturnValue
5572 */
5573 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5574 MethodType newType = collectArgumentsChecks(target, pos, filter);
5575 MethodType collectorType = filter.type();
5576 BoundMethodHandle result = target.rebind();
5577 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5578 return result.copyWithExtendL(newType, lform, filter);
5579 }
5580
5581 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5582 MethodType targetType = target.type();
5583 MethodType filterType = filter.type();
5584 Class<?> rtype = filterType.returnType();
5585 Class<?>[] filterArgs = filterType.ptypes();
5586 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5587 (rtype != void.class && pos >= targetType.parameterCount())) {
5588 throw newIllegalArgumentException("position is out of range for target", target, pos);
5589 }
5590 if (rtype == void.class) {
5591 return targetType.insertParameterTypes(pos, filterArgs);
5592 }
5593 if (rtype != targetType.parameterType(pos)) {
5594 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5595 }
5596 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5597 }
5598
5599 /**
5600 * Adapts a target method handle by post-processing
5601 * its return value (if any) with a filter (another method handle).
5602 * The result of the filter is returned from the adapter.
5603 * <p>
5604 * If the target returns a value, the filter must accept that value as
5605 * its only argument.
5606 * If the target returns void, the filter must accept no arguments.
5607 * <p>
5608 * The return type of the filter
5609 * replaces the return type of the target
5610 * in the resulting adapted method handle.
5611 * The argument type of the filter (if any) must be identical to the
5612 * return type of the target.
5613 * <p><b>Example:</b>
5614 * {@snippet lang="java" :
5615 import static java.lang.invoke.MethodHandles.*;
5616 import static java.lang.invoke.MethodType.*;
5617 ...
5618 MethodHandle cat = lookup().findVirtual(String.class,
5619 "concat", methodType(String.class, String.class));
5620 MethodHandle length = lookup().findVirtual(String.class,
5621 "length", methodType(int.class));
5622 System.out.println((String) cat.invokeExact("x", "y")); // xy
5623 MethodHandle f0 = filterReturnValue(cat, length);
5624 System.out.println((int) f0.invokeExact("x", "y")); // 2
5625 * }
5626 * <p>Here is pseudocode for the resulting adapter. In the code,
5627 * {@code T}/{@code t} represent the result type and value of the
5628 * {@code target}; {@code V}, the result type of the {@code filter}; and
5629 * {@code A}/{@code a}, the types and values of the parameters and arguments
5630 * of the {@code target} as well as the resulting adapter.
5631 * {@snippet lang="java" :
5632 * T target(A...);
5633 * V filter(T);
5634 * V adapter(A... a) {
5635 * T t = target(a...);
5636 * return filter(t);
5637 * }
5638 * // and if the target has a void return:
5639 * void target2(A...);
5640 * V filter2();
5641 * V adapter2(A... a) {
5642 * target2(a...);
5643 * return filter2();
5644 * }
5645 * // and if the filter has a void return:
5646 * T target3(A...);
5647 * void filter3(V);
5648 * void adapter3(A... a) {
5649 * T t = target3(a...);
5650 * filter3(t);
5651 * }
5652 * }
5653 * <p>
5654 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5655 * variable-arity method handle}, even if the original target method handle was.
5656 * @param target the method handle to invoke before filtering the return value
5657 * @param filter method handle to call on the return value
5658 * @return method handle which incorporates the specified return value filtering logic
5659 * @throws NullPointerException if either argument is null
5660 * @throws IllegalArgumentException if the argument list of {@code filter}
5661 * does not match the return type of target as described above
5662 */
5663 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5664 MethodType targetType = target.type();
5665 MethodType filterType = filter.type();
5666 filterReturnValueChecks(targetType, filterType);
5667 BoundMethodHandle result = target.rebind();
5668 BasicType rtype = BasicType.basicType(filterType.returnType());
5669 LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5670 MethodType newType = targetType.changeReturnType(filterType.returnType());
5671 result = result.copyWithExtendL(newType, lform, filter);
5672 return result;
5673 }
5674
5675 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5676 Class<?> rtype = targetType.returnType();
5677 int filterValues = filterType.parameterCount();
5678 if (filterValues == 0
5679 ? (rtype != void.class)
5680 : (rtype != filterType.parameterType(0) || filterValues != 1))
5681 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5682 }
5683
5684 /**
5685 * Filter the return value of a target method handle with a filter function. The filter function is
5686 * applied to the return value of the original handle; if the filter specifies more than one parameters,
5687 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5688 * as follows:
5689 * {@snippet lang="java" :
5690 * T target(A...)
5691 * V filter(B... , T)
5692 * V adapter(A... a, B... b) {
5693 * T t = target(a...);
5694 * return filter(b..., t);
5695 * }
5696 * }
5697 * <p>
5698 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5699 *
5700 * @param target the target method handle
5701 * @param filter the filter method handle
5702 * @return the adapter method handle
5703 */
5704 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5705 MethodType targetType = target.type();
5706 MethodType filterType = filter.type();
5707 BoundMethodHandle result = target.rebind();
5708 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5709 MethodType newType = targetType.changeReturnType(filterType.returnType());
5710 if (filterType.parameterCount() > 1) {
5711 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5712 newType = newType.appendParameterTypes(filterType.parameterType(i));
5713 }
5714 }
5715 result = result.copyWithExtendL(newType, lform, filter);
5716 return result;
5717 }
5718
5719 /**
5720 * Adapts a target method handle by pre-processing
5721 * some of its arguments, and then calling the target with
5722 * the result of the pre-processing, inserted into the original
5723 * sequence of arguments.
5724 * <p>
5725 * The pre-processing is performed by {@code combiner}, a second method handle.
5726 * Of the arguments passed to the adapter, the first {@code N} arguments
5727 * are copied to the combiner, which is then called.
5728 * (Here, {@code N} is defined as the parameter count of the combiner.)
5729 * After this, control passes to the target, with any result
5730 * from the combiner inserted before the original {@code N} incoming
5731 * arguments.
5732 * <p>
5733 * If the combiner returns a value, the first parameter type of the target
5734 * must be identical with the return type of the combiner, and the next
5735 * {@code N} parameter types of the target must exactly match the parameters
5736 * of the combiner.
5737 * <p>
5738 * If the combiner has a void return, no result will be inserted,
5739 * and the first {@code N} parameter types of the target
5740 * must exactly match the parameters of the combiner.
5741 * <p>
5742 * The resulting adapter is the same type as the target, except that the
5743 * first parameter type is dropped,
5744 * if it corresponds to the result of the combiner.
5745 * <p>
5746 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5747 * that either the combiner or the target does not wish to receive.
5748 * If some of the incoming arguments are destined only for the combiner,
5749 * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5750 * arguments will not need to be live on the stack on entry to the
5751 * target.)
5752 * <p><b>Example:</b>
5753 * {@snippet lang="java" :
5754 import static java.lang.invoke.MethodHandles.*;
5755 import static java.lang.invoke.MethodType.*;
5756 ...
5757 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5758 "println", methodType(void.class, String.class))
5759 .bindTo(System.out);
5760 MethodHandle cat = lookup().findVirtual(String.class,
5761 "concat", methodType(String.class, String.class));
5762 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5763 MethodHandle catTrace = foldArguments(cat, trace);
5764 // also prints "boo":
5765 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5766 * }
5767 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5768 * represents the result type of the {@code target} and resulting adapter.
5769 * {@code V}/{@code v} represent the type and value of the parameter and argument
5770 * of {@code target} that precedes the folding position; {@code V} also is
5771 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5772 * types and values of the {@code N} parameters and arguments at the folding
5773 * position. {@code B}/{@code b} represent the types and values of the
5774 * {@code target} parameters and arguments that follow the folded parameters
5775 * and arguments.
5776 * {@snippet lang="java" :
5777 * // there are N arguments in A...
5778 * T target(V, A[N]..., B...);
5779 * V combiner(A...);
5780 * T adapter(A... a, B... b) {
5781 * V v = combiner(a...);
5782 * return target(v, a..., b...);
5783 * }
5784 * // and if the combiner has a void return:
5785 * T target2(A[N]..., B...);
5786 * void combiner2(A...);
5787 * T adapter2(A... a, B... b) {
5788 * combiner2(a...);
5789 * return target2(a..., b...);
5790 * }
5791 * }
5792 * <p>
5793 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5794 * variable-arity method handle}, even if the original target method handle was.
5795 * @param target the method handle to invoke after arguments are combined
5796 * @param combiner method handle to call initially on the incoming arguments
5797 * @return method handle which incorporates the specified argument folding logic
5798 * @throws NullPointerException if either argument is null
5799 * @throws IllegalArgumentException if {@code combiner}'s return type
5800 * is non-void and not the same as the first argument type of
5801 * the target, or if the initial {@code N} argument types
5802 * of the target
5803 * (skipping one matching the {@code combiner}'s return type)
5804 * are not identical with the argument types of {@code combiner}
5805 */
5806 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5807 return foldArguments(target, 0, combiner);
5808 }
5809
5810 /**
5811 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5812 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5813 * before the folded arguments.
5814 * <p>
5815 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5816 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
5817 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
5818 * 0.
5819 *
5820 * @apiNote Example:
5821 * {@snippet lang="java" :
5822 import static java.lang.invoke.MethodHandles.*;
5823 import static java.lang.invoke.MethodType.*;
5824 ...
5825 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5826 "println", methodType(void.class, String.class))
5827 .bindTo(System.out);
5828 MethodHandle cat = lookup().findVirtual(String.class,
5829 "concat", methodType(String.class, String.class));
5830 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5831 MethodHandle catTrace = foldArguments(cat, 1, trace);
5832 // also prints "jum":
5833 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5834 * }
5835 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5836 * represents the result type of the {@code target} and resulting adapter.
5837 * {@code V}/{@code v} represent the type and value of the parameter and argument
5838 * of {@code target} that precedes the folding position; {@code V} also is
5839 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5840 * types and values of the {@code N} parameters and arguments at the folding
5841 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
5842 * and values of the {@code target} parameters and arguments that precede and
5843 * follow the folded parameters and arguments starting at {@code pos},
5844 * respectively.
5845 * {@snippet lang="java" :
5846 * // there are N arguments in A...
5847 * T target(Z..., V, A[N]..., B...);
5848 * V combiner(A...);
5849 * T adapter(Z... z, A... a, B... b) {
5850 * V v = combiner(a...);
5851 * return target(z..., v, a..., b...);
5852 * }
5853 * // and if the combiner has a void return:
5854 * T target2(Z..., A[N]..., B...);
5855 * void combiner2(A...);
5856 * T adapter2(Z... z, A... a, B... b) {
5857 * combiner2(a...);
5858 * return target2(z..., a..., b...);
5859 * }
5860 * }
5861 * <p>
5862 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5863 * variable-arity method handle}, even if the original target method handle was.
5864 *
5865 * @param target the method handle to invoke after arguments are combined
5866 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
5867 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5868 * @param combiner method handle to call initially on the incoming arguments
5869 * @return method handle which incorporates the specified argument folding logic
5870 * @throws NullPointerException if either argument is null
5871 * @throws IllegalArgumentException if either of the following two conditions holds:
5872 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5873 * {@code pos} of the target signature;
5874 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
5875 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
5876 *
5877 * @see #foldArguments(MethodHandle, MethodHandle)
5878 * @since 9
5879 */
5880 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
5881 MethodType targetType = target.type();
5882 MethodType combinerType = combiner.type();
5883 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
5884 BoundMethodHandle result = target.rebind();
5885 boolean dropResult = rtype == void.class;
5886 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
5887 MethodType newType = targetType;
5888 if (!dropResult) {
5889 newType = newType.dropParameterTypes(pos, pos + 1);
5890 }
5891 result = result.copyWithExtendL(newType, lform, combiner);
5892 return result;
5893 }
5894
5895 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
5896 int foldArgs = combinerType.parameterCount();
5897 Class<?> rtype = combinerType.returnType();
5898 int foldVals = rtype == void.class ? 0 : 1;
5899 int afterInsertPos = foldPos + foldVals;
5900 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
5901 if (ok) {
5902 for (int i = 0; i < foldArgs; i++) {
5903 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
5904 ok = false;
5905 break;
5906 }
5907 }
5908 }
5909 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
5910 ok = false;
5911 if (!ok)
5912 throw misMatchedTypes("target and combiner types", targetType, combinerType);
5913 return rtype;
5914 }
5915
5916 /**
5917 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
5918 * of the pre-processing replacing the argument at the given position.
5919 *
5920 * @param target the method handle to invoke after arguments are combined
5921 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5922 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5923 * @param combiner method handle to call initially on the incoming arguments
5924 * @param argPositions indexes of the target to pick arguments sent to the combiner from
5925 * @return method handle which incorporates the specified argument folding logic
5926 * @throws NullPointerException if either argument is null
5927 * @throws IllegalArgumentException if either of the following two conditions holds:
5928 * (1) {@code combiner}'s return type is not the same as the argument type at position
5929 * {@code pos} of the target signature;
5930 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
5931 * not identical with the argument types of {@code combiner}.
5932 */
5933 /*non-public*/
5934 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5935 return argumentsWithCombiner(true, target, position, combiner, argPositions);
5936 }
5937
5938 /**
5939 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
5940 * the pre-processing inserted into the original sequence of arguments at the given position.
5941 *
5942 * @param target the method handle to invoke after arguments are combined
5943 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5944 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5945 * @param combiner method handle to call initially on the incoming arguments
5946 * @param argPositions indexes of the target to pick arguments sent to the combiner from
5947 * @return method handle which incorporates the specified argument folding logic
5948 * @throws NullPointerException if either argument is null
5949 * @throws IllegalArgumentException if either of the following two conditions holds:
5950 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5951 * {@code pos} of the target signature;
5952 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
5953 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
5954 * with the argument types of {@code combiner}.
5955 */
5956 /*non-public*/
5957 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5958 return argumentsWithCombiner(false, target, position, combiner, argPositions);
5959 }
5960
5961 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5962 MethodType targetType = target.type();
5963 MethodType combinerType = combiner.type();
5964 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
5965 BoundMethodHandle result = target.rebind();
5966
5967 MethodType newType = targetType;
5968 LambdaForm lform;
5969 if (filter) {
5970 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
5971 } else {
5972 boolean dropResult = rtype == void.class;
5973 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
5974 if (!dropResult) {
5975 newType = newType.dropParameterTypes(position, position + 1);
5976 }
5977 }
5978 result = result.copyWithExtendL(newType, lform, combiner);
5979 return result;
5980 }
5981
5982 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
5983 int combinerArgs = combinerType.parameterCount();
5984 if (argPos.length != combinerArgs) {
5985 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
5986 }
5987 Class<?> rtype = combinerType.returnType();
5988
5989 for (int i = 0; i < combinerArgs; i++) {
5990 int arg = argPos[i];
5991 if (arg < 0 || arg > targetType.parameterCount()) {
5992 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
5993 }
5994 if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
5995 throw newIllegalArgumentException("target argument type at position " + arg
5996 + " must match combiner argument type at index " + i + ": " + targetType
5997 + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
5998 }
5999 }
6000 if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6001 throw misMatchedTypes("target and combiner types", targetType, combinerType);
6002 }
6003 return rtype;
6004 }
6005
6006 /**
6007 * Makes a method handle which adapts a target method handle,
6008 * by guarding it with a test, a boolean-valued method handle.
6009 * If the guard fails, a fallback handle is called instead.
6010 * All three method handles must have the same corresponding
6011 * argument and return types, except that the return type
6012 * of the test must be boolean, and the test is allowed
6013 * to have fewer arguments than the other two method handles.
6014 * <p>
6015 * Here is pseudocode for the resulting adapter. In the code, {@code T}
6016 * represents the uniform result type of the three involved handles;
6017 * {@code A}/{@code a}, the types and values of the {@code target}
6018 * parameters and arguments that are consumed by the {@code test}; and
6019 * {@code B}/{@code b}, those types and values of the {@code target}
6020 * parameters and arguments that are not consumed by the {@code test}.
6021 * {@snippet lang="java" :
6022 * boolean test(A...);
6023 * T target(A...,B...);
6024 * T fallback(A...,B...);
6025 * T adapter(A... a,B... b) {
6026 * if (test(a...))
6027 * return target(a..., b...);
6028 * else
6029 * return fallback(a..., b...);
6030 * }
6031 * }
6032 * Note that the test arguments ({@code a...} in the pseudocode) cannot
6033 * be modified by execution of the test, and so are passed unchanged
6034 * from the caller to the target or fallback as appropriate.
6035 * @param test method handle used for test, must return boolean
6036 * @param target method handle to call if test passes
6037 * @param fallback method handle to call if test fails
6038 * @return method handle which incorporates the specified if/then/else logic
6039 * @throws NullPointerException if any argument is null
6040 * @throws IllegalArgumentException if {@code test} does not return boolean,
6041 * or if all three method types do not match (with the return
6042 * type of {@code test} changed to match that of the target).
6043 */
6044 public static MethodHandle guardWithTest(MethodHandle test,
6045 MethodHandle target,
6046 MethodHandle fallback) {
6047 MethodType gtype = test.type();
6048 MethodType ttype = target.type();
6049 MethodType ftype = fallback.type();
6050 if (!ttype.equals(ftype))
6051 throw misMatchedTypes("target and fallback types", ttype, ftype);
6052 if (gtype.returnType() != boolean.class)
6053 throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6054
6055 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6056 if (test == null) {
6057 throw misMatchedTypes("target and test types", ttype, gtype);
6058 }
6059 return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6060 }
6061
6062 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6063 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6064 }
6065
6066 /**
6067 * Makes a method handle which adapts a target method handle,
6068 * by running it inside an exception handler.
6069 * If the target returns normally, the adapter returns that value.
6070 * If an exception matching the specified type is thrown, the fallback
6071 * handle is called instead on the exception, plus the original arguments.
6072 * <p>
6073 * The target and handler must have the same corresponding
6074 * argument and return types, except that handler may omit trailing arguments
6075 * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6076 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6077 * <p>
6078 * Here is pseudocode for the resulting adapter. In the code, {@code T}
6079 * represents the return type of the {@code target} and {@code handler},
6080 * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6081 * the types and values of arguments to the resulting handle consumed by
6082 * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6083 * resulting handle discarded by {@code handler}.
6084 * {@snippet lang="java" :
6085 * T target(A..., B...);
6086 * T handler(ExType, A...);
6087 * T adapter(A... a, B... b) {
6088 * try {
6089 * return target(a..., b...);
6090 * } catch (ExType ex) {
6091 * return handler(ex, a...);
6092 * }
6093 * }
6094 * }
6095 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6096 * be modified by execution of the target, and so are passed unchanged
6097 * from the caller to the handler, if the handler is invoked.
6098 * <p>
6099 * The target and handler must return the same type, even if the handler
6100 * always throws. (This might happen, for instance, because the handler
6101 * is simulating a {@code finally} clause).
6102 * To create such a throwing handler, compose the handler creation logic
6103 * with {@link #throwException throwException},
6104 * in order to create a method handle of the correct return type.
6105 * @param target method handle to call
6106 * @param exType the type of exception which the handler will catch
6107 * @param handler method handle to call if a matching exception is thrown
6108 * @return method handle which incorporates the specified try/catch logic
6109 * @throws NullPointerException if any argument is null
6110 * @throws IllegalArgumentException if {@code handler} does not accept
6111 * the given exception type, or if the method handle types do
6112 * not match in their return types and their
6113 * corresponding parameters
6114 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6115 */
6116 public static MethodHandle catchException(MethodHandle target,
6117 Class<? extends Throwable> exType,
6118 MethodHandle handler) {
6119 MethodType ttype = target.type();
6120 MethodType htype = handler.type();
6121 if (!Throwable.class.isAssignableFrom(exType))
6122 throw new ClassCastException(exType.getName());
6123 if (htype.parameterCount() < 1 ||
6124 !htype.parameterType(0).isAssignableFrom(exType))
6125 throw newIllegalArgumentException("handler does not accept exception type "+exType);
6126 if (htype.returnType() != ttype.returnType())
6127 throw misMatchedTypes("target and handler return types", ttype, htype);
6128 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6129 if (handler == null) {
6130 throw misMatchedTypes("target and handler types", ttype, htype);
6131 }
6132 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6133 }
6134
6135 /**
6136 * Produces a method handle which will throw exceptions of the given {@code exType}.
6137 * The method handle will accept a single argument of {@code exType},
6138 * and immediately throw it as an exception.
6139 * The method type will nominally specify a return of {@code returnType}.
6140 * The return type may be anything convenient: It doesn't matter to the
6141 * method handle's behavior, since it will never return normally.
6142 * @param returnType the return type of the desired method handle
6143 * @param exType the parameter type of the desired method handle
6144 * @return method handle which can throw the given exceptions
6145 * @throws NullPointerException if either argument is null
6146 */
6147 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6148 if (!Throwable.class.isAssignableFrom(exType))
6149 throw new ClassCastException(exType.getName());
6150 return MethodHandleImpl.throwException(methodType(returnType, exType));
6151 }
6152
6153 /**
6154 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6155 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6156 * delivers the loop's result, which is the return value of the resulting handle.
6157 * <p>
6158 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6159 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6160 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6161 * terms of method handles, each clause will specify up to four independent actions:<ul>
6162 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6163 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6164 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6165 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6166 * </ul>
6167 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6168 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually
6169 * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6170 * <p>
6171 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6172 * this case. See below for a detailed description.
6173 * <p>
6174 * <em>Parameters optional everywhere:</em>
6175 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6176 * As an exception, the init functions cannot take any {@code v} parameters,
6177 * because those values are not yet computed when the init functions are executed.
6178 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6179 * In fact, any clause function may take no arguments at all.
6180 * <p>
6181 * <em>Loop parameters:</em>
6182 * A clause function may take all the iteration variable values it is entitled to, in which case
6183 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6184 * with their types and values notated as {@code (A...)} and {@code (a...)}.
6185 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6186 * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6187 * init function is automatically a loop parameter {@code a}.)
6188 * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6189 * These loop parameters act as loop-invariant values visible across the whole loop.
6190 * <p>
6191 * <em>Parameters visible everywhere:</em>
6192 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6193 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6194 * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6195 * Most clause functions will not need all of this information, but they will be formally connected to it
6196 * as if by {@link #dropArguments}.
6197 * <a id="astar"></a>
6198 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6199 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6200 * In that notation, the general form of an init function parameter list
6201 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6202 * <p>
6203 * <em>Checking clause structure:</em>
6204 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6205 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6206 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6207 * met by the inputs to the loop combinator.
6208 * <p>
6209 * <em>Effectively identical sequences:</em>
6210 * <a id="effid"></a>
6211 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6212 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6213 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6214 * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6215 * that longest list.
6216 * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6217 * and the same is true if more sequences of the form {@code (V... A*)} are added.
6218 * <p>
6219 * <em>Step 0: Determine clause structure.</em><ol type="a">
6220 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6221 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6222 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6223 * four. Padding takes place by appending elements to the array.
6224 * <li>Clauses with all {@code null}s are disregarded.
6225 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6226 * </ol>
6227 * <p>
6228 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6229 * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6230 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6231 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6232 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6233 * iteration variable type.
6234 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6235 * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6236 * </ol>
6237 * <p>
6238 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6239 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6240 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6241 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6242 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6243 * (These types will be checked in step 2, along with all the clause function types.)
6244 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.)
6245 * <li>All of the collected parameter lists must be effectively identical.
6246 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6247 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6248 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6249 * the "internal parameter list".
6250 * </ul>
6251 * <p>
6252 * <em>Step 1C: Determine loop return type.</em><ol type="a">
6253 * <li>Examine fini function return types, disregarding omitted fini functions.
6254 * <li>If there are no fini functions, the loop return type is {@code void}.
6255 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6256 * type.
6257 * </ol>
6258 * <p>
6259 * <em>Step 1D: Check other types.</em><ol type="a">
6260 * <li>There must be at least one non-omitted pred function.
6261 * <li>Every non-omitted pred function must have a {@code boolean} return type.
6262 * </ol>
6263 * <p>
6264 * <em>Step 2: Determine parameter lists.</em><ol type="a">
6265 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6266 * <li>The parameter list for init functions will be adjusted to the external parameter list.
6267 * (Note that their parameter lists are already effectively identical to this list.)
6268 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6269 * effectively identical to the internal parameter list {@code (V... A...)}.
6270 * </ol>
6271 * <p>
6272 * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6273 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6274 * type.
6275 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6276 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6277 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6278 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6279 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.)
6280 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6281 * loop return type.
6282 * </ol>
6283 * <p>
6284 * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6285 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6286 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6287 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6288 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6289 * pad out the end of the list.
6290 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6291 * </ol>
6292 * <p>
6293 * <em>Final observations.</em><ol type="a">
6294 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6295 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6296 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6297 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6298 * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6299 * <li>Each pair of init and step functions agrees in their return type {@code V}.
6300 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6301 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6302 * </ol>
6303 * <p>
6304 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6305 * <ul>
6306 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6307 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6308 * (Only one {@code Pn} has to be non-{@code null}.)
6309 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6310 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6311 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6312 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6313 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6314 * the resulting loop handle's parameter types {@code (A...)}.
6315 * </ul>
6316 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6317 * which is natural if most of the loop computation happens in the steps. For some loops,
6318 * the burden of computation might be heaviest in the pred functions, and so the pred functions
6319 * might need to accept the loop parameter values. For loops with complex exit logic, the fini
6320 * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6321 * where the init functions will need the extra parameters. For such reasons, the rules for
6322 * determining these parameters are as symmetric as possible, across all clause parts.
6323 * In general, the loop parameters function as common invariant values across the whole
6324 * loop, while the iteration variables function as common variant values, or (if there is
6325 * no step function) as internal loop invariant temporaries.
6326 * <p>
6327 * <em>Loop execution.</em><ol type="a">
6328 * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6329 * every clause function. These locals are loop invariant.
6330 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6331 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6332 * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6333 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6334 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6335 * (in argument order).
6336 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6337 * returns {@code false}.
6338 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6339 * sequence {@code (v...)} of loop variables.
6340 * The updated value is immediately visible to all subsequent function calls.
6341 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6342 * (of type {@code R}) is returned from the loop as a whole.
6343 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6344 * except by throwing an exception.
6345 * </ol>
6346 * <p>
6347 * <em>Usage tips.</em>
6348 * <ul>
6349 * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6350 * sometimes a step function only needs to observe the current value of its own variable.
6351 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6352 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6353 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create
6354 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be
6355 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6356 * <li>If some of the clause functions are virtual methods on an instance, the instance
6357 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6358 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference
6359 * will be the first iteration variable value, and it will be easy to use virtual
6360 * methods as clause parts, since all of them will take a leading instance reference matching that value.
6361 * </ul>
6362 * <p>
6363 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6364 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6365 * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6366 * {@snippet lang="java" :
6367 * V... init...(A...);
6368 * boolean pred...(V..., A...);
6369 * V... step...(V..., A...);
6370 * R fini...(V..., A...);
6371 * R loop(A... a) {
6372 * V... v... = init...(a...);
6373 * for (;;) {
6374 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6375 * v = s(v..., a...);
6376 * if (!p(v..., a...)) {
6377 * return f(v..., a...);
6378 * }
6379 * }
6380 * }
6381 * }
6382 * }
6383 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6384 * to their full length, even though individual clause functions may neglect to take them all.
6385 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6386 *
6387 * @apiNote Example:
6388 * {@snippet lang="java" :
6389 * // iterative implementation of the factorial function as a loop handle
6390 * static int one(int k) { return 1; }
6391 * static int inc(int i, int acc, int k) { return i + 1; }
6392 * static int mult(int i, int acc, int k) { return i * acc; }
6393 * static boolean pred(int i, int acc, int k) { return i < k; }
6394 * static int fin(int i, int acc, int k) { return acc; }
6395 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6396 * // null initializer for counter, should initialize to 0
6397 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6398 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6399 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6400 * assertEquals(120, loop.invoke(5));
6401 * }
6402 * The same example, dropping arguments and using combinators:
6403 * {@snippet lang="java" :
6404 * // simplified implementation of the factorial function as a loop handle
6405 * static int inc(int i) { return i + 1; } // drop acc, k
6406 * static int mult(int i, int acc) { return i * acc; } //drop k
6407 * static boolean cmp(int i, int k) { return i < k; }
6408 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6409 * // null initializer for counter, should initialize to 0
6410 * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6411 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6412 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6413 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6414 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6415 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6416 * assertEquals(720, loop.invoke(6));
6417 * }
6418 * A similar example, using a helper object to hold a loop parameter:
6419 * {@snippet lang="java" :
6420 * // instance-based implementation of the factorial function as a loop handle
6421 * static class FacLoop {
6422 * final int k;
6423 * FacLoop(int k) { this.k = k; }
6424 * int inc(int i) { return i + 1; }
6425 * int mult(int i, int acc) { return i * acc; }
6426 * boolean pred(int i) { return i < k; }
6427 * int fin(int i, int acc) { return acc; }
6428 * }
6429 * // assume MH_FacLoop is a handle to the constructor
6430 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6431 * // null initializer for counter, should initialize to 0
6432 * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6433 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6434 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6435 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6436 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6437 * assertEquals(5040, loop.invoke(7));
6438 * }
6439 *
6440 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6441 *
6442 * @return a method handle embodying the looping behavior as defined by the arguments.
6443 *
6444 * @throws IllegalArgumentException in case any of the constraints described above is violated.
6445 *
6446 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6447 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6448 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6449 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6450 * @since 9
6451 */
6452 public static MethodHandle loop(MethodHandle[]... clauses) {
6453 // Step 0: determine clause structure.
6454 loopChecks0(clauses);
6455
6456 List<MethodHandle> init = new ArrayList<>();
6457 List<MethodHandle> step = new ArrayList<>();
6458 List<MethodHandle> pred = new ArrayList<>();
6459 List<MethodHandle> fini = new ArrayList<>();
6460
6461 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6462 init.add(clause[0]); // all clauses have at least length 1
6463 step.add(clause.length <= 1 ? null : clause[1]);
6464 pred.add(clause.length <= 2 ? null : clause[2]);
6465 fini.add(clause.length <= 3 ? null : clause[3]);
6466 });
6467
6468 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6469 final int nclauses = init.size();
6470
6471 // Step 1A: determine iteration variables (V...).
6472 final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6473 for (int i = 0; i < nclauses; ++i) {
6474 MethodHandle in = init.get(i);
6475 MethodHandle st = step.get(i);
6476 if (in == null && st == null) {
6477 iterationVariableTypes.add(void.class);
6478 } else if (in != null && st != null) {
6479 loopChecks1a(i, in, st);
6480 iterationVariableTypes.add(in.type().returnType());
6481 } else {
6482 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6483 }
6484 }
6485 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6486
6487 // Step 1B: determine loop parameters (A...).
6488 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6489 loopChecks1b(init, commonSuffix);
6490
6491 // Step 1C: determine loop return type.
6492 // Step 1D: check other types.
6493 // local variable required here; see JDK-8223553
6494 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6495 .map(MethodType::returnType);
6496 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6497 loopChecks1cd(pred, fini, loopReturnType);
6498
6499 // Step 2: determine parameter lists.
6500 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6501 commonParameterSequence.addAll(commonSuffix);
6502 loopChecks2(step, pred, fini, commonParameterSequence);
6503 // Step 3: fill in omitted functions.
6504 for (int i = 0; i < nclauses; ++i) {
6505 Class<?> t = iterationVariableTypes.get(i);
6506 if (init.get(i) == null) {
6507 init.set(i, empty(methodType(t, commonSuffix)));
6508 }
6509 if (step.get(i) == null) {
6510 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6511 }
6512 if (pred.get(i) == null) {
6513 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6514 }
6515 if (fini.get(i) == null) {
6516 fini.set(i, empty(methodType(t, commonParameterSequence)));
6517 }
6518 }
6519
6520 // Step 4: fill in missing parameter types.
6521 // Also convert all handles to fixed-arity handles.
6522 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6523 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6524 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6525 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6526
6527 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6528 allMatch(pl -> pl.equals(commonSuffix));
6529 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6530 allMatch(pl -> pl.equals(commonParameterSequence));
6531
6532 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6533 }
6534
6535 private static void loopChecks0(MethodHandle[][] clauses) {
6536 if (clauses == null || clauses.length == 0) {
6537 throw newIllegalArgumentException("null or no clauses passed");
6538 }
6539 if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6540 throw newIllegalArgumentException("null clauses are not allowed");
6541 }
6542 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6543 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6544 }
6545 }
6546
6547 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6548 if (in.type().returnType() != st.type().returnType()) {
6549 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6550 st.type().returnType());
6551 }
6552 }
6553
6554 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6555 return mhs.filter(Objects::nonNull)
6556 // take only those that can contribute to a common suffix because they are longer than the prefix
6557 .map(MethodHandle::type)
6558 .filter(t -> t.parameterCount() > skipSize)
6559 .max(Comparator.comparingInt(MethodType::parameterCount))
6560 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6561 .orElse(List.of());
6562 }
6563
6564 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6565 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6566 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6567 return longest1.size() >= longest2.size() ? longest1 : longest2;
6568 }
6569
6570 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6571 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6572 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6573 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6574 " (common suffix: " + commonSuffix + ")");
6575 }
6576 }
6577
6578 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6579 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6580 anyMatch(t -> t != loopReturnType)) {
6581 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6582 loopReturnType + ")");
6583 }
6584
6585 if (pred.stream().noneMatch(Objects::nonNull)) {
6586 throw newIllegalArgumentException("no predicate found", pred);
6587 }
6588 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6589 anyMatch(t -> t != boolean.class)) {
6590 throw newIllegalArgumentException("predicates must have boolean return type", pred);
6591 }
6592 }
6593
6594 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6595 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6596 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6597 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6598 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6599 }
6600 }
6601
6602 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6603 return hs.stream().map(h -> {
6604 int pc = h.type().parameterCount();
6605 int tpsize = targetParams.size();
6606 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6607 }).toList();
6608 }
6609
6610 private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6611 return hs.stream().map(MethodHandle::asFixedArity).toList();
6612 }
6613
6614 /**
6615 * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6616 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6617 * <p>
6618 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6619 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6620 * evaluates to {@code true}).
6621 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6622 * <p>
6623 * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6624 * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6625 * and updated with the value returned from its invocation. The result of loop execution will be
6626 * the final value of the additional loop-local variable (if present).
6627 * <p>
6628 * The following rules hold for these argument handles:<ul>
6629 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6630 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6631 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6632 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6633 * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6634 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6635 * It will constrain the parameter lists of the other loop parts.
6636 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6637 * list {@code (A...)} is called the <em>external parameter list</em>.
6638 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6639 * additional state variable of the loop.
6640 * The body must both accept and return a value of this type {@code V}.
6641 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6642 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6643 * <a href="MethodHandles.html#effid">effectively identical</a>
6644 * to the external parameter list {@code (A...)}.
6645 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6646 * {@linkplain #empty default value}.
6647 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type.
6648 * Its parameter list (either empty or of the form {@code (V A*)}) must be
6649 * effectively identical to the internal parameter list.
6650 * </ul>
6651 * <p>
6652 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6653 * <li>The loop handle's result type is the result type {@code V} of the body.
6654 * <li>The loop handle's parameter types are the types {@code (A...)},
6655 * from the external parameter list.
6656 * </ul>
6657 * <p>
6658 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6659 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6660 * passed to the loop.
6661 * {@snippet lang="java" :
6662 * V init(A...);
6663 * boolean pred(V, A...);
6664 * V body(V, A...);
6665 * V whileLoop(A... a...) {
6666 * V v = init(a...);
6667 * while (pred(v, a...)) {
6668 * v = body(v, a...);
6669 * }
6670 * return v;
6671 * }
6672 * }
6673 *
6674 * @apiNote Example:
6675 * {@snippet lang="java" :
6676 * // implement the zip function for lists as a loop handle
6677 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6678 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6679 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6680 * zip.add(a.next());
6681 * zip.add(b.next());
6682 * return zip;
6683 * }
6684 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6685 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6686 * List<String> a = Arrays.asList("a", "b", "c", "d");
6687 * List<String> b = Arrays.asList("e", "f", "g", "h");
6688 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6689 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6690 * }
6691 *
6692 *
6693 * @apiNote The implementation of this method can be expressed as follows:
6694 * {@snippet lang="java" :
6695 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6696 * MethodHandle fini = (body.type().returnType() == void.class
6697 * ? null : identity(body.type().returnType()));
6698 * MethodHandle[]
6699 * checkExit = { null, null, pred, fini },
6700 * varBody = { init, body };
6701 * return loop(checkExit, varBody);
6702 * }
6703 * }
6704 *
6705 * @param init optional initializer, providing the initial value of the loop variable.
6706 * May be {@code null}, implying a default initial value. See above for other constraints.
6707 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6708 * above for other constraints.
6709 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6710 * See above for other constraints.
6711 *
6712 * @return a method handle implementing the {@code while} loop as described by the arguments.
6713 * @throws IllegalArgumentException if the rules for the arguments are violated.
6714 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6715 *
6716 * @see #loop(MethodHandle[][])
6717 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6718 * @since 9
6719 */
6720 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6721 whileLoopChecks(init, pred, body);
6722 MethodHandle fini = identityOrVoid(body.type().returnType());
6723 MethodHandle[] checkExit = { null, null, pred, fini };
6724 MethodHandle[] varBody = { init, body };
6725 return loop(checkExit, varBody);
6726 }
6727
6728 /**
6729 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6730 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6731 * <p>
6732 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6733 * method will, in each iteration, first execute its body and then evaluate the predicate.
6734 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6735 * <p>
6736 * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6737 * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6738 * and updated with the value returned from its invocation. The result of loop execution will be
6739 * the final value of the additional loop-local variable (if present).
6740 * <p>
6741 * The following rules hold for these argument handles:<ul>
6742 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6743 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6744 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6745 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6746 * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6747 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6748 * It will constrain the parameter lists of the other loop parts.
6749 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6750 * list {@code (A...)} is called the <em>external parameter list</em>.
6751 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6752 * additional state variable of the loop.
6753 * The body must both accept and return a value of this type {@code V}.
6754 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6755 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6756 * <a href="MethodHandles.html#effid">effectively identical</a>
6757 * to the external parameter list {@code (A...)}.
6758 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6759 * {@linkplain #empty default value}.
6760 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type.
6761 * Its parameter list (either empty or of the form {@code (V A*)}) must be
6762 * effectively identical to the internal parameter list.
6763 * </ul>
6764 * <p>
6765 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6766 * <li>The loop handle's result type is the result type {@code V} of the body.
6767 * <li>The loop handle's parameter types are the types {@code (A...)},
6768 * from the external parameter list.
6769 * </ul>
6770 * <p>
6771 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6772 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6773 * passed to the loop.
6774 * {@snippet lang="java" :
6775 * V init(A...);
6776 * boolean pred(V, A...);
6777 * V body(V, A...);
6778 * V doWhileLoop(A... a...) {
6779 * V v = init(a...);
6780 * do {
6781 * v = body(v, a...);
6782 * } while (pred(v, a...));
6783 * return v;
6784 * }
6785 * }
6786 *
6787 * @apiNote Example:
6788 * {@snippet lang="java" :
6789 * // int i = 0; while (i < limit) { ++i; } return i; => limit
6790 * static int zero(int limit) { return 0; }
6791 * static int step(int i, int limit) { return i + 1; }
6792 * static boolean pred(int i, int limit) { return i < limit; }
6793 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6794 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6795 * assertEquals(23, loop.invoke(23));
6796 * }
6797 *
6798 *
6799 * @apiNote The implementation of this method can be expressed as follows:
6800 * {@snippet lang="java" :
6801 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6802 * MethodHandle fini = (body.type().returnType() == void.class
6803 * ? null : identity(body.type().returnType()));
6804 * MethodHandle[] clause = { init, body, pred, fini };
6805 * return loop(clause);
6806 * }
6807 * }
6808 *
6809 * @param init optional initializer, providing the initial value of the loop variable.
6810 * May be {@code null}, implying a default initial value. See above for other constraints.
6811 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6812 * See above for other constraints.
6813 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6814 * above for other constraints.
6815 *
6816 * @return a method handle implementing the {@code while} loop as described by the arguments.
6817 * @throws IllegalArgumentException if the rules for the arguments are violated.
6818 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6819 *
6820 * @see #loop(MethodHandle[][])
6821 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
6822 * @since 9
6823 */
6824 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6825 whileLoopChecks(init, pred, body);
6826 MethodHandle fini = identityOrVoid(body.type().returnType());
6827 MethodHandle[] clause = {init, body, pred, fini };
6828 return loop(clause);
6829 }
6830
6831 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
6832 Objects.requireNonNull(pred);
6833 Objects.requireNonNull(body);
6834 MethodType bodyType = body.type();
6835 Class<?> returnType = bodyType.returnType();
6836 List<Class<?>> innerList = bodyType.parameterList();
6837 List<Class<?>> outerList = innerList;
6838 if (returnType == void.class) {
6839 // OK
6840 } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
6841 // leading V argument missing => error
6842 MethodType expected = bodyType.insertParameterTypes(0, returnType);
6843 throw misMatchedTypes("body function", bodyType, expected);
6844 } else {
6845 outerList = innerList.subList(1, innerList.size());
6846 }
6847 MethodType predType = pred.type();
6848 if (predType.returnType() != boolean.class ||
6849 !predType.effectivelyIdenticalParameters(0, innerList)) {
6850 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
6851 }
6852 if (init != null) {
6853 MethodType initType = init.type();
6854 if (initType.returnType() != returnType ||
6855 !initType.effectivelyIdenticalParameters(0, outerList)) {
6856 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
6857 }
6858 }
6859 }
6860
6861 /**
6862 * Constructs a loop that runs a given number of iterations.
6863 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6864 * <p>
6865 * The number of iterations is determined by the {@code iterations} handle evaluation result.
6866 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
6867 * It will be initialized to 0 and incremented by 1 in each iteration.
6868 * <p>
6869 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6870 * of that type is also present. This variable is initialized using the optional {@code init} handle,
6871 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6872 * <p>
6873 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6874 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6875 * iteration variable.
6876 * The result of the loop handle execution will be the final {@code V} value of that variable
6877 * (or {@code void} if there is no {@code V} variable).
6878 * <p>
6879 * The following rules hold for the argument handles:<ul>
6880 * <li>The {@code iterations} handle must not be {@code null}, and must return
6881 * the type {@code int}, referred to here as {@code I} in parameter type lists.
6882 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6883 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
6884 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6885 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
6886 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
6887 * <li>The parameter list {@code (V I A...)} of the body contributes to a list
6888 * of types called the <em>internal parameter list</em>.
6889 * It will constrain the parameter lists of the other loop parts.
6890 * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
6891 * with no additional {@code A} types, then the internal parameter list is extended by
6892 * the argument types {@code A...} of the {@code iterations} handle.
6893 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
6894 * list {@code (A...)} is called the <em>external parameter list</em>.
6895 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6896 * additional state variable of the loop.
6897 * The body must both accept a leading parameter and return a value of this type {@code V}.
6898 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6899 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6900 * <a href="MethodHandles.html#effid">effectively identical</a>
6901 * to the external parameter list {@code (A...)}.
6902 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6903 * {@linkplain #empty default value}.
6904 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
6905 * effectively identical to the external parameter list {@code (A...)}.
6906 * </ul>
6907 * <p>
6908 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6909 * <li>The loop handle's result type is the result type {@code V} of the body.
6910 * <li>The loop handle's parameter types are the types {@code (A...)},
6911 * from the external parameter list.
6912 * </ul>
6913 * <p>
6914 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6915 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
6916 * arguments passed to the loop.
6917 * {@snippet lang="java" :
6918 * int iterations(A...);
6919 * V init(A...);
6920 * V body(V, int, A...);
6921 * V countedLoop(A... a...) {
6922 * int end = iterations(a...);
6923 * V v = init(a...);
6924 * for (int i = 0; i < end; ++i) {
6925 * v = body(v, i, a...);
6926 * }
6927 * return v;
6928 * }
6929 * }
6930 *
6931 * @apiNote Example with a fully conformant body method:
6932 * {@snippet lang="java" :
6933 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6934 * // => a variation on a well known theme
6935 * static String step(String v, int counter, String init) { return "na " + v; }
6936 * // assume MH_step is a handle to the method above
6937 * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
6938 * MethodHandle start = MethodHandles.identity(String.class);
6939 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
6940 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
6941 * }
6942 *
6943 * @apiNote Example with the simplest possible body method type,
6944 * and passing the number of iterations to the loop invocation:
6945 * {@snippet lang="java" :
6946 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6947 * // => a variation on a well known theme
6948 * static String step(String v, int counter ) { return "na " + v; }
6949 * // assume MH_step is a handle to the method above
6950 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
6951 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
6952 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v
6953 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
6954 * }
6955 *
6956 * @apiNote Example that treats the number of iterations, string to append to, and string to append
6957 * as loop parameters:
6958 * {@snippet lang="java" :
6959 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6960 * // => a variation on a well known theme
6961 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
6962 * // assume MH_step is a handle to the method above
6963 * MethodHandle count = MethodHandles.identity(int.class);
6964 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
6965 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v
6966 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
6967 * }
6968 *
6969 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
6970 * to enforce a loop type:
6971 * {@snippet lang="java" :
6972 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6973 * // => a variation on a well known theme
6974 * static String step(String v, int counter, String pre) { return pre + " " + v; }
6975 * // assume MH_step is a handle to the method above
6976 * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
6977 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1);
6978 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
6979 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0);
6980 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v
6981 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
6982 * }
6983 *
6984 * @apiNote The implementation of this method can be expressed as follows:
6985 * {@snippet lang="java" :
6986 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
6987 * return countedLoop(empty(iterations.type()), iterations, init, body);
6988 * }
6989 * }
6990 *
6991 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
6992 * result type must be {@code int}. See above for other constraints.
6993 * @param init optional initializer, providing the initial value of the loop variable.
6994 * May be {@code null}, implying a default initial value. See above for other constraints.
6995 * @param body body of the loop, which may not be {@code null}.
6996 * It controls the loop parameters and result type in the standard case (see above for details).
6997 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
6998 * and may accept any number of additional types.
6999 * See above for other constraints.
7000 *
7001 * @return a method handle representing the loop.
7002 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7003 * @throws IllegalArgumentException if any argument violates the rules formulated above.
7004 *
7005 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7006 * @since 9
7007 */
7008 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7009 return countedLoop(empty(iterations.type()), iterations, init, body);
7010 }
7011
7012 /**
7013 * Constructs a loop that counts over a range of numbers.
7014 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7015 * <p>
7016 * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7017 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7018 * values of the loop counter.
7019 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7020 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7021 * <p>
7022 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7023 * of that type is also present. This variable is initialized using the optional {@code init} handle,
7024 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7025 * <p>
7026 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7027 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7028 * iteration variable.
7029 * The result of the loop handle execution will be the final {@code V} value of that variable
7030 * (or {@code void} if there is no {@code V} variable).
7031 * <p>
7032 * The following rules hold for the argument handles:<ul>
7033 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7034 * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7035 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7036 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7037 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7038 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7039 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7040 * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7041 * of types called the <em>internal parameter list</em>.
7042 * It will constrain the parameter lists of the other loop parts.
7043 * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7044 * with no additional {@code A} types, then the internal parameter list is extended by
7045 * the argument types {@code A...} of the {@code end} handle.
7046 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7047 * list {@code (A...)} is called the <em>external parameter list</em>.
7048 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7049 * additional state variable of the loop.
7050 * The body must both accept a leading parameter and return a value of this type {@code V}.
7051 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7052 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7053 * <a href="MethodHandles.html#effid">effectively identical</a>
7054 * to the external parameter list {@code (A...)}.
7055 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7056 * {@linkplain #empty default value}.
7057 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7058 * effectively identical to the external parameter list {@code (A...)}.
7059 * <li>Likewise, the parameter list of {@code end} must be effectively identical
7060 * to the external parameter list.
7061 * </ul>
7062 * <p>
7063 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7064 * <li>The loop handle's result type is the result type {@code V} of the body.
7065 * <li>The loop handle's parameter types are the types {@code (A...)},
7066 * from the external parameter list.
7067 * </ul>
7068 * <p>
7069 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7070 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7071 * arguments passed to the loop.
7072 * {@snippet lang="java" :
7073 * int start(A...);
7074 * int end(A...);
7075 * V init(A...);
7076 * V body(V, int, A...);
7077 * V countedLoop(A... a...) {
7078 * int e = end(a...);
7079 * int s = start(a...);
7080 * V v = init(a...);
7081 * for (int i = s; i < e; ++i) {
7082 * v = body(v, i, a...);
7083 * }
7084 * return v;
7085 * }
7086 * }
7087 *
7088 * @apiNote The implementation of this method can be expressed as follows:
7089 * {@snippet lang="java" :
7090 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7091 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7092 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7093 * // the following semantics:
7094 * // MH_increment: (int limit, int counter) -> counter + 1
7095 * // MH_predicate: (int limit, int counter) -> counter < limit
7096 * Class<?> counterType = start.type().returnType(); // int
7097 * Class<?> returnType = body.type().returnType();
7098 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7099 * if (returnType != void.class) { // ignore the V variable
7100 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i)
7101 * pred = dropArguments(pred, 1, returnType); // ditto
7102 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7103 * }
7104 * body = dropArguments(body, 0, counterType); // ignore the limit variable
7105 * MethodHandle[]
7106 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v
7107 * bodyClause = { init, body }, // v = init(); v = body(v, i)
7108 * indexVar = { start, incr }; // i = start(); i = i + 1
7109 * return loop(loopLimit, bodyClause, indexVar);
7110 * }
7111 * }
7112 *
7113 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7114 * See above for other constraints.
7115 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7116 * {@code end-1}). The result type must be {@code int}. See above for other constraints.
7117 * @param init optional initializer, providing the initial value of the loop variable.
7118 * May be {@code null}, implying a default initial value. See above for other constraints.
7119 * @param body body of the loop, which may not be {@code null}.
7120 * It controls the loop parameters and result type in the standard case (see above for details).
7121 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7122 * and may accept any number of additional types.
7123 * See above for other constraints.
7124 *
7125 * @return a method handle representing the loop.
7126 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7127 * @throws IllegalArgumentException if any argument violates the rules formulated above.
7128 *
7129 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7130 * @since 9
7131 */
7132 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7133 countedLoopChecks(start, end, init, body);
7134 Class<?> counterType = start.type().returnType(); // int, but who's counting?
7135 Class<?> limitType = end.type().returnType(); // yes, int again
7136 Class<?> returnType = body.type().returnType();
7137 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7138 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7139 MethodHandle retv = null;
7140 if (returnType != void.class) {
7141 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i)
7142 pred = dropArguments(pred, 1, returnType); // ditto
7143 retv = dropArguments(identity(returnType), 0, counterType);
7144 }
7145 body = dropArguments(body, 0, counterType); // ignore the limit variable
7146 MethodHandle[]
7147 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v
7148 bodyClause = { init, body }, // v = init(); v = body(v, i)
7149 indexVar = { start, incr }; // i = start(); i = i + 1
7150 return loop(loopLimit, bodyClause, indexVar);
7151 }
7152
7153 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7154 Objects.requireNonNull(start);
7155 Objects.requireNonNull(end);
7156 Objects.requireNonNull(body);
7157 Class<?> counterType = start.type().returnType();
7158 if (counterType != int.class) {
7159 MethodType expected = start.type().changeReturnType(int.class);
7160 throw misMatchedTypes("start function", start.type(), expected);
7161 } else if (end.type().returnType() != counterType) {
7162 MethodType expected = end.type().changeReturnType(counterType);
7163 throw misMatchedTypes("end function", end.type(), expected);
7164 }
7165 MethodType bodyType = body.type();
7166 Class<?> returnType = bodyType.returnType();
7167 List<Class<?>> innerList = bodyType.parameterList();
7168 // strip leading V value if present
7169 int vsize = (returnType == void.class ? 0 : 1);
7170 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7171 // argument list has no "V" => error
7172 MethodType expected = bodyType.insertParameterTypes(0, returnType);
7173 throw misMatchedTypes("body function", bodyType, expected);
7174 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7175 // missing I type => error
7176 MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7177 throw misMatchedTypes("body function", bodyType, expected);
7178 }
7179 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7180 if (outerList.isEmpty()) {
7181 // special case; take lists from end handle
7182 outerList = end.type().parameterList();
7183 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7184 }
7185 MethodType expected = methodType(counterType, outerList);
7186 if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7187 throw misMatchedTypes("start parameter types", start.type(), expected);
7188 }
7189 if (end.type() != start.type() &&
7190 !end.type().effectivelyIdenticalParameters(0, outerList)) {
7191 throw misMatchedTypes("end parameter types", end.type(), expected);
7192 }
7193 if (init != null) {
7194 MethodType initType = init.type();
7195 if (initType.returnType() != returnType ||
7196 !initType.effectivelyIdenticalParameters(0, outerList)) {
7197 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7198 }
7199 }
7200 }
7201
7202 /**
7203 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7204 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7205 * <p>
7206 * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7207 * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7208 * <p>
7209 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7210 * of that type is also present. This variable is initialized using the optional {@code init} handle,
7211 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7212 * <p>
7213 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7214 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7215 * iteration variable.
7216 * The result of the loop handle execution will be the final {@code V} value of that variable
7217 * (or {@code void} if there is no {@code V} variable).
7218 * <p>
7219 * The following rules hold for the argument handles:<ul>
7220 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7221 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7222 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7223 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7224 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7225 * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7226 * of types called the <em>internal parameter list</em>.
7227 * It will constrain the parameter lists of the other loop parts.
7228 * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7229 * with no additional {@code A} types, then the internal parameter list is extended by
7230 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7231 * single type {@code Iterable} is added and constitutes the {@code A...} list.
7232 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7233 * list {@code (A...)} is called the <em>external parameter list</em>.
7234 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7235 * additional state variable of the loop.
7236 * The body must both accept a leading parameter and return a value of this type {@code V}.
7237 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7238 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7239 * <a href="MethodHandles.html#effid">effectively identical</a>
7240 * to the external parameter list {@code (A...)}.
7241 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7242 * {@linkplain #empty default value}.
7243 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7244 * type {@code java.util.Iterator} or a subtype thereof.
7245 * The iterator it produces when the loop is executed will be assumed
7246 * to yield values which can be converted to type {@code T}.
7247 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7248 * effectively identical to the external parameter list {@code (A...)}.
7249 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7250 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list
7251 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7252 * handle parameter is adjusted to accept the leading {@code A} type, as if by
7253 * the {@link MethodHandle#asType asType} conversion method.
7254 * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7255 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7256 * </ul>
7257 * <p>
7258 * The type {@code T} may be either a primitive or reference.
7259 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7260 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7261 * as if by the {@link MethodHandle#asType asType} conversion method.
7262 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7263 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7264 * <p>
7265 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7266 * <li>The loop handle's result type is the result type {@code V} of the body.
7267 * <li>The loop handle's parameter types are the types {@code (A...)},
7268 * from the external parameter list.
7269 * </ul>
7270 * <p>
7271 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7272 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7273 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7274 * {@snippet lang="java" :
7275 * Iterator<T> iterator(A...); // defaults to Iterable::iterator
7276 * V init(A...);
7277 * V body(V,T,A...);
7278 * V iteratedLoop(A... a...) {
7279 * Iterator<T> it = iterator(a...);
7280 * V v = init(a...);
7281 * while (it.hasNext()) {
7282 * T t = it.next();
7283 * v = body(v, t, a...);
7284 * }
7285 * return v;
7286 * }
7287 * }
7288 *
7289 * @apiNote Example:
7290 * {@snippet lang="java" :
7291 * // get an iterator from a list
7292 * static List<String> reverseStep(List<String> r, String e) {
7293 * r.add(0, e);
7294 * return r;
7295 * }
7296 * static List<String> newArrayList() { return new ArrayList<>(); }
7297 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7298 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7299 * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7300 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7301 * assertEquals(reversedList, (List<String>) loop.invoke(list));
7302 * }
7303 *
7304 * @apiNote The implementation of this method can be expressed approximately as follows:
7305 * {@snippet lang="java" :
7306 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7307 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7308 * Class<?> returnType = body.type().returnType();
7309 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7310 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7311 * MethodHandle retv = null, step = body, startIter = iterator;
7312 * if (returnType != void.class) {
7313 * // the simple thing first: in (I V A...), drop the I to get V
7314 * retv = dropArguments(identity(returnType), 0, Iterator.class);
7315 * // body type signature (V T A...), internal loop types (I V A...)
7316 * step = swapArguments(body, 0, 1); // swap V <-> T
7317 * }
7318 * if (startIter == null) startIter = MH_getIter;
7319 * MethodHandle[]
7320 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7321 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a)
7322 * return loop(iterVar, bodyClause);
7323 * }
7324 * }
7325 *
7326 * @param iterator an optional handle to return the iterator to start the loop.
7327 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7328 * See above for other constraints.
7329 * @param init optional initializer, providing the initial value of the loop variable.
7330 * May be {@code null}, implying a default initial value. See above for other constraints.
7331 * @param body body of the loop, which may not be {@code null}.
7332 * It controls the loop parameters and result type in the standard case (see above for details).
7333 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7334 * and may accept any number of additional types.
7335 * See above for other constraints.
7336 *
7337 * @return a method handle embodying the iteration loop functionality.
7338 * @throws NullPointerException if the {@code body} handle is {@code null}.
7339 * @throws IllegalArgumentException if any argument violates the above requirements.
7340 *
7341 * @since 9
7342 */
7343 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7344 Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7345 Class<?> returnType = body.type().returnType();
7346 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7347 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7348 MethodHandle startIter;
7349 MethodHandle nextVal;
7350 {
7351 MethodType iteratorType;
7352 if (iterator == null) {
7353 // derive argument type from body, if available, else use Iterable
7354 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7355 iteratorType = startIter.type().changeParameterType(0, iterableType);
7356 } else {
7357 // force return type to the internal iterator class
7358 iteratorType = iterator.type().changeReturnType(Iterator.class);
7359 startIter = iterator;
7360 }
7361 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7362 MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7363
7364 // perform the asType transforms under an exception transformer, as per spec.:
7365 try {
7366 startIter = startIter.asType(iteratorType);
7367 nextVal = nextRaw.asType(nextValType);
7368 } catch (WrongMethodTypeException ex) {
7369 throw new IllegalArgumentException(ex);
7370 }
7371 }
7372
7373 MethodHandle retv = null, step = body;
7374 if (returnType != void.class) {
7375 // the simple thing first: in (I V A...), drop the I to get V
7376 retv = dropArguments(identity(returnType), 0, Iterator.class);
7377 // body type signature (V T A...), internal loop types (I V A...)
7378 step = swapArguments(body, 0, 1); // swap V <-> T
7379 }
7380
7381 MethodHandle[]
7382 iterVar = { startIter, null, hasNext, retv },
7383 bodyClause = { init, filterArgument(step, 0, nextVal) };
7384 return loop(iterVar, bodyClause);
7385 }
7386
7387 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7388 Objects.requireNonNull(body);
7389 MethodType bodyType = body.type();
7390 Class<?> returnType = bodyType.returnType();
7391 List<Class<?>> internalParamList = bodyType.parameterList();
7392 // strip leading V value if present
7393 int vsize = (returnType == void.class ? 0 : 1);
7394 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7395 // argument list has no "V" => error
7396 MethodType expected = bodyType.insertParameterTypes(0, returnType);
7397 throw misMatchedTypes("body function", bodyType, expected);
7398 } else if (internalParamList.size() <= vsize) {
7399 // missing T type => error
7400 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7401 throw misMatchedTypes("body function", bodyType, expected);
7402 }
7403 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7404 Class<?> iterableType = null;
7405 if (iterator != null) {
7406 // special case; if the body handle only declares V and T then
7407 // the external parameter list is obtained from iterator handle
7408 if (externalParamList.isEmpty()) {
7409 externalParamList = iterator.type().parameterList();
7410 }
7411 MethodType itype = iterator.type();
7412 if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7413 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7414 }
7415 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7416 MethodType expected = methodType(itype.returnType(), externalParamList);
7417 throw misMatchedTypes("iterator parameters", itype, expected);
7418 }
7419 } else {
7420 if (externalParamList.isEmpty()) {
7421 // special case; if the iterator handle is null and the body handle
7422 // only declares V and T then the external parameter list consists
7423 // of Iterable
7424 externalParamList = List.of(Iterable.class);
7425 iterableType = Iterable.class;
7426 } else {
7427 // special case; if the iterator handle is null and the external
7428 // parameter list is not empty then the first parameter must be
7429 // assignable to Iterable
7430 iterableType = externalParamList.get(0);
7431 if (!Iterable.class.isAssignableFrom(iterableType)) {
7432 throw newIllegalArgumentException(
7433 "inferred first loop argument must inherit from Iterable: " + iterableType);
7434 }
7435 }
7436 }
7437 if (init != null) {
7438 MethodType initType = init.type();
7439 if (initType.returnType() != returnType ||
7440 !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7441 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7442 }
7443 }
7444 return iterableType; // help the caller a bit
7445 }
7446
7447 /*non-public*/
7448 static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7449 // there should be a better way to uncross my wires
7450 int arity = mh.type().parameterCount();
7451 int[] order = new int[arity];
7452 for (int k = 0; k < arity; k++) order[k] = k;
7453 order[i] = j; order[j] = i;
7454 Class<?>[] types = mh.type().parameterArray();
7455 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7456 MethodType swapType = methodType(mh.type().returnType(), types);
7457 return permuteArguments(mh, swapType, order);
7458 }
7459
7460 /**
7461 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7462 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7463 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7464 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The
7465 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7466 * {@code try-finally} handle.
7467 * <p>
7468 * The {@code cleanup} handle will be passed one or two additional leading arguments.
7469 * The first is the exception thrown during the
7470 * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7471 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7472 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7473 * The second argument is not present if the {@code target} handle has a {@code void} return type.
7474 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7475 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7476 * <p>
7477 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7478 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7479 * two extra leading parameters:<ul>
7480 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7481 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7482 * the result from the execution of the {@code target} handle.
7483 * This parameter is not present if the {@code target} returns {@code void}.
7484 * </ul>
7485 * <p>
7486 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7487 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7488 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7489 * the cleanup.
7490 * {@snippet lang="java" :
7491 * V target(A..., B...);
7492 * V cleanup(Throwable, V, A...);
7493 * V adapter(A... a, B... b) {
7494 * V result = (zero value for V);
7495 * Throwable throwable = null;
7496 * try {
7497 * result = target(a..., b...);
7498 * } catch (Throwable t) {
7499 * throwable = t;
7500 * throw t;
7501 * } finally {
7502 * result = cleanup(throwable, result, a...);
7503 * }
7504 * return result;
7505 * }
7506 * }
7507 * <p>
7508 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7509 * be modified by execution of the target, and so are passed unchanged
7510 * from the caller to the cleanup, if it is invoked.
7511 * <p>
7512 * The target and cleanup must return the same type, even if the cleanup
7513 * always throws.
7514 * To create such a throwing cleanup, compose the cleanup logic
7515 * with {@link #throwException throwException},
7516 * in order to create a method handle of the correct return type.
7517 * <p>
7518 * Note that {@code tryFinally} never converts exceptions into normal returns.
7519 * In rare cases where exceptions must be converted in that way, first wrap
7520 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7521 * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7522 * <p>
7523 * It is recommended that the first parameter type of {@code cleanup} be
7524 * declared {@code Throwable} rather than a narrower subtype. This ensures
7525 * {@code cleanup} will always be invoked with whatever exception that
7526 * {@code target} throws. Declaring a narrower type may result in a
7527 * {@code ClassCastException} being thrown by the {@code try-finally}
7528 * handle if the type of the exception thrown by {@code target} is not
7529 * assignable to the first parameter type of {@code cleanup}. Note that
7530 * various exception types of {@code VirtualMachineError},
7531 * {@code LinkageError}, and {@code RuntimeException} can in principle be
7532 * thrown by almost any kind of Java code, and a finally clause that
7533 * catches (say) only {@code IOException} would mask any of the others
7534 * behind a {@code ClassCastException}.
7535 *
7536 * @param target the handle whose execution is to be wrapped in a {@code try} block.
7537 * @param cleanup the handle that is invoked in the finally block.
7538 *
7539 * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7540 * @throws NullPointerException if any argument is null
7541 * @throws IllegalArgumentException if {@code cleanup} does not accept
7542 * the required leading arguments, or if the method handle types do
7543 * not match in their return types and their
7544 * corresponding trailing parameters
7545 *
7546 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7547 * @since 9
7548 */
7549 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7550 Class<?>[] targetParamTypes = target.type().ptypes();
7551 Class<?> rtype = target.type().returnType();
7552
7553 tryFinallyChecks(target, cleanup);
7554
7555 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7556 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7557 // target parameter list.
7558 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7559
7560 // Ensure that the intrinsic type checks the instance thrown by the
7561 // target against the first parameter of cleanup
7562 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7563
7564 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7565 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7566 }
7567
7568 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7569 Class<?> rtype = target.type().returnType();
7570 if (rtype != cleanup.type().returnType()) {
7571 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7572 }
7573 MethodType cleanupType = cleanup.type();
7574 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7575 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7576 }
7577 if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7578 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7579 }
7580 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7581 // target parameter list.
7582 int cleanupArgIndex = rtype == void.class ? 1 : 2;
7583 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7584 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7585 cleanup.type(), target.type());
7586 }
7587 }
7588
7589 /**
7590 * Creates a table switch method handle, which can be used to switch over a set of target
7591 * method handles, based on a given target index, called selector.
7592 * <p>
7593 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7594 * and where {@code N} is the number of target method handles, the table switch method
7595 * handle will invoke the n-th target method handle from the list of target method handles.
7596 * <p>
7597 * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7598 * method handle will invoke the given fallback method handle.
7599 * <p>
7600 * All method handles passed to this method must have the same type, with the additional
7601 * requirement that the leading parameter be of type {@code int}. The leading parameter
7602 * represents the selector.
7603 * <p>
7604 * Any trailing parameters present in the type will appear on the returned table switch
7605 * method handle as well. Any arguments assigned to these parameters will be forwarded,
7606 * together with the selector value, to the selected method handle when invoking it.
7607 *
7608 * @apiNote Example:
7609 * The cases each drop the {@code selector} value they are given, and take an additional
7610 * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7611 * to a specific constant label string for each case:
7612 * {@snippet lang="java" :
7613 * MethodHandles.Lookup lookup = MethodHandles.lookup();
7614 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7615 * MethodType.methodType(String.class, String.class));
7616 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7617 *
7618 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7619 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7620 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7621 *
7622 * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7623 * caseDefault,
7624 * case0,
7625 * case1
7626 * );
7627 *
7628 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7629 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7630 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7631 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7632 * }
7633 *
7634 * @param fallback the fallback method handle that is called when the selector is not
7635 * within the range {@code [0, N)}.
7636 * @param targets array of target method handles.
7637 * @return the table switch method handle.
7638 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7639 * any of the elements of the {@code targets} array are
7640 * {@code null}.
7641 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7642 * parameter of the fallback handle or any of the target
7643 * handles is not {@code int}, or if the types of
7644 * the fallback handle and all of target handles are
7645 * not the same.
7646 *
7647 * @since 17
7648 */
7649 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7650 Objects.requireNonNull(fallback);
7651 Objects.requireNonNull(targets);
7652 targets = targets.clone();
7653 MethodType type = tableSwitchChecks(fallback, targets);
7654 return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7655 }
7656
7657 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7658 if (caseActions.length == 0)
7659 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7660
7661 MethodType expectedType = defaultCase.type();
7662
7663 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7664 throw new IllegalArgumentException(
7665 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7666
7667 for (MethodHandle mh : caseActions) {
7668 Objects.requireNonNull(mh);
7669 if (mh.type() != expectedType)
7670 throw new IllegalArgumentException(
7671 "Case actions must have the same type: " + Arrays.toString(caseActions));
7672 }
7673
7674 return expectedType;
7675 }
7676
7677 /**
7678 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7679 * <p>
7680 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7681 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
7682 * to the target var handle.
7683 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
7684 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
7685 * is processed using the second filter and returned to the caller. More advanced access mode types, such as
7686 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
7687 * <p>
7688 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
7689 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
7690 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
7691 * will be appended to the coordinates of the target var handle).
7692 * <p>
7693 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
7694 * throw an {@link IllegalStateException}.
7695 * <p>
7696 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7697 * atomic access guarantees as those featured by the target var handle.
7698 *
7699 * @param target the target var handle
7700 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
7701 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
7702 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
7703 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
7704 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
7705 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
7706 * @throws NullPointerException if any of the arguments is {@code null}.
7707 * @since 22
7708 */
7709 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
7710 return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
7711 }
7712
7713 /**
7714 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
7715 * <p>
7716 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
7717 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
7718 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
7719 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
7720 * by the adaptation) to the target var handle.
7721 * <p>
7722 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
7723 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
7724 * <p>
7725 * If any of the filters throws a checked exception when invoked, the resulting var handle will
7726 * throw an {@link IllegalStateException}.
7727 * <p>
7728 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7729 * atomic access guarantees as those featured by the target var handle.
7730 *
7731 * @param target the target var handle
7732 * @param pos the position of the first coordinate to be transformed
7733 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
7734 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
7735 * to the new coordinate values.
7736 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
7737 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
7738 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7739 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
7740 * or if it's determined that any of the filters throws any checked exceptions.
7741 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
7742 * @since 22
7743 */
7744 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
7745 return VarHandles.filterCoordinates(target, pos, filters);
7746 }
7747
7748 /**
7749 * Provides a target var handle with one or more <em>bound coordinates</em>
7750 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
7751 * coordinate types than the target var handle.
7752 * <p>
7753 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
7754 * are joined with bound coordinate values, and then passed to the target var handle.
7755 * <p>
7756 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
7757 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
7758 * <p>
7759 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7760 * atomic access guarantees as those featured by the target var handle.
7761 *
7762 * @param target the var handle to invoke after the bound coordinates are inserted
7763 * @param pos the position of the first coordinate to be inserted
7764 * @param values the series of bound coordinates to insert
7765 * @return an adapter var handle which inserts additional coordinates,
7766 * before calling the target var handle
7767 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7768 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
7769 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
7770 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
7771 * of the target var handle.
7772 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
7773 * @since 22
7774 */
7775 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
7776 return VarHandles.insertCoordinates(target, pos, values);
7777 }
7778
7779 /**
7780 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
7781 * so that the new coordinates match the provided ones.
7782 * <p>
7783 * The given array controls the reordering.
7784 * Call {@code #I} the number of incoming coordinates (the value
7785 * {@code newCoordinates.size()}), and call {@code #O} the number
7786 * of outgoing coordinates (the number of coordinates associated with the target var handle).
7787 * Then the length of the reordering array must be {@code #O},
7788 * and each element must be a non-negative number less than {@code #I}.
7789 * For every {@code N} less than {@code #O}, the {@code N}-th
7790 * outgoing coordinate will be taken from the {@code I}-th incoming
7791 * coordinate, where {@code I} is {@code reorder[N]}.
7792 * <p>
7793 * No coordinate value conversions are applied.
7794 * The type of each incoming coordinate, as determined by {@code newCoordinates},
7795 * must be identical to the type of the corresponding outgoing coordinate
7796 * in the target var handle.
7797 * <p>
7798 * The reordering array need not specify an actual permutation.
7799 * An incoming coordinate will be duplicated if its index appears
7800 * more than once in the array, and an incoming coordinate will be dropped
7801 * if its index does not appear in the array.
7802 * <p>
7803 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7804 * atomic access guarantees as those featured by the target var handle.
7805 * @param target the var handle to invoke after the coordinates have been reordered
7806 * @param newCoordinates the new coordinate types
7807 * @param reorder an index array which controls the reordering
7808 * @return an adapter var handle which re-arranges the incoming coordinate values,
7809 * before calling the target var handle
7810 * @throws IllegalArgumentException if the index array length is not equal to
7811 * the number of coordinates of the target var handle, or if any index array element is not a valid index for
7812 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
7813 * the target var handle and in {@code newCoordinates} are not identical.
7814 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
7815 * @since 22
7816 */
7817 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
7818 return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
7819 }
7820
7821 /**
7822 * Adapts a target var handle by pre-processing
7823 * a sub-sequence of its coordinate values with a filter (a method handle).
7824 * The pre-processed coordinates are replaced by the result (if any) of the
7825 * filter function and the target var handle is then called on the modified (usually shortened)
7826 * coordinate list.
7827 * <p>
7828 * If {@code R} is the return type of the filter, then:
7829 * <ul>
7830 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
7831 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
7832 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
7833 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
7834 * target var handle.</li>
7835 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
7836 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
7837 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
7838 * downstream invocation of the target var handle.</li>
7839 * </ul>
7840 * <p>
7841 * If any of the filters throws a checked exception when invoked, the resulting var handle will
7842 * throw an {@link IllegalStateException}.
7843 * <p>
7844 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7845 * atomic access guarantees as those featured by the target var handle.
7846 *
7847 * @param target the var handle to invoke after the coordinates have been filtered
7848 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
7849 * @param filter the filter method handle
7850 * @return an adapter var handle which filters the incoming coordinate values,
7851 * before calling the target var handle
7852 * @throws IllegalArgumentException if the return type of {@code filter}
7853 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
7854 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7855 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
7856 * or if it's determined that {@code filter} throws any checked exceptions.
7857 * @throws NullPointerException if any of the arguments is {@code null}.
7858 * @since 22
7859 */
7860 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
7861 return VarHandles.collectCoordinates(target, pos, filter);
7862 }
7863
7864 /**
7865 * Returns a var handle which will discard some dummy coordinates before delegating to the
7866 * target var handle. As a consequence, the resulting var handle will feature more
7867 * coordinate types than the target var handle.
7868 * <p>
7869 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
7870 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
7871 * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
7872 * <p>
7873 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7874 * atomic access guarantees as those featured by the target var handle.
7875 *
7876 * @param target the var handle to invoke after the dummy coordinates are dropped
7877 * @param pos position of the first coordinate to drop (zero for the leftmost)
7878 * @param valueTypes the type(s) of the coordinate(s) to drop
7879 * @return an adapter var handle which drops some dummy coordinates,
7880 * before calling the target var handle
7881 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
7882 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
7883 * @since 22
7884 */
7885 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
7886 return VarHandles.dropCoordinates(target, pos, valueTypes);
7887 }
7888 }