1 /*
2 * Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang.invoke;
27
28 import 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 *
2667 *
2668 * @param refc the class or interface from which the method is accessed
2669 * @param type the type of the method, with the receiver argument omitted, and a void return type
2670 * @return the desired method handle
2671 * @throws NoSuchMethodException if the constructor does not exist
2672 * @throws IllegalAccessException if access checking fails
2673 * or if the method's variable arity modifier bit
2674 * is set and {@code asVarargsCollector} fails
2675 * @throws NullPointerException if any argument is null
2676 */
2677 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2678 if (refc.isArray()) {
2679 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2680 }
2681 if (type.returnType() != void.class) {
2682 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2683 }
2684 String name = ConstantDescs.INIT_NAME;
2685 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2686 return getDirectConstructor(refc, ctor);
2687 }
2688
2689 /**
2690 * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2691 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2692 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2693 * and then determines whether the class is accessible to this lookup object.
2694 * <p>
2695 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2696 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2697 * of {@code '['} and followed by the element type as encoded in the
2698 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2699 * <p>
2700 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2701 * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2702 *
2703 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2704 * or the string representing an array class
2705 * @return the requested class.
2706 * @throws LinkageError if the linkage fails
2707 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2708 * @throws IllegalAccessException if the class is not accessible, using the allowed access
2709 * modes.
2710 * @throws NullPointerException if {@code targetName} is null
2711 * @since 9
2712 * @jvms 5.4.3.1 Class and Interface Resolution
2713 */
2714 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2715 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2716 return accessClass(targetClass);
2717 }
2718
2719 /**
2720 * Ensures that {@code targetClass} has been initialized. The class
2721 * to be initialized must be {@linkplain #accessClass accessible}
2722 * to this {@code Lookup} object. This method causes {@code targetClass}
2723 * to be initialized if it has not been already initialized,
2724 * as specified in JVMS {@jvms 5.5}.
2725 *
2726 * <p>
2727 * This method returns when {@code targetClass} is fully initialized, or
2728 * when {@code targetClass} is being initialized by the current thread.
2729 *
2730 * @param <T> the type of the class to be initialized
2731 * @param targetClass the class to be initialized
2732 * @return {@code targetClass} that has been initialized, or that is being
2733 * initialized by the current thread.
2734 *
2735 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2736 * or array class
2737 * @throws IllegalAccessException if {@code targetClass} is not
2738 * {@linkplain #accessClass accessible} to this lookup
2739 * @throws ExceptionInInitializerError if the class initialization provoked
2740 * by this method fails
2741 * @since 15
2742 * @jvms 5.5 Initialization
2743 */
2744 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2745 if (targetClass.isPrimitive())
2746 throw new IllegalArgumentException(targetClass + " is a primitive class");
2747 if (targetClass.isArray())
2748 throw new IllegalArgumentException(targetClass + " is an array class");
2749
2750 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2751 throw makeAccessException(targetClass);
2752 }
2753
2754 // ensure class initialization
2755 Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2756 return targetClass;
2757 }
2758
2759 /*
2760 * Returns IllegalAccessException due to access violation to the given targetClass.
2761 *
2762 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2763 * which verifies access to a class rather a member.
2764 */
2765 private IllegalAccessException makeAccessException(Class<?> targetClass) {
2766 String message = "access violation: "+ targetClass;
2767 if (this == MethodHandles.publicLookup()) {
2768 message += ", from public Lookup";
2769 } else {
2770 Module m = lookupClass().getModule();
2771 message += ", from " + lookupClass() + " (" + m + ")";
2772 if (prevLookupClass != null) {
2773 message += ", previous lookup " +
2774 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2775 }
2776 }
2777 return new IllegalAccessException(message);
2778 }
2779
2780 /**
2781 * Determines if a class can be accessed from the lookup context defined by
2782 * this {@code Lookup} object. The static initializer of the class is not run.
2783 * If {@code targetClass} is an array class, {@code targetClass} is accessible
2784 * if the element type of the array class is accessible. Otherwise,
2785 * {@code targetClass} is determined as accessible as follows.
2786 *
2787 * <p>
2788 * If {@code targetClass} is in the same module as the lookup class,
2789 * the lookup class is {@code LC} in module {@code M1} and
2790 * the previous lookup class is in module {@code M0} or
2791 * {@code null} if not present,
2792 * {@code targetClass} is accessible if and only if one of the following is true:
2793 * <ul>
2794 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2795 * {@code LC} or other class in the same nest of {@code LC}.</li>
2796 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2797 * in the same runtime package of {@code LC}.</li>
2798 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2799 * a public type in {@code M1}.</li>
2800 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2801 * a public type in a package exported by {@code M1} to at least {@code M0}
2802 * if the previous lookup class is present; otherwise, {@code targetClass}
2803 * is a public type in a package exported by {@code M1} unconditionally.</li>
2804 * </ul>
2805 *
2806 * <p>
2807 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2808 * can access public types in all modules when the type is in a package
2809 * that is exported unconditionally.
2810 * <p>
2811 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2812 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2813 * is inaccessible.
2814 * <p>
2815 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2816 * {@code M1} is the module containing {@code lookupClass} and
2817 * {@code M2} is the module containing {@code targetClass},
2818 * then {@code targetClass} is accessible if and only if
2819 * <ul>
2820 * <li>{@code M1} reads {@code M2}, and
2821 * <li>{@code targetClass} is public and in a package exported by
2822 * {@code M2} at least to {@code M1}.
2823 * </ul>
2824 * <p>
2825 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2826 * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2827 * containing the previous lookup class, then {@code targetClass} is accessible
2828 * if and only if one of the following is true:
2829 * <ul>
2830 * <li>{@code targetClass} is in {@code M0} and {@code M1}
2831 * {@linkplain Module#canRead(Module)} reads} {@code M0} and the type is
2832 * in a package that is exported to at least {@code M1}.
2833 * <li>{@code targetClass} is in {@code M1} and {@code M0}
2834 * {@linkplain Module#canRead(Module)} reads} {@code M1} and the type is
2835 * in a package that is exported to at least {@code M0}.
2836 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2837 * and {@code M1} reads {@code M2} and the type is in a package
2838 * that is exported to at least both {@code M0} and {@code M2}.
2839 * </ul>
2840 * <p>
2841 * Otherwise, {@code targetClass} is not accessible.
2842 *
2843 * @param <T> the type of the class to be access-checked
2844 * @param targetClass the class to be access-checked
2845 * @return {@code targetClass} that has been access-checked
2846 * @throws IllegalAccessException if the class is not accessible from the lookup class
2847 * and previous lookup class, if present, using the allowed access modes.
2848 * @throws NullPointerException if {@code targetClass} is {@code null}
2849 * @since 9
2850 * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2851 */
2852 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
2853 if (!isClassAccessible(targetClass)) {
2854 throw makeAccessException(targetClass);
2855 }
2856 return targetClass;
2857 }
2858
2859 /**
2860 * Produces an early-bound method handle for a virtual method.
2861 * It will bypass checks for overriding methods on the receiver,
2862 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2863 * instruction from within the explicitly specified {@code specialCaller}.
2864 * The type of the method handle will be that of the method,
2865 * with a suitably restricted receiver type prepended.
2866 * (The receiver type will be {@code specialCaller} or a subtype.)
2867 * The method and all its argument types must be accessible
2868 * to the lookup object.
2869 * <p>
2870 * Before method resolution,
2871 * if the explicitly specified caller class is not identical with the
2872 * lookup class, or if this lookup object does not have
2873 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2874 * privileges, the access fails.
2875 * <p>
2876 * The returned method handle will have
2877 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2878 * the method's variable arity modifier bit ({@code 0x0080}) is set.
2879 * <p style="font-size:smaller;">
2880 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME}
2881 * are not visible to this API,
2882 * even though the {@code invokespecial} instruction can refer to them
2883 * in special circumstances. Use {@link #findConstructor findConstructor}
2884 * to access instance initialization methods in a safe manner.)</em>
2885 * <p><b>Example:</b>
2886 * {@snippet lang="java" :
2887 import static java.lang.invoke.MethodHandles.*;
2888 import static java.lang.invoke.MethodType.*;
2889 ...
2890 static class Listie extends ArrayList {
2891 public String toString() { return "[wee Listie]"; }
2892 static Lookup lookup() { return MethodHandles.lookup(); }
2893 }
2894 ...
2895 // no access to constructor via invokeSpecial:
2896 MethodHandle MH_newListie = Listie.lookup()
2897 .findConstructor(Listie.class, methodType(void.class));
2898 Listie l = (Listie) MH_newListie.invokeExact();
2899 try { assertEquals("impossible", Listie.lookup().findSpecial(
2900 Listie.class, "<init>", methodType(void.class), Listie.class));
2901 } catch (NoSuchMethodException ex) { } // OK
2902 // access to super and self methods via invokeSpecial:
2903 MethodHandle MH_super = Listie.lookup().findSpecial(
2904 ArrayList.class, "toString" , methodType(String.class), Listie.class);
2905 MethodHandle MH_this = Listie.lookup().findSpecial(
2906 Listie.class, "toString" , methodType(String.class), Listie.class);
2907 MethodHandle MH_duper = Listie.lookup().findSpecial(
2908 Object.class, "toString" , methodType(String.class), Listie.class);
2909 assertEquals("[]", (String) MH_super.invokeExact(l));
2910 assertEquals(""+l, (String) MH_this.invokeExact(l));
2911 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2912 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2913 String.class, "toString", methodType(String.class), Listie.class));
2914 } catch (IllegalAccessException ex) { } // OK
2915 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2916 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2917 * }
2918 *
2919 * @param refc the class or interface from which the method is accessed
2920 * @param name the name of the method (which must not be "<init>")
2921 * @param type the type of the method, with the receiver argument omitted
2922 * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2923 * @return the desired method handle
2924 * @throws NoSuchMethodException if the method does not exist
2925 * @throws IllegalAccessException if access checking fails,
2926 * or if the method is {@code static},
2927 * or if the method's variable arity modifier bit
2928 * is set and {@code asVarargsCollector} fails
2929 * @throws NullPointerException if any argument is null
2930 */
2931 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
2932 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
2933 checkSpecialCaller(specialCaller, refc);
2934 Lookup specialLookup = this.in(specialCaller);
2935 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
2936 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
2937 }
2938
2939 /**
2940 * Produces a method handle giving read access to a non-static field.
2941 * The type of the method handle will have a return type of the field's
2942 * value type.
2943 * The method handle's single argument will be the instance containing
2944 * the field.
2945 * Access checking is performed immediately on behalf of the lookup class.
2946 * @param refc the class or interface from which the method is accessed
2947 * @param name the field's name
2948 * @param type the field's type
2949 * @return a method handle which can load values from the field
2950 * @throws NoSuchFieldException if the field does not exist
2951 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2952 * @throws NullPointerException if any argument is null
2953 * @see #findVarHandle(Class, String, Class)
2954 */
2955 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2956 MemberName field = resolveOrFail(REF_getField, refc, name, type);
2957 return getDirectField(REF_getField, refc, field);
2958 }
2959
2960 /**
2961 * Produces a method handle giving write access to a non-static field.
2962 * The type of the method handle will have a void return type.
2963 * The method handle will take two arguments, the instance containing
2964 * the field, and the value to be stored.
2965 * The second argument will be of the field's value type.
2966 * Access checking is performed immediately on behalf of the lookup class.
2967 * @param refc the class or interface from which the method is accessed
2968 * @param name the field's name
2969 * @param type the field's type
2970 * @return a method handle which can store values into the field
2971 * @throws NoSuchFieldException if the field does not exist
2972 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2973 * or {@code final}
2974 * @throws NullPointerException if any argument is null
2975 * @see #findVarHandle(Class, String, Class)
2976 */
2977 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2978 MemberName field = resolveOrFail(REF_putField, refc, name, type);
2979 return getDirectField(REF_putField, refc, field);
2980 }
2981
2982 /**
2983 * Produces a VarHandle giving access to a non-static field {@code name}
2984 * of type {@code type} declared in a class of type {@code recv}.
2985 * The VarHandle's variable type is {@code type} and it has one
2986 * coordinate type, {@code recv}.
2987 * <p>
2988 * Access checking is performed immediately on behalf of the lookup
2989 * class.
2990 * <p>
2991 * Certain access modes of the returned VarHandle are unsupported under
2992 * the following conditions:
2993 * <ul>
2994 * <li>if the field is declared {@code final}, then the write, atomic
2995 * update, numeric atomic update, and bitwise atomic update access
2996 * modes are unsupported.
2997 * <li>if the field type is anything other than {@code byte},
2998 * {@code short}, {@code char}, {@code int}, {@code long},
2999 * {@code float}, or {@code double} then numeric atomic update
3000 * access modes are unsupported.
3001 * <li>if the field type is anything other than {@code boolean},
3002 * {@code byte}, {@code short}, {@code char}, {@code int} or
3003 * {@code long} then bitwise atomic update access modes are
3004 * unsupported.
3005 * </ul>
3006 * <p>
3007 * If the field is declared {@code volatile} then the returned VarHandle
3008 * will override access to the field (effectively ignore the
3009 * {@code volatile} declaration) in accordance to its specified
3010 * access modes.
3011 * <p>
3012 * If the field type is {@code float} or {@code double} then numeric
3013 * and atomic update access modes compare values using their bitwise
3014 * representation (see {@link Float#floatToRawIntBits} and
3015 * {@link Double#doubleToRawLongBits}, respectively).
3016 * @apiNote
3017 * Bitwise comparison of {@code float} values or {@code double} values,
3018 * as performed by the numeric and atomic update access modes, differ
3019 * from the primitive {@code ==} operator and the {@link Float#equals}
3020 * and {@link Double#equals} methods, specifically with respect to
3021 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3022 * Care should be taken when performing a compare and set or a compare
3023 * and exchange operation with such values since the operation may
3024 * unexpectedly fail.
3025 * There are many possible NaN values that are considered to be
3026 * {@code NaN} in Java, although no IEEE 754 floating-point operation
3027 * provided by Java can distinguish between them. Operation failure can
3028 * occur if the expected or witness value is a NaN value and it is
3029 * transformed (perhaps in a platform specific manner) into another NaN
3030 * value, and thus has a different bitwise representation (see
3031 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3032 * details).
3033 * The values {@code -0.0} and {@code +0.0} have different bitwise
3034 * representations but are considered equal when using the primitive
3035 * {@code ==} operator. Operation failure can occur if, for example, a
3036 * numeric algorithm computes an expected value to be say {@code -0.0}
3037 * and previously computed the witness value to be say {@code +0.0}.
3038 * @param recv the receiver class, of type {@code R}, that declares the
3039 * non-static field
3040 * @param name the field's name
3041 * @param type the field's type, of type {@code T}
3042 * @return a VarHandle giving access to non-static fields.
3043 * @throws NoSuchFieldException if the field does not exist
3044 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3045 * @throws NullPointerException if any argument is null
3046 * @since 9
3047 */
3048 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3049 MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3050 MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3051 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3052 }
3053
3054 /**
3055 * Produces a method handle giving read access to a static field.
3056 * The type of the method handle will have a return type of the field's
3057 * value type.
3058 * The method handle will take no arguments.
3059 * Access checking is performed immediately on behalf of the lookup class.
3060 * <p>
3061 * If the returned method handle is invoked, the field's class will
3062 * be initialized, if it has not already been initialized.
3063 * @param refc the class or interface from which the method is accessed
3064 * @param name the field's name
3065 * @param type the field's type
3066 * @return a method handle which can load values from the field
3067 * @throws NoSuchFieldException if the field does not exist
3068 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3069 * @throws NullPointerException if any argument is null
3070 */
3071 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3072 MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3073 return getDirectField(REF_getStatic, refc, field);
3074 }
3075
3076 /**
3077 * Produces a method handle giving write access to a static field.
3078 * The type of the method handle will have a void return type.
3079 * The method handle will take a single
3080 * argument, of the field's value type, the value to be stored.
3081 * Access checking is performed immediately on behalf of the lookup class.
3082 * <p>
3083 * If the returned method handle is invoked, the field's class will
3084 * be initialized, if it has not already been initialized.
3085 * @param refc the class or interface from which the method is accessed
3086 * @param name the field's name
3087 * @param type the field's type
3088 * @return a method handle which can store values into the field
3089 * @throws NoSuchFieldException if the field does not exist
3090 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3091 * or is {@code final}
3092 * @throws NullPointerException if any argument is null
3093 */
3094 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3095 MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3096 return getDirectField(REF_putStatic, refc, field);
3097 }
3098
3099 /**
3100 * Produces a VarHandle giving access to a static field {@code name} of
3101 * type {@code type} declared in a class of type {@code decl}.
3102 * The VarHandle's variable type is {@code type} and it has no
3103 * coordinate types.
3104 * <p>
3105 * Access checking is performed immediately on behalf of the lookup
3106 * class.
3107 * <p>
3108 * If the returned VarHandle is operated on, the declaring class will be
3109 * initialized, if it has not already been initialized.
3110 * <p>
3111 * Certain access modes of the returned VarHandle are unsupported under
3112 * the following conditions:
3113 * <ul>
3114 * <li>if the field is declared {@code final}, then the write, atomic
3115 * update, numeric atomic update, and bitwise atomic update access
3116 * modes are unsupported.
3117 * <li>if the field type is anything other than {@code byte},
3118 * {@code short}, {@code char}, {@code int}, {@code long},
3119 * {@code float}, or {@code double}, then numeric atomic update
3120 * access modes are unsupported.
3121 * <li>if the field type is anything other than {@code boolean},
3122 * {@code byte}, {@code short}, {@code char}, {@code int} or
3123 * {@code long} then bitwise atomic update access modes are
3124 * unsupported.
3125 * </ul>
3126 * <p>
3127 * If the field is declared {@code volatile} then the returned VarHandle
3128 * will override access to the field (effectively ignore the
3129 * {@code volatile} declaration) in accordance to its specified
3130 * access modes.
3131 * <p>
3132 * If the field type is {@code float} or {@code double} then numeric
3133 * and atomic update access modes compare values using their bitwise
3134 * representation (see {@link Float#floatToRawIntBits} and
3135 * {@link Double#doubleToRawLongBits}, respectively).
3136 * @apiNote
3137 * Bitwise comparison of {@code float} values or {@code double} values,
3138 * as performed by the numeric and atomic update access modes, differ
3139 * from the primitive {@code ==} operator and the {@link Float#equals}
3140 * and {@link Double#equals} methods, specifically with respect to
3141 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3142 * Care should be taken when performing a compare and set or a compare
3143 * and exchange operation with such values since the operation may
3144 * unexpectedly fail.
3145 * There are many possible NaN values that are considered to be
3146 * {@code NaN} in Java, although no IEEE 754 floating-point operation
3147 * provided by Java can distinguish between them. Operation failure can
3148 * occur if the expected or witness value is a NaN value and it is
3149 * transformed (perhaps in a platform specific manner) into another NaN
3150 * value, and thus has a different bitwise representation (see
3151 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3152 * details).
3153 * The values {@code -0.0} and {@code +0.0} have different bitwise
3154 * representations but are considered equal when using the primitive
3155 * {@code ==} operator. Operation failure can occur if, for example, a
3156 * numeric algorithm computes an expected value to be say {@code -0.0}
3157 * and previously computed the witness value to be say {@code +0.0}.
3158 * @param decl the class that declares the static field
3159 * @param name the field's name
3160 * @param type the field's type, of type {@code T}
3161 * @return a VarHandle giving access to a static field
3162 * @throws NoSuchFieldException if the field does not exist
3163 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3164 * @throws NullPointerException if any argument is null
3165 * @since 9
3166 */
3167 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3168 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3169 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3170 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3171 }
3172
3173 /**
3174 * Produces an early-bound method handle for a non-static method.
3175 * The receiver must have a supertype {@code defc} in which a method
3176 * of the given name and type is accessible to the lookup class.
3177 * The method and all its argument types must be accessible to the lookup object.
3178 * The type of the method handle will be that of the method,
3179 * without any insertion of an additional receiver parameter.
3180 * The given receiver will be bound into the method handle,
3181 * so that every call to the method handle will invoke the
3182 * requested method on the given receiver.
3183 * <p>
3184 * The returned method handle will have
3185 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3186 * the method's variable arity modifier bit ({@code 0x0080}) is set
3187 * <em>and</em> the trailing array argument is not the only argument.
3188 * (If the trailing array argument is the only argument,
3189 * the given receiver value will be bound to it.)
3190 * <p>
3191 * This is almost equivalent to the following code, with some differences noted below:
3192 * {@snippet lang="java" :
3193 import static java.lang.invoke.MethodHandles.*;
3194 import static java.lang.invoke.MethodType.*;
3195 ...
3196 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3197 MethodHandle mh1 = mh0.bindTo(receiver);
3198 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3199 return mh1;
3200 * }
3201 * where {@code defc} is either {@code receiver.getClass()} or a super
3202 * type of that class, in which the requested method is accessible
3203 * to the lookup class.
3204 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3205 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3206 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3207 * the receiver is restricted by {@code findVirtual} to the lookup class.)
3208 * @param receiver the object from which the method is accessed
3209 * @param name the name of the method
3210 * @param type the type of the method, with the receiver argument omitted
3211 * @return the desired method handle
3212 * @throws NoSuchMethodException if the method does not exist
3213 * @throws IllegalAccessException if access checking fails
3214 * or if the method's variable arity modifier bit
3215 * is set and {@code asVarargsCollector} fails
3216 * @throws NullPointerException if any argument is null
3217 * @see MethodHandle#bindTo
3218 * @see #findVirtual
3219 */
3220 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3221 Class<? extends Object> refc = receiver.getClass(); // may get NPE
3222 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3223 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3224 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3225 throw new IllegalAccessException("The restricted defining class " +
3226 mh.type().leadingReferenceParameter().getName() +
3227 " is not assignable from receiver class " +
3228 receiver.getClass().getName());
3229 }
3230 return mh.bindArgumentL(0, receiver).setVarargs(method);
3231 }
3232
3233 /**
3234 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3235 * to <i>m</i>, if the lookup class has permission.
3236 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3237 * If <i>m</i> is virtual, overriding is respected on every call.
3238 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3239 * The type of the method handle will be that of the method,
3240 * with the receiver type prepended (but only if it is non-static).
3241 * If the method's {@code accessible} flag is not set,
3242 * access checking is performed immediately on behalf of the lookup class.
3243 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3244 * <p>
3245 * The returned method handle will have
3246 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3247 * the method's variable arity modifier bit ({@code 0x0080}) is set.
3248 * <p>
3249 * If <i>m</i> is static, and
3250 * if the returned method handle is invoked, the method's class will
3251 * be initialized, if it has not already been initialized.
3252 * @param m the reflected method
3253 * @return a method handle which can invoke the reflected method
3254 * @throws IllegalAccessException if access checking fails
3255 * or if the method's variable arity modifier bit
3256 * is set and {@code asVarargsCollector} fails
3257 * @throws NullPointerException if the argument is null
3258 */
3259 public MethodHandle unreflect(Method m) throws IllegalAccessException {
3260 if (m.getDeclaringClass() == MethodHandle.class) {
3261 MethodHandle mh = unreflectForMH(m);
3262 if (mh != null) return mh;
3263 }
3264 if (m.getDeclaringClass() == VarHandle.class) {
3265 MethodHandle mh = unreflectForVH(m);
3266 if (mh != null) return mh;
3267 }
3268 MemberName method = new MemberName(m);
3269 byte refKind = method.getReferenceKind();
3270 if (refKind == REF_invokeSpecial)
3271 refKind = REF_invokeVirtual;
3272 assert(method.isMethod());
3273 @SuppressWarnings("deprecation")
3274 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3275 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3276 }
3277 private MethodHandle unreflectForMH(Method m) {
3278 // these names require special lookups because they throw UnsupportedOperationException
3279 if (MemberName.isMethodHandleInvokeName(m.getName()))
3280 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3281 return null;
3282 }
3283 private MethodHandle unreflectForVH(Method m) {
3284 // these names require special lookups because they throw UnsupportedOperationException
3285 if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3286 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3287 return null;
3288 }
3289
3290 /**
3291 * Produces a method handle for a reflected method.
3292 * It will bypass checks for overriding methods on the receiver,
3293 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3294 * instruction from within the explicitly specified {@code specialCaller}.
3295 * The type of the method handle will be that of the method,
3296 * with a suitably restricted receiver type prepended.
3297 * (The receiver type will be {@code specialCaller} or a subtype.)
3298 * If the method's {@code accessible} flag is not set,
3299 * access checking is performed immediately on behalf of the lookup class,
3300 * as if {@code invokespecial} instruction were being linked.
3301 * <p>
3302 * Before method resolution,
3303 * if the explicitly specified caller class is not identical with the
3304 * lookup class, or if this lookup object does not have
3305 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3306 * privileges, the access fails.
3307 * <p>
3308 * The returned method handle will have
3309 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3310 * the method's variable arity modifier bit ({@code 0x0080}) is set.
3311 * @param m the reflected method
3312 * @param specialCaller the class nominally calling the method
3313 * @return a method handle which can invoke the reflected method
3314 * @throws IllegalAccessException if access checking fails,
3315 * or if the method is {@code static},
3316 * or if the method's variable arity modifier bit
3317 * is set and {@code asVarargsCollector} fails
3318 * @throws NullPointerException if any argument is null
3319 */
3320 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3321 checkSpecialCaller(specialCaller, m.getDeclaringClass());
3322 Lookup specialLookup = this.in(specialCaller);
3323 MemberName method = new MemberName(m, true);
3324 assert(method.isMethod());
3325 // ignore m.isAccessible: this is a new kind of access
3326 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3327 }
3328
3329 /**
3330 * Produces a method handle for a reflected constructor.
3331 * The type of the method handle will be that of the constructor,
3332 * with the return type changed to the declaring class.
3333 * The method handle will perform a {@code newInstance} operation,
3334 * creating a new instance of the constructor's class on the
3335 * arguments passed to the method handle.
3336 * <p>
3337 * If the constructor's {@code accessible} flag is not set,
3338 * access checking is performed immediately on behalf of the lookup class.
3339 * <p>
3340 * The returned method handle will have
3341 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3342 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3343 * <p>
3344 * If the returned method handle is invoked, the constructor's class will
3345 * be initialized, if it has not already been initialized.
3346 * @param c the reflected constructor
3347 * @return a method handle which can invoke the reflected constructor
3348 * @throws IllegalAccessException if access checking fails
3349 * or if the method's variable arity modifier bit
3350 * is set and {@code asVarargsCollector} fails
3351 * @throws NullPointerException if the argument is null
3352 */
3353 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3354 MemberName ctor = new MemberName(c);
3355 assert(ctor.isConstructor());
3356 @SuppressWarnings("deprecation")
3357 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3358 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor);
3359 }
3360
3361 /*
3362 * Produces a method handle that is capable of creating instances of the given class
3363 * and instantiated by the given constructor.
3364 *
3365 * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3366 */
3367 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3368 MemberName ctor = new MemberName(c);
3369 assert(ctor.isConstructor() && constructorInSuperclass(decl, c));
3370 checkAccess(REF_newInvokeSpecial, decl, ctor);
3371 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
3372 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3373 }
3374
3375 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3376 if (decl == ctor.getDeclaringClass())
3377 return true;
3378
3379 Class<?> cl = decl;
3380 while ((cl = cl.getSuperclass()) != null) {
3381 if (cl == ctor.getDeclaringClass()) {
3382 return true;
3383 }
3384 }
3385 return false;
3386 }
3387
3388 /**
3389 * Produces a method handle giving read access to a reflected field.
3390 * The type of the method handle will have a return type of the field's
3391 * value type.
3392 * If the field is {@code static}, the method handle will take no arguments.
3393 * Otherwise, its single argument will be the instance containing
3394 * the field.
3395 * If the {@code Field} object's {@code accessible} flag is not set,
3396 * access checking is performed immediately on behalf of the lookup class.
3397 * <p>
3398 * If the field is static, and
3399 * if the returned method handle is invoked, the field's class will
3400 * be initialized, if it has not already been initialized.
3401 * @param f the reflected field
3402 * @return a method handle which can load values from the reflected field
3403 * @throws IllegalAccessException if access checking fails
3404 * @throws NullPointerException if the argument is null
3405 */
3406 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3407 return unreflectField(f, false);
3408 }
3409
3410 /**
3411 * Produces a method handle giving write access to a reflected field.
3412 * The type of the method handle will have a void return type.
3413 * If the field is {@code static}, the method handle will take a single
3414 * argument, of the field's value type, the value to be stored.
3415 * Otherwise, the two arguments will be the instance containing
3416 * the field, and the value to be stored.
3417 * If the {@code Field} object's {@code accessible} flag is not set,
3418 * access checking is performed immediately on behalf of the lookup class.
3419 * <p>
3420 * If the field is {@code final}, write access will not be
3421 * allowed and access checking will fail, except under certain
3422 * narrow circumstances documented for {@link Field#set Field.set}.
3423 * A method handle is returned only if a corresponding call to
3424 * the {@code Field} object's {@code set} method could return
3425 * normally. In particular, fields which are both {@code static}
3426 * and {@code final} may never be set.
3427 * <p>
3428 * If the field is {@code static}, and
3429 * if the returned method handle is invoked, the field's class will
3430 * be initialized, if it has not already been initialized.
3431 * @param f the reflected field
3432 * @return a method handle which can store values into the reflected field
3433 * @throws IllegalAccessException if access checking fails,
3434 * or if the field is {@code final} and write access
3435 * is not enabled on the {@code Field} object
3436 * @throws NullPointerException if the argument is null
3437 * @see <a href="{@docRoot}/java.base/java/lang/reflect/doc-files/MutationMethods.html">Mutation methods</a>
3438 */
3439 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3440 return unreflectField(f, true);
3441 }
3442
3443 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3444 @SuppressWarnings("deprecation")
3445 boolean isAccessible = f.isAccessible();
3446 MemberName field = new MemberName(f, isSetter);
3447 if (isSetter && field.isFinal()) {
3448 if (field.isTrustedFinalField()) {
3449 String msg = field.isStatic() ? "static final field has no write access"
3450 : "final field has no write access";
3451 throw field.makeAccessException(msg, this);
3452 }
3453 // check if write access to final field allowed
3454 if (!field.isStatic() && isAccessible) {
3455 SharedSecrets.getJavaLangReflectAccess().checkAllowedToUnreflectFinalSetter(lookupClass, f);
3456 }
3457 }
3458 assert(isSetter
3459 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3460 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3461 Lookup lookup = isAccessible ? IMPL_LOOKUP : this;
3462 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field);
3463 }
3464
3465 /**
3466 * Produces a VarHandle giving access to a reflected field {@code f}
3467 * of type {@code T} declared in a class of type {@code R}.
3468 * The VarHandle's variable type is {@code T}.
3469 * If the field is non-static the VarHandle has one coordinate type,
3470 * {@code R}. Otherwise, the field is static, and the VarHandle has no
3471 * coordinate types.
3472 * <p>
3473 * Access checking is performed immediately on behalf of the lookup
3474 * class, regardless of the value of the field's {@code accessible}
3475 * flag.
3476 * <p>
3477 * If the field is static, and if the returned VarHandle is operated
3478 * on, the field's declaring class will be initialized, if it has not
3479 * already been initialized.
3480 * <p>
3481 * Certain access modes of the returned VarHandle are unsupported under
3482 * the following conditions:
3483 * <ul>
3484 * <li>if the field is declared {@code final}, then the write, atomic
3485 * update, numeric atomic update, and bitwise atomic update access
3486 * modes are unsupported.
3487 * <li>if the field type is anything other than {@code byte},
3488 * {@code short}, {@code char}, {@code int}, {@code long},
3489 * {@code float}, or {@code double} then numeric atomic update
3490 * access modes are unsupported.
3491 * <li>if the field type is anything other than {@code boolean},
3492 * {@code byte}, {@code short}, {@code char}, {@code int} or
3493 * {@code long} then bitwise atomic update access modes are
3494 * unsupported.
3495 * </ul>
3496 * <p>
3497 * If the field is declared {@code volatile} then the returned VarHandle
3498 * will override access to the field (effectively ignore the
3499 * {@code volatile} declaration) in accordance to its specified
3500 * access modes.
3501 * <p>
3502 * If the field type is {@code float} or {@code double} then numeric
3503 * and atomic update access modes compare values using their bitwise
3504 * representation (see {@link Float#floatToRawIntBits} and
3505 * {@link Double#doubleToRawLongBits}, respectively).
3506 * @apiNote
3507 * Bitwise comparison of {@code float} values or {@code double} values,
3508 * as performed by the numeric and atomic update access modes, differ
3509 * from the primitive {@code ==} operator and the {@link Float#equals}
3510 * and {@link Double#equals} methods, specifically with respect to
3511 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3512 * Care should be taken when performing a compare and set or a compare
3513 * and exchange operation with such values since the operation may
3514 * unexpectedly fail.
3515 * There are many possible NaN values that are considered to be
3516 * {@code NaN} in Java, although no IEEE 754 floating-point operation
3517 * provided by Java can distinguish between them. Operation failure can
3518 * occur if the expected or witness value is a NaN value and it is
3519 * transformed (perhaps in a platform specific manner) into another NaN
3520 * value, and thus has a different bitwise representation (see
3521 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3522 * details).
3523 * The values {@code -0.0} and {@code +0.0} have different bitwise
3524 * representations but are considered equal when using the primitive
3525 * {@code ==} operator. Operation failure can occur if, for example, a
3526 * numeric algorithm computes an expected value to be say {@code -0.0}
3527 * and previously computed the witness value to be say {@code +0.0}.
3528 * @param f the reflected field, with a field of type {@code T}, and
3529 * a declaring class of type {@code R}
3530 * @return a VarHandle giving access to non-static fields or a static
3531 * field
3532 * @throws IllegalAccessException if access checking fails
3533 * @throws NullPointerException if the argument is null
3534 * @since 9
3535 */
3536 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3537 MemberName getField = new MemberName(f, false);
3538 MemberName putField = new MemberName(f, true);
3539 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(),
3540 f.getDeclaringClass(), getField, putField);
3541 }
3542
3543 /**
3544 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3545 * created by this lookup object or a similar one.
3546 * Security and access checks are performed to ensure that this lookup object
3547 * is capable of reproducing the target method handle.
3548 * This means that the cracking may fail if target is a direct method handle
3549 * but was created by an unrelated lookup object.
3550 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3551 * and was created by a lookup object for a different class.
3552 * @param target a direct method handle to crack into symbolic reference components
3553 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3554 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3555 * @throws NullPointerException if the target is {@code null}
3556 * @see MethodHandleInfo
3557 * @since 1.8
3558 */
3559 public MethodHandleInfo revealDirect(MethodHandle target) {
3560 if (!target.isCrackable()) {
3561 throw newIllegalArgumentException("not a direct method handle");
3562 }
3563 MemberName member = target.internalMemberName();
3564 Class<?> defc = member.getDeclaringClass();
3565 byte refKind = member.getReferenceKind();
3566 assert(MethodHandleNatives.refKindIsValid(refKind));
3567 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3568 // Devirtualized method invocation is usually formally virtual.
3569 // To avoid creating extra MemberName objects for this common case,
3570 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3571 refKind = REF_invokeVirtual;
3572 if (refKind == REF_invokeVirtual && defc.isInterface())
3573 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3574 refKind = REF_invokeInterface;
3575 // Check member access before cracking.
3576 try {
3577 checkAccess(refKind, defc, member);
3578 } catch (IllegalAccessException ex) {
3579 throw new IllegalArgumentException(ex);
3580 }
3581 if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3582 Class<?> callerClass = target.internalCallerClass();
3583 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3584 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3585 }
3586 // Produce the handle to the results.
3587 return new InfoFromMemberName(this, member, refKind);
3588 }
3589
3590 //--- Helper methods, all package-private.
3591
3592 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3593 checkSymbolicClass(refc); // do this before attempting to resolve
3594 Objects.requireNonNull(name);
3595 Objects.requireNonNull(type);
3596 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3597 NoSuchFieldException.class);
3598 }
3599
3600 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3601 checkSymbolicClass(refc); // do this before attempting to resolve
3602 Objects.requireNonNull(type);
3603 checkMethodName(refKind, name); // implicit null-check of name
3604 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3605 NoSuchMethodException.class);
3606 }
3607
3608 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3609 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve
3610 Objects.requireNonNull(member.getName());
3611 Objects.requireNonNull(member.getType());
3612 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3613 ReflectiveOperationException.class);
3614 }
3615
3616 MemberName resolveOrNull(byte refKind, MemberName member) {
3617 // do this before attempting to resolve
3618 if (!isClassAccessible(member.getDeclaringClass())) {
3619 return null;
3620 }
3621 Objects.requireNonNull(member.getName());
3622 Objects.requireNonNull(member.getType());
3623 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3624 }
3625
3626 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3627 // do this before attempting to resolve
3628 if (!isClassAccessible(refc)) {
3629 return null;
3630 }
3631 Objects.requireNonNull(type);
3632 // implicit null-check of name
3633 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3634 return null;
3635 }
3636 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3637 }
3638
3639 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3640 if (!isClassAccessible(refc)) {
3641 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3642 }
3643 }
3644
3645 boolean isClassAccessible(Class<?> refc) {
3646 Objects.requireNonNull(refc);
3647 Class<?> caller = lookupClassOrNull();
3648 Class<?> type = refc;
3649 while (type.isArray()) {
3650 type = type.getComponentType();
3651 }
3652 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3653 }
3654
3655 /** Check name for an illegal leading "<" character. */
3656 void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3657 if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3658 throw new NoSuchMethodException("illegal method name: "+name);
3659 }
3660
3661 /**
3662 * Find my trustable caller class if m is a caller sensitive method.
3663 * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3664 * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3665 */
3666 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3667 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3668 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3669 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3670 }
3671 return this;
3672 }
3673
3674 /**
3675 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3676 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3677 *
3678 * @deprecated This method was originally designed to test {@code PRIVATE} access
3679 * that implies full privilege access but {@code MODULE} access has since become
3680 * independent of {@code PRIVATE} access. It is recommended to call
3681 * {@link #hasFullPrivilegeAccess()} instead.
3682 * @since 9
3683 */
3684 @Deprecated(since="14")
3685 public boolean hasPrivateAccess() {
3686 return hasFullPrivilegeAccess();
3687 }
3688
3689 /**
3690 * Returns {@code true} if this lookup has <em>full privilege access</em>,
3691 * i.e. {@code PRIVATE} and {@code MODULE} access.
3692 * A {@code Lookup} object must have full privilege access in order to
3693 * access all members that are allowed to the
3694 * {@linkplain #lookupClass() lookup class}.
3695 *
3696 * @return {@code true} if this lookup has full privilege access.
3697 * @since 14
3698 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3699 */
3700 public boolean hasFullPrivilegeAccess() {
3701 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3702 }
3703
3704 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3705 boolean wantStatic = (refKind == REF_invokeStatic);
3706 String message;
3707 if (m.isConstructor())
3708 message = "expected a method, not a constructor";
3709 else if (!m.isMethod())
3710 message = "expected a method";
3711 else if (wantStatic != m.isStatic())
3712 message = wantStatic ? "expected a static method" : "expected a non-static method";
3713 else
3714 { checkAccess(refKind, refc, m); return; }
3715 throw m.makeAccessException(message, this);
3716 }
3717
3718 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3719 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3720 String message;
3721 if (wantStatic != m.isStatic())
3722 message = wantStatic ? "expected a static field" : "expected a non-static field";
3723 else
3724 { checkAccess(refKind, refc, m); return; }
3725 throw m.makeAccessException(message, this);
3726 }
3727
3728 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3729 return Modifier.isProtected(m.getModifiers()) &&
3730 refKind == REF_invokeVirtual &&
3731 m.getDeclaringClass() == Object.class &&
3732 m.getName().equals("clone") &&
3733 refc.isArray();
3734 }
3735
3736 /** Check public/protected/private bits on the symbolic reference class and its member. */
3737 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3738 assert(m.referenceKindIsConsistentWith(refKind) &&
3739 MethodHandleNatives.refKindIsValid(refKind) &&
3740 (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3741 int allowedModes = this.allowedModes;
3742 if (allowedModes == TRUSTED) return;
3743 int mods = m.getModifiers();
3744 if (isArrayClone(refKind, refc, m)) {
3745 // The JVM does this hack also.
3746 // (See ClassVerifier::verify_invoke_instructions
3747 // and LinkResolver::check_method_accessability.)
3748 // Because the JVM does not allow separate methods on array types,
3749 // there is no separate method for int[].clone.
3750 // All arrays simply inherit Object.clone.
3751 // But for access checking logic, we make Object.clone
3752 // (normally protected) appear to be public.
3753 // Later on, when the DirectMethodHandle is created,
3754 // its leading argument will be restricted to the
3755 // requested array type.
3756 // N.B. The return type is not adjusted, because
3757 // that is *not* the bytecode behavior.
3758 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3759 }
3760 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3761 // cannot "new" a protected ctor in a different package
3762 mods ^= Modifier.PROTECTED;
3763 }
3764 if (Modifier.isFinal(mods) &&
3765 MethodHandleNatives.refKindIsSetter(refKind))
3766 throw m.makeAccessException("unexpected set of a final field", this);
3767 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE
3768 if ((requestedModes & allowedModes) != 0) {
3769 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3770 mods, lookupClass(), previousLookupClass(), allowedModes))
3771 return;
3772 } else {
3773 // Protected members can also be checked as if they were package-private.
3774 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3775 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3776 return;
3777 }
3778 throw m.makeAccessException(accessFailedMessage(refc, m), this);
3779 }
3780
3781 String accessFailedMessage(Class<?> refc, MemberName m) {
3782 Class<?> defc = m.getDeclaringClass();
3783 int mods = m.getModifiers();
3784 // check the class first:
3785 boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3786 (defc == refc ||
3787 Modifier.isPublic(refc.getModifiers())));
3788 if (!classOK && (allowedModes & PACKAGE) != 0) {
3789 // ignore previous lookup class to check if default package access
3790 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3791 (defc == refc ||
3792 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3793 }
3794 if (!classOK)
3795 return "class is not public";
3796 if (Modifier.isPublic(mods))
3797 return "access to public member failed"; // (how?, module not readable?)
3798 if (Modifier.isPrivate(mods))
3799 return "member is private";
3800 if (Modifier.isProtected(mods))
3801 return "member is protected";
3802 return "member is private to package";
3803 }
3804
3805 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3806 int allowedModes = this.allowedModes;
3807 if (allowedModes == TRUSTED) return;
3808 if ((lookupModes() & PRIVATE) == 0
3809 || (specialCaller != lookupClass()
3810 // ensure non-abstract methods in superinterfaces can be special-invoked
3811 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3812 throw new MemberName(specialCaller).
3813 makeAccessException("no private access for invokespecial", this);
3814 }
3815
3816 private boolean restrictProtectedReceiver(MemberName method) {
3817 // The accessing class only has the right to use a protected member
3818 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc.
3819 if (!method.isProtected() || method.isStatic()
3820 || allowedModes == TRUSTED
3821 || method.getDeclaringClass() == lookupClass()
3822 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3823 return false;
3824 return true;
3825 }
3826 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3827 assert(!method.isStatic());
3828 // receiver type of mh is too wide; narrow to caller
3829 if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3830 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3831 }
3832 MethodType rawType = mh.type();
3833 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3834 MethodType narrowType = rawType.changeParameterType(0, caller);
3835 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness
3836 assert(mh.viewAsTypeChecks(narrowType, true));
3837 return mh.copyWith(narrowType, mh.form);
3838 }
3839
3840 /** Check access and get the requested method. */
3841 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3842 final boolean doRestrict = true;
3843 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup);
3844 }
3845 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3846 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3847 final boolean doRestrict = false;
3848 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup);
3849 }
3850 /** Common code for all methods; do not call directly except from immediately above. */
3851 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3852 boolean doRestrict,
3853 Lookup boundCaller) throws IllegalAccessException {
3854 checkMethod(refKind, refc, method);
3855 assert(!method.isMethodHandleInvoke());
3856 if (refKind == REF_invokeSpecial &&
3857 refc != lookupClass() &&
3858 !refc.isInterface() && !lookupClass().isInterface() &&
3859 refc != lookupClass().getSuperclass() &&
3860 refc.isAssignableFrom(lookupClass())) {
3861 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path
3862
3863 // Per JVMS 6.5, desc. of invokespecial instruction:
3864 // If the method is in a superclass of the LC,
3865 // and if our original search was above LC.super,
3866 // repeat the search (symbolic lookup) from LC.super
3867 // and continue with the direct superclass of that class,
3868 // and so forth, until a match is found or no further superclasses exist.
3869 // FIXME: MemberName.resolve should handle this instead.
3870 Class<?> refcAsSuper = lookupClass();
3871 MemberName m2;
3872 do {
3873 refcAsSuper = refcAsSuper.getSuperclass();
3874 m2 = new MemberName(refcAsSuper,
3875 method.getName(),
3876 method.getMethodType(),
3877 REF_invokeSpecial);
3878 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
3879 } while (m2 == null && // no method is found yet
3880 refc != refcAsSuper); // search up to refc
3881 if (m2 == null) throw new InternalError(method.toString());
3882 method = m2;
3883 refc = refcAsSuper;
3884 // redo basic checks
3885 checkMethod(refKind, refc, method);
3886 }
3887 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
3888 MethodHandle mh = dmh;
3889 // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
3890 if ((doRestrict && refKind == REF_invokeSpecial) ||
3891 (MethodHandleNatives.refKindHasReceiver(refKind) &&
3892 restrictProtectedReceiver(method) &&
3893 // All arrays simply inherit the protected Object.clone method.
3894 // The leading argument is already restricted to the requested
3895 // array type (not the lookup class).
3896 !isArrayClone(refKind, refc, method))) {
3897 mh = restrictReceiver(method, dmh, lookupClass());
3898 }
3899 mh = maybeBindCaller(method, mh, boundCaller);
3900 mh = mh.setVarargs(method);
3901 return mh;
3902 }
3903 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
3904 throws IllegalAccessException {
3905 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
3906 return mh;
3907
3908 // boundCaller must have full privilege access.
3909 // It should have been checked by findBoundCallerLookup. Safe to check this again.
3910 if ((boundCaller.lookupModes() & ORIGINAL) == 0)
3911 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3912
3913 assert boundCaller.hasFullPrivilegeAccess();
3914
3915 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
3916 // Note: caller will apply varargs after this step happens.
3917 return cbmh;
3918 }
3919
3920 /** Check access and get the requested field. */
3921 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3922 return getDirectFieldCommon(refKind, refc, field);
3923 }
3924 /** Common code for all fields; do not call directly except from immediately above. */
3925 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3926 checkField(refKind, refc, field);
3927 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
3928 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
3929 restrictProtectedReceiver(field));
3930 if (doRestrict)
3931 return restrictReceiver(field, dmh, lookupClass());
3932 return dmh;
3933 }
3934 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
3935 Class<?> refc, MemberName getField, MemberName putField)
3936 throws IllegalAccessException {
3937 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField);
3938 }
3939 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
3940 Class<?> refc, MemberName getField,
3941 MemberName putField) throws IllegalAccessException {
3942 assert getField.isStatic() == putField.isStatic();
3943 assert getField.isGetter() && putField.isSetter();
3944 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
3945 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
3946
3947 checkField(getRefKind, refc, getField);
3948
3949 if (!putField.isFinal()) {
3950 // A VarHandle does not support updates to final fields, any
3951 // such VarHandle to a final field will be read-only and
3952 // therefore the following write-based accessibility checks are
3953 // only required for non-final fields
3954 checkField(putRefKind, refc, putField);
3955 }
3956
3957 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3958 restrictProtectedReceiver(getField));
3959 if (doRestrict) {
3960 assert !getField.isStatic();
3961 // receiver type of VarHandle is too wide; narrow to caller
3962 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3963 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3964 }
3965 refc = lookupClass();
3966 }
3967 return VarHandles.makeFieldHandle(getField, refc,
3968 this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
3969 }
3970 /** Check access and get the requested constructor. */
3971 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3972 return getDirectConstructorCommon(refc, ctor);
3973 }
3974 /** Common code for all constructors; do not call directly except from immediately above. */
3975 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3976 assert(ctor.isConstructor());
3977 checkAccess(REF_newInvokeSpecial, refc, ctor);
3978 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
3979 return DirectMethodHandle.make(ctor).setVarargs(ctor);
3980 }
3981
3982 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
3983 */
3984 /*non-public*/
3985 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
3986 throws ReflectiveOperationException {
3987 if (!(type instanceof Class || type instanceof MethodType))
3988 throw new InternalError("unresolved MemberName");
3989 MemberName member = new MemberName(refKind, defc, name, type);
3990 MethodHandle mh = LOOKASIDE_TABLE.get(member);
3991 if (mh != null) {
3992 checkSymbolicClass(defc);
3993 return mh;
3994 }
3995 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
3996 // Treat MethodHandle.invoke and invokeExact specially.
3997 mh = findVirtualForMH(member.getName(), member.getMethodType());
3998 if (mh != null) {
3999 return mh;
4000 }
4001 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4002 // Treat signature-polymorphic methods on VarHandle specially.
4003 mh = findVirtualForVH(member.getName(), member.getMethodType());
4004 if (mh != null) {
4005 return mh;
4006 }
4007 }
4008 MemberName resolved = resolveOrFail(refKind, member);
4009 mh = getDirectMethodForConstant(refKind, defc, resolved);
4010 if (mh instanceof DirectMethodHandle dmh
4011 && canBeCached(refKind, defc, resolved)) {
4012 MemberName key = mh.internalMemberName();
4013 if (key != null) {
4014 key = key.asNormalOriginal();
4015 }
4016 if (member.equals(key)) { // better safe than sorry
4017 LOOKASIDE_TABLE.put(key, dmh);
4018 }
4019 }
4020 return mh;
4021 }
4022 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4023 if (refKind == REF_invokeSpecial) {
4024 return false;
4025 }
4026 if (!Modifier.isPublic(defc.getModifiers()) ||
4027 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4028 !member.isPublic() ||
4029 member.isCallerSensitive()) {
4030 return false;
4031 }
4032 ClassLoader loader = defc.getClassLoader();
4033 if (loader != null) {
4034 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4035 boolean found = false;
4036 while (sysl != null) {
4037 if (loader == sysl) { found = true; break; }
4038 sysl = sysl.getParent();
4039 }
4040 if (!found) {
4041 return false;
4042 }
4043 }
4044 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4045 new MemberName(refKind, defc, member.getName(), member.getType()));
4046 if (resolved2 == null) {
4047 return false;
4048 }
4049 return true;
4050 }
4051 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4052 throws ReflectiveOperationException {
4053 if (MethodHandleNatives.refKindIsField(refKind)) {
4054 return getDirectField(refKind, defc, member);
4055 } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4056 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member));
4057 } else if (refKind == REF_newInvokeSpecial) {
4058 return getDirectConstructor(defc, member);
4059 }
4060 // oops
4061 throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4062 }
4063
4064 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4065 }
4066
4067 /**
4068 * Produces a method handle constructing arrays of a desired type,
4069 * as if by the {@code anewarray} bytecode.
4070 * The return type of the method handle will be the array type.
4071 * The type of its sole argument will be {@code int}, which specifies the size of the array.
4072 *
4073 * <p> If the returned method handle is invoked with a negative
4074 * array size, a {@code NegativeArraySizeException} will be thrown.
4075 *
4076 * @param arrayClass an array type
4077 * @return a method handle which can create arrays of the given type
4078 * @throws NullPointerException if the argument is {@code null}
4079 * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4080 * @see java.lang.reflect.Array#newInstance(Class, int)
4081 * @jvms 6.5 {@code anewarray} Instruction
4082 * @since 9
4083 */
4084 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4085 if (!arrayClass.isArray()) {
4086 throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4087 }
4088 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4089 bindTo(arrayClass.getComponentType());
4090 return ani.asType(ani.type().changeReturnType(arrayClass));
4091 }
4092
4093 /**
4094 * Produces a method handle returning the length of an array,
4095 * as if by the {@code arraylength} bytecode.
4096 * The type of the method handle will have {@code int} as return type,
4097 * and its sole argument will be the array type.
4098 *
4099 * <p> If the returned method handle is invoked with a {@code null}
4100 * array reference, a {@code NullPointerException} will be thrown.
4101 *
4102 * @param arrayClass an array type
4103 * @return a method handle which can retrieve the length of an array of the given array type
4104 * @throws NullPointerException if the argument is {@code null}
4105 * @throws IllegalArgumentException if arrayClass is not an array type
4106 * @jvms 6.5 {@code arraylength} Instruction
4107 * @since 9
4108 */
4109 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4110 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4111 }
4112
4113 /**
4114 * Produces a method handle giving read access to elements of an array,
4115 * as if by the {@code aaload} bytecode.
4116 * The type of the method handle will have a return type of the array's
4117 * element type. Its first argument will be the array type,
4118 * and the second will be {@code int}.
4119 *
4120 * <p> When the returned method handle is invoked,
4121 * the array reference and array index are checked.
4122 * A {@code NullPointerException} will be thrown if the array reference
4123 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4124 * thrown if the index is negative or if it is greater than or equal to
4125 * the length of the array.
4126 *
4127 * @param arrayClass an array type
4128 * @return a method handle which can load values from the given array type
4129 * @throws NullPointerException if the argument is null
4130 * @throws IllegalArgumentException if arrayClass is not an array type
4131 * @jvms 6.5 {@code aaload} Instruction
4132 */
4133 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4134 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4135 }
4136
4137 /**
4138 * Produces a method handle giving write access to elements of an array,
4139 * as if by the {@code astore} bytecode.
4140 * The type of the method handle will have a void return type.
4141 * Its last argument will be the array's element type.
4142 * The first and second arguments will be the array type and int.
4143 *
4144 * <p> When the returned method handle is invoked,
4145 * the array reference and array index are checked.
4146 * A {@code NullPointerException} will be thrown if the array reference
4147 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4148 * thrown if the index is negative or if it is greater than or equal to
4149 * the length of the array.
4150 *
4151 * @param arrayClass the class of an array
4152 * @return a method handle which can store values into the array type
4153 * @throws NullPointerException if the argument is null
4154 * @throws IllegalArgumentException if arrayClass is not an array type
4155 * @jvms 6.5 {@code aastore} Instruction
4156 */
4157 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4158 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4159 }
4160
4161 /**
4162 * Produces a VarHandle giving access to elements of an array of type
4163 * {@code arrayClass}. The VarHandle's variable type is the component type
4164 * of {@code arrayClass} and the list of coordinate types is
4165 * {@code (arrayClass, int)}, where the {@code int} coordinate type
4166 * corresponds to an argument that is an index into an array.
4167 * <p>
4168 * Certain access modes of the returned VarHandle are unsupported under
4169 * the following conditions:
4170 * <ul>
4171 * <li>if the component type is anything other than {@code byte},
4172 * {@code short}, {@code char}, {@code int}, {@code long},
4173 * {@code float}, or {@code double} then numeric atomic update access
4174 * modes are unsupported.
4175 * <li>if the component type is anything other than {@code boolean},
4176 * {@code byte}, {@code short}, {@code char}, {@code int} or
4177 * {@code long} then bitwise atomic update access modes are
4178 * unsupported.
4179 * </ul>
4180 * <p>
4181 * If the component type is {@code float} or {@code double} then numeric
4182 * and atomic update access modes compare values using their bitwise
4183 * representation (see {@link Float#floatToRawIntBits} and
4184 * {@link Double#doubleToRawLongBits}, respectively).
4185 *
4186 * <p> When the returned {@code VarHandle} is invoked,
4187 * the array reference and array index are checked.
4188 * A {@code NullPointerException} will be thrown if the array reference
4189 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4190 * thrown if the index is negative or if it is greater than or equal to
4191 * the length of the array.
4192 *
4193 * @apiNote
4194 * Bitwise comparison of {@code float} values or {@code double} values,
4195 * as performed by the numeric and atomic update access modes, differ
4196 * from the primitive {@code ==} operator and the {@link Float#equals}
4197 * and {@link Double#equals} methods, specifically with respect to
4198 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4199 * Care should be taken when performing a compare and set or a compare
4200 * and exchange operation with such values since the operation may
4201 * unexpectedly fail.
4202 * There are many possible NaN values that are considered to be
4203 * {@code NaN} in Java, although no IEEE 754 floating-point operation
4204 * provided by Java can distinguish between them. Operation failure can
4205 * occur if the expected or witness value is a NaN value and it is
4206 * transformed (perhaps in a platform specific manner) into another NaN
4207 * value, and thus has a different bitwise representation (see
4208 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4209 * details).
4210 * The values {@code -0.0} and {@code +0.0} have different bitwise
4211 * representations but are considered equal when using the primitive
4212 * {@code ==} operator. Operation failure can occur if, for example, a
4213 * numeric algorithm computes an expected value to be say {@code -0.0}
4214 * and previously computed the witness value to be say {@code +0.0}.
4215 * @param arrayClass the class of an array, of type {@code T[]}
4216 * @return a VarHandle giving access to elements of an array
4217 * @throws NullPointerException if the arrayClass is null
4218 * @throws IllegalArgumentException if arrayClass is not an array type
4219 * @since 9
4220 */
4221 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4222 return VarHandles.makeArrayElementHandle(arrayClass);
4223 }
4224
4225 /**
4226 * Produces a VarHandle giving access to elements of a {@code byte[]} array
4227 * viewed as if it were a different primitive array type, such as
4228 * {@code int[]} or {@code long[]}.
4229 * The VarHandle's variable type is the component type of
4230 * {@code viewArrayClass} and the list of coordinate types is
4231 * {@code (byte[], int)}, where the {@code int} coordinate type
4232 * corresponds to an argument that is an index into a {@code byte[]} array.
4233 * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4234 * array, composing bytes to or from a value of the component type of
4235 * {@code viewArrayClass} according to the given endianness.
4236 * <p>
4237 * The supported component types (variables types) are {@code short},
4238 * {@code char}, {@code int}, {@code long}, {@code float} and
4239 * {@code double}.
4240 * <p>
4241 * Access of bytes at a given index will result in an
4242 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4243 * or greater than the {@code byte[]} array length minus the size (in bytes)
4244 * of {@code T}.
4245 * <p>
4246 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set}
4247 * access modes are supported by the returned var handle. For all other access modes, an
4248 * {@link UnsupportedOperationException} will be thrown.
4249 *
4250 * @apiNote if access modes other than plain access are required, clients should
4251 * consider using off-heap memory through
4252 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or
4253 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments},
4254 * or memory segments backed by a
4255 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}},
4256 * for which stronger alignment guarantees can be made.
4257 *
4258 * @param viewArrayClass the view array class, with a component type of
4259 * type {@code T}
4260 * @param byteOrder the endianness of the view array elements, as
4261 * stored in the underlying {@code byte} array
4262 * @return a VarHandle giving access to elements of a {@code byte[]} array
4263 * viewed as if elements corresponding to the components type of the view
4264 * array class
4265 * @throws NullPointerException if viewArrayClass or byteOrder is null
4266 * @throws IllegalArgumentException if viewArrayClass is not an array type
4267 * @throws UnsupportedOperationException if the component type of
4268 * viewArrayClass is not supported as a variable type
4269 * @since 9
4270 */
4271 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4272 ByteOrder byteOrder) throws IllegalArgumentException {
4273 Objects.requireNonNull(byteOrder);
4274 return VarHandles.byteArrayViewHandle(viewArrayClass,
4275 byteOrder == ByteOrder.BIG_ENDIAN);
4276 }
4277
4278 /**
4279 * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4280 * viewed as if it were an array of elements of a different primitive
4281 * component type to that of {@code byte}, such as {@code int[]} or
4282 * {@code long[]}.
4283 * The VarHandle's variable type is the component type of
4284 * {@code viewArrayClass} and the list of coordinate types is
4285 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4286 * corresponds to an argument that is an index into a {@code byte[]} array.
4287 * The returned VarHandle accesses bytes at an index in a
4288 * {@code ByteBuffer}, composing bytes to or from a value of the component
4289 * type of {@code viewArrayClass} according to the given endianness.
4290 * <p>
4291 * The supported component types (variables types) are {@code short},
4292 * {@code char}, {@code int}, {@code long}, {@code float} and
4293 * {@code double}.
4294 * <p>
4295 * Access will result in a {@code ReadOnlyBufferException} for anything
4296 * other than the read access modes if the {@code ByteBuffer} is read-only.
4297 * <p>
4298 * Access of bytes at a given index will result in an
4299 * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4300 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4301 * {@code T}.
4302 * <p>
4303 * For heap byte buffers, access is always unaligned. As a result, only the plain
4304 * {@linkplain VarHandle.AccessMode#GET get}
4305 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the
4306 * returned var handle. For all other access modes, an {@link IllegalStateException}
4307 * will be thrown.
4308 * <p>
4309 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T},
4310 * with respect to the underlying memory address, {@code A} say, associated
4311 * with the {@code ByteBuffer} and index.
4312 * If access is misaligned then access for anything other than the
4313 * {@code get} and {@code set} access modes will result in an
4314 * {@code IllegalStateException}. In such cases atomic access is only
4315 * guaranteed with respect to the largest power of two that divides the GCD
4316 * of {@code A} and the size (in bytes) of {@code T}.
4317 * If access is aligned then following access modes are supported and are
4318 * guaranteed to support atomic access:
4319 * <ul>
4320 * <li>read write access modes for all {@code T}. Access modes {@code get}
4321 * and {@code set} for {@code long} and {@code double} are supported but
4322 * have no atomicity guarantee, as described in Section {@jls 17.7} of
4323 * <cite>The Java Language Specification</cite>.
4324 * <li>atomic update access modes for {@code int}, {@code long},
4325 * {@code float} or {@code double}.
4326 * (Future major platform releases of the JDK may support additional
4327 * types for certain currently unsupported access modes.)
4328 * <li>numeric atomic update access modes for {@code int} and {@code long}.
4329 * (Future major platform releases of the JDK may support additional
4330 * numeric types for certain currently unsupported access modes.)
4331 * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4332 * (Future major platform releases of the JDK may support additional
4333 * numeric types for certain currently unsupported access modes.)
4334 * </ul>
4335 * <p>
4336 * Misaligned access, and therefore atomicity guarantees, may be determined
4337 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4338 * {@code index}, {@code T} and its corresponding boxed type,
4339 * {@code T_BOX}, as follows:
4340 * <pre>{@code
4341 * int sizeOfT = T_BOX.BYTES; // size in bytes of T
4342 * ByteBuffer bb = ...
4343 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4344 * boolean isMisaligned = misalignedAtIndex != 0;
4345 * }</pre>
4346 * <p>
4347 * If the variable type is {@code float} or {@code double} then atomic
4348 * update access modes compare values using their bitwise representation
4349 * (see {@link Float#floatToRawIntBits} and
4350 * {@link Double#doubleToRawLongBits}, respectively).
4351 * @param viewArrayClass the view array class, with a component type of
4352 * type {@code T}
4353 * @param byteOrder the endianness of the view array elements, as
4354 * stored in the underlying {@code ByteBuffer} (Note this overrides the
4355 * endianness of a {@code ByteBuffer})
4356 * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4357 * viewed as if elements corresponding to the components type of the view
4358 * array class
4359 * @throws NullPointerException if viewArrayClass or byteOrder is null
4360 * @throws IllegalArgumentException if viewArrayClass is not an array type
4361 * @throws UnsupportedOperationException if the component type of
4362 * viewArrayClass is not supported as a variable type
4363 * @since 9
4364 */
4365 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4366 ByteOrder byteOrder) throws IllegalArgumentException {
4367 Objects.requireNonNull(byteOrder);
4368 return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4369 byteOrder == ByteOrder.BIG_ENDIAN);
4370 }
4371
4372
4373 //--- method handle invocation (reflective style)
4374
4375 /**
4376 * Produces a method handle which will invoke any method handle of the
4377 * given {@code type}, with a given number of trailing arguments replaced by
4378 * a single trailing {@code Object[]} array.
4379 * The resulting invoker will be a method handle with the following
4380 * arguments:
4381 * <ul>
4382 * <li>a single {@code MethodHandle} target
4383 * <li>zero or more leading values (counted by {@code leadingArgCount})
4384 * <li>an {@code Object[]} array containing trailing arguments
4385 * </ul>
4386 * <p>
4387 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4388 * the indicated {@code type}.
4389 * That is, if the target is exactly of the given {@code type}, it will behave
4390 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4391 * is used to convert the target to the required {@code type}.
4392 * <p>
4393 * The type of the returned invoker will not be the given {@code type}, but rather
4394 * will have all parameters except the first {@code leadingArgCount}
4395 * replaced by a single array of type {@code Object[]}, which will be
4396 * the final parameter.
4397 * <p>
4398 * Before invoking its target, the invoker will spread the final array, apply
4399 * reference casts as necessary, and unbox and widen primitive arguments.
4400 * If, when the invoker is called, the supplied array argument does
4401 * not have the correct number of elements, the invoker will throw
4402 * an {@link IllegalArgumentException} instead of invoking the target.
4403 * <p>
4404 * This method is equivalent to the following code (though it may be more efficient):
4405 * {@snippet lang="java" :
4406 MethodHandle invoker = MethodHandles.invoker(type);
4407 int spreadArgCount = type.parameterCount() - leadingArgCount;
4408 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4409 return invoker;
4410 * }
4411 * This method throws no reflective exceptions.
4412 * @param type the desired target type
4413 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4414 * @return a method handle suitable for invoking any method handle of the given type
4415 * @throws NullPointerException if {@code type} is null
4416 * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4417 * the range from 0 to {@code type.parameterCount()} inclusive,
4418 * or if the resulting method handle's type would have
4419 * <a href="MethodHandle.html#maxarity">too many parameters</a>
4420 */
4421 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4422 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4423 throw newIllegalArgumentException("bad argument count", leadingArgCount);
4424 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4425 return type.invokers().spreadInvoker(leadingArgCount);
4426 }
4427
4428 /**
4429 * Produces a special <em>invoker method handle</em> which can be used to
4430 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4431 * The resulting invoker will have a type which is
4432 * exactly equal to the desired type, except that it will accept
4433 * an additional leading argument of type {@code MethodHandle}.
4434 * <p>
4435 * This method is equivalent to the following code (though it may be more efficient):
4436 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4437 *
4438 * <p style="font-size:smaller;">
4439 * <em>Discussion:</em>
4440 * Invoker method handles can be useful when working with variable method handles
4441 * of unknown types.
4442 * For example, to emulate an {@code invokeExact} call to a variable method
4443 * handle {@code M}, extract its type {@code T},
4444 * look up the invoker method {@code X} for {@code T},
4445 * and call the invoker method, as {@code X.invoke(T, A...)}.
4446 * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4447 * is unknown.)
4448 * If spreading, collecting, or other argument transformations are required,
4449 * they can be applied once to the invoker {@code X} and reused on many {@code M}
4450 * method handle values, as long as they are compatible with the type of {@code X}.
4451 * <p style="font-size:smaller;">
4452 * <em>(Note: The invoker method is not available via the Core Reflection API.
4453 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4454 * on the declared {@code invokeExact} or {@code invoke} method will raise an
4455 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4456 * <p>
4457 * This method throws no reflective exceptions.
4458 * @param type the desired target type
4459 * @return a method handle suitable for invoking any method handle of the given type
4460 * @throws IllegalArgumentException if the resulting method handle's type would have
4461 * <a href="MethodHandle.html#maxarity">too many parameters</a>
4462 */
4463 public static MethodHandle exactInvoker(MethodType type) {
4464 return type.invokers().exactInvoker();
4465 }
4466
4467 /**
4468 * Produces a special <em>invoker method handle</em> which can be used to
4469 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4470 * The resulting invoker will have a type which is
4471 * exactly equal to the desired type, except that it will accept
4472 * an additional leading argument of type {@code MethodHandle}.
4473 * <p>
4474 * Before invoking its target, if the target differs from the expected type,
4475 * the invoker will apply reference casts as
4476 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4477 * Similarly, the return value will be converted as necessary.
4478 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4479 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4480 * <p>
4481 * This method is equivalent to the following code (though it may be more efficient):
4482 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4483 * <p style="font-size:smaller;">
4484 * <em>Discussion:</em>
4485 * A {@linkplain MethodType#genericMethodType general method type} is one which
4486 * mentions only {@code Object} arguments and return values.
4487 * An invoker for such a type is capable of calling any method handle
4488 * of the same arity as the general type.
4489 * <p style="font-size:smaller;">
4490 * <em>(Note: The invoker method is not available via the Core Reflection API.
4491 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4492 * on the declared {@code invokeExact} or {@code invoke} method will raise an
4493 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4494 * <p>
4495 * This method throws no reflective exceptions.
4496 * @param type the desired target type
4497 * @return a method handle suitable for invoking any method handle convertible to the given type
4498 * @throws IllegalArgumentException if the resulting method handle's type would have
4499 * <a href="MethodHandle.html#maxarity">too many parameters</a>
4500 */
4501 public static MethodHandle invoker(MethodType type) {
4502 return type.invokers().genericInvoker();
4503 }
4504
4505 /**
4506 * Produces a special <em>invoker method handle</em> which can be used to
4507 * invoke a signature-polymorphic access mode method on any VarHandle whose
4508 * associated access mode type is compatible with the given type.
4509 * The resulting invoker will have a type which is exactly equal to the
4510 * desired given type, except that it will accept an additional leading
4511 * argument of type {@code VarHandle}.
4512 *
4513 * @param accessMode the VarHandle access mode
4514 * @param type the desired target type
4515 * @return a method handle suitable for invoking an access mode method of
4516 * any VarHandle whose access mode type is of the given type.
4517 * @since 9
4518 */
4519 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4520 return type.invokers().varHandleMethodExactInvoker(accessMode);
4521 }
4522
4523 /**
4524 * Produces a special <em>invoker method handle</em> which can be used to
4525 * invoke a signature-polymorphic access mode method on any VarHandle whose
4526 * associated access mode type is compatible with the given type.
4527 * The resulting invoker will have a type which is exactly equal to the
4528 * desired given type, except that it will accept an additional leading
4529 * argument of type {@code VarHandle}.
4530 * <p>
4531 * Before invoking its target, if the access mode type differs from the
4532 * desired given type, the invoker will apply reference casts as necessary
4533 * and box, unbox, or widen primitive values, as if by
4534 * {@link MethodHandle#asType asType}. Similarly, the return value will be
4535 * converted as necessary.
4536 * <p>
4537 * This method is equivalent to the following code (though it may be more
4538 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4539 *
4540 * @param accessMode the VarHandle access mode
4541 * @param type the desired target type
4542 * @return a method handle suitable for invoking an access mode method of
4543 * any VarHandle whose access mode type is convertible to the given
4544 * type.
4545 * @since 9
4546 */
4547 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4548 return type.invokers().varHandleMethodInvoker(accessMode);
4549 }
4550
4551 /*non-public*/
4552 static MethodHandle basicInvoker(MethodType type) {
4553 return type.invokers().basicInvoker();
4554 }
4555
4556 //--- method handle modification (creation from other method handles)
4557
4558 /**
4559 * Produces a method handle which adapts the type of the
4560 * given method handle to a new type by pairwise argument and return type conversion.
4561 * The original type and new type must have the same number of arguments.
4562 * The resulting method handle is guaranteed to report a type
4563 * which is equal to the desired new type.
4564 * <p>
4565 * If the original type and new type are equal, returns target.
4566 * <p>
4567 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4568 * and some additional conversions are also applied if those conversions fail.
4569 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4570 * if possible, before or instead of any conversions done by {@code asType}:
4571 * <ul>
4572 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4573 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4574 * (This treatment of interfaces follows the usage of the bytecode verifier.)
4575 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4576 * the boolean is converted to a byte value, 1 for true, 0 for false.
4577 * (This treatment follows the usage of the bytecode verifier.)
4578 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4579 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4580 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4581 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4582 * then a Java casting conversion (JLS {@jls 5.5}) is applied.
4583 * (Specifically, <em>T0</em> will convert to <em>T1</em> by
4584 * widening and/or narrowing.)
4585 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4586 * conversion will be applied at runtime, possibly followed
4587 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4588 * possibly followed by a conversion from byte to boolean by testing
4589 * the low-order bit.
4590 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4591 * and if the reference is null at runtime, a zero value is introduced.
4592 * </ul>
4593 * @param target the method handle to invoke after arguments are retyped
4594 * @param newType the expected type of the new method handle
4595 * @return a method handle which delegates to the target after performing
4596 * any necessary argument conversions, and arranges for any
4597 * necessary return value conversions
4598 * @throws NullPointerException if either argument is null
4599 * @throws WrongMethodTypeException if the conversion cannot be made
4600 * @see MethodHandle#asType
4601 */
4602 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4603 explicitCastArgumentsChecks(target, newType);
4604 // use the asTypeCache when possible:
4605 MethodType oldType = target.type();
4606 if (oldType == newType) return target;
4607 if (oldType.explicitCastEquivalentToAsType(newType)) {
4608 return target.asFixedArity().asType(newType);
4609 }
4610 return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4611 }
4612
4613 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4614 if (target.type().parameterCount() != newType.parameterCount()) {
4615 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4616 }
4617 }
4618
4619 /**
4620 * Produces a method handle which adapts the calling sequence of the
4621 * given method handle to a new type, by reordering the arguments.
4622 * The resulting method handle is guaranteed to report a type
4623 * which is equal to the desired new type.
4624 * <p>
4625 * The given array controls the reordering.
4626 * Call {@code #I} the number of incoming parameters (the value
4627 * {@code newType.parameterCount()}, and call {@code #O} the number
4628 * of outgoing parameters (the value {@code target.type().parameterCount()}).
4629 * Then the length of the reordering array must be {@code #O},
4630 * and each element must be a non-negative number less than {@code #I}.
4631 * For every {@code N} less than {@code #O}, the {@code N}-th
4632 * outgoing argument will be taken from the {@code I}-th incoming
4633 * argument, where {@code I} is {@code reorder[N]}.
4634 * <p>
4635 * No argument or return value conversions are applied.
4636 * The type of each incoming argument, as determined by {@code newType},
4637 * must be identical to the type of the corresponding outgoing parameter
4638 * or parameters in the target method handle.
4639 * The return type of {@code newType} must be identical to the return
4640 * type of the original target.
4641 * <p>
4642 * The reordering array need not specify an actual permutation.
4643 * An incoming argument will be duplicated if its index appears
4644 * more than once in the array, and an incoming argument will be dropped
4645 * if its index does not appear in the array.
4646 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4647 * incoming arguments which are not mentioned in the reordering array
4648 * may be of any type, as determined only by {@code newType}.
4649 * {@snippet lang="java" :
4650 import static java.lang.invoke.MethodHandles.*;
4651 import static java.lang.invoke.MethodType.*;
4652 ...
4653 MethodType intfn1 = methodType(int.class, int.class);
4654 MethodType intfn2 = methodType(int.class, int.class, int.class);
4655 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4656 assert(sub.type().equals(intfn2));
4657 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4658 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4659 assert((int)rsub.invokeExact(1, 100) == 99);
4660 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4661 assert(add.type().equals(intfn2));
4662 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4663 assert(twice.type().equals(intfn1));
4664 assert((int)twice.invokeExact(21) == 42);
4665 * }
4666 * <p>
4667 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4668 * variable-arity method handle}, even if the original target method handle was.
4669 * @param target the method handle to invoke after arguments are reordered
4670 * @param newType the expected type of the new method handle
4671 * @param reorder an index array which controls the reordering
4672 * @return a method handle which delegates to the target after it
4673 * drops unused arguments and moves and/or duplicates the other arguments
4674 * @throws NullPointerException if any argument is null
4675 * @throws IllegalArgumentException if the index array length is not equal to
4676 * the arity of the target, or if any index array element
4677 * not a valid index for a parameter of {@code newType},
4678 * or if two corresponding parameter types in
4679 * {@code target.type()} and {@code newType} are not identical,
4680 */
4681 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4682 reorder = reorder.clone(); // get a private copy
4683 MethodType oldType = target.type();
4684 permuteArgumentChecks(reorder, newType, oldType);
4685 // first detect dropped arguments and handle them separately
4686 int[] originalReorder = reorder;
4687 BoundMethodHandle result = target.rebind();
4688 LambdaForm form = result.form;
4689 int newArity = newType.parameterCount();
4690 // Normalize the reordering into a real permutation,
4691 // by removing duplicates and adding dropped elements.
4692 // This somewhat improves lambda form caching, as well
4693 // as simplifying the transform by breaking it up into steps.
4694 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4695 if (ddIdx > 0) {
4696 // We found a duplicated entry at reorder[ddIdx].
4697 // Example: (x,y,z)->asList(x,y,z)
4698 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4699 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4700 // The starred element corresponds to the argument
4701 // deleted by the dupArgumentForm transform.
4702 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4703 boolean killFirst = false;
4704 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4705 // Set killFirst if the dup is larger than an intervening position.
4706 // This will remove at least one inversion from the permutation.
4707 if (dupVal > val) killFirst = true;
4708 }
4709 if (!killFirst) {
4710 srcPos = dstPos;
4711 dstPos = ddIdx;
4712 }
4713 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4714 assert (reorder[srcPos] == reorder[dstPos]);
4715 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4716 // contract the reordering by removing the element at dstPos
4717 int tailPos = dstPos + 1;
4718 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4719 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4720 } else {
4721 int dropVal = ~ddIdx, insPos = 0;
4722 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4723 // Find first element of reorder larger than dropVal.
4724 // This is where we will insert the dropVal.
4725 insPos += 1;
4726 }
4727 Class<?> ptype = newType.parameterType(dropVal);
4728 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4729 oldType = oldType.insertParameterTypes(insPos, ptype);
4730 // expand the reordering by inserting an element at insPos
4731 int tailPos = insPos + 1;
4732 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4733 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4734 reorder[insPos] = dropVal;
4735 }
4736 assert (permuteArgumentChecks(reorder, newType, oldType));
4737 }
4738 assert (reorder.length == newArity); // a perfect permutation
4739 // Note: This may cache too many distinct LFs. Consider backing off to varargs code.
4740 form = form.editor().permuteArgumentsForm(1, reorder);
4741 if (newType == result.type() && form == result.internalForm())
4742 return result;
4743 return result.copyWith(newType, form);
4744 }
4745
4746 /**
4747 * Return an indication of any duplicate or omission in reorder.
4748 * If the reorder contains a duplicate entry, return the index of the second occurrence.
4749 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4750 * Otherwise, return zero.
4751 * If an element not in [0..newArity-1] is encountered, return reorder.length.
4752 */
4753 private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4754 final int BIT_LIMIT = 63; // max number of bits in bit mask
4755 if (newArity < BIT_LIMIT) {
4756 long mask = 0;
4757 for (int i = 0; i < reorder.length; i++) {
4758 int arg = reorder[i];
4759 if (arg >= newArity) {
4760 return reorder.length;
4761 }
4762 long bit = 1L << arg;
4763 if ((mask & bit) != 0) {
4764 return i; // >0 indicates a dup
4765 }
4766 mask |= bit;
4767 }
4768 if (mask == (1L << newArity) - 1) {
4769 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4770 return 0;
4771 }
4772 // find first zero
4773 long zeroBit = Long.lowestOneBit(~mask);
4774 int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4775 assert(zeroPos <= newArity);
4776 if (zeroPos == newArity) {
4777 return 0;
4778 }
4779 return ~zeroPos;
4780 } else {
4781 // same algorithm, different bit set
4782 BitSet mask = new BitSet(newArity);
4783 for (int i = 0; i < reorder.length; i++) {
4784 int arg = reorder[i];
4785 if (arg >= newArity) {
4786 return reorder.length;
4787 }
4788 if (mask.get(arg)) {
4789 return i; // >0 indicates a dup
4790 }
4791 mask.set(arg);
4792 }
4793 int zeroPos = mask.nextClearBit(0);
4794 assert(zeroPos <= newArity);
4795 if (zeroPos == newArity) {
4796 return 0;
4797 }
4798 return ~zeroPos;
4799 }
4800 }
4801
4802 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4803 if (newType.returnType() != oldType.returnType())
4804 throw newIllegalArgumentException("return types do not match",
4805 oldType, newType);
4806 if (reorder.length != oldType.parameterCount())
4807 throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
4808 oldType, Arrays.toString(reorder));
4809
4810 int limit = newType.parameterCount();
4811 for (int j = 0; j < reorder.length; j++) {
4812 int i = reorder[j];
4813 if (i < 0 || i >= limit) {
4814 throw newIllegalArgumentException("index is out of bounds for new type",
4815 i, newType);
4816 }
4817 Class<?> src = newType.parameterType(i);
4818 Class<?> dst = oldType.parameterType(j);
4819 if (src != dst)
4820 throw newIllegalArgumentException("parameter types do not match after reorder",
4821 oldType, newType);
4822 }
4823 return true;
4824 }
4825
4826 /**
4827 * Produces a method handle of the requested return type which returns the given
4828 * constant value every time it is invoked.
4829 * <p>
4830 * Before the method handle is returned, the passed-in value is converted to the requested type.
4831 * If the requested type is primitive, widening primitive conversions are attempted,
4832 * else reference conversions are attempted.
4833 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
4834 * @param type the return type of the desired method handle
4835 * @param value the value to return
4836 * @return a method handle of the given return type and no arguments, which always returns the given value
4837 * @throws NullPointerException if the {@code type} argument is null
4838 * @throws ClassCastException if the value cannot be converted to the required return type
4839 * @throws IllegalArgumentException if the given type is {@code void.class}
4840 */
4841 public static MethodHandle constant(Class<?> type, Object value) {
4842 if (Objects.requireNonNull(type) == void.class)
4843 throw newIllegalArgumentException("void type");
4844 return MethodHandleImpl.makeConstantReturning(type, value);
4845 }
4846
4847 /**
4848 * Produces a method handle which returns its sole argument when invoked.
4849 * @param type the type of the sole parameter and return value of the desired method handle
4850 * @return a unary method handle which accepts and returns the given type
4851 * @throws NullPointerException if the argument is null
4852 * @throws IllegalArgumentException if the given type is {@code void.class}
4853 */
4854 public static MethodHandle identity(Class<?> type) {
4855 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
4856 int pos = btw.ordinal();
4857 MethodHandle ident = IDENTITY_MHS[pos];
4858 if (ident == null) {
4859 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
4860 }
4861 if (ident.type().returnType() == type)
4862 return ident;
4863 // something like identity(Foo.class); do not bother to intern these
4864 assert (btw == Wrapper.OBJECT);
4865 return makeIdentity(type);
4866 }
4867
4868 /**
4869 * Produces a constant method handle of the requested return type which
4870 * returns the default value for that type every time it is invoked.
4871 * The resulting constant method handle will have no side effects.
4872 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
4873 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
4874 * since {@code explicitCastArguments} converts {@code null} to default values.
4875 * @param type the expected return type of the desired method handle
4876 * @return a constant method handle that takes no arguments
4877 * and returns the default value of the given type (or void, if the type is void)
4878 * @throws NullPointerException if the argument is null
4879 * @see MethodHandles#constant
4880 * @see MethodHandles#empty
4881 * @see MethodHandles#explicitCastArguments
4882 * @since 9
4883 */
4884 public static MethodHandle zero(Class<?> type) {
4885 Objects.requireNonNull(type);
4886 return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type))
4887 : MethodHandleImpl.makeConstantReturning(type, null);
4888 }
4889
4890 private static MethodHandle identityOrVoid(Class<?> type) {
4891 return type == void.class ? zero(type) : identity(type);
4892 }
4893
4894 /**
4895 * Produces a method handle of the requested type which ignores any arguments, does nothing,
4896 * and returns a suitable default depending on the return type.
4897 * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
4898 * <p>The returned method handle is equivalent to
4899 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
4900 *
4901 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
4902 * {@code guardWithTest(pred, target, empty(target.type())}.
4903 * @param type the type of the desired method handle
4904 * @return a constant method handle of the given type, which returns a default value of the given return type
4905 * @throws NullPointerException if the argument is null
4906 * @see MethodHandles#zero(Class)
4907 * @see MethodHandles#constant
4908 * @since 9
4909 */
4910 public static MethodHandle empty(MethodType type) {
4911 Objects.requireNonNull(type);
4912 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
4913 }
4914
4915 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
4916 private static MethodHandle makeIdentity(Class<?> ptype) {
4917 MethodType mtype = methodType(ptype, ptype); // throws IAE for void
4918 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
4919 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
4920 }
4921
4922 private static MethodHandle primitiveZero(Wrapper w) {
4923 assert w != Wrapper.OBJECT : w;
4924 int pos = w.ordinal();
4925 MethodHandle mh = PRIMITIVE_ZERO_MHS[pos];
4926 if (mh == null) {
4927 mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w));
4928 }
4929 assert (mh.type().returnType() == w.primitiveType()) : mh;
4930 return mh;
4931 }
4932
4933 private static MethodHandle makePrimitiveZero(Wrapper w) {
4934 if (w == Wrapper.VOID) {
4935 var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized
4936 return SimpleMethodHandle.make(MethodType.methodType(void.class), lf);
4937 } else {
4938 return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero());
4939 }
4940 }
4941
4942 private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT];
4943
4944 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
4945 // Simulate a CAS, to avoid racy duplication of results.
4946 MethodHandle prev = cache[pos];
4947 if (prev != null) return prev;
4948 return cache[pos] = value;
4949 }
4950
4951 /**
4952 * Provides a target method handle with one or more <em>bound arguments</em>
4953 * in advance of the method handle's invocation.
4954 * The formal parameters to the target corresponding to the bound
4955 * arguments are called <em>bound parameters</em>.
4956 * Returns a new method handle which saves away the bound arguments.
4957 * When it is invoked, it receives arguments for any non-bound parameters,
4958 * binds the saved arguments to their corresponding parameters,
4959 * and calls the original target.
4960 * <p>
4961 * The type of the new method handle will drop the types for the bound
4962 * parameters from the original target type, since the new method handle
4963 * will no longer require those arguments to be supplied by its callers.
4964 * <p>
4965 * Each given argument object must match the corresponding bound parameter type.
4966 * If a bound parameter type is a primitive, the argument object
4967 * must be a wrapper, and will be unboxed to produce the primitive value.
4968 * <p>
4969 * The {@code pos} argument selects which parameters are to be bound.
4970 * It may range between zero and <i>N-L</i> (inclusively),
4971 * where <i>N</i> is the arity of the target method handle
4972 * and <i>L</i> is the length of the values array.
4973 * <p>
4974 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4975 * variable-arity method handle}, even if the original target method handle was.
4976 * @param target the method handle to invoke after the argument is inserted
4977 * @param pos where to insert the argument (zero for the first)
4978 * @param values the series of arguments to insert
4979 * @return a method handle which inserts an additional argument,
4980 * before calling the original method handle
4981 * @throws NullPointerException if the target or the {@code values} array is null
4982 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
4983 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
4984 * is the length of the values array.
4985 * @throws ClassCastException if an argument does not match the corresponding bound parameter
4986 * type.
4987 * @see MethodHandle#bindTo
4988 */
4989 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
4990 int insCount = values.length;
4991 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
4992 if (insCount == 0) return target;
4993 BoundMethodHandle result = target.rebind();
4994 for (int i = 0; i < insCount; i++) {
4995 Object value = values[i];
4996 Class<?> ptype = ptypes[pos+i];
4997 if (ptype.isPrimitive()) {
4998 result = insertArgumentPrimitive(result, pos, ptype, value);
4999 } else {
5000 value = ptype.cast(value); // throw CCE if needed
5001 result = result.bindArgumentL(pos, value);
5002 }
5003 }
5004 return result;
5005 }
5006
5007 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5008 Class<?> ptype, Object value) {
5009 Wrapper w = Wrapper.forPrimitiveType(ptype);
5010 // perform unboxing and/or primitive conversion
5011 value = w.convert(value, ptype);
5012 return switch (w) {
5013 case INT -> result.bindArgumentI(pos, (int) value);
5014 case LONG -> result.bindArgumentJ(pos, (long) value);
5015 case FLOAT -> result.bindArgumentF(pos, (float) value);
5016 case DOUBLE -> result.bindArgumentD(pos, (double) value);
5017 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5018 };
5019 }
5020
5021 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5022 MethodType oldType = target.type();
5023 int outargs = oldType.parameterCount();
5024 int inargs = outargs - insCount;
5025 if (inargs < 0)
5026 throw newIllegalArgumentException("too many values to insert");
5027 if (pos < 0 || pos > inargs)
5028 throw newIllegalArgumentException("no argument type to append");
5029 return oldType.ptypes();
5030 }
5031
5032 /**
5033 * Produces a method handle which will discard some dummy arguments
5034 * before calling some other specified <i>target</i> method handle.
5035 * The type of the new method handle will be the same as the target's type,
5036 * except it will also include the dummy argument types,
5037 * at some given position.
5038 * <p>
5039 * The {@code pos} argument may range between zero and <i>N</i>,
5040 * where <i>N</i> is the arity of the target.
5041 * If {@code pos} is zero, the dummy arguments will precede
5042 * the target's real arguments; if {@code pos} is <i>N</i>
5043 * they will come after.
5044 * <p>
5045 * <b>Example:</b>
5046 * {@snippet lang="java" :
5047 import static java.lang.invoke.MethodHandles.*;
5048 import static java.lang.invoke.MethodType.*;
5049 ...
5050 MethodHandle cat = lookup().findVirtual(String.class,
5051 "concat", methodType(String.class, String.class));
5052 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5053 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5054 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5055 assertEquals(bigType, d0.type());
5056 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5057 * }
5058 * <p>
5059 * This method is also equivalent to the following code:
5060 * <blockquote><pre>
5061 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5062 * </pre></blockquote>
5063 * @param target the method handle to invoke after the arguments are dropped
5064 * @param pos position of first argument to drop (zero for the leftmost)
5065 * @param valueTypes the type(s) of the argument(s) to drop
5066 * @return a method handle which drops arguments of the given types,
5067 * before calling the original method handle
5068 * @throws NullPointerException if the target is null,
5069 * or if the {@code valueTypes} list or any of its elements is null
5070 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5071 * or if {@code pos} is negative or greater than the arity of the target,
5072 * or if the new method handle's type would have too many parameters
5073 */
5074 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5075 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5076 }
5077
5078 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5079 MethodType oldType = target.type(); // get NPE
5080 int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5081 MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5082 if (dropped == 0) return target;
5083 BoundMethodHandle result = target.rebind();
5084 LambdaForm lform = result.form;
5085 int insertFormArg = 1 + pos;
5086 for (Class<?> ptype : valueTypes) {
5087 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5088 }
5089 result = result.copyWith(newType, lform);
5090 return result;
5091 }
5092
5093 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5094 int dropped = valueTypes.length;
5095 MethodType.checkSlotCount(dropped);
5096 int outargs = oldType.parameterCount();
5097 int inargs = outargs + dropped;
5098 if (pos < 0 || pos > outargs)
5099 throw newIllegalArgumentException("no argument type to remove"
5100 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5101 );
5102 return dropped;
5103 }
5104
5105 /**
5106 * Produces a method handle which will discard some dummy arguments
5107 * before calling some other specified <i>target</i> method handle.
5108 * The type of the new method handle will be the same as the target's type,
5109 * except it will also include the dummy argument types,
5110 * at some given position.
5111 * <p>
5112 * The {@code pos} argument may range between zero and <i>N</i>,
5113 * where <i>N</i> is the arity of the target.
5114 * If {@code pos} is zero, the dummy arguments will precede
5115 * the target's real arguments; if {@code pos} is <i>N</i>
5116 * they will come after.
5117 * @apiNote
5118 * {@snippet lang="java" :
5119 import static java.lang.invoke.MethodHandles.*;
5120 import static java.lang.invoke.MethodType.*;
5121 ...
5122 MethodHandle cat = lookup().findVirtual(String.class,
5123 "concat", methodType(String.class, String.class));
5124 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5125 MethodHandle d0 = dropArguments(cat, 0, String.class);
5126 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5127 MethodHandle d1 = dropArguments(cat, 1, String.class);
5128 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5129 MethodHandle d2 = dropArguments(cat, 2, String.class);
5130 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5131 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5132 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5133 * }
5134 * <p>
5135 * This method is also equivalent to the following code:
5136 * <blockquote><pre>
5137 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5138 * </pre></blockquote>
5139 * @param target the method handle to invoke after the arguments are dropped
5140 * @param pos position of first argument to drop (zero for the leftmost)
5141 * @param valueTypes the type(s) of the argument(s) to drop
5142 * @return a method handle which drops arguments of the given types,
5143 * before calling the original method handle
5144 * @throws NullPointerException if the target is null,
5145 * or if the {@code valueTypes} array or any of its elements is null
5146 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5147 * or if {@code pos} is negative or greater than the arity of the target,
5148 * or if the new method handle's type would have
5149 * <a href="MethodHandle.html#maxarity">too many parameters</a>
5150 */
5151 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5152 return dropArgumentsTrusted(target, pos, valueTypes.clone());
5153 }
5154
5155 /* Convenience overloads for trusting internal low-arity call-sites */
5156 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5157 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5158 }
5159 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5160 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5161 }
5162
5163 // private version which allows caller some freedom with error handling
5164 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5165 boolean nullOnFailure) {
5166 Class<?>[] oldTypes = target.type().ptypes();
5167 int match = oldTypes.length;
5168 if (skip != 0) {
5169 if (skip < 0 || skip > match) {
5170 throw newIllegalArgumentException("illegal skip", skip, target);
5171 }
5172 oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5173 match -= skip;
5174 }
5175 Class<?>[] addTypes = newTypes;
5176 int add = addTypes.length;
5177 if (pos != 0) {
5178 if (pos < 0 || pos > add) {
5179 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5180 }
5181 addTypes = Arrays.copyOfRange(addTypes, pos, add);
5182 add -= pos;
5183 assert(addTypes.length == add);
5184 }
5185 // Do not add types which already match the existing arguments.
5186 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5187 if (nullOnFailure) {
5188 return null;
5189 }
5190 throw newIllegalArgumentException("argument lists do not match",
5191 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5192 }
5193 addTypes = Arrays.copyOfRange(addTypes, match, add);
5194 add -= match;
5195 assert(addTypes.length == add);
5196 // newTypes: ( P*[pos], M*[match], A*[add] )
5197 // target: ( S*[skip], M*[match] )
5198 MethodHandle adapter = target;
5199 if (add > 0) {
5200 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5201 }
5202 // adapter: (S*[skip], M*[match], A*[add] )
5203 if (pos > 0) {
5204 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5205 }
5206 // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5207 return adapter;
5208 }
5209
5210 /**
5211 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5212 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5213 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5214 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5215 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5216 * {@link #dropArguments(MethodHandle, int, Class[])}.
5217 * <p>
5218 * The resulting handle will have the same return type as the target handle.
5219 * <p>
5220 * In more formal terms, assume these two type lists:<ul>
5221 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5222 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5223 * {@code newTypes}.
5224 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5225 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5226 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5227 * sub-list.
5228 * </ul>
5229 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5230 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5231 * {@link #dropArguments(MethodHandle, int, Class[])}.
5232 *
5233 * @apiNote
5234 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5235 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5236 * {@snippet lang="java" :
5237 import static java.lang.invoke.MethodHandles.*;
5238 import static java.lang.invoke.MethodType.*;
5239 ...
5240 ...
5241 MethodHandle h0 = constant(boolean.class, true);
5242 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5243 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5244 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5245 if (h1.type().parameterCount() < h2.type().parameterCount())
5246 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1
5247 else
5248 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2
5249 MethodHandle h3 = guardWithTest(h0, h1, h2);
5250 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5251 * }
5252 * @param target the method handle to adapt
5253 * @param skip number of targets parameters to disregard (they will be unchanged)
5254 * @param newTypes the list of types to match {@code target}'s parameter type list to
5255 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5256 * @return a possibly adapted method handle
5257 * @throws NullPointerException if either argument is null
5258 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5259 * or if {@code skip} is negative or greater than the arity of the target,
5260 * or if {@code pos} is negative or greater than the newTypes list size,
5261 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5262 * {@code pos}.
5263 * @since 9
5264 */
5265 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5266 Objects.requireNonNull(target);
5267 Objects.requireNonNull(newTypes);
5268 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5269 }
5270
5271 /**
5272 * Drop the return value of the target handle (if any).
5273 * The returned method handle will have a {@code void} return type.
5274 *
5275 * @param target the method handle to adapt
5276 * @return a possibly adapted method handle
5277 * @throws NullPointerException if {@code target} is null
5278 * @since 16
5279 */
5280 public static MethodHandle dropReturn(MethodHandle target) {
5281 Objects.requireNonNull(target);
5282 MethodType oldType = target.type();
5283 Class<?> oldReturnType = oldType.returnType();
5284 if (oldReturnType == void.class)
5285 return target;
5286 MethodType newType = oldType.changeReturnType(void.class);
5287 BoundMethodHandle result = target.rebind();
5288 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5289 result = result.copyWith(newType, lform);
5290 return result;
5291 }
5292
5293 /**
5294 * Adapts a target method handle by pre-processing
5295 * one or more of its arguments, each with its own unary filter function,
5296 * and then calling the target with each pre-processed argument
5297 * replaced by the result of its corresponding filter function.
5298 * <p>
5299 * The pre-processing is performed by one or more method handles,
5300 * specified in the elements of the {@code filters} array.
5301 * The first element of the filter array corresponds to the {@code pos}
5302 * argument of the target, and so on in sequence.
5303 * The filter functions are invoked in left to right order.
5304 * <p>
5305 * Null arguments in the array are treated as identity functions,
5306 * and the corresponding arguments left unchanged.
5307 * (If there are no non-null elements in the array, the original target is returned.)
5308 * Each filter is applied to the corresponding argument of the adapter.
5309 * <p>
5310 * If a filter {@code F} applies to the {@code N}th argument of
5311 * the target, then {@code F} must be a method handle which
5312 * takes exactly one argument. The type of {@code F}'s sole argument
5313 * replaces the corresponding argument type of the target
5314 * in the resulting adapted method handle.
5315 * The return type of {@code F} must be identical to the corresponding
5316 * parameter type of the target.
5317 * <p>
5318 * It is an error if there are elements of {@code filters}
5319 * (null or not)
5320 * which do not correspond to argument positions in the target.
5321 * <p><b>Example:</b>
5322 * {@snippet lang="java" :
5323 import static java.lang.invoke.MethodHandles.*;
5324 import static java.lang.invoke.MethodType.*;
5325 ...
5326 MethodHandle cat = lookup().findVirtual(String.class,
5327 "concat", methodType(String.class, String.class));
5328 MethodHandle upcase = lookup().findVirtual(String.class,
5329 "toUpperCase", methodType(String.class));
5330 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5331 MethodHandle f0 = filterArguments(cat, 0, upcase);
5332 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5333 MethodHandle f1 = filterArguments(cat, 1, upcase);
5334 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5335 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5336 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5337 * }
5338 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5339 * denotes the return type of both the {@code target} and resulting adapter.
5340 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5341 * of the parameters and arguments that precede and follow the filter position
5342 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5343 * values of the filtered parameters and arguments; they also represent the
5344 * return types of the {@code filter[i]} handles. The latter accept arguments
5345 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5346 * the resulting adapter.
5347 * {@snippet lang="java" :
5348 * T target(P... p, A[i]... a[i], B... b);
5349 * A[i] filter[i](V[i]);
5350 * T adapter(P... p, V[i]... v[i], B... b) {
5351 * return target(p..., filter[i](v[i])..., b...);
5352 * }
5353 * }
5354 * <p>
5355 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5356 * variable-arity method handle}, even if the original target method handle was.
5357 *
5358 * @param target the method handle to invoke after arguments are filtered
5359 * @param pos the position of the first argument to filter
5360 * @param filters method handles to call initially on filtered arguments
5361 * @return method handle which incorporates the specified argument filtering logic
5362 * @throws NullPointerException if the target is null
5363 * or if the {@code filters} array is null
5364 * @throws IllegalArgumentException if a non-null element of {@code filters}
5365 * does not match a corresponding argument type of target as described above,
5366 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5367 * or if the resulting method handle's type would have
5368 * <a href="MethodHandle.html#maxarity">too many parameters</a>
5369 */
5370 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5371 // In method types arguments start at index 0, while the LF
5372 // editor have the MH receiver at position 0 - adjust appropriately.
5373 final int MH_RECEIVER_OFFSET = 1;
5374 filterArgumentsCheckArity(target, pos, filters);
5375 MethodHandle adapter = target;
5376
5377 // keep track of currently matched filters, as to optimize repeated filters
5378 int index = 0;
5379 int[] positions = new int[filters.length];
5380 MethodHandle filter = null;
5381
5382 // process filters in reverse order so that the invocation of
5383 // the resulting adapter will invoke the filters in left-to-right order
5384 for (int i = filters.length - 1; i >= 0; --i) {
5385 MethodHandle newFilter = filters[i];
5386 if (newFilter == null) continue; // ignore null elements of filters
5387
5388 // flush changes on update
5389 if (filter != newFilter) {
5390 if (filter != null) {
5391 if (index > 1) {
5392 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5393 } else {
5394 adapter = filterArgument(adapter, positions[0] - 1, filter);
5395 }
5396 }
5397 filter = newFilter;
5398 index = 0;
5399 }
5400
5401 filterArgumentChecks(target, pos + i, newFilter);
5402 positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5403 }
5404 if (index > 1) {
5405 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5406 } else if (index == 1) {
5407 adapter = filterArgument(adapter, positions[0] - 1, filter);
5408 }
5409 return adapter;
5410 }
5411
5412 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5413 MethodType targetType = adapter.type();
5414 MethodType filterType = filter.type();
5415 BoundMethodHandle result = adapter.rebind();
5416 Class<?> newParamType = filterType.parameterType(0);
5417
5418 Class<?>[] ptypes = targetType.ptypes().clone();
5419 for (int pos : positions) {
5420 ptypes[pos - 1] = newParamType;
5421 }
5422 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5423
5424 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5425 return result.copyWithExtendL(newType, lform, filter);
5426 }
5427
5428 /*non-public*/
5429 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5430 filterArgumentChecks(target, pos, filter);
5431 MethodType targetType = target.type();
5432 MethodType filterType = filter.type();
5433 BoundMethodHandle result = target.rebind();
5434 Class<?> newParamType = filterType.parameterType(0);
5435 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5436 MethodType newType = targetType.changeParameterType(pos, newParamType);
5437 result = result.copyWithExtendL(newType, lform, filter);
5438 return result;
5439 }
5440
5441 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5442 MethodType targetType = target.type();
5443 int maxPos = targetType.parameterCount();
5444 if (pos + filters.length > maxPos)
5445 throw newIllegalArgumentException("too many filters");
5446 }
5447
5448 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5449 MethodType targetType = target.type();
5450 MethodType filterType = filter.type();
5451 if (filterType.parameterCount() != 1
5452 || filterType.returnType() != targetType.parameterType(pos))
5453 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5454 }
5455
5456 /**
5457 * Adapts a target method handle by pre-processing
5458 * a sub-sequence of its arguments with a filter (another method handle).
5459 * The pre-processed arguments are replaced by the result (if any) of the
5460 * filter function.
5461 * The target is then called on the modified (usually shortened) argument list.
5462 * <p>
5463 * If the filter returns a value, the target must accept that value as
5464 * its argument in position {@code pos}, preceded and/or followed by
5465 * any arguments not passed to the filter.
5466 * If the filter returns void, the target must accept all arguments
5467 * not passed to the filter.
5468 * No arguments are reordered, and a result returned from the filter
5469 * replaces (in order) the whole subsequence of arguments originally
5470 * passed to the adapter.
5471 * <p>
5472 * The argument types (if any) of the filter
5473 * replace zero or one argument types of the target, at position {@code pos},
5474 * in the resulting adapted method handle.
5475 * The return type of the filter (if any) must be identical to the
5476 * argument type of the target at position {@code pos}, and that target argument
5477 * is supplied by the return value of the filter.
5478 * <p>
5479 * In all cases, {@code pos} must be greater than or equal to zero, and
5480 * {@code pos} must also be less than or equal to the target's arity.
5481 * <p><b>Example:</b>
5482 * {@snippet lang="java" :
5483 import static java.lang.invoke.MethodHandles.*;
5484 import static java.lang.invoke.MethodType.*;
5485 ...
5486 MethodHandle deepToString = publicLookup()
5487 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5488
5489 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5490 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5491
5492 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5493 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5494
5495 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5496 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5497 assertEquals("[top, [up, down], strange]",
5498 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5499
5500 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5501 assertEquals("[top, [up, down], [strange]]",
5502 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5503
5504 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5505 assertEquals("[top, [[up, down, strange], charm], bottom]",
5506 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5507 * }
5508 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5509 * represents the return type of the {@code target} and resulting adapter.
5510 * {@code V}/{@code v} stand for the return type and value of the
5511 * {@code filter}, which are also found in the signature and arguments of
5512 * the {@code target}, respectively, unless {@code V} is {@code void}.
5513 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5514 * and values preceding and following the collection position, {@code pos},
5515 * in the {@code target}'s signature. They also turn up in the resulting
5516 * adapter's signature and arguments, where they surround
5517 * {@code B}/{@code b}, which represent the parameter types and arguments
5518 * to the {@code filter} (if any).
5519 * {@snippet lang="java" :
5520 * T target(A...,V,C...);
5521 * V filter(B...);
5522 * T adapter(A... a,B... b,C... c) {
5523 * V v = filter(b...);
5524 * return target(a...,v,c...);
5525 * }
5526 * // and if the filter has no arguments:
5527 * T target2(A...,V,C...);
5528 * V filter2();
5529 * T adapter2(A... a,C... c) {
5530 * V v = filter2();
5531 * return target2(a...,v,c...);
5532 * }
5533 * // and if the filter has a void return:
5534 * T target3(A...,C...);
5535 * void filter3(B...);
5536 * T adapter3(A... a,B... b,C... c) {
5537 * filter3(b...);
5538 * return target3(a...,c...);
5539 * }
5540 * }
5541 * <p>
5542 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5543 * one which first "folds" the affected arguments, and then drops them, in separate
5544 * steps as follows:
5545 * {@snippet lang="java" :
5546 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5547 * mh = MethodHandles.foldArguments(mh, coll); //step 1
5548 * }
5549 * If the target method handle consumes no arguments besides than the result
5550 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5551 * is equivalent to {@code filterReturnValue(coll, mh)}.
5552 * If the filter method handle {@code coll} consumes one argument and produces
5553 * a non-void result, then {@code collectArguments(mh, N, coll)}
5554 * is equivalent to {@code filterArguments(mh, N, coll)}.
5555 * Other equivalences are possible but would require argument permutation.
5556 * <p>
5557 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5558 * variable-arity method handle}, even if the original target method handle was.
5559 *
5560 * @param target the method handle to invoke after filtering the subsequence of arguments
5561 * @param pos the position of the first adapter argument to pass to the filter,
5562 * and/or the target argument which receives the result of the filter
5563 * @param filter method handle to call on the subsequence of arguments
5564 * @return method handle which incorporates the specified argument subsequence filtering logic
5565 * @throws NullPointerException if either argument is null
5566 * @throws IllegalArgumentException if the return type of {@code filter}
5567 * is non-void and is not the same as the {@code pos} argument of the target,
5568 * or if {@code pos} is not between 0 and the target's arity, inclusive,
5569 * or if the resulting method handle's type would have
5570 * <a href="MethodHandle.html#maxarity">too many parameters</a>
5571 * @see MethodHandles#foldArguments
5572 * @see MethodHandles#filterArguments
5573 * @see MethodHandles#filterReturnValue
5574 */
5575 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5576 MethodType newType = collectArgumentsChecks(target, pos, filter);
5577 MethodType collectorType = filter.type();
5578 BoundMethodHandle result = target.rebind();
5579 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5580 return result.copyWithExtendL(newType, lform, filter);
5581 }
5582
5583 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5584 MethodType targetType = target.type();
5585 MethodType filterType = filter.type();
5586 Class<?> rtype = filterType.returnType();
5587 Class<?>[] filterArgs = filterType.ptypes();
5588 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5589 (rtype != void.class && pos >= targetType.parameterCount())) {
5590 throw newIllegalArgumentException("position is out of range for target", target, pos);
5591 }
5592 if (rtype == void.class) {
5593 return targetType.insertParameterTypes(pos, filterArgs);
5594 }
5595 if (rtype != targetType.parameterType(pos)) {
5596 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5597 }
5598 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5599 }
5600
5601 /**
5602 * Adapts a target method handle by post-processing
5603 * its return value (if any) with a filter (another method handle).
5604 * The result of the filter is returned from the adapter.
5605 * <p>
5606 * If the target returns a value, the filter must accept that value as
5607 * its only argument.
5608 * If the target returns void, the filter must accept no arguments.
5609 * <p>
5610 * The return type of the filter
5611 * replaces the return type of the target
5612 * in the resulting adapted method handle.
5613 * The argument type of the filter (if any) must be identical to the
5614 * return type of the target.
5615 * <p><b>Example:</b>
5616 * {@snippet lang="java" :
5617 import static java.lang.invoke.MethodHandles.*;
5618 import static java.lang.invoke.MethodType.*;
5619 ...
5620 MethodHandle cat = lookup().findVirtual(String.class,
5621 "concat", methodType(String.class, String.class));
5622 MethodHandle length = lookup().findVirtual(String.class,
5623 "length", methodType(int.class));
5624 System.out.println((String) cat.invokeExact("x", "y")); // xy
5625 MethodHandle f0 = filterReturnValue(cat, length);
5626 System.out.println((int) f0.invokeExact("x", "y")); // 2
5627 * }
5628 * <p>Here is pseudocode for the resulting adapter. In the code,
5629 * {@code T}/{@code t} represent the result type and value of the
5630 * {@code target}; {@code V}, the result type of the {@code filter}; and
5631 * {@code A}/{@code a}, the types and values of the parameters and arguments
5632 * of the {@code target} as well as the resulting adapter.
5633 * {@snippet lang="java" :
5634 * T target(A...);
5635 * V filter(T);
5636 * V adapter(A... a) {
5637 * T t = target(a...);
5638 * return filter(t);
5639 * }
5640 * // and if the target has a void return:
5641 * void target2(A...);
5642 * V filter2();
5643 * V adapter2(A... a) {
5644 * target2(a...);
5645 * return filter2();
5646 * }
5647 * // and if the filter has a void return:
5648 * T target3(A...);
5649 * void filter3(V);
5650 * void adapter3(A... a) {
5651 * T t = target3(a...);
5652 * filter3(t);
5653 * }
5654 * }
5655 * <p>
5656 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5657 * variable-arity method handle}, even if the original target method handle was.
5658 * @param target the method handle to invoke before filtering the return value
5659 * @param filter method handle to call on the return value
5660 * @return method handle which incorporates the specified return value filtering logic
5661 * @throws NullPointerException if either argument is null
5662 * @throws IllegalArgumentException if the argument list of {@code filter}
5663 * does not match the return type of target as described above
5664 */
5665 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5666 MethodType targetType = target.type();
5667 MethodType filterType = filter.type();
5668 filterReturnValueChecks(targetType, filterType);
5669 BoundMethodHandle result = target.rebind();
5670 BasicType rtype = BasicType.basicType(filterType.returnType());
5671 LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5672 MethodType newType = targetType.changeReturnType(filterType.returnType());
5673 result = result.copyWithExtendL(newType, lform, filter);
5674 return result;
5675 }
5676
5677 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5678 Class<?> rtype = targetType.returnType();
5679 int filterValues = filterType.parameterCount();
5680 if (filterValues == 0
5681 ? (rtype != void.class)
5682 : (rtype != filterType.parameterType(0) || filterValues != 1))
5683 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5684 }
5685
5686 /**
5687 * Filter the return value of a target method handle with a filter function. The filter function is
5688 * applied to the return value of the original handle; if the filter specifies more than one parameters,
5689 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5690 * as follows:
5691 * {@snippet lang="java" :
5692 * T target(A...)
5693 * V filter(B... , T)
5694 * V adapter(A... a, B... b) {
5695 * T t = target(a...);
5696 * return filter(b..., t);
5697 * }
5698 * }
5699 * <p>
5700 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5701 *
5702 * @param target the target method handle
5703 * @param filter the filter method handle
5704 * @return the adapter method handle
5705 */
5706 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5707 MethodType targetType = target.type();
5708 MethodType filterType = filter.type();
5709 BoundMethodHandle result = target.rebind();
5710 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5711 MethodType newType = targetType.changeReturnType(filterType.returnType());
5712 if (filterType.parameterCount() > 1) {
5713 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5714 newType = newType.appendParameterTypes(filterType.parameterType(i));
5715 }
5716 }
5717 result = result.copyWithExtendL(newType, lform, filter);
5718 return result;
5719 }
5720
5721 /**
5722 * Adapts a target method handle by pre-processing
5723 * some of its arguments, and then calling the target with
5724 * the result of the pre-processing, inserted into the original
5725 * sequence of arguments.
5726 * <p>
5727 * The pre-processing is performed by {@code combiner}, a second method handle.
5728 * Of the arguments passed to the adapter, the first {@code N} arguments
5729 * are copied to the combiner, which is then called.
5730 * (Here, {@code N} is defined as the parameter count of the combiner.)
5731 * After this, control passes to the target, with any result
5732 * from the combiner inserted before the original {@code N} incoming
5733 * arguments.
5734 * <p>
5735 * If the combiner returns a value, the first parameter type of the target
5736 * must be identical with the return type of the combiner, and the next
5737 * {@code N} parameter types of the target must exactly match the parameters
5738 * of the combiner.
5739 * <p>
5740 * If the combiner has a void return, no result will be inserted,
5741 * and the first {@code N} parameter types of the target
5742 * must exactly match the parameters of the combiner.
5743 * <p>
5744 * The resulting adapter is the same type as the target, except that the
5745 * first parameter type is dropped,
5746 * if it corresponds to the result of the combiner.
5747 * <p>
5748 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5749 * that either the combiner or the target does not wish to receive.
5750 * If some of the incoming arguments are destined only for the combiner,
5751 * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5752 * arguments will not need to be live on the stack on entry to the
5753 * target.)
5754 * <p><b>Example:</b>
5755 * {@snippet lang="java" :
5756 import static java.lang.invoke.MethodHandles.*;
5757 import static java.lang.invoke.MethodType.*;
5758 ...
5759 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5760 "println", methodType(void.class, String.class))
5761 .bindTo(System.out);
5762 MethodHandle cat = lookup().findVirtual(String.class,
5763 "concat", methodType(String.class, String.class));
5764 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5765 MethodHandle catTrace = foldArguments(cat, trace);
5766 // also prints "boo":
5767 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5768 * }
5769 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5770 * represents the result type of the {@code target} and resulting adapter.
5771 * {@code V}/{@code v} represent the type and value of the parameter and argument
5772 * of {@code target} that precedes the folding position; {@code V} also is
5773 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5774 * types and values of the {@code N} parameters and arguments at the folding
5775 * position. {@code B}/{@code b} represent the types and values of the
5776 * {@code target} parameters and arguments that follow the folded parameters
5777 * and arguments.
5778 * {@snippet lang="java" :
5779 * // there are N arguments in A...
5780 * T target(V, A[N]..., B...);
5781 * V combiner(A...);
5782 * T adapter(A... a, B... b) {
5783 * V v = combiner(a...);
5784 * return target(v, a..., b...);
5785 * }
5786 * // and if the combiner has a void return:
5787 * T target2(A[N]..., B...);
5788 * void combiner2(A...);
5789 * T adapter2(A... a, B... b) {
5790 * combiner2(a...);
5791 * return target2(a..., b...);
5792 * }
5793 * }
5794 * <p>
5795 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5796 * variable-arity method handle}, even if the original target method handle was.
5797 * @param target the method handle to invoke after arguments are combined
5798 * @param combiner method handle to call initially on the incoming arguments
5799 * @return method handle which incorporates the specified argument folding logic
5800 * @throws NullPointerException if either argument is null
5801 * @throws IllegalArgumentException if {@code combiner}'s return type
5802 * is non-void and not the same as the first argument type of
5803 * the target, or if the initial {@code N} argument types
5804 * of the target
5805 * (skipping one matching the {@code combiner}'s return type)
5806 * are not identical with the argument types of {@code combiner}
5807 */
5808 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5809 return foldArguments(target, 0, combiner);
5810 }
5811
5812 /**
5813 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5814 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5815 * before the folded arguments.
5816 * <p>
5817 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5818 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
5819 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
5820 * 0.
5821 *
5822 * @apiNote Example:
5823 * {@snippet lang="java" :
5824 import static java.lang.invoke.MethodHandles.*;
5825 import static java.lang.invoke.MethodType.*;
5826 ...
5827 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5828 "println", methodType(void.class, String.class))
5829 .bindTo(System.out);
5830 MethodHandle cat = lookup().findVirtual(String.class,
5831 "concat", methodType(String.class, String.class));
5832 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5833 MethodHandle catTrace = foldArguments(cat, 1, trace);
5834 // also prints "jum":
5835 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5836 * }
5837 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5838 * represents the result type of the {@code target} and resulting adapter.
5839 * {@code V}/{@code v} represent the type and value of the parameter and argument
5840 * of {@code target} that precedes the folding position; {@code V} also is
5841 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5842 * types and values of the {@code N} parameters and arguments at the folding
5843 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
5844 * and values of the {@code target} parameters and arguments that precede and
5845 * follow the folded parameters and arguments starting at {@code pos},
5846 * respectively.
5847 * {@snippet lang="java" :
5848 * // there are N arguments in A...
5849 * T target(Z..., V, A[N]..., B...);
5850 * V combiner(A...);
5851 * T adapter(Z... z, A... a, B... b) {
5852 * V v = combiner(a...);
5853 * return target(z..., v, a..., b...);
5854 * }
5855 * // and if the combiner has a void return:
5856 * T target2(Z..., A[N]..., B...);
5857 * void combiner2(A...);
5858 * T adapter2(Z... z, A... a, B... b) {
5859 * combiner2(a...);
5860 * return target2(z..., a..., b...);
5861 * }
5862 * }
5863 * <p>
5864 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5865 * variable-arity method handle}, even if the original target method handle was.
5866 *
5867 * @param target the method handle to invoke after arguments are combined
5868 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
5869 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5870 * @param combiner method handle to call initially on the incoming arguments
5871 * @return method handle which incorporates the specified argument folding logic
5872 * @throws NullPointerException if either argument is null
5873 * @throws IllegalArgumentException if either of the following two conditions holds:
5874 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5875 * {@code pos} of the target signature;
5876 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
5877 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
5878 *
5879 * @see #foldArguments(MethodHandle, MethodHandle)
5880 * @since 9
5881 */
5882 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
5883 MethodType targetType = target.type();
5884 MethodType combinerType = combiner.type();
5885 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
5886 BoundMethodHandle result = target.rebind();
5887 boolean dropResult = rtype == void.class;
5888 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
5889 MethodType newType = targetType;
5890 if (!dropResult) {
5891 newType = newType.dropParameterTypes(pos, pos + 1);
5892 }
5893 result = result.copyWithExtendL(newType, lform, combiner);
5894 return result;
5895 }
5896
5897 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
5898 int foldArgs = combinerType.parameterCount();
5899 Class<?> rtype = combinerType.returnType();
5900 int foldVals = rtype == void.class ? 0 : 1;
5901 int afterInsertPos = foldPos + foldVals;
5902 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
5903 if (ok) {
5904 for (int i = 0; i < foldArgs; i++) {
5905 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
5906 ok = false;
5907 break;
5908 }
5909 }
5910 }
5911 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
5912 ok = false;
5913 if (!ok)
5914 throw misMatchedTypes("target and combiner types", targetType, combinerType);
5915 return rtype;
5916 }
5917
5918 /**
5919 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
5920 * of the pre-processing replacing the argument at the given position.
5921 *
5922 * @param target the method handle to invoke after arguments are combined
5923 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5924 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5925 * @param combiner method handle to call initially on the incoming arguments
5926 * @param argPositions indexes of the target to pick arguments sent to the combiner from
5927 * @return method handle which incorporates the specified argument folding logic
5928 * @throws NullPointerException if either argument is null
5929 * @throws IllegalArgumentException if either of the following two conditions holds:
5930 * (1) {@code combiner}'s return type is not the same as the argument type at position
5931 * {@code pos} of the target signature;
5932 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
5933 * not identical with the argument types of {@code combiner}.
5934 */
5935 /*non-public*/
5936 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5937 return argumentsWithCombiner(true, target, position, combiner, argPositions);
5938 }
5939
5940 /**
5941 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
5942 * the pre-processing inserted into the original sequence of arguments at the given position.
5943 *
5944 * @param target the method handle to invoke after arguments are combined
5945 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5946 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5947 * @param combiner method handle to call initially on the incoming arguments
5948 * @param argPositions indexes of the target to pick arguments sent to the combiner from
5949 * @return method handle which incorporates the specified argument folding logic
5950 * @throws NullPointerException if either argument is null
5951 * @throws IllegalArgumentException if either of the following two conditions holds:
5952 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5953 * {@code pos} of the target signature;
5954 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
5955 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
5956 * with the argument types of {@code combiner}.
5957 */
5958 /*non-public*/
5959 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5960 return argumentsWithCombiner(false, target, position, combiner, argPositions);
5961 }
5962
5963 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5964 MethodType targetType = target.type();
5965 MethodType combinerType = combiner.type();
5966 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
5967 BoundMethodHandle result = target.rebind();
5968
5969 MethodType newType = targetType;
5970 LambdaForm lform;
5971 if (filter) {
5972 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
5973 } else {
5974 boolean dropResult = rtype == void.class;
5975 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
5976 if (!dropResult) {
5977 newType = newType.dropParameterTypes(position, position + 1);
5978 }
5979 }
5980 result = result.copyWithExtendL(newType, lform, combiner);
5981 return result;
5982 }
5983
5984 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
5985 int combinerArgs = combinerType.parameterCount();
5986 if (argPos.length != combinerArgs) {
5987 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
5988 }
5989 Class<?> rtype = combinerType.returnType();
5990
5991 for (int i = 0; i < combinerArgs; i++) {
5992 int arg = argPos[i];
5993 if (arg < 0 || arg > targetType.parameterCount()) {
5994 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
5995 }
5996 if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
5997 throw newIllegalArgumentException("target argument type at position " + arg
5998 + " must match combiner argument type at index " + i + ": " + targetType
5999 + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6000 }
6001 }
6002 if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6003 throw misMatchedTypes("target and combiner types", targetType, combinerType);
6004 }
6005 return rtype;
6006 }
6007
6008 /**
6009 * Makes a method handle which adapts a target method handle,
6010 * by guarding it with a test, a boolean-valued method handle.
6011 * If the guard fails, a fallback handle is called instead.
6012 * All three method handles must have the same corresponding
6013 * argument and return types, except that the return type
6014 * of the test must be boolean, and the test is allowed
6015 * to have fewer arguments than the other two method handles.
6016 * <p>
6017 * Here is pseudocode for the resulting adapter. In the code, {@code T}
6018 * represents the uniform result type of the three involved handles;
6019 * {@code A}/{@code a}, the types and values of the {@code target}
6020 * parameters and arguments that are consumed by the {@code test}; and
6021 * {@code B}/{@code b}, those types and values of the {@code target}
6022 * parameters and arguments that are not consumed by the {@code test}.
6023 * {@snippet lang="java" :
6024 * boolean test(A...);
6025 * T target(A...,B...);
6026 * T fallback(A...,B...);
6027 * T adapter(A... a,B... b) {
6028 * if (test(a...))
6029 * return target(a..., b...);
6030 * else
6031 * return fallback(a..., b...);
6032 * }
6033 * }
6034 * Note that the test arguments ({@code a...} in the pseudocode) cannot
6035 * be modified by execution of the test, and so are passed unchanged
6036 * from the caller to the target or fallback as appropriate.
6037 * @param test method handle used for test, must return boolean
6038 * @param target method handle to call if test passes
6039 * @param fallback method handle to call if test fails
6040 * @return method handle which incorporates the specified if/then/else logic
6041 * @throws NullPointerException if any argument is null
6042 * @throws IllegalArgumentException if {@code test} does not return boolean,
6043 * or if all three method types do not match (with the return
6044 * type of {@code test} changed to match that of the target).
6045 */
6046 public static MethodHandle guardWithTest(MethodHandle test,
6047 MethodHandle target,
6048 MethodHandle fallback) {
6049 MethodType gtype = test.type();
6050 MethodType ttype = target.type();
6051 MethodType ftype = fallback.type();
6052 if (!ttype.equals(ftype))
6053 throw misMatchedTypes("target and fallback types", ttype, ftype);
6054 if (gtype.returnType() != boolean.class)
6055 throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6056
6057 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6058 if (test == null) {
6059 throw misMatchedTypes("target and test types", ttype, gtype);
6060 }
6061 return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6062 }
6063
6064 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6065 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6066 }
6067
6068 /**
6069 * Makes a method handle which adapts a target method handle,
6070 * by running it inside an exception handler.
6071 * If the target returns normally, the adapter returns that value.
6072 * If an exception matching the specified type is thrown, the fallback
6073 * handle is called instead on the exception, plus the original arguments.
6074 * <p>
6075 * The target and handler must have the same corresponding
6076 * argument and return types, except that handler may omit trailing arguments
6077 * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6078 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6079 * <p>
6080 * Here is pseudocode for the resulting adapter. In the code, {@code T}
6081 * represents the return type of the {@code target} and {@code handler},
6082 * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6083 * the types and values of arguments to the resulting handle consumed by
6084 * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6085 * resulting handle discarded by {@code handler}.
6086 * {@snippet lang="java" :
6087 * T target(A..., B...);
6088 * T handler(ExType, A...);
6089 * T adapter(A... a, B... b) {
6090 * try {
6091 * return target(a..., b...);
6092 * } catch (ExType ex) {
6093 * return handler(ex, a...);
6094 * }
6095 * }
6096 * }
6097 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6098 * be modified by execution of the target, and so are passed unchanged
6099 * from the caller to the handler, if the handler is invoked.
6100 * <p>
6101 * The target and handler must return the same type, even if the handler
6102 * always throws. (This might happen, for instance, because the handler
6103 * is simulating a {@code finally} clause).
6104 * To create such a throwing handler, compose the handler creation logic
6105 * with {@link #throwException throwException},
6106 * in order to create a method handle of the correct return type.
6107 * @param target method handle to call
6108 * @param exType the type of exception which the handler will catch
6109 * @param handler method handle to call if a matching exception is thrown
6110 * @return method handle which incorporates the specified try/catch logic
6111 * @throws NullPointerException if any argument is null
6112 * @throws IllegalArgumentException if {@code handler} does not accept
6113 * the given exception type, or if the method handle types do
6114 * not match in their return types and their
6115 * corresponding parameters
6116 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6117 */
6118 public static MethodHandle catchException(MethodHandle target,
6119 Class<? extends Throwable> exType,
6120 MethodHandle handler) {
6121 MethodType ttype = target.type();
6122 MethodType htype = handler.type();
6123 if (!Throwable.class.isAssignableFrom(exType))
6124 throw new ClassCastException(exType.getName());
6125 if (htype.parameterCount() < 1 ||
6126 !htype.parameterType(0).isAssignableFrom(exType))
6127 throw newIllegalArgumentException("handler does not accept exception type "+exType);
6128 if (htype.returnType() != ttype.returnType())
6129 throw misMatchedTypes("target and handler return types", ttype, htype);
6130 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6131 if (handler == null) {
6132 throw misMatchedTypes("target and handler types", ttype, htype);
6133 }
6134 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6135 }
6136
6137 /**
6138 * Produces a method handle which will throw exceptions of the given {@code exType}.
6139 * The method handle will accept a single argument of {@code exType},
6140 * and immediately throw it as an exception.
6141 * The method type will nominally specify a return of {@code returnType}.
6142 * The return type may be anything convenient: It doesn't matter to the
6143 * method handle's behavior, since it will never return normally.
6144 * @param returnType the return type of the desired method handle
6145 * @param exType the parameter type of the desired method handle
6146 * @return method handle which can throw the given exceptions
6147 * @throws NullPointerException if either argument is null
6148 */
6149 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6150 if (!Throwable.class.isAssignableFrom(exType))
6151 throw new ClassCastException(exType.getName());
6152 return MethodHandleImpl.throwException(methodType(returnType, exType));
6153 }
6154
6155 /**
6156 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6157 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6158 * delivers the loop's result, which is the return value of the resulting handle.
6159 * <p>
6160 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6161 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6162 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6163 * terms of method handles, each clause will specify up to four independent actions:<ul>
6164 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6165 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6166 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6167 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6168 * </ul>
6169 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6170 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually
6171 * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6172 * <p>
6173 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6174 * this case. See below for a detailed description.
6175 * <p>
6176 * <em>Parameters optional everywhere:</em>
6177 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6178 * As an exception, the init functions cannot take any {@code v} parameters,
6179 * because those values are not yet computed when the init functions are executed.
6180 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6181 * In fact, any clause function may take no arguments at all.
6182 * <p>
6183 * <em>Loop parameters:</em>
6184 * A clause function may take all the iteration variable values it is entitled to, in which case
6185 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6186 * with their types and values notated as {@code (A...)} and {@code (a...)}.
6187 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6188 * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6189 * init function is automatically a loop parameter {@code a}.)
6190 * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6191 * These loop parameters act as loop-invariant values visible across the whole loop.
6192 * <p>
6193 * <em>Parameters visible everywhere:</em>
6194 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6195 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6196 * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6197 * Most clause functions will not need all of this information, but they will be formally connected to it
6198 * as if by {@link #dropArguments}.
6199 * <a id="astar"></a>
6200 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6201 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6202 * In that notation, the general form of an init function parameter list
6203 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6204 * <p>
6205 * <em>Checking clause structure:</em>
6206 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6207 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6208 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6209 * met by the inputs to the loop combinator.
6210 * <p>
6211 * <em>Effectively identical sequences:</em>
6212 * <a id="effid"></a>
6213 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6214 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6215 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6216 * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6217 * that longest list.
6218 * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6219 * and the same is true if more sequences of the form {@code (V... A*)} are added.
6220 * <p>
6221 * <em>Step 0: Determine clause structure.</em><ol type="a">
6222 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6223 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6224 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6225 * four. Padding takes place by appending elements to the array.
6226 * <li>Clauses with all {@code null}s are disregarded.
6227 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6228 * </ol>
6229 * <p>
6230 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6231 * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6232 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6233 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6234 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6235 * iteration variable type.
6236 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6237 * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6238 * </ol>
6239 * <p>
6240 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6241 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6242 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6243 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6244 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6245 * (These types will be checked in step 2, along with all the clause function types.)
6246 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.)
6247 * <li>All of the collected parameter lists must be effectively identical.
6248 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6249 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6250 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6251 * the "internal parameter list".
6252 * </ul>
6253 * <p>
6254 * <em>Step 1C: Determine loop return type.</em><ol type="a">
6255 * <li>Examine fini function return types, disregarding omitted fini functions.
6256 * <li>If there are no fini functions, the loop return type is {@code void}.
6257 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6258 * type.
6259 * </ol>
6260 * <p>
6261 * <em>Step 1D: Check other types.</em><ol type="a">
6262 * <li>There must be at least one non-omitted pred function.
6263 * <li>Every non-omitted pred function must have a {@code boolean} return type.
6264 * </ol>
6265 * <p>
6266 * <em>Step 2: Determine parameter lists.</em><ol type="a">
6267 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6268 * <li>The parameter list for init functions will be adjusted to the external parameter list.
6269 * (Note that their parameter lists are already effectively identical to this list.)
6270 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6271 * effectively identical to the internal parameter list {@code (V... A...)}.
6272 * </ol>
6273 * <p>
6274 * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6275 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6276 * type.
6277 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6278 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6279 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6280 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6281 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.)
6282 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6283 * loop return type.
6284 * </ol>
6285 * <p>
6286 * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6287 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6288 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6289 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6290 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6291 * pad out the end of the list.
6292 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6293 * </ol>
6294 * <p>
6295 * <em>Final observations.</em><ol type="a">
6296 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6297 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6298 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6299 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6300 * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6301 * <li>Each pair of init and step functions agrees in their return type {@code V}.
6302 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6303 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6304 * </ol>
6305 * <p>
6306 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6307 * <ul>
6308 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6309 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6310 * (Only one {@code Pn} has to be non-{@code null}.)
6311 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6312 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6313 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6314 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6315 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6316 * the resulting loop handle's parameter types {@code (A...)}.
6317 * </ul>
6318 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6319 * which is natural if most of the loop computation happens in the steps. For some loops,
6320 * the burden of computation might be heaviest in the pred functions, and so the pred functions
6321 * might need to accept the loop parameter values. For loops with complex exit logic, the fini
6322 * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6323 * where the init functions will need the extra parameters. For such reasons, the rules for
6324 * determining these parameters are as symmetric as possible, across all clause parts.
6325 * In general, the loop parameters function as common invariant values across the whole
6326 * loop, while the iteration variables function as common variant values, or (if there is
6327 * no step function) as internal loop invariant temporaries.
6328 * <p>
6329 * <em>Loop execution.</em><ol type="a">
6330 * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6331 * every clause function. These locals are loop invariant.
6332 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6333 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6334 * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6335 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6336 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6337 * (in argument order).
6338 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6339 * returns {@code false}.
6340 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6341 * sequence {@code (v...)} of loop variables.
6342 * The updated value is immediately visible to all subsequent function calls.
6343 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6344 * (of type {@code R}) is returned from the loop as a whole.
6345 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6346 * except by throwing an exception.
6347 * </ol>
6348 * <p>
6349 * <em>Usage tips.</em>
6350 * <ul>
6351 * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6352 * sometimes a step function only needs to observe the current value of its own variable.
6353 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6354 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6355 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create
6356 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be
6357 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6358 * <li>If some of the clause functions are virtual methods on an instance, the instance
6359 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6360 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference
6361 * will be the first iteration variable value, and it will be easy to use virtual
6362 * methods as clause parts, since all of them will take a leading instance reference matching that value.
6363 * </ul>
6364 * <p>
6365 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6366 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6367 * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6368 * {@snippet lang="java" :
6369 * V... init...(A...);
6370 * boolean pred...(V..., A...);
6371 * V... step...(V..., A...);
6372 * R fini...(V..., A...);
6373 * R loop(A... a) {
6374 * V... v... = init...(a...);
6375 * for (;;) {
6376 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6377 * v = s(v..., a...);
6378 * if (!p(v..., a...)) {
6379 * return f(v..., a...);
6380 * }
6381 * }
6382 * }
6383 * }
6384 * }
6385 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6386 * to their full length, even though individual clause functions may neglect to take them all.
6387 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6388 *
6389 * @apiNote Example:
6390 * {@snippet lang="java" :
6391 * // iterative implementation of the factorial function as a loop handle
6392 * static int one(int k) { return 1; }
6393 * static int inc(int i, int acc, int k) { return i + 1; }
6394 * static int mult(int i, int acc, int k) { return i * acc; }
6395 * static boolean pred(int i, int acc, int k) { return i < k; }
6396 * static int fin(int i, int acc, int k) { return acc; }
6397 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6398 * // null initializer for counter, should initialize to 0
6399 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6400 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6401 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6402 * assertEquals(120, loop.invoke(5));
6403 * }
6404 * The same example, dropping arguments and using combinators:
6405 * {@snippet lang="java" :
6406 * // simplified implementation of the factorial function as a loop handle
6407 * static int inc(int i) { return i + 1; } // drop acc, k
6408 * static int mult(int i, int acc) { return i * acc; } //drop k
6409 * static boolean cmp(int i, int k) { return i < k; }
6410 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6411 * // null initializer for counter, should initialize to 0
6412 * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6413 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6414 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6415 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6416 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6417 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6418 * assertEquals(720, loop.invoke(6));
6419 * }
6420 * A similar example, using a helper object to hold a loop parameter:
6421 * {@snippet lang="java" :
6422 * // instance-based implementation of the factorial function as a loop handle
6423 * static class FacLoop {
6424 * final int k;
6425 * FacLoop(int k) { this.k = k; }
6426 * int inc(int i) { return i + 1; }
6427 * int mult(int i, int acc) { return i * acc; }
6428 * boolean pred(int i) { return i < k; }
6429 * int fin(int i, int acc) { return acc; }
6430 * }
6431 * // assume MH_FacLoop is a handle to the constructor
6432 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6433 * // null initializer for counter, should initialize to 0
6434 * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6435 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6436 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6437 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6438 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6439 * assertEquals(5040, loop.invoke(7));
6440 * }
6441 *
6442 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6443 *
6444 * @return a method handle embodying the looping behavior as defined by the arguments.
6445 *
6446 * @throws IllegalArgumentException in case any of the constraints described above is violated.
6447 *
6448 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6449 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6450 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6451 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6452 * @since 9
6453 */
6454 public static MethodHandle loop(MethodHandle[]... clauses) {
6455 // Step 0: determine clause structure.
6456 loopChecks0(clauses);
6457
6458 List<MethodHandle> init = new ArrayList<>();
6459 List<MethodHandle> step = new ArrayList<>();
6460 List<MethodHandle> pred = new ArrayList<>();
6461 List<MethodHandle> fini = new ArrayList<>();
6462
6463 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6464 init.add(clause[0]); // all clauses have at least length 1
6465 step.add(clause.length <= 1 ? null : clause[1]);
6466 pred.add(clause.length <= 2 ? null : clause[2]);
6467 fini.add(clause.length <= 3 ? null : clause[3]);
6468 });
6469
6470 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6471 final int nclauses = init.size();
6472
6473 // Step 1A: determine iteration variables (V...).
6474 final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6475 for (int i = 0; i < nclauses; ++i) {
6476 MethodHandle in = init.get(i);
6477 MethodHandle st = step.get(i);
6478 if (in == null && st == null) {
6479 iterationVariableTypes.add(void.class);
6480 } else if (in != null && st != null) {
6481 loopChecks1a(i, in, st);
6482 iterationVariableTypes.add(in.type().returnType());
6483 } else {
6484 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6485 }
6486 }
6487 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6488
6489 // Step 1B: determine loop parameters (A...).
6490 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6491 loopChecks1b(init, commonSuffix);
6492
6493 // Step 1C: determine loop return type.
6494 // Step 1D: check other types.
6495 // local variable required here; see JDK-8223553
6496 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6497 .map(MethodType::returnType);
6498 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6499 loopChecks1cd(pred, fini, loopReturnType);
6500
6501 // Step 2: determine parameter lists.
6502 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6503 commonParameterSequence.addAll(commonSuffix);
6504 loopChecks2(step, pred, fini, commonParameterSequence);
6505 // Step 3: fill in omitted functions.
6506 for (int i = 0; i < nclauses; ++i) {
6507 Class<?> t = iterationVariableTypes.get(i);
6508 if (init.get(i) == null) {
6509 init.set(i, empty(methodType(t, commonSuffix)));
6510 }
6511 if (step.get(i) == null) {
6512 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6513 }
6514 if (pred.get(i) == null) {
6515 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6516 }
6517 if (fini.get(i) == null) {
6518 fini.set(i, empty(methodType(t, commonParameterSequence)));
6519 }
6520 }
6521
6522 // Step 4: fill in missing parameter types.
6523 // Also convert all handles to fixed-arity handles.
6524 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6525 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6526 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6527 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6528
6529 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6530 allMatch(pl -> pl.equals(commonSuffix));
6531 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6532 allMatch(pl -> pl.equals(commonParameterSequence));
6533
6534 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6535 }
6536
6537 private static void loopChecks0(MethodHandle[][] clauses) {
6538 if (clauses == null || clauses.length == 0) {
6539 throw newIllegalArgumentException("null or no clauses passed");
6540 }
6541 if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6542 throw newIllegalArgumentException("null clauses are not allowed");
6543 }
6544 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6545 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6546 }
6547 }
6548
6549 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6550 if (in.type().returnType() != st.type().returnType()) {
6551 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6552 st.type().returnType());
6553 }
6554 }
6555
6556 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6557 return mhs.filter(Objects::nonNull)
6558 // take only those that can contribute to a common suffix because they are longer than the prefix
6559 .map(MethodHandle::type)
6560 .filter(t -> t.parameterCount() > skipSize)
6561 .max(Comparator.comparingInt(MethodType::parameterCount))
6562 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6563 .orElse(List.of());
6564 }
6565
6566 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6567 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6568 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6569 return longest1.size() >= longest2.size() ? longest1 : longest2;
6570 }
6571
6572 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6573 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6574 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6575 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6576 " (common suffix: " + commonSuffix + ")");
6577 }
6578 }
6579
6580 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6581 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6582 anyMatch(t -> t != loopReturnType)) {
6583 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6584 loopReturnType + ")");
6585 }
6586
6587 if (pred.stream().noneMatch(Objects::nonNull)) {
6588 throw newIllegalArgumentException("no predicate found", pred);
6589 }
6590 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6591 anyMatch(t -> t != boolean.class)) {
6592 throw newIllegalArgumentException("predicates must have boolean return type", pred);
6593 }
6594 }
6595
6596 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6597 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6598 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6599 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6600 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6601 }
6602 }
6603
6604 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6605 return hs.stream().map(h -> {
6606 int pc = h.type().parameterCount();
6607 int tpsize = targetParams.size();
6608 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6609 }).toList();
6610 }
6611
6612 private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6613 return hs.stream().map(MethodHandle::asFixedArity).toList();
6614 }
6615
6616 /**
6617 * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6618 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6619 * <p>
6620 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6621 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6622 * evaluates to {@code true}).
6623 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6624 * <p>
6625 * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6626 * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6627 * and updated with the value returned from its invocation. The result of loop execution will be
6628 * the final value of the additional loop-local variable (if present).
6629 * <p>
6630 * The following rules hold for these argument handles:<ul>
6631 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6632 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6633 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6634 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6635 * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6636 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6637 * It will constrain the parameter lists of the other loop parts.
6638 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6639 * list {@code (A...)} is called the <em>external parameter list</em>.
6640 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6641 * additional state variable of the loop.
6642 * The body must both accept and return a value of this type {@code V}.
6643 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6644 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6645 * <a href="MethodHandles.html#effid">effectively identical</a>
6646 * to the external parameter list {@code (A...)}.
6647 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6648 * {@linkplain #empty default value}.
6649 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type.
6650 * Its parameter list (either empty or of the form {@code (V A*)}) must be
6651 * effectively identical to the internal parameter list.
6652 * </ul>
6653 * <p>
6654 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6655 * <li>The loop handle's result type is the result type {@code V} of the body.
6656 * <li>The loop handle's parameter types are the types {@code (A...)},
6657 * from the external parameter list.
6658 * </ul>
6659 * <p>
6660 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6661 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6662 * passed to the loop.
6663 * {@snippet lang="java" :
6664 * V init(A...);
6665 * boolean pred(V, A...);
6666 * V body(V, A...);
6667 * V whileLoop(A... a...) {
6668 * V v = init(a...);
6669 * while (pred(v, a...)) {
6670 * v = body(v, a...);
6671 * }
6672 * return v;
6673 * }
6674 * }
6675 *
6676 * @apiNote Example:
6677 * {@snippet lang="java" :
6678 * // implement the zip function for lists as a loop handle
6679 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6680 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6681 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6682 * zip.add(a.next());
6683 * zip.add(b.next());
6684 * return zip;
6685 * }
6686 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6687 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6688 * List<String> a = Arrays.asList("a", "b", "c", "d");
6689 * List<String> b = Arrays.asList("e", "f", "g", "h");
6690 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6691 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6692 * }
6693 *
6694 *
6695 * @apiNote The implementation of this method can be expressed as follows:
6696 * {@snippet lang="java" :
6697 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6698 * MethodHandle fini = (body.type().returnType() == void.class
6699 * ? null : identity(body.type().returnType()));
6700 * MethodHandle[]
6701 * checkExit = { null, null, pred, fini },
6702 * varBody = { init, body };
6703 * return loop(checkExit, varBody);
6704 * }
6705 * }
6706 *
6707 * @param init optional initializer, providing the initial value of the loop variable.
6708 * May be {@code null}, implying a default initial value. See above for other constraints.
6709 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6710 * above for other constraints.
6711 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6712 * See above for other constraints.
6713 *
6714 * @return a method handle implementing the {@code while} loop as described by the arguments.
6715 * @throws IllegalArgumentException if the rules for the arguments are violated.
6716 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6717 *
6718 * @see #loop(MethodHandle[][])
6719 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6720 * @since 9
6721 */
6722 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6723 whileLoopChecks(init, pred, body);
6724 MethodHandle fini = identityOrVoid(body.type().returnType());
6725 MethodHandle[] checkExit = { null, null, pred, fini };
6726 MethodHandle[] varBody = { init, body };
6727 return loop(checkExit, varBody);
6728 }
6729
6730 /**
6731 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6732 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6733 * <p>
6734 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6735 * method will, in each iteration, first execute its body and then evaluate the predicate.
6736 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6737 * <p>
6738 * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6739 * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6740 * and updated with the value returned from its invocation. The result of loop execution will be
6741 * the final value of the additional loop-local variable (if present).
6742 * <p>
6743 * The following rules hold for these argument handles:<ul>
6744 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6745 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6746 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6747 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6748 * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6749 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6750 * It will constrain the parameter lists of the other loop parts.
6751 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6752 * list {@code (A...)} is called the <em>external parameter list</em>.
6753 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6754 * additional state variable of the loop.
6755 * The body must both accept and return a value of this type {@code V}.
6756 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6757 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6758 * <a href="MethodHandles.html#effid">effectively identical</a>
6759 * to the external parameter list {@code (A...)}.
6760 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6761 * {@linkplain #empty default value}.
6762 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type.
6763 * Its parameter list (either empty or of the form {@code (V A*)}) must be
6764 * effectively identical to the internal parameter list.
6765 * </ul>
6766 * <p>
6767 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6768 * <li>The loop handle's result type is the result type {@code V} of the body.
6769 * <li>The loop handle's parameter types are the types {@code (A...)},
6770 * from the external parameter list.
6771 * </ul>
6772 * <p>
6773 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6774 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6775 * passed to the loop.
6776 * {@snippet lang="java" :
6777 * V init(A...);
6778 * boolean pred(V, A...);
6779 * V body(V, A...);
6780 * V doWhileLoop(A... a...) {
6781 * V v = init(a...);
6782 * do {
6783 * v = body(v, a...);
6784 * } while (pred(v, a...));
6785 * return v;
6786 * }
6787 * }
6788 *
6789 * @apiNote Example:
6790 * {@snippet lang="java" :
6791 * // int i = 0; while (i < limit) { ++i; } return i; => limit
6792 * static int zero(int limit) { return 0; }
6793 * static int step(int i, int limit) { return i + 1; }
6794 * static boolean pred(int i, int limit) { return i < limit; }
6795 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6796 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6797 * assertEquals(23, loop.invoke(23));
6798 * }
6799 *
6800 *
6801 * @apiNote The implementation of this method can be expressed as follows:
6802 * {@snippet lang="java" :
6803 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6804 * MethodHandle fini = (body.type().returnType() == void.class
6805 * ? null : identity(body.type().returnType()));
6806 * MethodHandle[] clause = { init, body, pred, fini };
6807 * return loop(clause);
6808 * }
6809 * }
6810 *
6811 * @param init optional initializer, providing the initial value of the loop variable.
6812 * May be {@code null}, implying a default initial value. See above for other constraints.
6813 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6814 * See above for other constraints.
6815 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6816 * above for other constraints.
6817 *
6818 * @return a method handle implementing the {@code while} loop as described by the arguments.
6819 * @throws IllegalArgumentException if the rules for the arguments are violated.
6820 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6821 *
6822 * @see #loop(MethodHandle[][])
6823 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
6824 * @since 9
6825 */
6826 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6827 whileLoopChecks(init, pred, body);
6828 MethodHandle fini = identityOrVoid(body.type().returnType());
6829 MethodHandle[] clause = {init, body, pred, fini };
6830 return loop(clause);
6831 }
6832
6833 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
6834 Objects.requireNonNull(pred);
6835 Objects.requireNonNull(body);
6836 MethodType bodyType = body.type();
6837 Class<?> returnType = bodyType.returnType();
6838 List<Class<?>> innerList = bodyType.parameterList();
6839 List<Class<?>> outerList = innerList;
6840 if (returnType == void.class) {
6841 // OK
6842 } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
6843 // leading V argument missing => error
6844 MethodType expected = bodyType.insertParameterTypes(0, returnType);
6845 throw misMatchedTypes("body function", bodyType, expected);
6846 } else {
6847 outerList = innerList.subList(1, innerList.size());
6848 }
6849 MethodType predType = pred.type();
6850 if (predType.returnType() != boolean.class ||
6851 !predType.effectivelyIdenticalParameters(0, innerList)) {
6852 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
6853 }
6854 if (init != null) {
6855 MethodType initType = init.type();
6856 if (initType.returnType() != returnType ||
6857 !initType.effectivelyIdenticalParameters(0, outerList)) {
6858 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
6859 }
6860 }
6861 }
6862
6863 /**
6864 * Constructs a loop that runs a given number of iterations.
6865 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6866 * <p>
6867 * The number of iterations is determined by the {@code iterations} handle evaluation result.
6868 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
6869 * It will be initialized to 0 and incremented by 1 in each iteration.
6870 * <p>
6871 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6872 * of that type is also present. This variable is initialized using the optional {@code init} handle,
6873 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6874 * <p>
6875 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6876 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6877 * iteration variable.
6878 * The result of the loop handle execution will be the final {@code V} value of that variable
6879 * (or {@code void} if there is no {@code V} variable).
6880 * <p>
6881 * The following rules hold for the argument handles:<ul>
6882 * <li>The {@code iterations} handle must not be {@code null}, and must return
6883 * the type {@code int}, referred to here as {@code I} in parameter type lists.
6884 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6885 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
6886 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6887 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
6888 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
6889 * <li>The parameter list {@code (V I A...)} of the body contributes to a list
6890 * of types called the <em>internal parameter list</em>.
6891 * It will constrain the parameter lists of the other loop parts.
6892 * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
6893 * with no additional {@code A} types, then the internal parameter list is extended by
6894 * the argument types {@code A...} of the {@code iterations} handle.
6895 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
6896 * list {@code (A...)} is called the <em>external parameter list</em>.
6897 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6898 * additional state variable of the loop.
6899 * The body must both accept a leading parameter and return a value of this type {@code V}.
6900 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6901 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6902 * <a href="MethodHandles.html#effid">effectively identical</a>
6903 * to the external parameter list {@code (A...)}.
6904 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6905 * {@linkplain #empty default value}.
6906 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
6907 * effectively identical to the external parameter list {@code (A...)}.
6908 * </ul>
6909 * <p>
6910 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6911 * <li>The loop handle's result type is the result type {@code V} of the body.
6912 * <li>The loop handle's parameter types are the types {@code (A...)},
6913 * from the external parameter list.
6914 * </ul>
6915 * <p>
6916 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6917 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
6918 * arguments passed to the loop.
6919 * {@snippet lang="java" :
6920 * int iterations(A...);
6921 * V init(A...);
6922 * V body(V, int, A...);
6923 * V countedLoop(A... a...) {
6924 * int end = iterations(a...);
6925 * V v = init(a...);
6926 * for (int i = 0; i < end; ++i) {
6927 * v = body(v, i, a...);
6928 * }
6929 * return v;
6930 * }
6931 * }
6932 *
6933 * @apiNote Example with a fully conformant body method:
6934 * {@snippet lang="java" :
6935 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6936 * // => a variation on a well known theme
6937 * static String step(String v, int counter, String init) { return "na " + v; }
6938 * // assume MH_step is a handle to the method above
6939 * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
6940 * MethodHandle start = MethodHandles.identity(String.class);
6941 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
6942 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
6943 * }
6944 *
6945 * @apiNote Example with the simplest possible body method type,
6946 * and passing the number of iterations to the loop invocation:
6947 * {@snippet lang="java" :
6948 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6949 * // => a variation on a well known theme
6950 * static String step(String v, int counter ) { return "na " + v; }
6951 * // assume MH_step is a handle to the method above
6952 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
6953 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
6954 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v
6955 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
6956 * }
6957 *
6958 * @apiNote Example that treats the number of iterations, string to append to, and string to append
6959 * as loop parameters:
6960 * {@snippet lang="java" :
6961 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6962 * // => a variation on a well known theme
6963 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
6964 * // assume MH_step is a handle to the method above
6965 * MethodHandle count = MethodHandles.identity(int.class);
6966 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
6967 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v
6968 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
6969 * }
6970 *
6971 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
6972 * to enforce a loop type:
6973 * {@snippet lang="java" :
6974 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6975 * // => a variation on a well known theme
6976 * static String step(String v, int counter, String pre) { return pre + " " + v; }
6977 * // assume MH_step is a handle to the method above
6978 * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
6979 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1);
6980 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
6981 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0);
6982 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v
6983 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
6984 * }
6985 *
6986 * @apiNote The implementation of this method can be expressed as follows:
6987 * {@snippet lang="java" :
6988 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
6989 * return countedLoop(empty(iterations.type()), iterations, init, body);
6990 * }
6991 * }
6992 *
6993 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
6994 * result type must be {@code int}. See above for other constraints.
6995 * @param init optional initializer, providing the initial value of the loop variable.
6996 * May be {@code null}, implying a default initial value. See above for other constraints.
6997 * @param body body of the loop, which may not be {@code null}.
6998 * It controls the loop parameters and result type in the standard case (see above for details).
6999 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7000 * and may accept any number of additional types.
7001 * See above for other constraints.
7002 *
7003 * @return a method handle representing the loop.
7004 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7005 * @throws IllegalArgumentException if any argument violates the rules formulated above.
7006 *
7007 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7008 * @since 9
7009 */
7010 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7011 return countedLoop(empty(iterations.type()), iterations, init, body);
7012 }
7013
7014 /**
7015 * Constructs a loop that counts over a range of numbers.
7016 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7017 * <p>
7018 * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7019 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7020 * values of the loop counter.
7021 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7022 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7023 * <p>
7024 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7025 * of that type is also present. This variable is initialized using the optional {@code init} handle,
7026 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7027 * <p>
7028 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7029 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7030 * iteration variable.
7031 * The result of the loop handle execution will be the final {@code V} value of that variable
7032 * (or {@code void} if there is no {@code V} variable).
7033 * <p>
7034 * The following rules hold for the argument handles:<ul>
7035 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7036 * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7037 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7038 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7039 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7040 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7041 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7042 * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7043 * of types called the <em>internal parameter list</em>.
7044 * It will constrain the parameter lists of the other loop parts.
7045 * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7046 * with no additional {@code A} types, then the internal parameter list is extended by
7047 * the argument types {@code A...} of the {@code end} handle.
7048 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7049 * list {@code (A...)} is called the <em>external parameter list</em>.
7050 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7051 * additional state variable of the loop.
7052 * The body must both accept a leading parameter and return a value of this type {@code V}.
7053 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7054 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7055 * <a href="MethodHandles.html#effid">effectively identical</a>
7056 * to the external parameter list {@code (A...)}.
7057 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7058 * {@linkplain #empty default value}.
7059 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7060 * effectively identical to the external parameter list {@code (A...)}.
7061 * <li>Likewise, the parameter list of {@code end} must be effectively identical
7062 * to the external parameter list.
7063 * </ul>
7064 * <p>
7065 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7066 * <li>The loop handle's result type is the result type {@code V} of the body.
7067 * <li>The loop handle's parameter types are the types {@code (A...)},
7068 * from the external parameter list.
7069 * </ul>
7070 * <p>
7071 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7072 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7073 * arguments passed to the loop.
7074 * {@snippet lang="java" :
7075 * int start(A...);
7076 * int end(A...);
7077 * V init(A...);
7078 * V body(V, int, A...);
7079 * V countedLoop(A... a...) {
7080 * int e = end(a...);
7081 * int s = start(a...);
7082 * V v = init(a...);
7083 * for (int i = s; i < e; ++i) {
7084 * v = body(v, i, a...);
7085 * }
7086 * return v;
7087 * }
7088 * }
7089 *
7090 * @apiNote The implementation of this method can be expressed as follows:
7091 * {@snippet lang="java" :
7092 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7093 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7094 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7095 * // the following semantics:
7096 * // MH_increment: (int limit, int counter) -> counter + 1
7097 * // MH_predicate: (int limit, int counter) -> counter < limit
7098 * Class<?> counterType = start.type().returnType(); // int
7099 * Class<?> returnType = body.type().returnType();
7100 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7101 * if (returnType != void.class) { // ignore the V variable
7102 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i)
7103 * pred = dropArguments(pred, 1, returnType); // ditto
7104 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7105 * }
7106 * body = dropArguments(body, 0, counterType); // ignore the limit variable
7107 * MethodHandle[]
7108 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v
7109 * bodyClause = { init, body }, // v = init(); v = body(v, i)
7110 * indexVar = { start, incr }; // i = start(); i = i + 1
7111 * return loop(loopLimit, bodyClause, indexVar);
7112 * }
7113 * }
7114 *
7115 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7116 * See above for other constraints.
7117 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7118 * {@code end-1}). The result type must be {@code int}. See above for other constraints.
7119 * @param init optional initializer, providing the initial value of the loop variable.
7120 * May be {@code null}, implying a default initial value. See above for other constraints.
7121 * @param body body of the loop, which may not be {@code null}.
7122 * It controls the loop parameters and result type in the standard case (see above for details).
7123 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7124 * and may accept any number of additional types.
7125 * See above for other constraints.
7126 *
7127 * @return a method handle representing the loop.
7128 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7129 * @throws IllegalArgumentException if any argument violates the rules formulated above.
7130 *
7131 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7132 * @since 9
7133 */
7134 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7135 countedLoopChecks(start, end, init, body);
7136 Class<?> counterType = start.type().returnType(); // int, but who's counting?
7137 Class<?> limitType = end.type().returnType(); // yes, int again
7138 Class<?> returnType = body.type().returnType();
7139 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7140 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7141 MethodHandle retv = null;
7142 if (returnType != void.class) {
7143 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i)
7144 pred = dropArguments(pred, 1, returnType); // ditto
7145 retv = dropArguments(identity(returnType), 0, counterType);
7146 }
7147 body = dropArguments(body, 0, counterType); // ignore the limit variable
7148 MethodHandle[]
7149 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v
7150 bodyClause = { init, body }, // v = init(); v = body(v, i)
7151 indexVar = { start, incr }; // i = start(); i = i + 1
7152 return loop(loopLimit, bodyClause, indexVar);
7153 }
7154
7155 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7156 Objects.requireNonNull(start);
7157 Objects.requireNonNull(end);
7158 Objects.requireNonNull(body);
7159 Class<?> counterType = start.type().returnType();
7160 if (counterType != int.class) {
7161 MethodType expected = start.type().changeReturnType(int.class);
7162 throw misMatchedTypes("start function", start.type(), expected);
7163 } else if (end.type().returnType() != counterType) {
7164 MethodType expected = end.type().changeReturnType(counterType);
7165 throw misMatchedTypes("end function", end.type(), expected);
7166 }
7167 MethodType bodyType = body.type();
7168 Class<?> returnType = bodyType.returnType();
7169 List<Class<?>> innerList = bodyType.parameterList();
7170 // strip leading V value if present
7171 int vsize = (returnType == void.class ? 0 : 1);
7172 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7173 // argument list has no "V" => error
7174 MethodType expected = bodyType.insertParameterTypes(0, returnType);
7175 throw misMatchedTypes("body function", bodyType, expected);
7176 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7177 // missing I type => error
7178 MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7179 throw misMatchedTypes("body function", bodyType, expected);
7180 }
7181 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7182 if (outerList.isEmpty()) {
7183 // special case; take lists from end handle
7184 outerList = end.type().parameterList();
7185 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7186 }
7187 MethodType expected = methodType(counterType, outerList);
7188 if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7189 throw misMatchedTypes("start parameter types", start.type(), expected);
7190 }
7191 if (end.type() != start.type() &&
7192 !end.type().effectivelyIdenticalParameters(0, outerList)) {
7193 throw misMatchedTypes("end parameter types", end.type(), expected);
7194 }
7195 if (init != null) {
7196 MethodType initType = init.type();
7197 if (initType.returnType() != returnType ||
7198 !initType.effectivelyIdenticalParameters(0, outerList)) {
7199 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7200 }
7201 }
7202 }
7203
7204 /**
7205 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7206 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7207 * <p>
7208 * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7209 * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7210 * <p>
7211 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7212 * of that type is also present. This variable is initialized using the optional {@code init} handle,
7213 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7214 * <p>
7215 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7216 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7217 * iteration variable.
7218 * The result of the loop handle execution will be the final {@code V} value of that variable
7219 * (or {@code void} if there is no {@code V} variable).
7220 * <p>
7221 * The following rules hold for the argument handles:<ul>
7222 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7223 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7224 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7225 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7226 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7227 * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7228 * of types called the <em>internal parameter list</em>.
7229 * It will constrain the parameter lists of the other loop parts.
7230 * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7231 * with no additional {@code A} types, then the internal parameter list is extended by
7232 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7233 * single type {@code Iterable} is added and constitutes the {@code A...} list.
7234 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7235 * list {@code (A...)} is called the <em>external parameter list</em>.
7236 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7237 * additional state variable of the loop.
7238 * The body must both accept a leading parameter and return a value of this type {@code V}.
7239 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7240 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7241 * <a href="MethodHandles.html#effid">effectively identical</a>
7242 * to the external parameter list {@code (A...)}.
7243 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7244 * {@linkplain #empty default value}.
7245 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7246 * type {@code java.util.Iterator} or a subtype thereof.
7247 * The iterator it produces when the loop is executed will be assumed
7248 * to yield values which can be converted to type {@code T}.
7249 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7250 * effectively identical to the external parameter list {@code (A...)}.
7251 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7252 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list
7253 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7254 * handle parameter is adjusted to accept the leading {@code A} type, as if by
7255 * the {@link MethodHandle#asType asType} conversion method.
7256 * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7257 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7258 * </ul>
7259 * <p>
7260 * The type {@code T} may be either a primitive or reference.
7261 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7262 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7263 * as if by the {@link MethodHandle#asType asType} conversion method.
7264 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7265 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7266 * <p>
7267 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7268 * <li>The loop handle's result type is the result type {@code V} of the body.
7269 * <li>The loop handle's parameter types are the types {@code (A...)},
7270 * from the external parameter list.
7271 * </ul>
7272 * <p>
7273 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7274 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7275 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7276 * {@snippet lang="java" :
7277 * Iterator<T> iterator(A...); // defaults to Iterable::iterator
7278 * V init(A...);
7279 * V body(V,T,A...);
7280 * V iteratedLoop(A... a...) {
7281 * Iterator<T> it = iterator(a...);
7282 * V v = init(a...);
7283 * while (it.hasNext()) {
7284 * T t = it.next();
7285 * v = body(v, t, a...);
7286 * }
7287 * return v;
7288 * }
7289 * }
7290 *
7291 * @apiNote Example:
7292 * {@snippet lang="java" :
7293 * // get an iterator from a list
7294 * static List<String> reverseStep(List<String> r, String e) {
7295 * r.add(0, e);
7296 * return r;
7297 * }
7298 * static List<String> newArrayList() { return new ArrayList<>(); }
7299 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7300 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7301 * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7302 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7303 * assertEquals(reversedList, (List<String>) loop.invoke(list));
7304 * }
7305 *
7306 * @apiNote The implementation of this method can be expressed approximately as follows:
7307 * {@snippet lang="java" :
7308 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7309 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7310 * Class<?> returnType = body.type().returnType();
7311 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7312 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7313 * MethodHandle retv = null, step = body, startIter = iterator;
7314 * if (returnType != void.class) {
7315 * // the simple thing first: in (I V A...), drop the I to get V
7316 * retv = dropArguments(identity(returnType), 0, Iterator.class);
7317 * // body type signature (V T A...), internal loop types (I V A...)
7318 * step = swapArguments(body, 0, 1); // swap V <-> T
7319 * }
7320 * if (startIter == null) startIter = MH_getIter;
7321 * MethodHandle[]
7322 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7323 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a)
7324 * return loop(iterVar, bodyClause);
7325 * }
7326 * }
7327 *
7328 * @param iterator an optional handle to return the iterator to start the loop.
7329 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7330 * See above for other constraints.
7331 * @param init optional initializer, providing the initial value of the loop variable.
7332 * May be {@code null}, implying a default initial value. See above for other constraints.
7333 * @param body body of the loop, which may not be {@code null}.
7334 * It controls the loop parameters and result type in the standard case (see above for details).
7335 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7336 * and may accept any number of additional types.
7337 * See above for other constraints.
7338 *
7339 * @return a method handle embodying the iteration loop functionality.
7340 * @throws NullPointerException if the {@code body} handle is {@code null}.
7341 * @throws IllegalArgumentException if any argument violates the above requirements.
7342 *
7343 * @since 9
7344 */
7345 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7346 Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7347 Class<?> returnType = body.type().returnType();
7348 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7349 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7350 MethodHandle startIter;
7351 MethodHandle nextVal;
7352 {
7353 MethodType iteratorType;
7354 if (iterator == null) {
7355 // derive argument type from body, if available, else use Iterable
7356 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7357 iteratorType = startIter.type().changeParameterType(0, iterableType);
7358 } else {
7359 // force return type to the internal iterator class
7360 iteratorType = iterator.type().changeReturnType(Iterator.class);
7361 startIter = iterator;
7362 }
7363 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7364 MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7365
7366 // perform the asType transforms under an exception transformer, as per spec.:
7367 try {
7368 startIter = startIter.asType(iteratorType);
7369 nextVal = nextRaw.asType(nextValType);
7370 } catch (WrongMethodTypeException ex) {
7371 throw new IllegalArgumentException(ex);
7372 }
7373 }
7374
7375 MethodHandle retv = null, step = body;
7376 if (returnType != void.class) {
7377 // the simple thing first: in (I V A...), drop the I to get V
7378 retv = dropArguments(identity(returnType), 0, Iterator.class);
7379 // body type signature (V T A...), internal loop types (I V A...)
7380 step = swapArguments(body, 0, 1); // swap V <-> T
7381 }
7382
7383 MethodHandle[]
7384 iterVar = { startIter, null, hasNext, retv },
7385 bodyClause = { init, filterArgument(step, 0, nextVal) };
7386 return loop(iterVar, bodyClause);
7387 }
7388
7389 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7390 Objects.requireNonNull(body);
7391 MethodType bodyType = body.type();
7392 Class<?> returnType = bodyType.returnType();
7393 List<Class<?>> internalParamList = bodyType.parameterList();
7394 // strip leading V value if present
7395 int vsize = (returnType == void.class ? 0 : 1);
7396 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7397 // argument list has no "V" => error
7398 MethodType expected = bodyType.insertParameterTypes(0, returnType);
7399 throw misMatchedTypes("body function", bodyType, expected);
7400 } else if (internalParamList.size() <= vsize) {
7401 // missing T type => error
7402 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7403 throw misMatchedTypes("body function", bodyType, expected);
7404 }
7405 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7406 Class<?> iterableType = null;
7407 if (iterator != null) {
7408 // special case; if the body handle only declares V and T then
7409 // the external parameter list is obtained from iterator handle
7410 if (externalParamList.isEmpty()) {
7411 externalParamList = iterator.type().parameterList();
7412 }
7413 MethodType itype = iterator.type();
7414 if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7415 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7416 }
7417 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7418 MethodType expected = methodType(itype.returnType(), externalParamList);
7419 throw misMatchedTypes("iterator parameters", itype, expected);
7420 }
7421 } else {
7422 if (externalParamList.isEmpty()) {
7423 // special case; if the iterator handle is null and the body handle
7424 // only declares V and T then the external parameter list consists
7425 // of Iterable
7426 externalParamList = List.of(Iterable.class);
7427 iterableType = Iterable.class;
7428 } else {
7429 // special case; if the iterator handle is null and the external
7430 // parameter list is not empty then the first parameter must be
7431 // assignable to Iterable
7432 iterableType = externalParamList.get(0);
7433 if (!Iterable.class.isAssignableFrom(iterableType)) {
7434 throw newIllegalArgumentException(
7435 "inferred first loop argument must inherit from Iterable: " + iterableType);
7436 }
7437 }
7438 }
7439 if (init != null) {
7440 MethodType initType = init.type();
7441 if (initType.returnType() != returnType ||
7442 !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7443 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7444 }
7445 }
7446 return iterableType; // help the caller a bit
7447 }
7448
7449 /*non-public*/
7450 static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7451 // there should be a better way to uncross my wires
7452 int arity = mh.type().parameterCount();
7453 int[] order = new int[arity];
7454 for (int k = 0; k < arity; k++) order[k] = k;
7455 order[i] = j; order[j] = i;
7456 Class<?>[] types = mh.type().parameterArray();
7457 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7458 MethodType swapType = methodType(mh.type().returnType(), types);
7459 return permuteArguments(mh, swapType, order);
7460 }
7461
7462 /**
7463 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7464 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7465 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7466 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The
7467 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7468 * {@code try-finally} handle.
7469 * <p>
7470 * The {@code cleanup} handle will be passed one or two additional leading arguments.
7471 * The first is the exception thrown during the
7472 * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7473 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7474 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7475 * The second argument is not present if the {@code target} handle has a {@code void} return type.
7476 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7477 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7478 * <p>
7479 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7480 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7481 * two extra leading parameters:<ul>
7482 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7483 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7484 * the result from the execution of the {@code target} handle.
7485 * This parameter is not present if the {@code target} returns {@code void}.
7486 * </ul>
7487 * <p>
7488 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7489 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7490 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7491 * the cleanup.
7492 * {@snippet lang="java" :
7493 * V target(A..., B...);
7494 * V cleanup(Throwable, V, A...);
7495 * V adapter(A... a, B... b) {
7496 * V result = (zero value for V);
7497 * Throwable throwable = null;
7498 * try {
7499 * result = target(a..., b...);
7500 * } catch (Throwable t) {
7501 * throwable = t;
7502 * throw t;
7503 * } finally {
7504 * result = cleanup(throwable, result, a...);
7505 * }
7506 * return result;
7507 * }
7508 * }
7509 * <p>
7510 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7511 * be modified by execution of the target, and so are passed unchanged
7512 * from the caller to the cleanup, if it is invoked.
7513 * <p>
7514 * The target and cleanup must return the same type, even if the cleanup
7515 * always throws.
7516 * To create such a throwing cleanup, compose the cleanup logic
7517 * with {@link #throwException throwException},
7518 * in order to create a method handle of the correct return type.
7519 * <p>
7520 * Note that {@code tryFinally} never converts exceptions into normal returns.
7521 * In rare cases where exceptions must be converted in that way, first wrap
7522 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7523 * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7524 * <p>
7525 * It is recommended that the first parameter type of {@code cleanup} be
7526 * declared {@code Throwable} rather than a narrower subtype. This ensures
7527 * {@code cleanup} will always be invoked with whatever exception that
7528 * {@code target} throws. Declaring a narrower type may result in a
7529 * {@code ClassCastException} being thrown by the {@code try-finally}
7530 * handle if the type of the exception thrown by {@code target} is not
7531 * assignable to the first parameter type of {@code cleanup}. Note that
7532 * various exception types of {@code VirtualMachineError},
7533 * {@code LinkageError}, and {@code RuntimeException} can in principle be
7534 * thrown by almost any kind of Java code, and a finally clause that
7535 * catches (say) only {@code IOException} would mask any of the others
7536 * behind a {@code ClassCastException}.
7537 *
7538 * @param target the handle whose execution is to be wrapped in a {@code try} block.
7539 * @param cleanup the handle that is invoked in the finally block.
7540 *
7541 * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7542 * @throws NullPointerException if any argument is null
7543 * @throws IllegalArgumentException if {@code cleanup} does not accept
7544 * the required leading arguments, or if the method handle types do
7545 * not match in their return types and their
7546 * corresponding trailing parameters
7547 *
7548 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7549 * @since 9
7550 */
7551 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7552 Class<?>[] targetParamTypes = target.type().ptypes();
7553 Class<?> rtype = target.type().returnType();
7554
7555 tryFinallyChecks(target, cleanup);
7556
7557 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7558 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7559 // target parameter list.
7560 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7561
7562 // Ensure that the intrinsic type checks the instance thrown by the
7563 // target against the first parameter of cleanup
7564 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7565
7566 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7567 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7568 }
7569
7570 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7571 Class<?> rtype = target.type().returnType();
7572 if (rtype != cleanup.type().returnType()) {
7573 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7574 }
7575 MethodType cleanupType = cleanup.type();
7576 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7577 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7578 }
7579 if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7580 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7581 }
7582 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7583 // target parameter list.
7584 int cleanupArgIndex = rtype == void.class ? 1 : 2;
7585 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7586 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7587 cleanup.type(), target.type());
7588 }
7589 }
7590
7591 /**
7592 * Creates a table switch method handle, which can be used to switch over a set of target
7593 * method handles, based on a given target index, called selector.
7594 * <p>
7595 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7596 * and where {@code N} is the number of target method handles, the table switch method
7597 * handle will invoke the n-th target method handle from the list of target method handles.
7598 * <p>
7599 * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7600 * method handle will invoke the given fallback method handle.
7601 * <p>
7602 * All method handles passed to this method must have the same type, with the additional
7603 * requirement that the leading parameter be of type {@code int}. The leading parameter
7604 * represents the selector.
7605 * <p>
7606 * Any trailing parameters present in the type will appear on the returned table switch
7607 * method handle as well. Any arguments assigned to these parameters will be forwarded,
7608 * together with the selector value, to the selected method handle when invoking it.
7609 *
7610 * @apiNote Example:
7611 * The cases each drop the {@code selector} value they are given, and take an additional
7612 * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7613 * to a specific constant label string for each case:
7614 * {@snippet lang="java" :
7615 * MethodHandles.Lookup lookup = MethodHandles.lookup();
7616 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7617 * MethodType.methodType(String.class, String.class));
7618 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7619 *
7620 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7621 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7622 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7623 *
7624 * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7625 * caseDefault,
7626 * case0,
7627 * case1
7628 * );
7629 *
7630 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7631 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7632 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7633 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7634 * }
7635 *
7636 * @param fallback the fallback method handle that is called when the selector is not
7637 * within the range {@code [0, N)}.
7638 * @param targets array of target method handles.
7639 * @return the table switch method handle.
7640 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7641 * any of the elements of the {@code targets} array are
7642 * {@code null}.
7643 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7644 * parameter of the fallback handle or any of the target
7645 * handles is not {@code int}, or if the types of
7646 * the fallback handle and all of target handles are
7647 * not the same.
7648 *
7649 * @since 17
7650 */
7651 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7652 Objects.requireNonNull(fallback);
7653 Objects.requireNonNull(targets);
7654 targets = targets.clone();
7655 MethodType type = tableSwitchChecks(fallback, targets);
7656 return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7657 }
7658
7659 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7660 if (caseActions.length == 0)
7661 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7662
7663 MethodType expectedType = defaultCase.type();
7664
7665 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7666 throw new IllegalArgumentException(
7667 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7668
7669 for (MethodHandle mh : caseActions) {
7670 Objects.requireNonNull(mh);
7671 if (mh.type() != expectedType)
7672 throw new IllegalArgumentException(
7673 "Case actions must have the same type: " + Arrays.toString(caseActions));
7674 }
7675
7676 return expectedType;
7677 }
7678
7679 /**
7680 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7681 * <p>
7682 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7683 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
7684 * to the target var handle.
7685 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
7686 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
7687 * is processed using the second filter and returned to the caller. More advanced access mode types, such as
7688 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
7689 * <p>
7690 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
7691 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
7692 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
7693 * will be appended to the coordinates of the target var handle).
7694 * <p>
7695 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
7696 * throw an {@link IllegalStateException}.
7697 * <p>
7698 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7699 * atomic access guarantees as those featured by the target var handle.
7700 *
7701 * @param target the target var handle
7702 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
7703 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
7704 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
7705 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
7706 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
7707 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
7708 * @throws NullPointerException if any of the arguments is {@code null}.
7709 * @since 22
7710 */
7711 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
7712 return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
7713 }
7714
7715 /**
7716 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
7717 * <p>
7718 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
7719 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
7720 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
7721 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
7722 * by the adaptation) to the target var handle.
7723 * <p>
7724 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
7725 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
7726 * <p>
7727 * If any of the filters throws a checked exception when invoked, the resulting var handle will
7728 * throw an {@link IllegalStateException}.
7729 * <p>
7730 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7731 * atomic access guarantees as those featured by the target var handle.
7732 *
7733 * @param target the target var handle
7734 * @param pos the position of the first coordinate to be transformed
7735 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
7736 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
7737 * to the new coordinate values.
7738 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
7739 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
7740 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7741 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
7742 * or if it's determined that any of the filters throws any checked exceptions.
7743 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
7744 * @since 22
7745 */
7746 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
7747 return VarHandles.filterCoordinates(target, pos, filters);
7748 }
7749
7750 /**
7751 * Provides a target var handle with one or more <em>bound coordinates</em>
7752 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
7753 * coordinate types than the target var handle.
7754 * <p>
7755 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
7756 * are joined with bound coordinate values, and then passed to the target var handle.
7757 * <p>
7758 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
7759 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
7760 * <p>
7761 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7762 * atomic access guarantees as those featured by the target var handle.
7763 *
7764 * @param target the var handle to invoke after the bound coordinates are inserted
7765 * @param pos the position of the first coordinate to be inserted
7766 * @param values the series of bound coordinates to insert
7767 * @return an adapter var handle which inserts additional coordinates,
7768 * before calling the target var handle
7769 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7770 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
7771 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
7772 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
7773 * of the target var handle.
7774 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
7775 * @since 22
7776 */
7777 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
7778 return VarHandles.insertCoordinates(target, pos, values);
7779 }
7780
7781 /**
7782 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
7783 * so that the new coordinates match the provided ones.
7784 * <p>
7785 * The given array controls the reordering.
7786 * Call {@code #I} the number of incoming coordinates (the value
7787 * {@code newCoordinates.size()}), and call {@code #O} the number
7788 * of outgoing coordinates (the number of coordinates associated with the target var handle).
7789 * Then the length of the reordering array must be {@code #O},
7790 * and each element must be a non-negative number less than {@code #I}.
7791 * For every {@code N} less than {@code #O}, the {@code N}-th
7792 * outgoing coordinate will be taken from the {@code I}-th incoming
7793 * coordinate, where {@code I} is {@code reorder[N]}.
7794 * <p>
7795 * No coordinate value conversions are applied.
7796 * The type of each incoming coordinate, as determined by {@code newCoordinates},
7797 * must be identical to the type of the corresponding outgoing coordinate
7798 * in the target var handle.
7799 * <p>
7800 * The reordering array need not specify an actual permutation.
7801 * An incoming coordinate will be duplicated if its index appears
7802 * more than once in the array, and an incoming coordinate will be dropped
7803 * if its index does not appear in the array.
7804 * <p>
7805 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7806 * atomic access guarantees as those featured by the target var handle.
7807 * @param target the var handle to invoke after the coordinates have been reordered
7808 * @param newCoordinates the new coordinate types
7809 * @param reorder an index array which controls the reordering
7810 * @return an adapter var handle which re-arranges the incoming coordinate values,
7811 * before calling the target var handle
7812 * @throws IllegalArgumentException if the index array length is not equal to
7813 * the number of coordinates of the target var handle, or if any index array element is not a valid index for
7814 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
7815 * the target var handle and in {@code newCoordinates} are not identical.
7816 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
7817 * @since 22
7818 */
7819 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
7820 return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
7821 }
7822
7823 /**
7824 * Adapts a target var handle by pre-processing
7825 * a sub-sequence of its coordinate values with a filter (a method handle).
7826 * The pre-processed coordinates are replaced by the result (if any) of the
7827 * filter function and the target var handle is then called on the modified (usually shortened)
7828 * coordinate list.
7829 * <p>
7830 * If {@code R} is the return type of the filter, then:
7831 * <ul>
7832 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
7833 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
7834 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
7835 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
7836 * target var handle.</li>
7837 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
7838 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
7839 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
7840 * downstream invocation of the target var handle.</li>
7841 * </ul>
7842 * <p>
7843 * If any of the filters throws a checked exception when invoked, the resulting var handle will
7844 * throw an {@link IllegalStateException}.
7845 * <p>
7846 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7847 * atomic access guarantees as those featured by the target var handle.
7848 *
7849 * @param target the var handle to invoke after the coordinates have been filtered
7850 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
7851 * @param filter the filter method handle
7852 * @return an adapter var handle which filters the incoming coordinate values,
7853 * before calling the target var handle
7854 * @throws IllegalArgumentException if the return type of {@code filter}
7855 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
7856 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7857 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
7858 * or if it's determined that {@code filter} throws any checked exceptions.
7859 * @throws NullPointerException if any of the arguments is {@code null}.
7860 * @since 22
7861 */
7862 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
7863 return VarHandles.collectCoordinates(target, pos, filter);
7864 }
7865
7866 /**
7867 * Returns a var handle which will discard some dummy coordinates before delegating to the
7868 * target var handle. As a consequence, the resulting var handle will feature more
7869 * coordinate types than the target var handle.
7870 * <p>
7871 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
7872 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
7873 * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
7874 * <p>
7875 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7876 * atomic access guarantees as those featured by the target var handle.
7877 *
7878 * @param target the var handle to invoke after the dummy coordinates are dropped
7879 * @param pos position of the first coordinate to drop (zero for the leftmost)
7880 * @param valueTypes the type(s) of the coordinate(s) to drop
7881 * @return an adapter var handle which drops some dummy coordinates,
7882 * before calling the target var handle
7883 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
7884 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
7885 * @since 22
7886 */
7887 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
7888 return VarHandles.dropCoordinates(target, pos, valueTypes);
7889 }
7890 }