1 /* 2 * Copyright (c) 2008, 2022, 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.foreign.Utils; 30 import jdk.internal.javac.PreviewFeature; 31 import jdk.internal.misc.Unsafe; 32 import jdk.internal.misc.VM; 33 import jdk.internal.org.objectweb.asm.ClassReader; 34 import jdk.internal.org.objectweb.asm.Opcodes; 35 import jdk.internal.org.objectweb.asm.Type; 36 import jdk.internal.reflect.CallerSensitive; 37 import jdk.internal.reflect.CallerSensitiveAdapter; 38 import jdk.internal.reflect.Reflection; 39 import jdk.internal.vm.annotation.ForceInline; 40 import sun.invoke.util.ValueConversions; 41 import sun.invoke.util.VerifyAccess; 42 import sun.invoke.util.Wrapper; 43 import sun.reflect.misc.ReflectUtil; 44 import sun.security.util.SecurityConstants; 45 46 import java.lang.constant.ConstantDescs; 47 import java.lang.foreign.GroupLayout; 48 import java.lang.foreign.MemoryLayout; 49 import java.lang.foreign.MemorySegment; 50 import java.lang.foreign.ValueLayout; 51 import java.lang.invoke.LambdaForm.BasicType; 52 import java.lang.reflect.Constructor; 53 import java.lang.reflect.Field; 54 import java.lang.reflect.Member; 55 import java.lang.reflect.Method; 56 import java.lang.reflect.Modifier; 57 import java.nio.ByteOrder; 58 import java.security.ProtectionDomain; 59 import java.util.ArrayList; 60 import java.util.Arrays; 61 import java.util.BitSet; 62 import java.util.Iterator; 63 import java.util.List; 64 import java.util.Objects; 65 import java.util.Set; 66 import java.util.concurrent.ConcurrentHashMap; 67 import java.util.stream.Stream; 68 69 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 70 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 71 import static java.lang.invoke.MethodHandleNatives.Constants.*; 72 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 73 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 74 import static java.lang.invoke.MethodHandleStatics.newInternalError; 75 import static java.lang.invoke.MethodType.methodType; 76 77 /** 78 * This class consists exclusively of static methods that operate on or return 79 * method handles. They fall into several categories: 80 * <ul> 81 * <li>Lookup methods which help create method handles for methods and fields. 82 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 83 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 84 * </ul> 85 * A lookup, combinator, or factory method will fail and throw an 86 * {@code IllegalArgumentException} if the created method handle's type 87 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 88 * 89 * @author John Rose, JSR 292 EG 90 * @since 1.7 91 */ 92 public class MethodHandles { 93 94 private MethodHandles() { } // do not instantiate 95 96 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 97 98 // See IMPL_LOOKUP below. 99 100 //// Method handle creation from ordinary methods. 101 102 /** 103 * Returns a {@link Lookup lookup object} with 104 * full capabilities to emulate all supported bytecode behaviors of the caller. 105 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 106 * Factory methods on the lookup object can create 107 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 108 * for any member that the caller has access to via bytecodes, 109 * including protected and private fields and methods. 110 * This lookup object is created by the original lookup class 111 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 112 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 113 * Do not store it in place where untrusted code can access it. 114 * <p> 115 * This method is caller sensitive, which means that it may return different 116 * values to different callers. 117 * In cases where {@code MethodHandles.lookup} is called from a context where 118 * there is no caller frame on the stack (e.g. when called directly 119 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 120 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 121 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 122 * to obtain a low-privileged lookup instead. 123 * @return a lookup object for the caller of this method, with 124 * {@linkplain Lookup#ORIGINAL original} and 125 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 126 * @throws IllegalCallerException if there is no caller frame on the stack. 127 */ 128 @CallerSensitive 129 @ForceInline // to ensure Reflection.getCallerClass optimization 130 public static Lookup lookup() { 131 final Class<?> c = Reflection.getCallerClass(); 132 if (c == null) { 133 throw new IllegalCallerException("no caller frame"); 134 } 135 return new Lookup(c); 136 } 137 138 /** 139 * This lookup method is the alternate implementation of 140 * the lookup method with a leading caller class argument which is 141 * non-caller-sensitive. This method is only invoked by reflection 142 * and method handle. 143 */ 144 @CallerSensitiveAdapter 145 private static Lookup lookup(Class<?> caller) { 146 if (caller.getClassLoader() == null) { 147 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 148 } 149 return new Lookup(caller); 150 } 151 152 /** 153 * Returns a {@link Lookup lookup object} which is trusted minimally. 154 * The lookup has the {@code UNCONDITIONAL} mode. 155 * It can only be used to create method handles to public members of 156 * public classes in packages that are exported unconditionally. 157 * <p> 158 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 159 * of this lookup object will be {@link java.lang.Object}. 160 * 161 * @apiNote The use of Object is conventional, and because the lookup modes are 162 * limited, there is no special access provided to the internals of Object, its package 163 * or its module. This public lookup object or other lookup object with 164 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 165 * is not used to determine the lookup context. 166 * 167 * <p style="font-size:smaller;"> 168 * <em>Discussion:</em> 169 * The lookup class can be changed to any other class {@code C} using an expression of the form 170 * {@link Lookup#in publicLookup().in(C.class)}. 171 * A public lookup object is always subject to 172 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 173 * Also, it cannot access 174 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 175 * @return a lookup object which is trusted minimally 176 * 177 * @revised 9 178 */ 179 public static Lookup publicLookup() { 180 return Lookup.PUBLIC_LOOKUP; 181 } 182 183 /** 184 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 185 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 186 * The returned lookup object can provide access to classes in modules and packages, 187 * and members of those classes, outside the normal rules of Java access control, 188 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 189 * <p> 190 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 191 * allowed to do deep reflection on module {@code M2} and package of the target class 192 * if and only if all of the following conditions are {@code true}: 193 * <ul> 194 * <li>If there is a security manager, its {@code checkPermission} method is 195 * called to check {@code ReflectPermission("suppressAccessChecks")} and 196 * that must return normally. 197 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 198 * full privilege access}. Specifically: 199 * <ul> 200 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 201 * (This is because otherwise there would be no way to ensure the original lookup 202 * creator was a member of any particular module, and so any subsequent checks 203 * for readability and qualified exports would become ineffective.) 204 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 205 * (This is because an application intending to share intra-module access 206 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 207 * deep reflection to its own module.) 208 * </ul> 209 * <li>The target class must be a proper class, not a primitive or array class. 210 * (Thus, {@code M2} is well-defined.) 211 * <li>If the caller module {@code M1} differs from 212 * the target module {@code M2} then both of the following must be true: 213 * <ul> 214 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 215 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 216 * containing the target class to at least {@code M1}.</li> 217 * </ul> 218 * </ul> 219 * <p> 220 * If any of the above checks is violated, this method fails with an 221 * exception. 222 * <p> 223 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 224 * returns a {@code Lookup} on {@code targetClass} with 225 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 226 * with {@code null} previous lookup class. 227 * <p> 228 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 229 * returns a {@code Lookup} on {@code targetClass} that records 230 * the lookup class of the caller as the new previous lookup class with 231 * {@code PRIVATE} access but no {@code MODULE} access. 232 * <p> 233 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 234 * 235 * @param targetClass the target class 236 * @param caller the caller lookup object 237 * @return a lookup object for the target class, with private access 238 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 239 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 240 * @throws SecurityException if denied by the security manager 241 * @throws IllegalAccessException if any of the other access checks specified above fails 242 * @since 9 243 * @see Lookup#dropLookupMode 244 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 245 */ 246 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 247 if (caller.allowedModes == Lookup.TRUSTED) { 248 return new Lookup(targetClass); 249 } 250 251 @SuppressWarnings("removal") 252 SecurityManager sm = System.getSecurityManager(); 253 if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION); 254 if (targetClass.isPrimitive()) 255 throw new IllegalArgumentException(targetClass + " is a primitive class"); 256 if (targetClass.isArray()) 257 throw new IllegalArgumentException(targetClass + " is an array class"); 258 // Ensure that we can reason accurately about private and module access. 259 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 260 if ((caller.lookupModes() & requireAccess) != requireAccess) 261 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 262 263 // previous lookup class is never set if it has MODULE access 264 assert caller.previousLookupClass() == null; 265 266 Class<?> callerClass = caller.lookupClass(); 267 Module callerModule = callerClass.getModule(); // M1 268 Module targetModule = targetClass.getModule(); // M2 269 Class<?> newPreviousClass = null; 270 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 271 272 if (targetModule != callerModule) { 273 if (!callerModule.canRead(targetModule)) 274 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 275 if (targetModule.isNamed()) { 276 String pn = targetClass.getPackageName(); 277 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 278 if (!targetModule.isOpen(pn, callerModule)) 279 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 280 } 281 282 // M2 != M1, set previous lookup class to M1 and drop MODULE access 283 newPreviousClass = callerClass; 284 newModes &= ~Lookup.MODULE; 285 } 286 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 287 } 288 289 /** 290 * Returns the <em>class data</em> associated with the lookup class 291 * of the given {@code caller} lookup object, or {@code null}. 292 * 293 * <p> A hidden class with class data can be created by calling 294 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 295 * Lookup::defineHiddenClassWithClassData}. 296 * This method will cause the static class initializer of the lookup 297 * class of the given {@code caller} lookup object be executed if 298 * it has not been initialized. 299 * 300 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 301 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 302 * {@code null} is returned if this method is called on the lookup object 303 * on these classes. 304 * 305 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 306 * must have {@linkplain Lookup#ORIGINAL original access} 307 * in order to retrieve the class data. 308 * 309 * @apiNote 310 * This method can be called as a bootstrap method for a dynamically computed 311 * constant. A framework can create a hidden class with class data, for 312 * example that can be {@code Class} or {@code MethodHandle} object. 313 * The class data is accessible only to the lookup object 314 * created by the original caller but inaccessible to other members 315 * in the same nest. If a framework passes security sensitive objects 316 * to a hidden class via class data, it is recommended to load the value 317 * of class data as a dynamically computed constant instead of storing 318 * the class data in private static field(s) which are accessible to 319 * other nestmates. 320 * 321 * @param <T> the type to cast the class data object to 322 * @param caller the lookup context describing the class performing the 323 * operation (normally stacked by the JVM) 324 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 325 * ({@code "_"}) 326 * @param type the type of the class data 327 * @return the value of the class data if present in the lookup class; 328 * otherwise {@code null} 329 * @throws IllegalArgumentException if name is not {@code "_"} 330 * @throws IllegalAccessException if the lookup context does not have 331 * {@linkplain Lookup#ORIGINAL original} access 332 * @throws ClassCastException if the class data cannot be converted to 333 * the given {@code type} 334 * @throws NullPointerException if {@code caller} or {@code type} argument 335 * is {@code null} 336 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 337 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 338 * @since 16 339 * @jvms 5.5 Initialization 340 */ 341 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 342 Objects.requireNonNull(caller); 343 Objects.requireNonNull(type); 344 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 345 throw new IllegalArgumentException("name must be \"_\": " + name); 346 } 347 348 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 349 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 350 } 351 352 Object classdata = classData(caller.lookupClass()); 353 if (classdata == null) return null; 354 355 try { 356 return BootstrapMethodInvoker.widenAndCast(classdata, type); 357 } catch (RuntimeException|Error e) { 358 throw e; // let CCE and other runtime exceptions through 359 } catch (Throwable e) { 360 throw new InternalError(e); 361 } 362 } 363 364 /* 365 * Returns the class data set by the VM in the Class::classData field. 366 * 367 * This is also invoked by LambdaForms as it cannot use condy via 368 * MethodHandles::classData due to bootstrapping issue. 369 */ 370 static Object classData(Class<?> c) { 371 UNSAFE.ensureClassInitialized(c); 372 return SharedSecrets.getJavaLangAccess().classData(c); 373 } 374 375 /** 376 * Returns the element at the specified index in the 377 * {@linkplain #classData(Lookup, String, Class) class data}, 378 * if the class data associated with the lookup class 379 * of the given {@code caller} lookup object is a {@code List}. 380 * If the class data is not present in this lookup class, this method 381 * returns {@code null}. 382 * 383 * <p> A hidden class with class data can be created by calling 384 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 385 * Lookup::defineHiddenClassWithClassData}. 386 * This method will cause the static class initializer of the lookup 387 * class of the given {@code caller} lookup object be executed if 388 * it has not been initialized. 389 * 390 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 391 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 392 * {@code null} is returned if this method is called on the lookup object 393 * on these classes. 394 * 395 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 396 * must have {@linkplain Lookup#ORIGINAL original access} 397 * in order to retrieve the class data. 398 * 399 * @apiNote 400 * This method can be called as a bootstrap method for a dynamically computed 401 * constant. A framework can create a hidden class with class data, for 402 * example that can be {@code List.of(o1, o2, o3....)} containing more than 403 * one object and use this method to load one element at a specific index. 404 * The class data is accessible only to the lookup object 405 * created by the original caller but inaccessible to other members 406 * in the same nest. If a framework passes security sensitive objects 407 * to a hidden class via class data, it is recommended to load the value 408 * of class data as a dynamically computed constant instead of storing 409 * the class data in private static field(s) which are accessible to other 410 * nestmates. 411 * 412 * @param <T> the type to cast the result object to 413 * @param caller the lookup context describing the class performing the 414 * operation (normally stacked by the JVM) 415 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 416 * ({@code "_"}) 417 * @param type the type of the element at the given index in the class data 418 * @param index index of the element in the class data 419 * @return the element at the given index in the class data 420 * if the class data is present; otherwise {@code null} 421 * @throws IllegalArgumentException if name is not {@code "_"} 422 * @throws IllegalAccessException if the lookup context does not have 423 * {@linkplain Lookup#ORIGINAL original} access 424 * @throws ClassCastException if the class data cannot be converted to {@code List} 425 * or the element at the specified index cannot be converted to the given type 426 * @throws IndexOutOfBoundsException if the index is out of range 427 * @throws NullPointerException if {@code caller} or {@code type} argument is 428 * {@code null}; or if unboxing operation fails because 429 * the element at the given index is {@code null} 430 * 431 * @since 16 432 * @see #classData(Lookup, String, Class) 433 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 434 */ 435 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 436 throws IllegalAccessException 437 { 438 @SuppressWarnings("unchecked") 439 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 440 if (classdata == null) return null; 441 442 try { 443 Object element = classdata.get(index); 444 return BootstrapMethodInvoker.widenAndCast(element, type); 445 } catch (RuntimeException|Error e) { 446 throw e; // let specified exceptions and other runtime exceptions/errors through 447 } catch (Throwable e) { 448 throw new InternalError(e); 449 } 450 } 451 452 /** 453 * Performs an unchecked "crack" of a 454 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 455 * The result is as if the user had obtained a lookup object capable enough 456 * to crack the target method handle, called 457 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 458 * on the target to obtain its symbolic reference, and then called 459 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 460 * to resolve the symbolic reference to a member. 461 * <p> 462 * If there is a security manager, its {@code checkPermission} method 463 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 464 * @param <T> the desired type of the result, either {@link Member} or a subtype 465 * @param target a direct method handle to crack into symbolic reference components 466 * @param expected a class object representing the desired result type {@code T} 467 * @return a reference to the method, constructor, or field object 468 * @throws SecurityException if the caller is not privileged to call {@code setAccessible} 469 * @throws NullPointerException if either argument is {@code null} 470 * @throws IllegalArgumentException if the target is not a direct method handle 471 * @throws ClassCastException if the member is not of the expected type 472 * @since 1.8 473 */ 474 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 475 @SuppressWarnings("removal") 476 SecurityManager smgr = System.getSecurityManager(); 477 if (smgr != null) smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION); 478 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 479 return lookup.revealDirect(target).reflectAs(expected, lookup); 480 } 481 482 /** 483 * A <em>lookup object</em> is a factory for creating method handles, 484 * when the creation requires access checking. 485 * Method handles do not perform 486 * access checks when they are called, but rather when they are created. 487 * Therefore, method handle access 488 * restrictions must be enforced when a method handle is created. 489 * The caller class against which those restrictions are enforced 490 * is known as the {@linkplain #lookupClass() lookup class}. 491 * <p> 492 * A lookup class which needs to create method handles will call 493 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 494 * When the {@code Lookup} factory object is created, the identity of the lookup class is 495 * determined, and securely stored in the {@code Lookup} object. 496 * The lookup class (or its delegates) may then use factory methods 497 * on the {@code Lookup} object to create method handles for access-checked members. 498 * This includes all methods, constructors, and fields which are allowed to the lookup class, 499 * even private ones. 500 * 501 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 502 * The factory methods on a {@code Lookup} object correspond to all major 503 * use cases for methods, constructors, and fields. 504 * Each method handle created by a factory method is the functional 505 * equivalent of a particular <em>bytecode behavior</em>. 506 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 507 * the Java Virtual Machine Specification.) 508 * Here is a summary of the correspondence between these factory methods and 509 * the behavior of the resulting method handles: 510 * <table class="striped"> 511 * <caption style="display:none">lookup method behaviors</caption> 512 * <thead> 513 * <tr> 514 * <th scope="col"><a id="equiv"></a>lookup expression</th> 515 * <th scope="col">member</th> 516 * <th scope="col">bytecode behavior</th> 517 * </tr> 518 * </thead> 519 * <tbody> 520 * <tr> 521 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 522 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 523 * </tr> 524 * <tr> 525 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 526 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 527 * </tr> 528 * <tr> 529 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 530 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 531 * </tr> 532 * <tr> 533 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 534 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 535 * </tr> 536 * <tr> 537 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 538 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 539 * </tr> 540 * <tr> 541 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 542 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 543 * </tr> 544 * <tr> 545 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 546 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 547 * </tr> 548 * <tr> 549 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 550 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 551 * </tr> 552 * <tr> 553 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 554 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 555 * </tr> 556 * <tr> 557 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 558 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 559 * </tr> 560 * <tr> 561 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 562 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 563 * </tr> 564 * <tr> 565 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 566 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 567 * </tr> 568 * <tr> 569 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 570 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 571 * </tr> 572 * <tr> 573 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 574 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 575 * </tr> 576 * </tbody> 577 * </table> 578 * 579 * Here, the type {@code C} is the class or interface being searched for a member, 580 * documented as a parameter named {@code refc} in the lookup methods. 581 * The method type {@code MT} is composed from the return type {@code T} 582 * and the sequence of argument types {@code A*}. 583 * The constructor also has a sequence of argument types {@code A*} and 584 * is deemed to return the newly-created object of type {@code C}. 585 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 586 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 587 * if it is present, it is always the leading argument to the method handle invocation. 588 * (In the case of some {@code protected} members, {@code this} may be 589 * restricted in type to the lookup class; see below.) 590 * The name {@code arg} stands for all the other method handle arguments. 591 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 592 * stands for a null reference if the accessed method or field is static, 593 * and {@code this} otherwise. 594 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 595 * for reflective objects corresponding to the given members declared in type {@code C}. 596 * <p> 597 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 598 * as if by {@code ldc CONSTANT_Class}. 599 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 600 * <p> 601 * In cases where the given member is of variable arity (i.e., a method or constructor) 602 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 603 * In all other cases, the returned method handle will be of fixed arity. 604 * <p style="font-size:smaller;"> 605 * <em>Discussion:</em> 606 * The equivalence between looked-up method handles and underlying 607 * class members and bytecode behaviors 608 * can break down in a few ways: 609 * <ul style="font-size:smaller;"> 610 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 611 * the lookup can still succeed, even when there is no equivalent 612 * Java expression or bytecoded constant. 613 * <li>Likewise, if {@code T} or {@code MT} 614 * is not symbolically accessible from the lookup class's loader, 615 * the lookup can still succeed. 616 * For example, lookups for {@code MethodHandle.invokeExact} and 617 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 618 * <li>If there is a security manager installed, it can forbid the lookup 619 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 620 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 621 * constant is not subject to security manager checks. 622 * <li>If the looked-up method has a 623 * <a href="MethodHandle.html#maxarity">very large arity</a>, 624 * the method handle creation may fail with an 625 * {@code IllegalArgumentException}, due to the method handle type having 626 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 627 * </ul> 628 * 629 * <h2><a id="access"></a>Access checking</h2> 630 * Access checks are applied in the factory methods of {@code Lookup}, 631 * when a method handle is created. 632 * This is a key difference from the Core Reflection API, since 633 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 634 * performs access checking against every caller, on every call. 635 * <p> 636 * All access checks start from a {@code Lookup} object, which 637 * compares its recorded lookup class against all requests to 638 * create method handles. 639 * A single {@code Lookup} object can be used to create any number 640 * of access-checked method handles, all checked against a single 641 * lookup class. 642 * <p> 643 * A {@code Lookup} object can be shared with other trusted code, 644 * such as a metaobject protocol. 645 * A shared {@code Lookup} object delegates the capability 646 * to create method handles on private members of the lookup class. 647 * Even if privileged code uses the {@code Lookup} object, 648 * the access checking is confined to the privileges of the 649 * original lookup class. 650 * <p> 651 * A lookup can fail, because 652 * the containing class is not accessible to the lookup class, or 653 * because the desired class member is missing, or because the 654 * desired class member is not accessible to the lookup class, or 655 * because the lookup object is not trusted enough to access the member. 656 * In the case of a field setter function on a {@code final} field, 657 * finality enforcement is treated as a kind of access control, 658 * and the lookup will fail, except in special cases of 659 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 660 * In any of these cases, a {@code ReflectiveOperationException} will be 661 * thrown from the attempted lookup. The exact class will be one of 662 * the following: 663 * <ul> 664 * <li>NoSuchMethodException — if a method is requested but does not exist 665 * <li>NoSuchFieldException — if a field is requested but does not exist 666 * <li>IllegalAccessException — if the member exists but an access check fails 667 * </ul> 668 * <p> 669 * In general, the conditions under which a method handle may be 670 * looked up for a method {@code M} are no more restrictive than the conditions 671 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 672 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 673 * a method handle lookup will generally raise a corresponding 674 * checked exception, such as {@code NoSuchMethodException}. 675 * And the effect of invoking the method handle resulting from the lookup 676 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 677 * to executing the compiled, verified, and resolved call to {@code M}. 678 * The same point is true of fields and constructors. 679 * <p style="font-size:smaller;"> 680 * <em>Discussion:</em> 681 * Access checks only apply to named and reflected methods, 682 * constructors, and fields. 683 * Other method handle creation methods, such as 684 * {@link MethodHandle#asType MethodHandle.asType}, 685 * do not require any access checks, and are used 686 * independently of any {@code Lookup} object. 687 * <p> 688 * If the desired member is {@code protected}, the usual JVM rules apply, 689 * including the requirement that the lookup class must either be in the 690 * same package as the desired member, or must inherit that member. 691 * (See the Java Virtual Machine Specification, sections {@jvms 692 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 693 * In addition, if the desired member is a non-static field or method 694 * in a different package, the resulting method handle may only be applied 695 * to objects of the lookup class or one of its subclasses. 696 * This requirement is enforced by narrowing the type of the leading 697 * {@code this} parameter from {@code C} 698 * (which will necessarily be a superclass of the lookup class) 699 * to the lookup class itself. 700 * <p> 701 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 702 * that the receiver argument must match both the resolved method <em>and</em> 703 * the current class. Again, this requirement is enforced by narrowing the 704 * type of the leading parameter to the resulting method handle. 705 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 706 * <p> 707 * The JVM represents constructors and static initializer blocks as internal methods 708 * with special names ({@code "<init>"} and {@code "<clinit>"}). 709 * The internal syntax of invocation instructions allows them to refer to such internal 710 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 711 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 712 * <p> 713 * If the relationship between nested types is expressed directly through the 714 * {@code NestHost} and {@code NestMembers} attributes 715 * (see the Java Virtual Machine Specification, sections {@jvms 716 * 4.7.28} and {@jvms 4.7.29}), 717 * then the associated {@code Lookup} object provides direct access to 718 * the lookup class and all of its nestmates 719 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 720 * Otherwise, access between nested classes is obtained by the Java compiler creating 721 * a wrapper method to access a private method of another class in the same nest. 722 * For example, a nested class {@code C.D} 723 * can access private members within other related classes such as 724 * {@code C}, {@code C.D.E}, or {@code C.B}, 725 * but the Java compiler may need to generate wrapper methods in 726 * those related classes. In such cases, a {@code Lookup} object on 727 * {@code C.E} would be unable to access those private members. 728 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 729 * which can transform a lookup on {@code C.E} into one on any of those other 730 * classes, without special elevation of privilege. 731 * <p> 732 * The accesses permitted to a given lookup object may be limited, 733 * according to its set of {@link #lookupModes lookupModes}, 734 * to a subset of members normally accessible to the lookup class. 735 * For example, the {@link MethodHandles#publicLookup publicLookup} 736 * method produces a lookup object which is only allowed to access 737 * public members in public classes of exported packages. 738 * The caller sensitive method {@link MethodHandles#lookup lookup} 739 * produces a lookup object with full capabilities relative to 740 * its caller class, to emulate all supported bytecode behaviors. 741 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 742 * with fewer access modes than the original lookup object. 743 * 744 * <p style="font-size:smaller;"> 745 * <a id="privacc"></a> 746 * <em>Discussion of private and module access:</em> 747 * We say that a lookup has <em>private access</em> 748 * if its {@linkplain #lookupModes lookup modes} 749 * include the possibility of accessing {@code private} members 750 * (which includes the private members of nestmates). 751 * As documented in the relevant methods elsewhere, 752 * only lookups with private access possess the following capabilities: 753 * <ul style="font-size:smaller;"> 754 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 755 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 756 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 757 * for classes accessible to the lookup class 758 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 759 * within the same package member 760 * </ul> 761 * <p style="font-size:smaller;"> 762 * Similarly, a lookup with module access ensures that the original lookup creator was 763 * a member in the same module as the lookup class. 764 * <p style="font-size:smaller;"> 765 * Private and module access are independently determined modes; a lookup may have 766 * either or both or neither. A lookup which possesses both access modes is said to 767 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 768 * <p style="font-size:smaller;"> 769 * A lookup with <em>original access</em> ensures that this lookup is created by 770 * the original lookup class and the bootstrap method invoked by the VM. 771 * Such a lookup with original access also has private and module access 772 * which has the following additional capability: 773 * <ul style="font-size:smaller;"> 774 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 775 * such as {@code Class.forName} 776 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 777 * class data} associated with the lookup class</li> 778 * </ul> 779 * <p style="font-size:smaller;"> 780 * Each of these permissions is a consequence of the fact that a lookup object 781 * with private access can be securely traced back to an originating class, 782 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 783 * can be reliably determined and emulated by method handles. 784 * 785 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 786 * When a lookup class in one module {@code M1} accesses a class in another module 787 * {@code M2}, extra access checking is performed beyond the access mode bits. 788 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 789 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 790 * and when the type is in a package of {@code M2} that is exported to 791 * at least {@code M1}. 792 * <p> 793 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 794 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 795 * MethodHandles.privateLookupIn} methods. 796 * Teleporting across modules will always record the original lookup class as 797 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 798 * and drops {@link Lookup#MODULE MODULE} access. 799 * If the target class is in the same module as the lookup class {@code C}, 800 * then the target class becomes the new lookup class 801 * and there is no change to the previous lookup class. 802 * If the target class is in a different module from {@code M1} ({@code C}'s module), 803 * {@code C} becomes the new previous lookup class 804 * and the target class becomes the new lookup class. 805 * In that case, if there was already a previous lookup class in {@code M0}, 806 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 807 * drops all privileges. 808 * For example, 809 * {@snippet lang="java" : 810 * Lookup lookup = MethodHandles.lookup(); // in class C 811 * Lookup lookup2 = lookup.in(D.class); 812 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 813 * } 814 * <p> 815 * The {@link #lookup()} factory method produces a {@code Lookup} object 816 * with {@code null} previous lookup class. 817 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 818 * to class {@code D} without elevation of privileges. 819 * If {@code C} and {@code D} are in the same module, 820 * {@code lookup2} records {@code D} as the new lookup class and keeps the 821 * same previous lookup class as the original {@code lookup}, or 822 * {@code null} if not present. 823 * <p> 824 * When a {@code Lookup} teleports from a class 825 * in one nest to another nest, {@code PRIVATE} access is dropped. 826 * When a {@code Lookup} teleports from a class in one package to 827 * another package, {@code PACKAGE} access is dropped. 828 * When a {@code Lookup} teleports from a class in one module to another module, 829 * {@code MODULE} access is dropped. 830 * Teleporting across modules drops the ability to access non-exported classes 831 * in both the module of the new lookup class and the module of the old lookup class 832 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 833 * A {@code Lookup} can teleport back and forth to a class in the module of 834 * the lookup class and the module of the previous class lookup. 835 * Teleporting across modules can only decrease access but cannot increase it. 836 * Teleporting to some third module drops all accesses. 837 * <p> 838 * In the above example, if {@code C} and {@code D} are in different modules, 839 * {@code lookup2} records {@code D} as its lookup class and 840 * {@code C} as its previous lookup class and {@code lookup2} has only 841 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 842 * {@code C}'s module and {@code D}'s module. 843 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 844 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 845 * class {@code D} is recorded as its previous lookup class. 846 * <p> 847 * Teleporting across modules restricts access to the public types that 848 * both the lookup class and the previous lookup class can equally access 849 * (see below). 850 * <p> 851 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 852 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 853 * and create a new {@code Lookup} with <a href="#privacc">private access</a> 854 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 855 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 856 * to call {@code privateLookupIn}. 857 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 858 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 859 * produces a new {@code Lookup} on {@code T} with full capabilities. 860 * A {@code lookup} on {@code C} is also allowed 861 * to do deep reflection on {@code T} in another module {@code M2} if 862 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 863 * the package containing {@code T} to at least {@code M1}. 864 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 865 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 866 * The resulting {@code Lookup} can be used to do member lookup or teleport 867 * to another lookup class by calling {@link #in Lookup::in}. But 868 * it cannot be used to obtain another private {@code Lookup} by calling 869 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 870 * because it has no {@code MODULE} access. 871 * 872 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 873 * 874 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 875 * allows cross-module access. The access checking is performed with respect 876 * to both the lookup class and the previous lookup class if present. 877 * <p> 878 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 879 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 880 * exported unconditionally}. 881 * <p> 882 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 883 * the lookup with {@link #PUBLIC} mode can access all public types in modules 884 * that are readable to {@code M1} and the type is in a package that is exported 885 * at least to {@code M1}. 886 * <p> 887 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 888 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 889 * the intersection of all public types that are accessible to {@code M1} 890 * with all public types that are accessible to {@code M0}. {@code M0} 891 * reads {@code M1} and hence the set of accessible types includes: 892 * 893 * <ul> 894 * <li>unconditional-exported packages from {@code M1}</li> 895 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 896 * <li> 897 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 898 * and {@code M1} read {@code M2} 899 * </li> 900 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 901 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 902 * <li> 903 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 904 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 905 * </li> 906 * </ul> 907 * 908 * <h2><a id="access-modes"></a>Access modes</h2> 909 * 910 * The table below shows the access modes of a {@code Lookup} produced by 911 * any of the following factory or transformation methods: 912 * <ul> 913 * <li>{@link #lookup() MethodHandles::lookup}</li> 914 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 915 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 916 * <li>{@link Lookup#in Lookup::in}</li> 917 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 918 * </ul> 919 * 920 * <table class="striped"> 921 * <caption style="display:none"> 922 * Access mode summary 923 * </caption> 924 * <thead> 925 * <tr> 926 * <th scope="col">Lookup object</th> 927 * <th style="text-align:center">original</th> 928 * <th style="text-align:center">protected</th> 929 * <th style="text-align:center">private</th> 930 * <th style="text-align:center">package</th> 931 * <th style="text-align:center">module</th> 932 * <th style="text-align:center">public</th> 933 * </tr> 934 * </thead> 935 * <tbody> 936 * <tr> 937 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 938 * <td style="text-align:center">ORI</td> 939 * <td style="text-align:center">PRO</td> 940 * <td style="text-align:center">PRI</td> 941 * <td style="text-align:center">PAC</td> 942 * <td style="text-align:center">MOD</td> 943 * <td style="text-align:center">1R</td> 944 * </tr> 945 * <tr> 946 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 947 * <td></td> 948 * <td></td> 949 * <td></td> 950 * <td style="text-align:center">PAC</td> 951 * <td style="text-align:center">MOD</td> 952 * <td style="text-align:center">1R</td> 953 * </tr> 954 * <tr> 955 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 956 * <td></td> 957 * <td></td> 958 * <td></td> 959 * <td></td> 960 * <td style="text-align:center">MOD</td> 961 * <td style="text-align:center">1R</td> 962 * </tr> 963 * <tr> 964 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 965 * <td></td> 966 * <td></td> 967 * <td></td> 968 * <td></td> 969 * <td></td> 970 * <td style="text-align:center">2R</td> 971 * </tr> 972 * <tr> 973 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 974 * <td></td> 975 * <td></td> 976 * <td></td> 977 * <td></td> 978 * <td></td> 979 * <td style="text-align:center">2R</td> 980 * </tr> 981 * <tr> 982 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 983 * <td></td> 984 * <td style="text-align:center">PRO</td> 985 * <td style="text-align:center">PRI</td> 986 * <td style="text-align:center">PAC</td> 987 * <td style="text-align:center">MOD</td> 988 * <td style="text-align:center">1R</td> 989 * </tr> 990 * <tr> 991 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 992 * <td></td> 993 * <td style="text-align:center">PRO</td> 994 * <td style="text-align:center">PRI</td> 995 * <td style="text-align:center">PAC</td> 996 * <td style="text-align:center">MOD</td> 997 * <td style="text-align:center">1R</td> 998 * </tr> 999 * <tr> 1000 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1001 * <td></td> 1002 * <td></td> 1003 * <td></td> 1004 * <td style="text-align:center">PAC</td> 1005 * <td style="text-align:center">MOD</td> 1006 * <td style="text-align:center">1R</td> 1007 * </tr> 1008 * <tr> 1009 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1010 * <td></td> 1011 * <td></td> 1012 * <td></td> 1013 * <td></td> 1014 * <td style="text-align:center">MOD</td> 1015 * <td style="text-align:center">1R</td> 1016 * </tr> 1017 * <tr> 1018 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1019 * <td></td> 1020 * <td></td> 1021 * <td></td> 1022 * <td></td> 1023 * <td></td> 1024 * <td style="text-align:center">2R</td> 1025 * </tr> 1026 * <tr> 1027 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1028 * <td></td> 1029 * <td></td> 1030 * <td style="text-align:center">PRI</td> 1031 * <td style="text-align:center">PAC</td> 1032 * <td style="text-align:center">MOD</td> 1033 * <td style="text-align:center">1R</td> 1034 * </tr> 1035 * <tr> 1036 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1037 * <td></td> 1038 * <td></td> 1039 * <td></td> 1040 * <td style="text-align:center">PAC</td> 1041 * <td style="text-align:center">MOD</td> 1042 * <td style="text-align:center">1R</td> 1043 * </tr> 1044 * <tr> 1045 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1046 * <td></td> 1047 * <td></td> 1048 * <td></td> 1049 * <td></td> 1050 * <td style="text-align:center">MOD</td> 1051 * <td style="text-align:center">1R</td> 1052 * </tr> 1053 * <tr> 1054 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1055 * <td></td> 1056 * <td></td> 1057 * <td></td> 1058 * <td></td> 1059 * <td></td> 1060 * <td style="text-align:center">1R</td> 1061 * </tr> 1062 * <tr> 1063 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1064 * <td></td> 1065 * <td></td> 1066 * <td></td> 1067 * <td></td> 1068 * <td></td> 1069 * <td style="text-align:center">none</td> 1070 * <tr> 1071 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1072 * <td></td> 1073 * <td style="text-align:center">PRO</td> 1074 * <td style="text-align:center">PRI</td> 1075 * <td style="text-align:center">PAC</td> 1076 * <td></td> 1077 * <td style="text-align:center">2R</td> 1078 * </tr> 1079 * <tr> 1080 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1081 * <td></td> 1082 * <td style="text-align:center">PRO</td> 1083 * <td style="text-align:center">PRI</td> 1084 * <td style="text-align:center">PAC</td> 1085 * <td></td> 1086 * <td style="text-align:center">2R</td> 1087 * </tr> 1088 * <tr> 1089 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1090 * <td></td> 1091 * <td></td> 1092 * <td></td> 1093 * <td></td> 1094 * <td></td> 1095 * <td style="text-align:center">IAE</td> 1096 * </tr> 1097 * <tr> 1098 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1099 * <td></td> 1100 * <td></td> 1101 * <td></td> 1102 * <td style="text-align:center">PAC</td> 1103 * <td></td> 1104 * <td style="text-align:center">2R</td> 1105 * </tr> 1106 * <tr> 1107 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1108 * <td></td> 1109 * <td></td> 1110 * <td></td> 1111 * <td></td> 1112 * <td></td> 1113 * <td style="text-align:center">2R</td> 1114 * </tr> 1115 * <tr> 1116 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1117 * <td></td> 1118 * <td></td> 1119 * <td></td> 1120 * <td></td> 1121 * <td></td> 1122 * <td style="text-align:center">2R</td> 1123 * </tr> 1124 * <tr> 1125 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1126 * <td></td> 1127 * <td></td> 1128 * <td></td> 1129 * <td></td> 1130 * <td></td> 1131 * <td style="text-align:center">none</td> 1132 * </tr> 1133 * <tr> 1134 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1135 * <td></td> 1136 * <td></td> 1137 * <td style="text-align:center">PRI</td> 1138 * <td style="text-align:center">PAC</td> 1139 * <td></td> 1140 * <td style="text-align:center">2R</td> 1141 * </tr> 1142 * <tr> 1143 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1144 * <td></td> 1145 * <td></td> 1146 * <td></td> 1147 * <td style="text-align:center">PAC</td> 1148 * <td></td> 1149 * <td style="text-align:center">2R</td> 1150 * </tr> 1151 * <tr> 1152 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1153 * <td></td> 1154 * <td></td> 1155 * <td></td> 1156 * <td></td> 1157 * <td></td> 1158 * <td style="text-align:center">2R</td> 1159 * </tr> 1160 * <tr> 1161 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1162 * <td></td> 1163 * <td></td> 1164 * <td></td> 1165 * <td></td> 1166 * <td></td> 1167 * <td style="text-align:center">2R</td> 1168 * </tr> 1169 * <tr> 1170 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1171 * <td></td> 1172 * <td></td> 1173 * <td></td> 1174 * <td></td> 1175 * <td></td> 1176 * <td style="text-align:center">none</td> 1177 * </tr> 1178 * <tr> 1179 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1180 * <td></td> 1181 * <td></td> 1182 * <td style="text-align:center">PRI</td> 1183 * <td style="text-align:center">PAC</td> 1184 * <td style="text-align:center">MOD</td> 1185 * <td style="text-align:center">1R</td> 1186 * </tr> 1187 * <tr> 1188 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1189 * <td></td> 1190 * <td></td> 1191 * <td></td> 1192 * <td style="text-align:center">PAC</td> 1193 * <td style="text-align:center">MOD</td> 1194 * <td style="text-align:center">1R</td> 1195 * </tr> 1196 * <tr> 1197 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1198 * <td></td> 1199 * <td></td> 1200 * <td></td> 1201 * <td></td> 1202 * <td style="text-align:center">MOD</td> 1203 * <td style="text-align:center">1R</td> 1204 * </tr> 1205 * <tr> 1206 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1207 * <td></td> 1208 * <td></td> 1209 * <td></td> 1210 * <td></td> 1211 * <td></td> 1212 * <td style="text-align:center">1R</td> 1213 * </tr> 1214 * <tr> 1215 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1216 * <td></td> 1217 * <td></td> 1218 * <td></td> 1219 * <td></td> 1220 * <td></td> 1221 * <td style="text-align:center">none</td> 1222 * </tr> 1223 * <tr> 1224 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1225 * <td></td> 1226 * <td></td> 1227 * <td></td> 1228 * <td></td> 1229 * <td></td> 1230 * <td style="text-align:center">U</td> 1231 * </tr> 1232 * <tr> 1233 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1234 * <td></td> 1235 * <td></td> 1236 * <td></td> 1237 * <td></td> 1238 * <td></td> 1239 * <td style="text-align:center">U</td> 1240 * </tr> 1241 * <tr> 1242 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1243 * <td></td> 1244 * <td></td> 1245 * <td></td> 1246 * <td></td> 1247 * <td></td> 1248 * <td style="text-align:center">U</td> 1249 * </tr> 1250 * <tr> 1251 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1252 * <td></td> 1253 * <td></td> 1254 * <td></td> 1255 * <td></td> 1256 * <td></td> 1257 * <td style="text-align:center">none</td> 1258 * </tr> 1259 * <tr> 1260 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1261 * <td></td> 1262 * <td></td> 1263 * <td></td> 1264 * <td></td> 1265 * <td></td> 1266 * <td style="text-align:center">IAE</td> 1267 * </tr> 1268 * <tr> 1269 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1270 * <td></td> 1271 * <td></td> 1272 * <td></td> 1273 * <td></td> 1274 * <td></td> 1275 * <td style="text-align:center">none</td> 1276 * </tr> 1277 * </tbody> 1278 * </table> 1279 * 1280 * <p> 1281 * Notes: 1282 * <ul> 1283 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1284 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1285 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1286 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1287 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1288 * {@code PRO} indicates {@link #PROTECTED} bit set, 1289 * {@code PRI} indicates {@link #PRIVATE} bit set, 1290 * {@code PAC} indicates {@link #PACKAGE} bit set, 1291 * {@code MOD} indicates {@link #MODULE} bit set, 1292 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1293 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1294 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1295 * <li>Public access comes in three kinds: 1296 * <ul> 1297 * <li>unconditional ({@code U}): the lookup assumes readability. 1298 * The lookup has {@code null} previous lookup class. 1299 * <li>one-module-reads ({@code 1R}): the module access checking is 1300 * performed with respect to the lookup class. The lookup has {@code null} 1301 * previous lookup class. 1302 * <li>two-module-reads ({@code 2R}): the module access checking is 1303 * performed with respect to the lookup class and the previous lookup class. 1304 * The lookup has a non-null previous lookup class which is in a 1305 * different module from the current lookup class. 1306 * </ul> 1307 * <li>Any attempt to reach a third module loses all access.</li> 1308 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1309 * all access modes are dropped.</li> 1310 * </ul> 1311 * 1312 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1313 * Although bytecode instructions can only refer to classes in 1314 * a related class loader, this API can search for methods in any 1315 * class, as long as a reference to its {@code Class} object is 1316 * available. Such cross-loader references are also possible with the 1317 * Core Reflection API, and are impossible to bytecode instructions 1318 * such as {@code invokestatic} or {@code getfield}. 1319 * There is a {@linkplain java.lang.SecurityManager security manager API} 1320 * to allow applications to check such cross-loader references. 1321 * These checks apply to both the {@code MethodHandles.Lookup} API 1322 * and the Core Reflection API 1323 * (as found on {@link java.lang.Class Class}). 1324 * <p> 1325 * If a security manager is present, member and class lookups are subject to 1326 * additional checks. 1327 * From one to three calls are made to the security manager. 1328 * Any of these calls can refuse access by throwing a 1329 * {@link java.lang.SecurityException SecurityException}. 1330 * Define {@code smgr} as the security manager, 1331 * {@code lookc} as the lookup class of the current lookup object, 1332 * {@code refc} as the containing class in which the member 1333 * is being sought, and {@code defc} as the class in which the 1334 * member is actually defined. 1335 * (If a class or other type is being accessed, 1336 * the {@code refc} and {@code defc} values are the class itself.) 1337 * The value {@code lookc} is defined as <em>not present</em> 1338 * if the current lookup object does not have 1339 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1340 * The calls are made according to the following rules: 1341 * <ul> 1342 * <li><b>Step 1:</b> 1343 * If {@code lookc} is not present, or if its class loader is not 1344 * the same as or an ancestor of the class loader of {@code refc}, 1345 * then {@link SecurityManager#checkPackageAccess 1346 * smgr.checkPackageAccess(refcPkg)} is called, 1347 * where {@code refcPkg} is the package of {@code refc}. 1348 * <li><b>Step 2a:</b> 1349 * If the retrieved member is not public and 1350 * {@code lookc} is not present, then 1351 * {@link SecurityManager#checkPermission smgr.checkPermission} 1352 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1353 * <li><b>Step 2b:</b> 1354 * If the retrieved class has a {@code null} class loader, 1355 * and {@code lookc} is not present, then 1356 * {@link SecurityManager#checkPermission smgr.checkPermission} 1357 * with {@code RuntimePermission("getClassLoader")} is called. 1358 * <li><b>Step 3:</b> 1359 * If the retrieved member is not public, 1360 * and if {@code lookc} is not present, 1361 * and if {@code defc} and {@code refc} are different, 1362 * then {@link SecurityManager#checkPackageAccess 1363 * smgr.checkPackageAccess(defcPkg)} is called, 1364 * where {@code defcPkg} is the package of {@code defc}. 1365 * </ul> 1366 * Security checks are performed after other access checks have passed. 1367 * Therefore, the above rules presuppose a member or class that is public, 1368 * or else that is being accessed from a lookup class that has 1369 * rights to access the member or class. 1370 * <p> 1371 * If a security manager is present and the current lookup object does not have 1372 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1373 * {@link #defineClass(byte[]) defineClass}, 1374 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1375 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1376 * defineHiddenClassWithClassData} 1377 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1378 * with {@code RuntimePermission("defineClass")}. 1379 * 1380 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1381 * A small number of Java methods have a special property called caller sensitivity. 1382 * A <em>caller-sensitive</em> method can behave differently depending on the 1383 * identity of its immediate caller. 1384 * <p> 1385 * If a method handle for a caller-sensitive method is requested, 1386 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1387 * but they take account of the lookup class in a special way. 1388 * The resulting method handle behaves as if it were called 1389 * from an instruction contained in the lookup class, 1390 * so that the caller-sensitive method detects the lookup class. 1391 * (By contrast, the invoker of the method handle is disregarded.) 1392 * Thus, in the case of caller-sensitive methods, 1393 * different lookup classes may give rise to 1394 * differently behaving method handles. 1395 * <p> 1396 * In cases where the lookup object is 1397 * {@link MethodHandles#publicLookup() publicLookup()}, 1398 * or some other lookup object without the 1399 * {@linkplain #ORIGINAL original access}, 1400 * the lookup class is disregarded. 1401 * In such cases, no caller-sensitive method handle can be created, 1402 * access is forbidden, and the lookup fails with an 1403 * {@code IllegalAccessException}. 1404 * <p style="font-size:smaller;"> 1405 * <em>Discussion:</em> 1406 * For example, the caller-sensitive method 1407 * {@link java.lang.Class#forName(String) Class.forName(x)} 1408 * can return varying classes or throw varying exceptions, 1409 * depending on the class loader of the class that calls it. 1410 * A public lookup of {@code Class.forName} will fail, because 1411 * there is no reasonable way to determine its bytecode behavior. 1412 * <p style="font-size:smaller;"> 1413 * If an application caches method handles for broad sharing, 1414 * it should use {@code publicLookup()} to create them. 1415 * If there is a lookup of {@code Class.forName}, it will fail, 1416 * and the application must take appropriate action in that case. 1417 * It may be that a later lookup, perhaps during the invocation of a 1418 * bootstrap method, can incorporate the specific identity 1419 * of the caller, making the method accessible. 1420 * <p style="font-size:smaller;"> 1421 * The function {@code MethodHandles.lookup} is caller sensitive 1422 * so that there can be a secure foundation for lookups. 1423 * Nearly all other methods in the JSR 292 API rely on lookup 1424 * objects to check access requests. 1425 * 1426 * @revised 9 1427 */ 1428 public static final 1429 class Lookup { 1430 /** The class on behalf of whom the lookup is being performed. */ 1431 private final Class<?> lookupClass; 1432 1433 /** previous lookup class */ 1434 private final Class<?> prevLookupClass; 1435 1436 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1437 private final int allowedModes; 1438 1439 static { 1440 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1441 } 1442 1443 /** A single-bit mask representing {@code public} access, 1444 * which may contribute to the result of {@link #lookupModes lookupModes}. 1445 * The value, {@code 0x01}, happens to be the same as the value of the 1446 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1447 * <p> 1448 * A {@code Lookup} with this lookup mode performs cross-module access check 1449 * with respect to the {@linkplain #lookupClass() lookup class} and 1450 * {@linkplain #previousLookupClass() previous lookup class} if present. 1451 */ 1452 public static final int PUBLIC = Modifier.PUBLIC; 1453 1454 /** A single-bit mask representing {@code private} access, 1455 * which may contribute to the result of {@link #lookupModes lookupModes}. 1456 * The value, {@code 0x02}, happens to be the same as the value of the 1457 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1458 */ 1459 public static final int PRIVATE = Modifier.PRIVATE; 1460 1461 /** A single-bit mask representing {@code protected} access, 1462 * which may contribute to the result of {@link #lookupModes lookupModes}. 1463 * The value, {@code 0x04}, happens to be the same as the value of the 1464 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1465 */ 1466 public static final int PROTECTED = Modifier.PROTECTED; 1467 1468 /** A single-bit mask representing {@code package} access (default access), 1469 * which may contribute to the result of {@link #lookupModes lookupModes}. 1470 * The value is {@code 0x08}, which does not correspond meaningfully to 1471 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1472 */ 1473 public static final int PACKAGE = Modifier.STATIC; 1474 1475 /** A single-bit mask representing {@code module} access, 1476 * which may contribute to the result of {@link #lookupModes lookupModes}. 1477 * The value is {@code 0x10}, which does not correspond meaningfully to 1478 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1479 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1480 * with this lookup mode can access all public types in the module of the 1481 * lookup class and public types in packages exported by other modules 1482 * to the module of the lookup class. 1483 * <p> 1484 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1485 * previous lookup class} is always {@code null}. 1486 * 1487 * @since 9 1488 */ 1489 public static final int MODULE = PACKAGE << 1; 1490 1491 /** A single-bit mask representing {@code unconditional} access 1492 * which may contribute to the result of {@link #lookupModes lookupModes}. 1493 * The value is {@code 0x20}, which does not correspond meaningfully to 1494 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1495 * A {@code Lookup} with this lookup mode assumes {@linkplain 1496 * java.lang.Module#canRead(java.lang.Module) readability}. 1497 * This lookup mode can access all public members of public types 1498 * of all modules when the type is in a package that is {@link 1499 * java.lang.Module#isExported(String) exported unconditionally}. 1500 * 1501 * <p> 1502 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1503 * previous lookup class} is always {@code null}. 1504 * 1505 * @since 9 1506 * @see #publicLookup() 1507 */ 1508 public static final int UNCONDITIONAL = PACKAGE << 2; 1509 1510 /** A single-bit mask representing {@code original} access 1511 * which may contribute to the result of {@link #lookupModes lookupModes}. 1512 * The value is {@code 0x40}, which does not correspond meaningfully to 1513 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1514 * 1515 * <p> 1516 * If this lookup mode is set, the {@code Lookup} object must be 1517 * created by the original lookup class by calling 1518 * {@link MethodHandles#lookup()} method or by a bootstrap method 1519 * invoked by the VM. The {@code Lookup} object with this lookup 1520 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1521 * 1522 * @since 16 1523 */ 1524 public static final int ORIGINAL = PACKAGE << 3; 1525 1526 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1527 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1528 private static final int TRUSTED = -1; 1529 1530 /* 1531 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1532 * Adjust 0 => PACKAGE 1533 */ 1534 private static int fixmods(int mods) { 1535 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1536 if (Modifier.isPublic(mods)) 1537 mods |= UNCONDITIONAL; 1538 return (mods != 0) ? mods : PACKAGE; 1539 } 1540 1541 /** Tells which class is performing the lookup. It is this class against 1542 * which checks are performed for visibility and access permissions. 1543 * <p> 1544 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1545 * access checks are performed against both the lookup class and the previous lookup class. 1546 * <p> 1547 * The class implies a maximum level of access permission, 1548 * but the permissions may be additionally limited by the bitmask 1549 * {@link #lookupModes lookupModes}, which controls whether non-public members 1550 * can be accessed. 1551 * @return the lookup class, on behalf of which this lookup object finds members 1552 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1553 */ 1554 public Class<?> lookupClass() { 1555 return lookupClass; 1556 } 1557 1558 /** Reports a lookup class in another module that this lookup object 1559 * was previously teleported from, or {@code null}. 1560 * <p> 1561 * A {@code Lookup} object produced by the factory methods, such as the 1562 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1563 * has {@code null} previous lookup class. 1564 * A {@code Lookup} object has a non-null previous lookup class 1565 * when this lookup was teleported from an old lookup class 1566 * in one module to a new lookup class in another module. 1567 * 1568 * @return the lookup class in another module that this lookup object was 1569 * previously teleported from, or {@code null} 1570 * @since 14 1571 * @see #in(Class) 1572 * @see MethodHandles#privateLookupIn(Class, Lookup) 1573 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1574 */ 1575 public Class<?> previousLookupClass() { 1576 return prevLookupClass; 1577 } 1578 1579 // This is just for calling out to MethodHandleImpl. 1580 private Class<?> lookupClassOrNull() { 1581 return (allowedModes == TRUSTED) ? null : lookupClass; 1582 } 1583 1584 /** Tells which access-protection classes of members this lookup object can produce. 1585 * The result is a bit-mask of the bits 1586 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1587 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1588 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1589 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1590 * {@linkplain #MODULE MODULE (0x10)}, 1591 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1592 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1593 * <p> 1594 * A freshly-created lookup object 1595 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1596 * all possible bits set, except {@code UNCONDITIONAL}. 1597 * A lookup object on a new lookup class 1598 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1599 * may have some mode bits set to zero. 1600 * Mode bits can also be 1601 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1602 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1603 * The purpose of this is to restrict access via the new lookup object, 1604 * so that it can access only names which can be reached by the original 1605 * lookup object, and also by the new lookup class. 1606 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1607 * @see #in 1608 * @see #dropLookupMode 1609 * 1610 * @revised 9 1611 */ 1612 public int lookupModes() { 1613 return allowedModes & ALL_MODES; 1614 } 1615 1616 /** Embody the current class (the lookupClass) as a lookup class 1617 * for method handle creation. 1618 * Must be called by from a method in this package, 1619 * which in turn is called by a method not in this package. 1620 */ 1621 Lookup(Class<?> lookupClass) { 1622 this(lookupClass, null, FULL_POWER_MODES); 1623 } 1624 1625 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1626 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1627 && prevLookupClass.getModule() != lookupClass.getModule()); 1628 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1629 this.lookupClass = lookupClass; 1630 this.prevLookupClass = prevLookupClass; 1631 this.allowedModes = allowedModes; 1632 } 1633 1634 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1635 // make sure we haven't accidentally picked up a privileged class: 1636 checkUnprivilegedlookupClass(lookupClass); 1637 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1638 } 1639 1640 /** 1641 * Creates a lookup on the specified new lookup class. 1642 * The resulting object will report the specified 1643 * class as its own {@link #lookupClass() lookupClass}. 1644 * 1645 * <p> 1646 * However, the resulting {@code Lookup} object is guaranteed 1647 * to have no more access capabilities than the original. 1648 * In particular, access capabilities can be lost as follows:<ul> 1649 * <li>If the new lookup class is different from the old lookup class, 1650 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1651 * <li>If the new lookup class is in a different module from the old one, 1652 * i.e. {@link #MODULE MODULE} access is lost. 1653 * <li>If the new lookup class is in a different package 1654 * than the old one, protected and default (package) members will not be accessible, 1655 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1656 * <li>If the new lookup class is not within the same package member 1657 * as the old one, private members will not be accessible, and protected members 1658 * will not be accessible by virtue of inheritance, 1659 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1660 * (Protected members may continue to be accessible because of package sharing.) 1661 * <li>If the new lookup class is not 1662 * {@linkplain #accessClass(Class) accessible} to this lookup, 1663 * then no members, not even public members, will be accessible 1664 * i.e. all access modes are lost. 1665 * <li>If the new lookup class, the old lookup class and the previous lookup class 1666 * are all in different modules i.e. teleporting to a third module, 1667 * all access modes are lost. 1668 * </ul> 1669 * <p> 1670 * The new previous lookup class is chosen as follows: 1671 * <ul> 1672 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1673 * the new previous lookup class is {@code null}. 1674 * <li>If the new lookup class is in the same module as the old lookup class, 1675 * the new previous lookup class is the old previous lookup class. 1676 * <li>If the new lookup class is in a different module from the old lookup class, 1677 * the new previous lookup class is the old lookup class. 1678 *</ul> 1679 * <p> 1680 * The resulting lookup's capabilities for loading classes 1681 * (used during {@link #findClass} invocations) 1682 * are determined by the lookup class' loader, 1683 * which may change due to this operation. 1684 * 1685 * @param requestedLookupClass the desired lookup class for the new lookup object 1686 * @return a lookup object which reports the desired lookup class, or the same object 1687 * if there is no change 1688 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1689 * @throws NullPointerException if the argument is null 1690 * 1691 * @revised 9 1692 * @see #accessClass(Class) 1693 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1694 */ 1695 public Lookup in(Class<?> requestedLookupClass) { 1696 Objects.requireNonNull(requestedLookupClass); 1697 if (requestedLookupClass.isPrimitive()) 1698 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1699 if (requestedLookupClass.isArray()) 1700 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1701 1702 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1703 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1704 if (requestedLookupClass == this.lookupClass) 1705 return this; // keep same capabilities 1706 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1707 Module fromModule = this.lookupClass.getModule(); 1708 Module targetModule = requestedLookupClass.getModule(); 1709 Class<?> plc = this.previousLookupClass(); 1710 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1711 assert plc == null; 1712 newModes = UNCONDITIONAL; 1713 } else if (fromModule != targetModule) { 1714 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1715 // allow hopping back and forth between fromModule and plc's module 1716 // but not the third module 1717 newModes = 0; 1718 } 1719 // drop MODULE access 1720 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1721 // teleport from this lookup class 1722 plc = this.lookupClass; 1723 } 1724 if ((newModes & PACKAGE) != 0 1725 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1726 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1727 } 1728 // Allow nestmate lookups to be created without special privilege: 1729 if ((newModes & PRIVATE) != 0 1730 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1731 newModes &= ~(PRIVATE|PROTECTED); 1732 } 1733 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1734 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1735 // The requested class it not accessible from the lookup class. 1736 // No permissions. 1737 newModes = 0; 1738 } 1739 return newLookup(requestedLookupClass, plc, newModes); 1740 } 1741 1742 /** 1743 * Creates a lookup on the same lookup class which this lookup object 1744 * finds members, but with a lookup mode that has lost the given lookup mode. 1745 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1746 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1747 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1748 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1749 * 1750 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1751 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1752 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1753 * lookup has no access. 1754 * 1755 * <p> If this lookup is not a public lookup, then the following applies 1756 * regardless of its {@linkplain #lookupModes() lookup modes}. 1757 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1758 * dropped and so the resulting lookup mode will never have these access 1759 * capabilities. When dropping {@code PACKAGE} 1760 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1761 * access. When dropping {@code MODULE} then the resulting lookup will not 1762 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1763 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1764 * 1765 * @apiNote 1766 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1767 * delegate non-public access within the package of the lookup class without 1768 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1769 * A lookup with {@code MODULE} but not 1770 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1771 * the module of the lookup class without conferring package access. 1772 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1773 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1774 * to public classes accessible to both the module of the lookup class 1775 * and the module of the previous lookup class. 1776 * 1777 * @param modeToDrop the lookup mode to drop 1778 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1779 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1780 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1781 * or {@code UNCONDITIONAL} 1782 * @see MethodHandles#privateLookupIn 1783 * @since 9 1784 */ 1785 public Lookup dropLookupMode(int modeToDrop) { 1786 int oldModes = lookupModes(); 1787 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1788 switch (modeToDrop) { 1789 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1790 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1791 case PACKAGE: newModes &= ~(PRIVATE); break; 1792 case PROTECTED: 1793 case PRIVATE: 1794 case ORIGINAL: 1795 case UNCONDITIONAL: break; 1796 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1797 } 1798 if (newModes == oldModes) return this; // return self if no change 1799 return newLookup(lookupClass(), previousLookupClass(), newModes); 1800 } 1801 1802 /** 1803 * Creates and links a class or interface from {@code bytes} 1804 * with the same class loader and in the same runtime package and 1805 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1806 * {@linkplain #lookupClass() lookup class} as if calling 1807 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1808 * ClassLoader::defineClass}. 1809 * 1810 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1811 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1812 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1813 * that the lookup object was created by a caller in the runtime package (or derived 1814 * from a lookup originally created by suitably privileged code to a target class in 1815 * the runtime package). </p> 1816 * 1817 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1818 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1819 * same package as the lookup class. </p> 1820 * 1821 * <p> This method does not run the class initializer. The class initializer may 1822 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1823 * Specification</em>. </p> 1824 * 1825 * <p> If there is a security manager and this lookup does not have {@linkplain 1826 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1827 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1828 * 1829 * @param bytes the class bytes 1830 * @return the {@code Class} object for the class 1831 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1832 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1833 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1834 * than the lookup class or {@code bytes} is not a class or interface 1835 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1836 * @throws VerifyError if the newly created class cannot be verified 1837 * @throws LinkageError if the newly created class cannot be linked for any other reason 1838 * @throws SecurityException if a security manager is present and it 1839 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1840 * @throws NullPointerException if {@code bytes} is {@code null} 1841 * @since 9 1842 * @see Lookup#privateLookupIn 1843 * @see Lookup#dropLookupMode 1844 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1845 */ 1846 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1847 ensureDefineClassPermission(); 1848 if ((lookupModes() & PACKAGE) == 0) 1849 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1850 return makeClassDefiner(bytes.clone()).defineClass(false); 1851 } 1852 1853 private void ensureDefineClassPermission() { 1854 if (allowedModes == TRUSTED) return; 1855 1856 if (!hasFullPrivilegeAccess()) { 1857 @SuppressWarnings("removal") 1858 SecurityManager sm = System.getSecurityManager(); 1859 if (sm != null) 1860 sm.checkPermission(new RuntimePermission("defineClass")); 1861 } 1862 } 1863 1864 /** 1865 * The set of class options that specify whether a hidden class created by 1866 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1867 * Lookup::defineHiddenClass} method is dynamically added as a new member 1868 * to the nest of a lookup class and/or whether a hidden class has 1869 * a strong relationship with the class loader marked as its defining loader. 1870 * 1871 * @since 15 1872 */ 1873 public enum ClassOption { 1874 /** 1875 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1876 * of a lookup class as a nestmate. 1877 * 1878 * <p> A hidden nestmate class has access to the private members of all 1879 * classes and interfaces in the same nest. 1880 * 1881 * @see Class#getNestHost() 1882 */ 1883 NESTMATE(NESTMATE_CLASS), 1884 1885 /** 1886 * Specifies that a hidden class has a <em>strong</em> 1887 * relationship with the class loader marked as its defining loader, 1888 * as a normal class or interface has with its own defining loader. 1889 * This means that the hidden class may be unloaded if and only if 1890 * its defining loader is not reachable and thus may be reclaimed 1891 * by a garbage collector (JLS {@jls 12.7}). 1892 * 1893 * <p> By default, a hidden class or interface may be unloaded 1894 * even if the class loader that is marked as its defining loader is 1895 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1896 1897 * 1898 * @jls 12.7 Unloading of Classes and Interfaces 1899 */ 1900 STRONG(STRONG_LOADER_LINK); 1901 1902 /* the flag value is used by VM at define class time */ 1903 private final int flag; 1904 ClassOption(int flag) { 1905 this.flag = flag; 1906 } 1907 1908 static int optionsToFlag(Set<ClassOption> options) { 1909 int flags = 0; 1910 for (ClassOption cp : options) { 1911 flags |= cp.flag; 1912 } 1913 return flags; 1914 } 1915 } 1916 1917 /** 1918 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1919 * returning a {@code Lookup} on the newly created class or interface. 1920 * 1921 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1922 * which either defines {@code C} directly or delegates to another class loader. 1923 * A class loader defines {@code C} directly by invoking 1924 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1925 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1926 * to derive {@code C} from a purported representation in {@code class} file format. 1927 * In situations where use of a class loader is undesirable, a class or interface 1928 * {@code C} can be created by this method instead. This method is capable of 1929 * defining {@code C}, and thereby creating it, without invoking 1930 * {@code ClassLoader::defineClass}. 1931 * Instead, this method defines {@code C} as if by arranging for 1932 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1933 * from a purported representation in {@code class} file format 1934 * using the following rules: 1935 * 1936 * <ol> 1937 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1938 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1939 * This level of access is needed to create {@code C} in the module 1940 * of the lookup class of this {@code Lookup}.</li> 1941 * 1942 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1943 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1944 * The major and minor version may differ from the {@code class} file version 1945 * of the lookup class of this {@code Lookup}.</li> 1946 * 1947 * <li> The value of {@code this_class} must be a valid index in the 1948 * {@code constant_pool} table, and the entry at that index must be a valid 1949 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1950 * encoded in internal form that is specified by this structure. {@code N} must 1951 * denote a class or interface in the same package as the lookup class.</li> 1952 * 1953 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1954 * where {@code <suffix>} is an unqualified name. 1955 * 1956 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1957 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1958 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1959 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1960 * refers to the new {@code CONSTANT_Utf8_info} structure. 1961 * 1962 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1963 * 1964 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1965 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1966 * with the following adjustments: 1967 * <ul> 1968 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1969 * that includes a single {@code "."} character, even though this is not a valid 1970 * binary class or interface name in internal form.</li> 1971 * 1972 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1973 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1974 * 1975 * <li> {@code C} is considered to have the same runtime 1976 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1977 * and {@linkplain java.security.ProtectionDomain protection domain} 1978 * as the lookup class of this {@code Lookup}. 1979 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1980 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1981 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1982 * <ul> 1983 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1984 * even though this is not a valid binary class or interface name.</li> 1985 * <li> {@link Class#descriptorString()} returns the string 1986 * {@code "L" + N + "." + <suffix> + ";"}, 1987 * even though this is not a valid type descriptor name.</li> 1988 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1989 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1990 * </ul> 1991 * </ul> 1992 * </li> 1993 * </ol> 1994 * 1995 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1996 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1997 * <ul> 1998 * <li> During verification, whenever it is necessary to load the class named 1999 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2000 * made of any class loader.</li> 2001 * 2002 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2003 * by {@code this_class}, the symbolic reference is considered to be resolved to 2004 * {@code C} and resolution always succeeds immediately.</li> 2005 * </ul> 2006 * 2007 * <p> If the {@code initialize} parameter is {@code true}, 2008 * then {@code C} is initialized by the Java Virtual Machine. 2009 * 2010 * <p> The newly created class or interface {@code C} serves as the 2011 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2012 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2013 * no other class or interface can refer to {@code C} via a constant pool entry. 2014 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2015 * a method parameter type, or a method return type by any other class. 2016 * This is because a hidden class or interface does not have a binary name, so 2017 * there is no internal form available to record in any class's constant pool. 2018 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2019 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2020 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2021 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2022 * JVM Tool Interface</a>. 2023 * 2024 * <p> A class or interface created by 2025 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2026 * a class loader} has a strong relationship with that class loader. 2027 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2028 * that {@linkplain Class#getClassLoader() defined it}. 2029 * This means that a class created by a class loader may be unloaded if and 2030 * only if its defining loader is not reachable and thus may be reclaimed 2031 * by a garbage collector (JLS {@jls 12.7}). 2032 * 2033 * By default, however, a hidden class or interface may be unloaded even if 2034 * the class loader that is marked as its defining loader is 2035 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2036 * This behavior is useful when a hidden class or interface serves multiple 2037 * classes defined by arbitrary class loaders. In other cases, a hidden 2038 * class or interface may be linked to a single class (or a small number of classes) 2039 * with the same defining loader as the hidden class or interface. 2040 * In such cases, where the hidden class or interface must be coterminous 2041 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2042 * option may be passed in {@code options}. 2043 * This arranges for a hidden class to have the same strong relationship 2044 * with the class loader marked as its defining loader, 2045 * as a normal class or interface has with its own defining loader. 2046 * 2047 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2048 * may still prevent a hidden class or interface from being 2049 * unloaded by ensuring that the {@code Class} object is reachable. 2050 * 2051 * <p> The unloading characteristics are set for each hidden class when it is 2052 * defined, and cannot be changed later. An advantage of allowing hidden classes 2053 * to be unloaded independently of the class loader marked as their defining loader 2054 * is that a very large number of hidden classes may be created by an application. 2055 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2056 * just as if normal classes were created by class loaders. 2057 * 2058 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2059 * their private members. The nest relationship is determined by 2060 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2061 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2062 * By default, a hidden class belongs to a nest consisting only of itself 2063 * because a hidden class has no binary name. 2064 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2065 * to create a hidden class or interface {@code C} as a member of a nest. 2066 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2067 * in the {@code ClassFile} structure from which {@code C} was derived. 2068 * Instead, the following rules determine the nest host of {@code C}: 2069 * <ul> 2070 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2071 * been determined, then let {@code H} be the nest host of the lookup class. 2072 * Otherwise, the nest host of the lookup class is determined using the 2073 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2074 * <li>The nest host of {@code C} is determined to be {@code H}, 2075 * the nest host of the lookup class.</li> 2076 * </ul> 2077 * 2078 * <p> A hidden class or interface may be serializable, but this requires a custom 2079 * serialization mechanism in order to ensure that instances are properly serialized 2080 * and deserialized. The default serialization mechanism supports only classes and 2081 * interfaces that are discoverable by their class name. 2082 * 2083 * @param bytes the bytes that make up the class data, 2084 * in the format of a valid {@code class} file as defined by 2085 * <cite>The Java Virtual Machine Specification</cite>. 2086 * @param initialize if {@code true} the class will be initialized. 2087 * @param options {@linkplain ClassOption class options} 2088 * @return the {@code Lookup} object on the hidden class, 2089 * with {@linkplain #ORIGINAL original} and 2090 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2091 * 2092 * @throws IllegalAccessException if this {@code Lookup} does not have 2093 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2094 * @throws SecurityException if a security manager is present and it 2095 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2096 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2097 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2098 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2099 * than the lookup class or {@code bytes} is not a class or interface 2100 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2101 * @throws IncompatibleClassChangeError if the class or interface named as 2102 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2103 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2104 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2105 * {@code C} is {@code C} itself 2106 * @throws VerifyError if the newly created class cannot be verified 2107 * @throws LinkageError if the newly created class cannot be linked for any other reason 2108 * @throws NullPointerException if any parameter is {@code null} 2109 * 2110 * @since 15 2111 * @see Class#isHidden() 2112 * @jvms 4.2.1 Binary Class and Interface Names 2113 * @jvms 4.2.2 Unqualified Names 2114 * @jvms 4.7.28 The {@code NestHost} Attribute 2115 * @jvms 4.7.29 The {@code NestMembers} Attribute 2116 * @jvms 5.4.3.1 Class and Interface Resolution 2117 * @jvms 5.4.4 Access Control 2118 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2119 * @jvms 5.4 Linking 2120 * @jvms 5.5 Initialization 2121 * @jls 12.7 Unloading of Classes and Interfaces 2122 */ 2123 @SuppressWarnings("doclint:reference") // cross-module links 2124 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2125 throws IllegalAccessException 2126 { 2127 Objects.requireNonNull(bytes); 2128 Objects.requireNonNull(options); 2129 2130 ensureDefineClassPermission(); 2131 if (!hasFullPrivilegeAccess()) { 2132 throw new IllegalAccessException(this + " does not have full privilege access"); 2133 } 2134 2135 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize); 2136 } 2137 2138 /** 2139 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2140 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2141 * returning a {@code Lookup} on the newly created class or interface. 2142 * 2143 * <p> This method is equivalent to calling 2144 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2145 * as if the hidden class is injected with a private static final <i>unnamed</i> 2146 * field which is initialized with the given {@code classData} at 2147 * the first instruction of the class initializer. 2148 * The newly created class is linked by the Java Virtual Machine. 2149 * 2150 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2151 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2152 * methods can be used to retrieve the {@code classData}. 2153 * 2154 * @apiNote 2155 * A framework can create a hidden class with class data with one or more 2156 * objects and load the class data as dynamically-computed constant(s) 2157 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2158 * Class data} is accessible only to the lookup object created by the newly 2159 * defined hidden class but inaccessible to other members in the same nest 2160 * (unlike private static fields that are accessible to nestmates). 2161 * Care should be taken w.r.t. mutability for example when passing 2162 * an array or other mutable structure through the class data. 2163 * Changing any value stored in the class data at runtime may lead to 2164 * unpredictable behavior. 2165 * If the class data is a {@code List}, it is good practice to make it 2166 * unmodifiable for example via {@link List#of List::of}. 2167 * 2168 * @param bytes the class bytes 2169 * @param classData pre-initialized class data 2170 * @param initialize if {@code true} the class will be initialized. 2171 * @param options {@linkplain ClassOption class options} 2172 * @return the {@code Lookup} object on the hidden class, 2173 * with {@linkplain #ORIGINAL original} and 2174 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2175 * 2176 * @throws IllegalAccessException if this {@code Lookup} does not have 2177 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2178 * @throws SecurityException if a security manager is present and it 2179 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2180 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2181 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2182 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2183 * than the lookup class or {@code bytes} is not a class or interface 2184 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2185 * @throws IncompatibleClassChangeError if the class or interface named as 2186 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2187 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2188 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2189 * {@code C} is {@code C} itself 2190 * @throws VerifyError if the newly created class cannot be verified 2191 * @throws LinkageError if the newly created class cannot be linked for any other reason 2192 * @throws NullPointerException if any parameter is {@code null} 2193 * 2194 * @since 16 2195 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2196 * @see Class#isHidden() 2197 * @see MethodHandles#classData(Lookup, String, Class) 2198 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2199 * @jvms 4.2.1 Binary Class and Interface Names 2200 * @jvms 4.2.2 Unqualified Names 2201 * @jvms 4.7.28 The {@code NestHost} Attribute 2202 * @jvms 4.7.29 The {@code NestMembers} Attribute 2203 * @jvms 5.4.3.1 Class and Interface Resolution 2204 * @jvms 5.4.4 Access Control 2205 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2206 * @jvms 5.4 Linking 2207 * @jvms 5.5 Initialization 2208 * @jls 12.7 Unloading of Classes and Interface 2209 */ 2210 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2211 throws IllegalAccessException 2212 { 2213 Objects.requireNonNull(bytes); 2214 Objects.requireNonNull(classData); 2215 Objects.requireNonNull(options); 2216 2217 ensureDefineClassPermission(); 2218 if (!hasFullPrivilegeAccess()) { 2219 throw new IllegalAccessException(this + " does not have full privilege access"); 2220 } 2221 2222 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false) 2223 .defineClassAsLookup(initialize, classData); 2224 } 2225 2226 static class ClassFile { 2227 final String name; 2228 final int accessFlags; 2229 final byte[] bytes; 2230 ClassFile(String name, int accessFlags, byte[] bytes) { 2231 this.name = name; 2232 this.accessFlags = accessFlags; 2233 this.bytes = bytes; 2234 } 2235 2236 static ClassFile newInstanceNoCheck(String name, byte[] bytes) { 2237 return new ClassFile(name, 0, bytes); 2238 } 2239 2240 /** 2241 * This method checks the class file version and the structure of `this_class`. 2242 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2243 * that is in the named package. 2244 * 2245 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2246 * or the class is not in the given package name. 2247 */ 2248 static ClassFile newInstance(byte[] bytes, String pkgName) { 2249 int magic = readInt(bytes, 0); 2250 if (magic != 0xCAFEBABE) { 2251 throw new ClassFormatError("Incompatible magic value: " + magic); 2252 } 2253 int minor = readUnsignedShort(bytes, 4); 2254 int major = readUnsignedShort(bytes, 6); 2255 if (!VM.isSupportedClassFileVersion(major, minor)) { 2256 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2257 } 2258 2259 String name; 2260 int accessFlags; 2261 try { 2262 ClassReader reader = new ClassReader(bytes); 2263 // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info 2264 // workaround to read `this_class` using readConst and validate the value 2265 int thisClass = reader.readUnsignedShort(reader.header + 2); 2266 Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]); 2267 if (!(constant instanceof Type type)) { 2268 throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info"); 2269 } 2270 if (!type.getDescriptor().startsWith("L")) { 2271 throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info"); 2272 } 2273 name = type.getClassName(); 2274 accessFlags = reader.readUnsignedShort(reader.header); 2275 } catch (RuntimeException e) { 2276 // ASM exceptions are poorly specified 2277 ClassFormatError cfe = new ClassFormatError(); 2278 cfe.initCause(e); 2279 throw cfe; 2280 } 2281 2282 // must be a class or interface 2283 if ((accessFlags & Opcodes.ACC_MODULE) != 0) { 2284 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2285 } 2286 2287 // check if it's in the named package 2288 int index = name.lastIndexOf('.'); 2289 String pn = (index == -1) ? "" : name.substring(0, index); 2290 if (!pn.equals(pkgName)) { 2291 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2292 } 2293 2294 return new ClassFile(name, accessFlags, bytes); 2295 } 2296 2297 private static int readInt(byte[] bytes, int offset) { 2298 if ((offset+4) > bytes.length) { 2299 throw new ClassFormatError("Invalid ClassFile structure"); 2300 } 2301 return ((bytes[offset] & 0xFF) << 24) 2302 | ((bytes[offset + 1] & 0xFF) << 16) 2303 | ((bytes[offset + 2] & 0xFF) << 8) 2304 | (bytes[offset + 3] & 0xFF); 2305 } 2306 2307 private static int readUnsignedShort(byte[] bytes, int offset) { 2308 if ((offset+2) > bytes.length) { 2309 throw new ClassFormatError("Invalid ClassFile structure"); 2310 } 2311 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2312 } 2313 } 2314 2315 /* 2316 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2317 * from the given bytes. 2318 * 2319 * Caller should make a defensive copy of the arguments if needed 2320 * before calling this factory method. 2321 * 2322 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2323 * {@bytes} denotes a class in a different package than the lookup class 2324 */ 2325 private ClassDefiner makeClassDefiner(byte[] bytes) { 2326 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2327 return new ClassDefiner(this, cf, STRONG_LOADER_LINK); 2328 } 2329 2330 /** 2331 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2332 * from the given bytes. The name must be in the same package as the lookup class. 2333 * 2334 * Caller should make a defensive copy of the arguments if needed 2335 * before calling this factory method. 2336 * 2337 * @param bytes class bytes 2338 * @return ClassDefiner that defines a hidden class of the given bytes. 2339 * 2340 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2341 * {@bytes} denotes a class in a different package than the lookup class 2342 */ 2343 ClassDefiner makeHiddenClassDefiner(byte[] bytes) { 2344 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2345 return makeHiddenClassDefiner(cf, Set.of(), false); 2346 } 2347 2348 /** 2349 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2350 * from the given bytes and options. 2351 * The name must be in the same package as the lookup class. 2352 * 2353 * Caller should make a defensive copy of the arguments if needed 2354 * before calling this factory method. 2355 * 2356 * @param bytes class bytes 2357 * @param options class options 2358 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2359 * @return ClassDefiner that defines a hidden class of the given bytes and options 2360 * 2361 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2362 * {@bytes} denotes a class in a different package than the lookup class 2363 */ 2364 ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2365 Set<ClassOption> options, 2366 boolean accessVmAnnotations) { 2367 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2368 return makeHiddenClassDefiner(cf, options, accessVmAnnotations); 2369 } 2370 2371 /** 2372 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2373 * from the given bytes and the given options. No package name check on the given name. 2374 * 2375 * @param name fully-qualified name that specifies the prefix of the hidden class 2376 * @param bytes class bytes 2377 * @param options class options 2378 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2379 */ 2380 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options) { 2381 // skip name and access flags validation 2382 return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false); 2383 } 2384 2385 /** 2386 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2387 * from the given class file and options. 2388 * 2389 * @param cf ClassFile 2390 * @param options class options 2391 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2392 */ 2393 private ClassDefiner makeHiddenClassDefiner(ClassFile cf, 2394 Set<ClassOption> options, 2395 boolean accessVmAnnotations) { 2396 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options); 2397 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2398 // jdk.internal.vm.annotations are permitted for classes 2399 // defined to boot loader and platform loader 2400 flags |= ACCESS_VM_ANNOTATIONS; 2401 } 2402 2403 return new ClassDefiner(this, cf, flags); 2404 } 2405 2406 static class ClassDefiner { 2407 private final Lookup lookup; 2408 private final String name; 2409 private final byte[] bytes; 2410 private final int classFlags; 2411 2412 private ClassDefiner(Lookup lookup, ClassFile cf, int flags) { 2413 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2414 this.lookup = lookup; 2415 this.bytes = cf.bytes; 2416 this.name = cf.name; 2417 this.classFlags = flags; 2418 } 2419 2420 String className() { 2421 return name; 2422 } 2423 2424 Class<?> defineClass(boolean initialize) { 2425 return defineClass(initialize, null); 2426 } 2427 2428 Lookup defineClassAsLookup(boolean initialize) { 2429 Class<?> c = defineClass(initialize, null); 2430 return new Lookup(c, null, FULL_POWER_MODES); 2431 } 2432 2433 /** 2434 * Defines the class of the given bytes and the given classData. 2435 * If {@code initialize} parameter is true, then the class will be initialized. 2436 * 2437 * @param initialize true if the class to be initialized 2438 * @param classData classData or null 2439 * @return the class 2440 * 2441 * @throws LinkageError linkage error 2442 */ 2443 Class<?> defineClass(boolean initialize, Object classData) { 2444 Class<?> lookupClass = lookup.lookupClass(); 2445 ClassLoader loader = lookupClass.getClassLoader(); 2446 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2447 Class<?> c = SharedSecrets.getJavaLangAccess() 2448 .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData); 2449 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2450 return c; 2451 } 2452 2453 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2454 Class<?> c = defineClass(initialize, classData); 2455 return new Lookup(c, null, FULL_POWER_MODES); 2456 } 2457 2458 private boolean isNestmate() { 2459 return (classFlags & NESTMATE_CLASS) != 0; 2460 } 2461 } 2462 2463 private ProtectionDomain lookupClassProtectionDomain() { 2464 ProtectionDomain pd = cachedProtectionDomain; 2465 if (pd == null) { 2466 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2467 } 2468 return pd; 2469 } 2470 2471 // cached protection domain 2472 private volatile ProtectionDomain cachedProtectionDomain; 2473 2474 // Make sure outer class is initialized first. 2475 static { IMPL_NAMES.getClass(); } 2476 2477 /** Package-private version of lookup which is trusted. */ 2478 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2479 2480 /** Version of lookup which is trusted minimally. 2481 * It can only be used to create method handles to publicly accessible 2482 * members in packages that are exported unconditionally. 2483 */ 2484 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2485 2486 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2487 String name = lookupClass.getName(); 2488 if (name.startsWith("java.lang.invoke.")) 2489 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2490 } 2491 2492 /** 2493 * Displays the name of the class from which lookups are to be made, 2494 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2495 * previous lookup class} if present. 2496 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2497 * If there are restrictions on the access permitted to this lookup, 2498 * this is indicated by adding a suffix to the class name, consisting 2499 * of a slash and a keyword. The keyword represents the strongest 2500 * allowed access, and is chosen as follows: 2501 * <ul> 2502 * <li>If no access is allowed, the suffix is "/noaccess". 2503 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2504 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2505 * <li>If only public and module access are allowed, the suffix is "/module". 2506 * <li>If public and package access are allowed, the suffix is "/package". 2507 * <li>If public, package, and private access are allowed, the suffix is "/private". 2508 * </ul> 2509 * If none of the above cases apply, it is the case that 2510 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2511 * (public, module, package, private, and protected) is allowed. 2512 * In this case, no suffix is added. 2513 * This is true only of an object obtained originally from 2514 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2515 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2516 * always have restricted access, and will display a suffix. 2517 * <p> 2518 * (It may seem strange that protected access should be 2519 * stronger than private access. Viewed independently from 2520 * package access, protected access is the first to be lost, 2521 * because it requires a direct subclass relationship between 2522 * caller and callee.) 2523 * @see #in 2524 * 2525 * @revised 9 2526 */ 2527 @Override 2528 public String toString() { 2529 String cname = lookupClass.getName(); 2530 if (prevLookupClass != null) 2531 cname += "/" + prevLookupClass.getName(); 2532 switch (allowedModes) { 2533 case 0: // no privileges 2534 return cname + "/noaccess"; 2535 case UNCONDITIONAL: 2536 return cname + "/publicLookup"; 2537 case PUBLIC: 2538 return cname + "/public"; 2539 case PUBLIC|MODULE: 2540 return cname + "/module"; 2541 case PUBLIC|PACKAGE: 2542 case PUBLIC|MODULE|PACKAGE: 2543 return cname + "/package"; 2544 case PUBLIC|PACKAGE|PRIVATE: 2545 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2546 return cname + "/private"; 2547 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2548 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2549 case FULL_POWER_MODES: 2550 return cname; 2551 case TRUSTED: 2552 return "/trusted"; // internal only; not exported 2553 default: // Should not happen, but it's a bitfield... 2554 cname = cname + "/" + Integer.toHexString(allowedModes); 2555 assert(false) : cname; 2556 return cname; 2557 } 2558 } 2559 2560 /** 2561 * Produces a method handle for a static method. 2562 * The type of the method handle will be that of the method. 2563 * (Since static methods do not take receivers, there is no 2564 * additional receiver argument inserted into the method handle type, 2565 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2566 * The method and all its argument types must be accessible to the lookup object. 2567 * <p> 2568 * The returned method handle will have 2569 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2570 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2571 * <p> 2572 * If the returned method handle is invoked, the method's class will 2573 * be initialized, if it has not already been initialized. 2574 * <p><b>Example:</b> 2575 * {@snippet lang="java" : 2576 import static java.lang.invoke.MethodHandles.*; 2577 import static java.lang.invoke.MethodType.*; 2578 ... 2579 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2580 "asList", methodType(List.class, Object[].class)); 2581 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2582 * } 2583 * @param refc the class from which the method is accessed 2584 * @param name the name of the method 2585 * @param type the type of the method 2586 * @return the desired method handle 2587 * @throws NoSuchMethodException if the method does not exist 2588 * @throws IllegalAccessException if access checking fails, 2589 * or if the method is not {@code static}, 2590 * or if the method's variable arity modifier bit 2591 * is set and {@code asVarargsCollector} fails 2592 * @throws SecurityException if a security manager is present and it 2593 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2594 * @throws NullPointerException if any argument is null 2595 */ 2596 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2597 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2598 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2599 } 2600 2601 /** 2602 * Produces a method handle for a virtual method. 2603 * The type of the method handle will be that of the method, 2604 * with the receiver type (usually {@code refc}) prepended. 2605 * The method and all its argument types must be accessible to the lookup object. 2606 * <p> 2607 * When called, the handle will treat the first argument as a receiver 2608 * and, for non-private methods, dispatch on the receiver's type to determine which method 2609 * implementation to enter. 2610 * For private methods the named method in {@code refc} will be invoked on the receiver. 2611 * (The dispatching action is identical with that performed by an 2612 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2613 * <p> 2614 * The first argument will be of type {@code refc} if the lookup 2615 * class has full privileges to access the member. Otherwise 2616 * the member must be {@code protected} and the first argument 2617 * will be restricted in type to the lookup class. 2618 * <p> 2619 * The returned method handle will have 2620 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2621 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2622 * <p> 2623 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2624 * instructions and method handles produced by {@code findVirtual}, 2625 * if the class is {@code MethodHandle} and the name string is 2626 * {@code invokeExact} or {@code invoke}, the resulting 2627 * method handle is equivalent to one produced by 2628 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2629 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2630 * with the same {@code type} argument. 2631 * <p> 2632 * If the class is {@code VarHandle} and the name string corresponds to 2633 * the name of a signature-polymorphic access mode method, the resulting 2634 * method handle is equivalent to one produced by 2635 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2636 * the access mode corresponding to the name string and with the same 2637 * {@code type} arguments. 2638 * <p> 2639 * <b>Example:</b> 2640 * {@snippet lang="java" : 2641 import static java.lang.invoke.MethodHandles.*; 2642 import static java.lang.invoke.MethodType.*; 2643 ... 2644 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2645 "concat", methodType(String.class, String.class)); 2646 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2647 "hashCode", methodType(int.class)); 2648 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2649 "hashCode", methodType(int.class)); 2650 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2651 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2652 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2653 // interface method: 2654 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2655 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2656 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2657 // constructor "internal method" must be accessed differently: 2658 MethodType MT_newString = methodType(void.class); //()V for new String() 2659 try { assertEquals("impossible", lookup() 2660 .findVirtual(String.class, "<init>", MT_newString)); 2661 } catch (NoSuchMethodException ex) { } // OK 2662 MethodHandle MH_newString = publicLookup() 2663 .findConstructor(String.class, MT_newString); 2664 assertEquals("", (String) MH_newString.invokeExact()); 2665 * } 2666 * 2667 * @param refc the class or interface from which the method is accessed 2668 * @param name the name of the method 2669 * @param type the type of the method, with the receiver argument omitted 2670 * @return the desired method handle 2671 * @throws NoSuchMethodException if the method does not exist 2672 * @throws IllegalAccessException if access checking fails, 2673 * or if the method is {@code static}, 2674 * or if the method's variable arity modifier bit 2675 * is set and {@code asVarargsCollector} fails 2676 * @throws SecurityException if a security manager is present and it 2677 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2678 * @throws NullPointerException if any argument is null 2679 */ 2680 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2681 if (refc == MethodHandle.class) { 2682 MethodHandle mh = findVirtualForMH(name, type); 2683 if (mh != null) return mh; 2684 } else if (refc == VarHandle.class) { 2685 MethodHandle mh = findVirtualForVH(name, type); 2686 if (mh != null) return mh; 2687 } 2688 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2689 MemberName method = resolveOrFail(refKind, refc, name, type); 2690 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2691 } 2692 private MethodHandle findVirtualForMH(String name, MethodType type) { 2693 // these names require special lookups because of the implicit MethodType argument 2694 if ("invoke".equals(name)) 2695 return invoker(type); 2696 if ("invokeExact".equals(name)) 2697 return exactInvoker(type); 2698 assert(!MemberName.isMethodHandleInvokeName(name)); 2699 return null; 2700 } 2701 private MethodHandle findVirtualForVH(String name, MethodType type) { 2702 try { 2703 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2704 } catch (IllegalArgumentException e) { 2705 return null; 2706 } 2707 } 2708 2709 /** 2710 * Produces a method handle which creates an object and initializes it, using 2711 * the constructor of the specified type. 2712 * The parameter types of the method handle will be those of the constructor, 2713 * while the return type will be a reference to the constructor's class. 2714 * The constructor and all its argument types must be accessible to the lookup object. 2715 * <p> 2716 * The requested type must have a return type of {@code void}. 2717 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2718 * <p> 2719 * The returned method handle will have 2720 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2721 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2722 * <p> 2723 * If the returned method handle is invoked, the constructor's class will 2724 * be initialized, if it has not already been initialized. 2725 * <p><b>Example:</b> 2726 * {@snippet lang="java" : 2727 import static java.lang.invoke.MethodHandles.*; 2728 import static java.lang.invoke.MethodType.*; 2729 ... 2730 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2731 ArrayList.class, methodType(void.class, Collection.class)); 2732 Collection orig = Arrays.asList("x", "y"); 2733 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2734 assert(orig != copy); 2735 assertEquals(orig, copy); 2736 // a variable-arity constructor: 2737 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2738 ProcessBuilder.class, methodType(void.class, String[].class)); 2739 ProcessBuilder pb = (ProcessBuilder) 2740 MH_newProcessBuilder.invoke("x", "y", "z"); 2741 assertEquals("[x, y, z]", pb.command().toString()); 2742 * } 2743 * @param refc the class or interface from which the method is accessed 2744 * @param type the type of the method, with the receiver argument omitted, and a void return type 2745 * @return the desired method handle 2746 * @throws NoSuchMethodException if the constructor does not exist 2747 * @throws IllegalAccessException if access checking fails 2748 * or if the method's variable arity modifier bit 2749 * is set and {@code asVarargsCollector} fails 2750 * @throws SecurityException if a security manager is present and it 2751 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2752 * @throws NullPointerException if any argument is null 2753 */ 2754 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2755 if (refc.isArray()) { 2756 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2757 } 2758 String name = "<init>"; 2759 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2760 return getDirectConstructor(refc, ctor); 2761 } 2762 2763 /** 2764 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2765 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2766 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2767 * and then determines whether the class is accessible to this lookup object. 2768 * <p> 2769 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2770 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2771 * 2772 * @param targetName the fully qualified name of the class to be looked up. 2773 * @return the requested class. 2774 * @throws SecurityException if a security manager is present and it 2775 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2776 * @throws LinkageError if the linkage fails 2777 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2778 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2779 * modes. 2780 * @throws NullPointerException if {@code targetName} is null 2781 * @since 9 2782 * @jvms 5.4.3.1 Class and Interface Resolution 2783 */ 2784 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2785 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2786 return accessClass(targetClass); 2787 } 2788 2789 /** 2790 * Ensures that {@code targetClass} has been initialized. The class 2791 * to be initialized must be {@linkplain #accessClass accessible} 2792 * to this {@code Lookup} object. This method causes {@code targetClass} 2793 * to be initialized if it has not been already initialized, 2794 * as specified in JVMS {@jvms 5.5}. 2795 * 2796 * <p> 2797 * This method returns when {@code targetClass} is fully initialized, or 2798 * when {@code targetClass} is being initialized by the current thread. 2799 * 2800 * @param targetClass the class to be initialized 2801 * @return {@code targetClass} that has been initialized, or that is being 2802 * initialized by the current thread. 2803 * 2804 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2805 * or array class 2806 * @throws IllegalAccessException if {@code targetClass} is not 2807 * {@linkplain #accessClass accessible} to this lookup 2808 * @throws ExceptionInInitializerError if the class initialization provoked 2809 * by this method fails 2810 * @throws SecurityException if a security manager is present and it 2811 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2812 * @since 15 2813 * @jvms 5.5 Initialization 2814 */ 2815 public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException { 2816 if (targetClass.isPrimitive()) 2817 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2818 if (targetClass.isArray()) 2819 throw new IllegalArgumentException(targetClass + " is an array class"); 2820 2821 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2822 throw makeAccessException(targetClass); 2823 } 2824 checkSecurityManager(targetClass); 2825 2826 // ensure class initialization 2827 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2828 return targetClass; 2829 } 2830 2831 /* 2832 * Returns IllegalAccessException due to access violation to the given targetClass. 2833 * 2834 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2835 * which verifies access to a class rather a member. 2836 */ 2837 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2838 String message = "access violation: "+ targetClass; 2839 if (this == MethodHandles.publicLookup()) { 2840 message += ", from public Lookup"; 2841 } else { 2842 Module m = lookupClass().getModule(); 2843 message += ", from " + lookupClass() + " (" + m + ")"; 2844 if (prevLookupClass != null) { 2845 message += ", previous lookup " + 2846 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2847 } 2848 } 2849 return new IllegalAccessException(message); 2850 } 2851 2852 /** 2853 * Determines if a class can be accessed from the lookup context defined by 2854 * this {@code Lookup} object. The static initializer of the class is not run. 2855 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2856 * if the element type of the array class is accessible. Otherwise, 2857 * {@code targetClass} is determined as accessible as follows. 2858 * 2859 * <p> 2860 * If {@code targetClass} is in the same module as the lookup class, 2861 * the lookup class is {@code LC} in module {@code M1} and 2862 * the previous lookup class is in module {@code M0} or 2863 * {@code null} if not present, 2864 * {@code targetClass} is accessible if and only if one of the following is true: 2865 * <ul> 2866 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2867 * {@code LC} or other class in the same nest of {@code LC}.</li> 2868 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2869 * in the same runtime package of {@code LC}.</li> 2870 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2871 * a public type in {@code M1}.</li> 2872 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2873 * a public type in a package exported by {@code M1} to at least {@code M0} 2874 * if the previous lookup class is present; otherwise, {@code targetClass} 2875 * is a public type in a package exported by {@code M1} unconditionally.</li> 2876 * </ul> 2877 * 2878 * <p> 2879 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2880 * can access public types in all modules when the type is in a package 2881 * that is exported unconditionally. 2882 * <p> 2883 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2884 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2885 * is inaccessible. 2886 * <p> 2887 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2888 * {@code M1} is the module containing {@code lookupClass} and 2889 * {@code M2} is the module containing {@code targetClass}, 2890 * then {@code targetClass} is accessible if and only if 2891 * <ul> 2892 * <li>{@code M1} reads {@code M2}, and 2893 * <li>{@code targetClass} is public and in a package exported by 2894 * {@code M2} at least to {@code M1}. 2895 * </ul> 2896 * <p> 2897 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2898 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2899 * containing the previous lookup class, then {@code targetClass} is accessible 2900 * if and only if one of the following is true: 2901 * <ul> 2902 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2903 * {@linkplain Module#reads reads} {@code M0} and the type is 2904 * in a package that is exported to at least {@code M1}. 2905 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2906 * {@linkplain Module#reads reads} {@code M1} and the type is 2907 * in a package that is exported to at least {@code M0}. 2908 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2909 * and {@code M1} reads {@code M2} and the type is in a package 2910 * that is exported to at least both {@code M0} and {@code M2}. 2911 * </ul> 2912 * <p> 2913 * Otherwise, {@code targetClass} is not accessible. 2914 * 2915 * @param targetClass the class to be access-checked 2916 * @return the class that has been access-checked 2917 * @throws IllegalAccessException if the class is not accessible from the lookup class 2918 * and previous lookup class, if present, using the allowed access modes. 2919 * @throws SecurityException if a security manager is present and it 2920 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2921 * @throws NullPointerException if {@code targetClass} is {@code null} 2922 * @since 9 2923 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2924 */ 2925 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { 2926 if (!isClassAccessible(targetClass)) { 2927 throw makeAccessException(targetClass); 2928 } 2929 checkSecurityManager(targetClass); 2930 return targetClass; 2931 } 2932 2933 /** 2934 * Produces an early-bound method handle for a virtual method. 2935 * It will bypass checks for overriding methods on the receiver, 2936 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2937 * instruction from within the explicitly specified {@code specialCaller}. 2938 * The type of the method handle will be that of the method, 2939 * with a suitably restricted receiver type prepended. 2940 * (The receiver type will be {@code specialCaller} or a subtype.) 2941 * The method and all its argument types must be accessible 2942 * to the lookup object. 2943 * <p> 2944 * Before method resolution, 2945 * if the explicitly specified caller class is not identical with the 2946 * lookup class, or if this lookup object does not have 2947 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2948 * privileges, the access fails. 2949 * <p> 2950 * The returned method handle will have 2951 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2952 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2953 * <p style="font-size:smaller;"> 2954 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 2955 * even though the {@code invokespecial} instruction can refer to them 2956 * in special circumstances. Use {@link #findConstructor findConstructor} 2957 * to access instance initialization methods in a safe manner.)</em> 2958 * <p><b>Example:</b> 2959 * {@snippet lang="java" : 2960 import static java.lang.invoke.MethodHandles.*; 2961 import static java.lang.invoke.MethodType.*; 2962 ... 2963 static class Listie extends ArrayList { 2964 public String toString() { return "[wee Listie]"; } 2965 static Lookup lookup() { return MethodHandles.lookup(); } 2966 } 2967 ... 2968 // no access to constructor via invokeSpecial: 2969 MethodHandle MH_newListie = Listie.lookup() 2970 .findConstructor(Listie.class, methodType(void.class)); 2971 Listie l = (Listie) MH_newListie.invokeExact(); 2972 try { assertEquals("impossible", Listie.lookup().findSpecial( 2973 Listie.class, "<init>", methodType(void.class), Listie.class)); 2974 } catch (NoSuchMethodException ex) { } // OK 2975 // access to super and self methods via invokeSpecial: 2976 MethodHandle MH_super = Listie.lookup().findSpecial( 2977 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2978 MethodHandle MH_this = Listie.lookup().findSpecial( 2979 Listie.class, "toString" , methodType(String.class), Listie.class); 2980 MethodHandle MH_duper = Listie.lookup().findSpecial( 2981 Object.class, "toString" , methodType(String.class), Listie.class); 2982 assertEquals("[]", (String) MH_super.invokeExact(l)); 2983 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2984 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2985 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2986 String.class, "toString", methodType(String.class), Listie.class)); 2987 } catch (IllegalAccessException ex) { } // OK 2988 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2989 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2990 * } 2991 * 2992 * @param refc the class or interface from which the method is accessed 2993 * @param name the name of the method (which must not be "<init>") 2994 * @param type the type of the method, with the receiver argument omitted 2995 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2996 * @return the desired method handle 2997 * @throws NoSuchMethodException if the method does not exist 2998 * @throws IllegalAccessException if access checking fails, 2999 * or if the method is {@code static}, 3000 * or if the method's variable arity modifier bit 3001 * is set and {@code asVarargsCollector} fails 3002 * @throws SecurityException if a security manager is present and it 3003 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3004 * @throws NullPointerException if any argument is null 3005 */ 3006 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3007 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3008 checkSpecialCaller(specialCaller, refc); 3009 Lookup specialLookup = this.in(specialCaller); 3010 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3011 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3012 } 3013 3014 /** 3015 * Produces a method handle giving read access to a non-static field. 3016 * The type of the method handle will have a return type of the field's 3017 * value type. 3018 * The method handle's single argument will be the instance containing 3019 * the field. 3020 * Access checking is performed immediately on behalf of the lookup class. 3021 * @param refc the class or interface from which the method is accessed 3022 * @param name the field's name 3023 * @param type the field's type 3024 * @return a method handle which can load values from the field 3025 * @throws NoSuchFieldException if the field does not exist 3026 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3027 * @throws SecurityException if a security manager is present and it 3028 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3029 * @throws NullPointerException if any argument is null 3030 * @see #findVarHandle(Class, String, Class) 3031 */ 3032 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3033 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3034 return getDirectField(REF_getField, refc, field); 3035 } 3036 3037 /** 3038 * Produces a method handle giving write access to a non-static field. 3039 * The type of the method handle will have a void return type. 3040 * The method handle will take two arguments, the instance containing 3041 * the field, and the value to be stored. 3042 * The second argument will be of the field's value type. 3043 * Access checking is performed immediately on behalf of the lookup class. 3044 * @param refc the class or interface from which the method is accessed 3045 * @param name the field's name 3046 * @param type the field's type 3047 * @return a method handle which can store values into the field 3048 * @throws NoSuchFieldException if the field does not exist 3049 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3050 * or {@code final} 3051 * @throws SecurityException if a security manager is present and it 3052 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3053 * @throws NullPointerException if any argument is null 3054 * @see #findVarHandle(Class, String, Class) 3055 */ 3056 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3057 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3058 return getDirectField(REF_putField, refc, field); 3059 } 3060 3061 /** 3062 * Produces a VarHandle giving access to a non-static field {@code name} 3063 * of type {@code type} declared in a class of type {@code recv}. 3064 * The VarHandle's variable type is {@code type} and it has one 3065 * coordinate type, {@code recv}. 3066 * <p> 3067 * Access checking is performed immediately on behalf of the lookup 3068 * class. 3069 * <p> 3070 * Certain access modes of the returned VarHandle are unsupported under 3071 * the following conditions: 3072 * <ul> 3073 * <li>if the field is declared {@code final}, then the write, atomic 3074 * update, numeric atomic update, and bitwise atomic update access 3075 * modes are unsupported. 3076 * <li>if the field type is anything other than {@code byte}, 3077 * {@code short}, {@code char}, {@code int}, {@code long}, 3078 * {@code float}, or {@code double} then numeric atomic update 3079 * access modes are unsupported. 3080 * <li>if the field type is anything other than {@code boolean}, 3081 * {@code byte}, {@code short}, {@code char}, {@code int} or 3082 * {@code long} then bitwise atomic update access modes are 3083 * unsupported. 3084 * </ul> 3085 * <p> 3086 * If the field is declared {@code volatile} then the returned VarHandle 3087 * will override access to the field (effectively ignore the 3088 * {@code volatile} declaration) in accordance to its specified 3089 * access modes. 3090 * <p> 3091 * If the field type is {@code float} or {@code double} then numeric 3092 * and atomic update access modes compare values using their bitwise 3093 * representation (see {@link Float#floatToRawIntBits} and 3094 * {@link Double#doubleToRawLongBits}, respectively). 3095 * @apiNote 3096 * Bitwise comparison of {@code float} values or {@code double} values, 3097 * as performed by the numeric and atomic update access modes, differ 3098 * from the primitive {@code ==} operator and the {@link Float#equals} 3099 * and {@link Double#equals} methods, specifically with respect to 3100 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3101 * Care should be taken when performing a compare and set or a compare 3102 * and exchange operation with such values since the operation may 3103 * unexpectedly fail. 3104 * There are many possible NaN values that are considered to be 3105 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3106 * provided by Java can distinguish between them. Operation failure can 3107 * occur if the expected or witness value is a NaN value and it is 3108 * transformed (perhaps in a platform specific manner) into another NaN 3109 * value, and thus has a different bitwise representation (see 3110 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3111 * details). 3112 * The values {@code -0.0} and {@code +0.0} have different bitwise 3113 * representations but are considered equal when using the primitive 3114 * {@code ==} operator. Operation failure can occur if, for example, a 3115 * numeric algorithm computes an expected value to be say {@code -0.0} 3116 * and previously computed the witness value to be say {@code +0.0}. 3117 * @param recv the receiver class, of type {@code R}, that declares the 3118 * non-static field 3119 * @param name the field's name 3120 * @param type the field's type, of type {@code T} 3121 * @return a VarHandle giving access to non-static fields. 3122 * @throws NoSuchFieldException if the field does not exist 3123 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3124 * @throws SecurityException if a security manager is present and it 3125 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3126 * @throws NullPointerException if any argument is null 3127 * @since 9 3128 */ 3129 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3130 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3131 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3132 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3133 } 3134 3135 /** 3136 * Produces a method handle giving read access to a static field. 3137 * The type of the method handle will have a return type of the field's 3138 * value type. 3139 * The method handle will take no arguments. 3140 * Access checking is performed immediately on behalf of the lookup class. 3141 * <p> 3142 * If the returned method handle is invoked, the field's class will 3143 * be initialized, if it has not already been initialized. 3144 * @param refc the class or interface from which the method is accessed 3145 * @param name the field's name 3146 * @param type the field's type 3147 * @return a method handle which can load values from the field 3148 * @throws NoSuchFieldException if the field does not exist 3149 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3150 * @throws SecurityException if a security manager is present and it 3151 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3152 * @throws NullPointerException if any argument is null 3153 */ 3154 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3155 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3156 return getDirectField(REF_getStatic, refc, field); 3157 } 3158 3159 /** 3160 * Produces a method handle giving write access to a static field. 3161 * The type of the method handle will have a void return type. 3162 * The method handle will take a single 3163 * argument, of the field's value type, the value to be stored. 3164 * Access checking is performed immediately on behalf of the lookup class. 3165 * <p> 3166 * If the returned method handle is invoked, the field's class will 3167 * be initialized, if it has not already been initialized. 3168 * @param refc the class or interface from which the method is accessed 3169 * @param name the field's name 3170 * @param type the field's type 3171 * @return a method handle which can store values into the field 3172 * @throws NoSuchFieldException if the field does not exist 3173 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3174 * or is {@code final} 3175 * @throws SecurityException if a security manager is present and it 3176 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3177 * @throws NullPointerException if any argument is null 3178 */ 3179 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3180 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3181 return getDirectField(REF_putStatic, refc, field); 3182 } 3183 3184 /** 3185 * Produces a VarHandle giving access to a static field {@code name} of 3186 * type {@code type} declared in a class of type {@code decl}. 3187 * The VarHandle's variable type is {@code type} and it has no 3188 * coordinate types. 3189 * <p> 3190 * Access checking is performed immediately on behalf of the lookup 3191 * class. 3192 * <p> 3193 * If the returned VarHandle is operated on, the declaring class will be 3194 * initialized, if it has not already been initialized. 3195 * <p> 3196 * Certain access modes of the returned VarHandle are unsupported under 3197 * the following conditions: 3198 * <ul> 3199 * <li>if the field is declared {@code final}, then the write, atomic 3200 * update, numeric atomic update, and bitwise atomic update access 3201 * modes are unsupported. 3202 * <li>if the field type is anything other than {@code byte}, 3203 * {@code short}, {@code char}, {@code int}, {@code long}, 3204 * {@code float}, or {@code double}, then numeric atomic update 3205 * access modes are unsupported. 3206 * <li>if the field type is anything other than {@code boolean}, 3207 * {@code byte}, {@code short}, {@code char}, {@code int} or 3208 * {@code long} then bitwise atomic update access modes are 3209 * unsupported. 3210 * </ul> 3211 * <p> 3212 * If the field is declared {@code volatile} then the returned VarHandle 3213 * will override access to the field (effectively ignore the 3214 * {@code volatile} declaration) in accordance to its specified 3215 * access modes. 3216 * <p> 3217 * If the field type is {@code float} or {@code double} then numeric 3218 * and atomic update access modes compare values using their bitwise 3219 * representation (see {@link Float#floatToRawIntBits} and 3220 * {@link Double#doubleToRawLongBits}, respectively). 3221 * @apiNote 3222 * Bitwise comparison of {@code float} values or {@code double} values, 3223 * as performed by the numeric and atomic update access modes, differ 3224 * from the primitive {@code ==} operator and the {@link Float#equals} 3225 * and {@link Double#equals} methods, specifically with respect to 3226 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3227 * Care should be taken when performing a compare and set or a compare 3228 * and exchange operation with such values since the operation may 3229 * unexpectedly fail. 3230 * There are many possible NaN values that are considered to be 3231 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3232 * provided by Java can distinguish between them. Operation failure can 3233 * occur if the expected or witness value is a NaN value and it is 3234 * transformed (perhaps in a platform specific manner) into another NaN 3235 * value, and thus has a different bitwise representation (see 3236 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3237 * details). 3238 * The values {@code -0.0} and {@code +0.0} have different bitwise 3239 * representations but are considered equal when using the primitive 3240 * {@code ==} operator. Operation failure can occur if, for example, a 3241 * numeric algorithm computes an expected value to be say {@code -0.0} 3242 * and previously computed the witness value to be say {@code +0.0}. 3243 * @param decl the class that declares the static field 3244 * @param name the field's name 3245 * @param type the field's type, of type {@code T} 3246 * @return a VarHandle giving access to a static field 3247 * @throws NoSuchFieldException if the field does not exist 3248 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3249 * @throws SecurityException if a security manager is present and it 3250 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3251 * @throws NullPointerException if any argument is null 3252 * @since 9 3253 */ 3254 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3255 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3256 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3257 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3258 } 3259 3260 /** 3261 * Produces an early-bound method handle for a non-static method. 3262 * The receiver must have a supertype {@code defc} in which a method 3263 * of the given name and type is accessible to the lookup class. 3264 * The method and all its argument types must be accessible to the lookup object. 3265 * The type of the method handle will be that of the method, 3266 * without any insertion of an additional receiver parameter. 3267 * The given receiver will be bound into the method handle, 3268 * so that every call to the method handle will invoke the 3269 * requested method on the given receiver. 3270 * <p> 3271 * The returned method handle will have 3272 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3273 * the method's variable arity modifier bit ({@code 0x0080}) is set 3274 * <em>and</em> the trailing array argument is not the only argument. 3275 * (If the trailing array argument is the only argument, 3276 * the given receiver value will be bound to it.) 3277 * <p> 3278 * This is almost equivalent to the following code, with some differences noted below: 3279 * {@snippet lang="java" : 3280 import static java.lang.invoke.MethodHandles.*; 3281 import static java.lang.invoke.MethodType.*; 3282 ... 3283 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3284 MethodHandle mh1 = mh0.bindTo(receiver); 3285 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3286 return mh1; 3287 * } 3288 * where {@code defc} is either {@code receiver.getClass()} or a super 3289 * type of that class, in which the requested method is accessible 3290 * to the lookup class. 3291 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3292 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3293 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3294 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3295 * @param receiver the object from which the method is accessed 3296 * @param name the name of the method 3297 * @param type the type of the method, with the receiver argument omitted 3298 * @return the desired method handle 3299 * @throws NoSuchMethodException if the method does not exist 3300 * @throws IllegalAccessException if access checking fails 3301 * or if the method's variable arity modifier bit 3302 * is set and {@code asVarargsCollector} fails 3303 * @throws SecurityException if a security manager is present and it 3304 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3305 * @throws NullPointerException if any argument is null 3306 * @see MethodHandle#bindTo 3307 * @see #findVirtual 3308 */ 3309 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3310 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3311 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3312 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3313 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3314 throw new IllegalAccessException("The restricted defining class " + 3315 mh.type().leadingReferenceParameter().getName() + 3316 " is not assignable from receiver class " + 3317 receiver.getClass().getName()); 3318 } 3319 return mh.bindArgumentL(0, receiver).setVarargs(method); 3320 } 3321 3322 /** 3323 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3324 * to <i>m</i>, if the lookup class has permission. 3325 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3326 * If <i>m</i> is virtual, overriding is respected on every call. 3327 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3328 * The type of the method handle will be that of the method, 3329 * with the receiver type prepended (but only if it is non-static). 3330 * If the method's {@code accessible} flag is not set, 3331 * access checking is performed immediately on behalf of the lookup class. 3332 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3333 * <p> 3334 * The returned method handle will have 3335 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3336 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3337 * <p> 3338 * If <i>m</i> is static, and 3339 * if the returned method handle is invoked, the method's class will 3340 * be initialized, if it has not already been initialized. 3341 * @param m the reflected method 3342 * @return a method handle which can invoke the reflected method 3343 * @throws IllegalAccessException if access checking fails 3344 * or if the method's variable arity modifier bit 3345 * is set and {@code asVarargsCollector} fails 3346 * @throws NullPointerException if the argument is null 3347 */ 3348 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3349 if (m.getDeclaringClass() == MethodHandle.class) { 3350 MethodHandle mh = unreflectForMH(m); 3351 if (mh != null) return mh; 3352 } 3353 if (m.getDeclaringClass() == VarHandle.class) { 3354 MethodHandle mh = unreflectForVH(m); 3355 if (mh != null) return mh; 3356 } 3357 MemberName method = new MemberName(m); 3358 byte refKind = method.getReferenceKind(); 3359 if (refKind == REF_invokeSpecial) 3360 refKind = REF_invokeVirtual; 3361 assert(method.isMethod()); 3362 @SuppressWarnings("deprecation") 3363 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3364 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3365 } 3366 private MethodHandle unreflectForMH(Method m) { 3367 // these names require special lookups because they throw UnsupportedOperationException 3368 if (MemberName.isMethodHandleInvokeName(m.getName())) 3369 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3370 return null; 3371 } 3372 private MethodHandle unreflectForVH(Method m) { 3373 // these names require special lookups because they throw UnsupportedOperationException 3374 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3375 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3376 return null; 3377 } 3378 3379 /** 3380 * Produces a method handle for a reflected method. 3381 * It will bypass checks for overriding methods on the receiver, 3382 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3383 * instruction from within the explicitly specified {@code specialCaller}. 3384 * The type of the method handle will be that of the method, 3385 * with a suitably restricted receiver type prepended. 3386 * (The receiver type will be {@code specialCaller} or a subtype.) 3387 * If the method's {@code accessible} flag is not set, 3388 * access checking is performed immediately on behalf of the lookup class, 3389 * as if {@code invokespecial} instruction were being linked. 3390 * <p> 3391 * Before method resolution, 3392 * if the explicitly specified caller class is not identical with the 3393 * lookup class, or if this lookup object does not have 3394 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3395 * privileges, the access fails. 3396 * <p> 3397 * The returned method handle will have 3398 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3399 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3400 * @param m the reflected method 3401 * @param specialCaller the class nominally calling the method 3402 * @return a method handle which can invoke the reflected method 3403 * @throws IllegalAccessException if access checking fails, 3404 * or if the method is {@code static}, 3405 * or if the method's variable arity modifier bit 3406 * is set and {@code asVarargsCollector} fails 3407 * @throws NullPointerException if any argument is null 3408 */ 3409 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3410 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3411 Lookup specialLookup = this.in(specialCaller); 3412 MemberName method = new MemberName(m, true); 3413 assert(method.isMethod()); 3414 // ignore m.isAccessible: this is a new kind of access 3415 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3416 } 3417 3418 /** 3419 * Produces a method handle for a reflected constructor. 3420 * The type of the method handle will be that of the constructor, 3421 * with the return type changed to the declaring class. 3422 * The method handle will perform a {@code newInstance} operation, 3423 * creating a new instance of the constructor's class on the 3424 * arguments passed to the method handle. 3425 * <p> 3426 * If the constructor's {@code accessible} flag is not set, 3427 * access checking is performed immediately on behalf of the lookup class. 3428 * <p> 3429 * The returned method handle will have 3430 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3431 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3432 * <p> 3433 * If the returned method handle is invoked, the constructor's class will 3434 * be initialized, if it has not already been initialized. 3435 * @param c the reflected constructor 3436 * @return a method handle which can invoke the reflected constructor 3437 * @throws IllegalAccessException if access checking fails 3438 * or if the method's variable arity modifier bit 3439 * is set and {@code asVarargsCollector} fails 3440 * @throws NullPointerException if the argument is null 3441 */ 3442 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3443 MemberName ctor = new MemberName(c); 3444 assert(ctor.isConstructor()); 3445 @SuppressWarnings("deprecation") 3446 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3447 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3448 } 3449 3450 /** 3451 * Produces a method handle giving read access to a reflected field. 3452 * The type of the method handle will have a return type of the field's 3453 * value type. 3454 * If the field is {@code static}, the method handle will take no arguments. 3455 * Otherwise, its single argument will be the instance containing 3456 * the field. 3457 * If the {@code Field} object's {@code accessible} flag is not set, 3458 * access checking is performed immediately on behalf of the lookup class. 3459 * <p> 3460 * If the field is static, and 3461 * if the returned method handle is invoked, the field's class will 3462 * be initialized, if it has not already been initialized. 3463 * @param f the reflected field 3464 * @return a method handle which can load values from the reflected field 3465 * @throws IllegalAccessException if access checking fails 3466 * @throws NullPointerException if the argument is null 3467 */ 3468 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3469 return unreflectField(f, false); 3470 } 3471 3472 /** 3473 * Produces a method handle giving write access to a reflected field. 3474 * The type of the method handle will have a void return type. 3475 * If the field is {@code static}, the method handle will take a single 3476 * argument, of the field's value type, the value to be stored. 3477 * Otherwise, the two arguments will be the instance containing 3478 * the field, and the value to be stored. 3479 * If the {@code Field} object's {@code accessible} flag is not set, 3480 * access checking is performed immediately on behalf of the lookup class. 3481 * <p> 3482 * If the field is {@code final}, write access will not be 3483 * allowed and access checking will fail, except under certain 3484 * narrow circumstances documented for {@link Field#set Field.set}. 3485 * A method handle is returned only if a corresponding call to 3486 * the {@code Field} object's {@code set} method could return 3487 * normally. In particular, fields which are both {@code static} 3488 * and {@code final} may never be set. 3489 * <p> 3490 * If the field is {@code static}, and 3491 * if the returned method handle is invoked, the field's class will 3492 * be initialized, if it has not already been initialized. 3493 * @param f the reflected field 3494 * @return a method handle which can store values into the reflected field 3495 * @throws IllegalAccessException if access checking fails, 3496 * or if the field is {@code final} and write access 3497 * is not enabled on the {@code Field} object 3498 * @throws NullPointerException if the argument is null 3499 */ 3500 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3501 return unreflectField(f, true); 3502 } 3503 3504 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3505 MemberName field = new MemberName(f, isSetter); 3506 if (isSetter && field.isFinal()) { 3507 if (field.isTrustedFinalField()) { 3508 String msg = field.isStatic() ? "static final field has no write access" 3509 : "final field has no write access"; 3510 throw field.makeAccessException(msg, this); 3511 } 3512 } 3513 assert(isSetter 3514 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3515 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3516 @SuppressWarnings("deprecation") 3517 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3518 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3519 } 3520 3521 /** 3522 * Produces a VarHandle giving access to a reflected field {@code f} 3523 * of type {@code T} declared in a class of type {@code R}. 3524 * The VarHandle's variable type is {@code T}. 3525 * If the field is non-static the VarHandle has one coordinate type, 3526 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3527 * coordinate types. 3528 * <p> 3529 * Access checking is performed immediately on behalf of the lookup 3530 * class, regardless of the value of the field's {@code accessible} 3531 * flag. 3532 * <p> 3533 * If the field is static, and if the returned VarHandle is operated 3534 * on, the field's declaring class will be initialized, if it has not 3535 * already been initialized. 3536 * <p> 3537 * Certain access modes of the returned VarHandle are unsupported under 3538 * the following conditions: 3539 * <ul> 3540 * <li>if the field is declared {@code final}, then the write, atomic 3541 * update, numeric atomic update, and bitwise atomic update access 3542 * modes are unsupported. 3543 * <li>if the field type is anything other than {@code byte}, 3544 * {@code short}, {@code char}, {@code int}, {@code long}, 3545 * {@code float}, or {@code double} then numeric atomic update 3546 * access modes are unsupported. 3547 * <li>if the field type is anything other than {@code boolean}, 3548 * {@code byte}, {@code short}, {@code char}, {@code int} or 3549 * {@code long} then bitwise atomic update access modes are 3550 * unsupported. 3551 * </ul> 3552 * <p> 3553 * If the field is declared {@code volatile} then the returned VarHandle 3554 * will override access to the field (effectively ignore the 3555 * {@code volatile} declaration) in accordance to its specified 3556 * access modes. 3557 * <p> 3558 * If the field type is {@code float} or {@code double} then numeric 3559 * and atomic update access modes compare values using their bitwise 3560 * representation (see {@link Float#floatToRawIntBits} and 3561 * {@link Double#doubleToRawLongBits}, respectively). 3562 * @apiNote 3563 * Bitwise comparison of {@code float} values or {@code double} values, 3564 * as performed by the numeric and atomic update access modes, differ 3565 * from the primitive {@code ==} operator and the {@link Float#equals} 3566 * and {@link Double#equals} methods, specifically with respect to 3567 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3568 * Care should be taken when performing a compare and set or a compare 3569 * and exchange operation with such values since the operation may 3570 * unexpectedly fail. 3571 * There are many possible NaN values that are considered to be 3572 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3573 * provided by Java can distinguish between them. Operation failure can 3574 * occur if the expected or witness value is a NaN value and it is 3575 * transformed (perhaps in a platform specific manner) into another NaN 3576 * value, and thus has a different bitwise representation (see 3577 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3578 * details). 3579 * The values {@code -0.0} and {@code +0.0} have different bitwise 3580 * representations but are considered equal when using the primitive 3581 * {@code ==} operator. Operation failure can occur if, for example, a 3582 * numeric algorithm computes an expected value to be say {@code -0.0} 3583 * and previously computed the witness value to be say {@code +0.0}. 3584 * @param f the reflected field, with a field of type {@code T}, and 3585 * a declaring class of type {@code R} 3586 * @return a VarHandle giving access to non-static fields or a static 3587 * field 3588 * @throws IllegalAccessException if access checking fails 3589 * @throws NullPointerException if the argument is null 3590 * @since 9 3591 */ 3592 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3593 MemberName getField = new MemberName(f, false); 3594 MemberName putField = new MemberName(f, true); 3595 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3596 f.getDeclaringClass(), getField, putField); 3597 } 3598 3599 /** 3600 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3601 * created by this lookup object or a similar one. 3602 * Security and access checks are performed to ensure that this lookup object 3603 * is capable of reproducing the target method handle. 3604 * This means that the cracking may fail if target is a direct method handle 3605 * but was created by an unrelated lookup object. 3606 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3607 * and was created by a lookup object for a different class. 3608 * @param target a direct method handle to crack into symbolic reference components 3609 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3610 * @throws SecurityException if a security manager is present and it 3611 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3612 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3613 * @throws NullPointerException if the target is {@code null} 3614 * @see MethodHandleInfo 3615 * @since 1.8 3616 */ 3617 public MethodHandleInfo revealDirect(MethodHandle target) { 3618 if (!target.isCrackable()) { 3619 throw newIllegalArgumentException("not a direct method handle"); 3620 } 3621 MemberName member = target.internalMemberName(); 3622 Class<?> defc = member.getDeclaringClass(); 3623 byte refKind = member.getReferenceKind(); 3624 assert(MethodHandleNatives.refKindIsValid(refKind)); 3625 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3626 // Devirtualized method invocation is usually formally virtual. 3627 // To avoid creating extra MemberName objects for this common case, 3628 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3629 refKind = REF_invokeVirtual; 3630 if (refKind == REF_invokeVirtual && defc.isInterface()) 3631 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3632 refKind = REF_invokeInterface; 3633 // Check SM permissions and member access before cracking. 3634 try { 3635 checkAccess(refKind, defc, member); 3636 checkSecurityManager(defc, member); 3637 } catch (IllegalAccessException ex) { 3638 throw new IllegalArgumentException(ex); 3639 } 3640 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3641 Class<?> callerClass = target.internalCallerClass(); 3642 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3643 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3644 } 3645 // Produce the handle to the results. 3646 return new InfoFromMemberName(this, member, refKind); 3647 } 3648 3649 /// Helper methods, all package-private. 3650 3651 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3652 checkSymbolicClass(refc); // do this before attempting to resolve 3653 Objects.requireNonNull(name); 3654 Objects.requireNonNull(type); 3655 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3656 NoSuchFieldException.class); 3657 } 3658 3659 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3660 checkSymbolicClass(refc); // do this before attempting to resolve 3661 Objects.requireNonNull(type); 3662 checkMethodName(refKind, name); // implicit null-check of name 3663 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3664 NoSuchMethodException.class); 3665 } 3666 3667 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3668 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3669 Objects.requireNonNull(member.getName()); 3670 Objects.requireNonNull(member.getType()); 3671 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3672 ReflectiveOperationException.class); 3673 } 3674 3675 MemberName resolveOrNull(byte refKind, MemberName member) { 3676 // do this before attempting to resolve 3677 if (!isClassAccessible(member.getDeclaringClass())) { 3678 return null; 3679 } 3680 Objects.requireNonNull(member.getName()); 3681 Objects.requireNonNull(member.getType()); 3682 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3683 } 3684 3685 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3686 // do this before attempting to resolve 3687 if (!isClassAccessible(refc)) { 3688 return null; 3689 } 3690 Objects.requireNonNull(type); 3691 // implicit null-check of name 3692 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3693 return null; 3694 } 3695 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3696 } 3697 3698 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3699 if (!isClassAccessible(refc)) { 3700 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3701 } 3702 } 3703 3704 boolean isClassAccessible(Class<?> refc) { 3705 Objects.requireNonNull(refc); 3706 Class<?> caller = lookupClassOrNull(); 3707 Class<?> type = refc; 3708 while (type.isArray()) { 3709 type = type.getComponentType(); 3710 } 3711 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3712 } 3713 3714 /** Check name for an illegal leading "<" character. */ 3715 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3716 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3717 throw new NoSuchMethodException("illegal method name: "+name); 3718 } 3719 3720 /** 3721 * Find my trustable caller class if m is a caller sensitive method. 3722 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3723 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3724 */ 3725 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3726 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3727 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3728 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3729 } 3730 return this; 3731 } 3732 3733 /** 3734 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3735 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3736 * 3737 * @deprecated This method was originally designed to test {@code PRIVATE} access 3738 * that implies full privilege access but {@code MODULE} access has since become 3739 * independent of {@code PRIVATE} access. It is recommended to call 3740 * {@link #hasFullPrivilegeAccess()} instead. 3741 * @since 9 3742 */ 3743 @Deprecated(since="14") 3744 public boolean hasPrivateAccess() { 3745 return hasFullPrivilegeAccess(); 3746 } 3747 3748 /** 3749 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3750 * i.e. {@code PRIVATE} and {@code MODULE} access. 3751 * A {@code Lookup} object must have full privilege access in order to 3752 * access all members that are allowed to the 3753 * {@linkplain #lookupClass() lookup class}. 3754 * 3755 * @return {@code true} if this lookup has full privilege access. 3756 * @since 14 3757 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3758 */ 3759 public boolean hasFullPrivilegeAccess() { 3760 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3761 } 3762 3763 /** 3764 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3765 * for ensureInitialzed, findClass or accessClass. 3766 */ 3767 void checkSecurityManager(Class<?> refc) { 3768 if (allowedModes == TRUSTED) return; 3769 3770 @SuppressWarnings("removal") 3771 SecurityManager smgr = System.getSecurityManager(); 3772 if (smgr == null) return; 3773 3774 // Step 1: 3775 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3776 if (!fullPrivilegeLookup || 3777 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3778 ReflectUtil.checkPackageAccess(refc); 3779 } 3780 3781 // Step 2b: 3782 if (!fullPrivilegeLookup) { 3783 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3784 } 3785 } 3786 3787 /** 3788 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3789 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3790 * If this lookup object has full privilege access except original access, 3791 * then the caller class is the lookupClass. 3792 * 3793 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3794 * from the same module skips the security permission check. 3795 */ 3796 void checkSecurityManager(Class<?> refc, MemberName m) { 3797 Objects.requireNonNull(refc); 3798 Objects.requireNonNull(m); 3799 3800 if (allowedModes == TRUSTED) return; 3801 3802 @SuppressWarnings("removal") 3803 SecurityManager smgr = System.getSecurityManager(); 3804 if (smgr == null) return; 3805 3806 // Step 1: 3807 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3808 if (!fullPrivilegeLookup || 3809 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3810 ReflectUtil.checkPackageAccess(refc); 3811 } 3812 3813 // Step 2a: 3814 if (m.isPublic()) return; 3815 if (!fullPrivilegeLookup) { 3816 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3817 } 3818 3819 // Step 3: 3820 Class<?> defc = m.getDeclaringClass(); 3821 if (!fullPrivilegeLookup && defc != refc) { 3822 ReflectUtil.checkPackageAccess(defc); 3823 } 3824 } 3825 3826 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3827 boolean wantStatic = (refKind == REF_invokeStatic); 3828 String message; 3829 if (m.isConstructor()) 3830 message = "expected a method, not a constructor"; 3831 else if (!m.isMethod()) 3832 message = "expected a method"; 3833 else if (wantStatic != m.isStatic()) 3834 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3835 else 3836 { checkAccess(refKind, refc, m); return; } 3837 throw m.makeAccessException(message, this); 3838 } 3839 3840 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3841 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3842 String message; 3843 if (wantStatic != m.isStatic()) 3844 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3845 else 3846 { checkAccess(refKind, refc, m); return; } 3847 throw m.makeAccessException(message, this); 3848 } 3849 3850 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3851 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3852 assert(m.referenceKindIsConsistentWith(refKind) && 3853 MethodHandleNatives.refKindIsValid(refKind) && 3854 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3855 int allowedModes = this.allowedModes; 3856 if (allowedModes == TRUSTED) return; 3857 int mods = m.getModifiers(); 3858 if (Modifier.isProtected(mods) && 3859 refKind == REF_invokeVirtual && 3860 m.getDeclaringClass() == Object.class && 3861 m.getName().equals("clone") && 3862 refc.isArray()) { 3863 // The JVM does this hack also. 3864 // (See ClassVerifier::verify_invoke_instructions 3865 // and LinkResolver::check_method_accessability.) 3866 // Because the JVM does not allow separate methods on array types, 3867 // there is no separate method for int[].clone. 3868 // All arrays simply inherit Object.clone. 3869 // But for access checking logic, we make Object.clone 3870 // (normally protected) appear to be public. 3871 // Later on, when the DirectMethodHandle is created, 3872 // its leading argument will be restricted to the 3873 // requested array type. 3874 // N.B. The return type is not adjusted, because 3875 // that is *not* the bytecode behavior. 3876 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3877 } 3878 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3879 // cannot "new" a protected ctor in a different package 3880 mods ^= Modifier.PROTECTED; 3881 } 3882 if (Modifier.isFinal(mods) && 3883 MethodHandleNatives.refKindIsSetter(refKind)) 3884 throw m.makeAccessException("unexpected set of a final field", this); 3885 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3886 if ((requestedModes & allowedModes) != 0) { 3887 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3888 mods, lookupClass(), previousLookupClass(), allowedModes)) 3889 return; 3890 } else { 3891 // Protected members can also be checked as if they were package-private. 3892 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3893 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3894 return; 3895 } 3896 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3897 } 3898 3899 String accessFailedMessage(Class<?> refc, MemberName m) { 3900 Class<?> defc = m.getDeclaringClass(); 3901 int mods = m.getModifiers(); 3902 // check the class first: 3903 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3904 (defc == refc || 3905 Modifier.isPublic(refc.getModifiers()))); 3906 if (!classOK && (allowedModes & PACKAGE) != 0) { 3907 // ignore previous lookup class to check if default package access 3908 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3909 (defc == refc || 3910 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3911 } 3912 if (!classOK) 3913 return "class is not public"; 3914 if (Modifier.isPublic(mods)) 3915 return "access to public member failed"; // (how?, module not readable?) 3916 if (Modifier.isPrivate(mods)) 3917 return "member is private"; 3918 if (Modifier.isProtected(mods)) 3919 return "member is protected"; 3920 return "member is private to package"; 3921 } 3922 3923 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3924 int allowedModes = this.allowedModes; 3925 if (allowedModes == TRUSTED) return; 3926 if ((lookupModes() & PRIVATE) == 0 3927 || (specialCaller != lookupClass() 3928 // ensure non-abstract methods in superinterfaces can be special-invoked 3929 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3930 throw new MemberName(specialCaller). 3931 makeAccessException("no private access for invokespecial", this); 3932 } 3933 3934 private boolean restrictProtectedReceiver(MemberName method) { 3935 // The accessing class only has the right to use a protected member 3936 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3937 if (!method.isProtected() || method.isStatic() 3938 || allowedModes == TRUSTED 3939 || method.getDeclaringClass() == lookupClass() 3940 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3941 return false; 3942 return true; 3943 } 3944 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3945 assert(!method.isStatic()); 3946 // receiver type of mh is too wide; narrow to caller 3947 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3948 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3949 } 3950 MethodType rawType = mh.type(); 3951 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3952 MethodType narrowType = rawType.changeParameterType(0, caller); 3953 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3954 assert(mh.viewAsTypeChecks(narrowType, true)); 3955 return mh.copyWith(narrowType, mh.form); 3956 } 3957 3958 /** Check access and get the requested method. */ 3959 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3960 final boolean doRestrict = true; 3961 final boolean checkSecurity = true; 3962 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 3963 } 3964 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3965 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3966 final boolean doRestrict = false; 3967 final boolean checkSecurity = true; 3968 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 3969 } 3970 /** Check access and get the requested method, eliding security manager checks. */ 3971 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3972 final boolean doRestrict = true; 3973 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 3974 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 3975 } 3976 /** Common code for all methods; do not call directly except from immediately above. */ 3977 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3978 boolean checkSecurity, 3979 boolean doRestrict, 3980 Lookup boundCaller) throws IllegalAccessException { 3981 checkMethod(refKind, refc, method); 3982 // Optionally check with the security manager; this isn't needed for unreflect* calls. 3983 if (checkSecurity) 3984 checkSecurityManager(refc, method); 3985 assert(!method.isMethodHandleInvoke()); 3986 3987 if (refKind == REF_invokeSpecial && 3988 refc != lookupClass() && 3989 !refc.isInterface() && 3990 refc != lookupClass().getSuperclass() && 3991 refc.isAssignableFrom(lookupClass())) { 3992 assert(!method.getName().equals("<init>")); // not this code path 3993 3994 // Per JVMS 6.5, desc. of invokespecial instruction: 3995 // If the method is in a superclass of the LC, 3996 // and if our original search was above LC.super, 3997 // repeat the search (symbolic lookup) from LC.super 3998 // and continue with the direct superclass of that class, 3999 // and so forth, until a match is found or no further superclasses exist. 4000 // FIXME: MemberName.resolve should handle this instead. 4001 Class<?> refcAsSuper = lookupClass(); 4002 MemberName m2; 4003 do { 4004 refcAsSuper = refcAsSuper.getSuperclass(); 4005 m2 = new MemberName(refcAsSuper, 4006 method.getName(), 4007 method.getMethodType(), 4008 REF_invokeSpecial); 4009 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4010 } while (m2 == null && // no method is found yet 4011 refc != refcAsSuper); // search up to refc 4012 if (m2 == null) throw new InternalError(method.toString()); 4013 method = m2; 4014 refc = refcAsSuper; 4015 // redo basic checks 4016 checkMethod(refKind, refc, method); 4017 } 4018 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4019 MethodHandle mh = dmh; 4020 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4021 if ((doRestrict && refKind == REF_invokeSpecial) || 4022 (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) { 4023 mh = restrictReceiver(method, dmh, lookupClass()); 4024 } 4025 mh = maybeBindCaller(method, mh, boundCaller); 4026 mh = mh.setVarargs(method); 4027 return mh; 4028 } 4029 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4030 throws IllegalAccessException { 4031 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4032 return mh; 4033 4034 // boundCaller must have full privilege access. 4035 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4036 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4037 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4038 4039 assert boundCaller.hasFullPrivilegeAccess(); 4040 4041 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4042 // Note: caller will apply varargs after this step happens. 4043 return cbmh; 4044 } 4045 4046 /** Check access and get the requested field. */ 4047 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4048 final boolean checkSecurity = true; 4049 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4050 } 4051 /** Check access and get the requested field, eliding security manager checks. */ 4052 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4053 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4054 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4055 } 4056 /** Common code for all fields; do not call directly except from immediately above. */ 4057 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4058 boolean checkSecurity) throws IllegalAccessException { 4059 checkField(refKind, refc, field); 4060 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4061 if (checkSecurity) 4062 checkSecurityManager(refc, field); 4063 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4064 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4065 restrictProtectedReceiver(field)); 4066 if (doRestrict) 4067 return restrictReceiver(field, dmh, lookupClass()); 4068 return dmh; 4069 } 4070 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4071 Class<?> refc, MemberName getField, MemberName putField) 4072 throws IllegalAccessException { 4073 final boolean checkSecurity = true; 4074 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4075 } 4076 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4077 Class<?> refc, MemberName getField, MemberName putField) 4078 throws IllegalAccessException { 4079 final boolean checkSecurity = false; 4080 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4081 } 4082 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4083 Class<?> refc, MemberName getField, MemberName putField, 4084 boolean checkSecurity) throws IllegalAccessException { 4085 assert getField.isStatic() == putField.isStatic(); 4086 assert getField.isGetter() && putField.isSetter(); 4087 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4088 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4089 4090 checkField(getRefKind, refc, getField); 4091 if (checkSecurity) 4092 checkSecurityManager(refc, getField); 4093 4094 if (!putField.isFinal()) { 4095 // A VarHandle does not support updates to final fields, any 4096 // such VarHandle to a final field will be read-only and 4097 // therefore the following write-based accessibility checks are 4098 // only required for non-final fields 4099 checkField(putRefKind, refc, putField); 4100 if (checkSecurity) 4101 checkSecurityManager(refc, putField); 4102 } 4103 4104 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4105 restrictProtectedReceiver(getField)); 4106 if (doRestrict) { 4107 assert !getField.isStatic(); 4108 // receiver type of VarHandle is too wide; narrow to caller 4109 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4110 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4111 } 4112 refc = lookupClass(); 4113 } 4114 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), 4115 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4116 } 4117 /** Check access and get the requested constructor. */ 4118 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4119 final boolean checkSecurity = true; 4120 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4121 } 4122 /** Check access and get the requested constructor, eliding security manager checks. */ 4123 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4124 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4125 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4126 } 4127 /** Common code for all constructors; do not call directly except from immediately above. */ 4128 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4129 boolean checkSecurity) throws IllegalAccessException { 4130 assert(ctor.isConstructor()); 4131 checkAccess(REF_newInvokeSpecial, refc, ctor); 4132 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4133 if (checkSecurity) 4134 checkSecurityManager(refc, ctor); 4135 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4136 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4137 } 4138 4139 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4140 */ 4141 /*non-public*/ 4142 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4143 throws ReflectiveOperationException { 4144 if (!(type instanceof Class || type instanceof MethodType)) 4145 throw new InternalError("unresolved MemberName"); 4146 MemberName member = new MemberName(refKind, defc, name, type); 4147 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4148 if (mh != null) { 4149 checkSymbolicClass(defc); 4150 return mh; 4151 } 4152 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4153 // Treat MethodHandle.invoke and invokeExact specially. 4154 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4155 if (mh != null) { 4156 return mh; 4157 } 4158 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4159 // Treat signature-polymorphic methods on VarHandle specially. 4160 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4161 if (mh != null) { 4162 return mh; 4163 } 4164 } 4165 MemberName resolved = resolveOrFail(refKind, member); 4166 mh = getDirectMethodForConstant(refKind, defc, resolved); 4167 if (mh instanceof DirectMethodHandle 4168 && canBeCached(refKind, defc, resolved)) { 4169 MemberName key = mh.internalMemberName(); 4170 if (key != null) { 4171 key = key.asNormalOriginal(); 4172 } 4173 if (member.equals(key)) { // better safe than sorry 4174 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 4175 } 4176 } 4177 return mh; 4178 } 4179 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4180 if (refKind == REF_invokeSpecial) { 4181 return false; 4182 } 4183 if (!Modifier.isPublic(defc.getModifiers()) || 4184 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4185 !member.isPublic() || 4186 member.isCallerSensitive()) { 4187 return false; 4188 } 4189 ClassLoader loader = defc.getClassLoader(); 4190 if (loader != null) { 4191 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4192 boolean found = false; 4193 while (sysl != null) { 4194 if (loader == sysl) { found = true; break; } 4195 sysl = sysl.getParent(); 4196 } 4197 if (!found) { 4198 return false; 4199 } 4200 } 4201 try { 4202 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4203 new MemberName(refKind, defc, member.getName(), member.getType())); 4204 if (resolved2 == null) { 4205 return false; 4206 } 4207 checkSecurityManager(defc, resolved2); 4208 } catch (SecurityException ex) { 4209 return false; 4210 } 4211 return true; 4212 } 4213 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4214 throws ReflectiveOperationException { 4215 if (MethodHandleNatives.refKindIsField(refKind)) { 4216 return getDirectFieldNoSecurityManager(refKind, defc, member); 4217 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4218 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4219 } else if (refKind == REF_newInvokeSpecial) { 4220 return getDirectConstructorNoSecurityManager(defc, member); 4221 } 4222 // oops 4223 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4224 } 4225 4226 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4227 } 4228 4229 /** 4230 * Produces a method handle constructing arrays of a desired type, 4231 * as if by the {@code anewarray} bytecode. 4232 * The return type of the method handle will be the array type. 4233 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4234 * 4235 * <p> If the returned method handle is invoked with a negative 4236 * array size, a {@code NegativeArraySizeException} will be thrown. 4237 * 4238 * @param arrayClass an array type 4239 * @return a method handle which can create arrays of the given type 4240 * @throws NullPointerException if the argument is {@code null} 4241 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4242 * @see java.lang.reflect.Array#newInstance(Class, int) 4243 * @jvms 6.5 {@code anewarray} Instruction 4244 * @since 9 4245 */ 4246 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4247 if (!arrayClass.isArray()) { 4248 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4249 } 4250 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4251 bindTo(arrayClass.getComponentType()); 4252 return ani.asType(ani.type().changeReturnType(arrayClass)); 4253 } 4254 4255 /** 4256 * Produces a method handle returning the length of an array, 4257 * as if by the {@code arraylength} bytecode. 4258 * The type of the method handle will have {@code int} as return type, 4259 * and its sole argument will be the array type. 4260 * 4261 * <p> If the returned method handle is invoked with a {@code null} 4262 * array reference, a {@code NullPointerException} will be thrown. 4263 * 4264 * @param arrayClass an array type 4265 * @return a method handle which can retrieve the length of an array of the given array type 4266 * @throws NullPointerException if the argument is {@code null} 4267 * @throws IllegalArgumentException if arrayClass is not an array type 4268 * @jvms 6.5 {@code arraylength} Instruction 4269 * @since 9 4270 */ 4271 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4272 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4273 } 4274 4275 /** 4276 * Produces a method handle giving read access to elements of an array, 4277 * as if by the {@code aaload} bytecode. 4278 * The type of the method handle will have a return type of the array's 4279 * element type. Its first argument will be the array type, 4280 * and the second will be {@code int}. 4281 * 4282 * <p> When the returned method handle is invoked, 4283 * the array reference and array index are checked. 4284 * A {@code NullPointerException} will be thrown if the array reference 4285 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4286 * thrown if the index is negative or if it is greater than or equal to 4287 * the length of the array. 4288 * 4289 * @param arrayClass an array type 4290 * @return a method handle which can load values from the given array type 4291 * @throws NullPointerException if the argument is null 4292 * @throws IllegalArgumentException if arrayClass is not an array type 4293 * @jvms 6.5 {@code aaload} Instruction 4294 */ 4295 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4296 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4297 } 4298 4299 /** 4300 * Produces a method handle giving write access to elements of an array, 4301 * as if by the {@code astore} bytecode. 4302 * The type of the method handle will have a void return type. 4303 * Its last argument will be the array's element type. 4304 * The first and second arguments will be the array type and int. 4305 * 4306 * <p> When the returned method handle is invoked, 4307 * the array reference and array index are checked. 4308 * A {@code NullPointerException} will be thrown if the array reference 4309 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4310 * thrown if the index is negative or if it is greater than or equal to 4311 * the length of the array. 4312 * 4313 * @param arrayClass the class of an array 4314 * @return a method handle which can store values into the array type 4315 * @throws NullPointerException if the argument is null 4316 * @throws IllegalArgumentException if arrayClass is not an array type 4317 * @jvms 6.5 {@code aastore} Instruction 4318 */ 4319 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4320 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4321 } 4322 4323 /** 4324 * Produces a VarHandle giving access to elements of an array of type 4325 * {@code arrayClass}. The VarHandle's variable type is the component type 4326 * of {@code arrayClass} and the list of coordinate types is 4327 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4328 * corresponds to an argument that is an index into an array. 4329 * <p> 4330 * Certain access modes of the returned VarHandle are unsupported under 4331 * the following conditions: 4332 * <ul> 4333 * <li>if the component type is anything other than {@code byte}, 4334 * {@code short}, {@code char}, {@code int}, {@code long}, 4335 * {@code float}, or {@code double} then numeric atomic update access 4336 * modes are unsupported. 4337 * <li>if the component type is anything other than {@code boolean}, 4338 * {@code byte}, {@code short}, {@code char}, {@code int} or 4339 * {@code long} then bitwise atomic update access modes are 4340 * unsupported. 4341 * </ul> 4342 * <p> 4343 * If the component type is {@code float} or {@code double} then numeric 4344 * and atomic update access modes compare values using their bitwise 4345 * representation (see {@link Float#floatToRawIntBits} and 4346 * {@link Double#doubleToRawLongBits}, respectively). 4347 * 4348 * <p> When the returned {@code VarHandle} is invoked, 4349 * the array reference and array index are checked. 4350 * A {@code NullPointerException} will be thrown if the array reference 4351 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4352 * thrown if the index is negative or if it is greater than or equal to 4353 * the length of the array. 4354 * 4355 * @apiNote 4356 * Bitwise comparison of {@code float} values or {@code double} values, 4357 * as performed by the numeric and atomic update access modes, differ 4358 * from the primitive {@code ==} operator and the {@link Float#equals} 4359 * and {@link Double#equals} methods, specifically with respect to 4360 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4361 * Care should be taken when performing a compare and set or a compare 4362 * and exchange operation with such values since the operation may 4363 * unexpectedly fail. 4364 * There are many possible NaN values that are considered to be 4365 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4366 * provided by Java can distinguish between them. Operation failure can 4367 * occur if the expected or witness value is a NaN value and it is 4368 * transformed (perhaps in a platform specific manner) into another NaN 4369 * value, and thus has a different bitwise representation (see 4370 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4371 * details). 4372 * The values {@code -0.0} and {@code +0.0} have different bitwise 4373 * representations but are considered equal when using the primitive 4374 * {@code ==} operator. Operation failure can occur if, for example, a 4375 * numeric algorithm computes an expected value to be say {@code -0.0} 4376 * and previously computed the witness value to be say {@code +0.0}. 4377 * @param arrayClass the class of an array, of type {@code T[]} 4378 * @return a VarHandle giving access to elements of an array 4379 * @throws NullPointerException if the arrayClass is null 4380 * @throws IllegalArgumentException if arrayClass is not an array type 4381 * @since 9 4382 */ 4383 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4384 return VarHandles.makeArrayElementHandle(arrayClass); 4385 } 4386 4387 /** 4388 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4389 * viewed as if it were a different primitive array type, such as 4390 * {@code int[]} or {@code long[]}. 4391 * The VarHandle's variable type is the component type of 4392 * {@code viewArrayClass} and the list of coordinate types is 4393 * {@code (byte[], int)}, where the {@code int} coordinate type 4394 * corresponds to an argument that is an index into a {@code byte[]} array. 4395 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4396 * array, composing bytes to or from a value of the component type of 4397 * {@code viewArrayClass} according to the given endianness. 4398 * <p> 4399 * The supported component types (variables types) are {@code short}, 4400 * {@code char}, {@code int}, {@code long}, {@code float} and 4401 * {@code double}. 4402 * <p> 4403 * Access of bytes at a given index will result in an 4404 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4405 * or greater than the {@code byte[]} array length minus the size (in bytes) 4406 * of {@code T}. 4407 * <p> 4408 * Access of bytes at an index may be aligned or misaligned for {@code T}, 4409 * with respect to the underlying memory address, {@code A} say, associated 4410 * with the array and index. 4411 * If access is misaligned then access for anything other than the 4412 * {@code get} and {@code set} access modes will result in an 4413 * {@code IllegalStateException}. In such cases atomic access is only 4414 * guaranteed with respect to the largest power of two that divides the GCD 4415 * of {@code A} and the size (in bytes) of {@code T}. 4416 * If access is aligned then following access modes are supported and are 4417 * guaranteed to support atomic access: 4418 * <ul> 4419 * <li>read write access modes for all {@code T}, with the exception of 4420 * access modes {@code get} and {@code set} for {@code long} and 4421 * {@code double} on 32-bit platforms. 4422 * <li>atomic update access modes for {@code int}, {@code long}, 4423 * {@code float} or {@code double}. 4424 * (Future major platform releases of the JDK may support additional 4425 * types for certain currently unsupported access modes.) 4426 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4427 * (Future major platform releases of the JDK may support additional 4428 * numeric types for certain currently unsupported access modes.) 4429 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4430 * (Future major platform releases of the JDK may support additional 4431 * numeric types for certain currently unsupported access modes.) 4432 * </ul> 4433 * <p> 4434 * Misaligned access, and therefore atomicity guarantees, may be determined 4435 * for {@code byte[]} arrays without operating on a specific array. Given 4436 * an {@code index}, {@code T} and its corresponding boxed type, 4437 * {@code T_BOX}, misalignment may be determined as follows: 4438 * <pre>{@code 4439 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4440 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 4441 * alignmentOffset(0, sizeOfT); 4442 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 4443 * boolean isMisaligned = misalignedAtIndex != 0; 4444 * }</pre> 4445 * <p> 4446 * If the variable type is {@code float} or {@code double} then atomic 4447 * update access modes compare values using their bitwise representation 4448 * (see {@link Float#floatToRawIntBits} and 4449 * {@link Double#doubleToRawLongBits}, respectively). 4450 * @param viewArrayClass the view array class, with a component type of 4451 * type {@code T} 4452 * @param byteOrder the endianness of the view array elements, as 4453 * stored in the underlying {@code byte} array 4454 * @return a VarHandle giving access to elements of a {@code byte[]} array 4455 * viewed as if elements corresponding to the components type of the view 4456 * array class 4457 * @throws NullPointerException if viewArrayClass or byteOrder is null 4458 * @throws IllegalArgumentException if viewArrayClass is not an array type 4459 * @throws UnsupportedOperationException if the component type of 4460 * viewArrayClass is not supported as a variable type 4461 * @since 9 4462 */ 4463 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4464 ByteOrder byteOrder) throws IllegalArgumentException { 4465 Objects.requireNonNull(byteOrder); 4466 return VarHandles.byteArrayViewHandle(viewArrayClass, 4467 byteOrder == ByteOrder.BIG_ENDIAN); 4468 } 4469 4470 /** 4471 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4472 * viewed as if it were an array of elements of a different primitive 4473 * component type to that of {@code byte}, such as {@code int[]} or 4474 * {@code long[]}. 4475 * The VarHandle's variable type is the component type of 4476 * {@code viewArrayClass} and the list of coordinate types is 4477 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4478 * corresponds to an argument that is an index into a {@code byte[]} array. 4479 * The returned VarHandle accesses bytes at an index in a 4480 * {@code ByteBuffer}, composing bytes to or from a value of the component 4481 * type of {@code viewArrayClass} according to the given endianness. 4482 * <p> 4483 * The supported component types (variables types) are {@code short}, 4484 * {@code char}, {@code int}, {@code long}, {@code float} and 4485 * {@code double}. 4486 * <p> 4487 * Access will result in a {@code ReadOnlyBufferException} for anything 4488 * other than the read access modes if the {@code ByteBuffer} is read-only. 4489 * <p> 4490 * Access of bytes at a given index will result in an 4491 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4492 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4493 * {@code T}. 4494 * <p> 4495 * Access of bytes at an index may be aligned or misaligned for {@code T}, 4496 * with respect to the underlying memory address, {@code A} say, associated 4497 * with the {@code ByteBuffer} and index. 4498 * If access is misaligned then access for anything other than the 4499 * {@code get} and {@code set} access modes will result in an 4500 * {@code IllegalStateException}. In such cases atomic access is only 4501 * guaranteed with respect to the largest power of two that divides the GCD 4502 * of {@code A} and the size (in bytes) of {@code T}. 4503 * If access is aligned then following access modes are supported and are 4504 * guaranteed to support atomic access: 4505 * <ul> 4506 * <li>read write access modes for all {@code T}, with the exception of 4507 * access modes {@code get} and {@code set} for {@code long} and 4508 * {@code double} on 32-bit platforms. 4509 * <li>atomic update access modes for {@code int}, {@code long}, 4510 * {@code float} or {@code double}. 4511 * (Future major platform releases of the JDK may support additional 4512 * types for certain currently unsupported access modes.) 4513 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4514 * (Future major platform releases of the JDK may support additional 4515 * numeric types for certain currently unsupported access modes.) 4516 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4517 * (Future major platform releases of the JDK may support additional 4518 * numeric types for certain currently unsupported access modes.) 4519 * </ul> 4520 * <p> 4521 * Misaligned access, and therefore atomicity guarantees, may be determined 4522 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4523 * {@code index}, {@code T} and its corresponding boxed type, 4524 * {@code T_BOX}, as follows: 4525 * <pre>{@code 4526 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4527 * ByteBuffer bb = ... 4528 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4529 * boolean isMisaligned = misalignedAtIndex != 0; 4530 * }</pre> 4531 * <p> 4532 * If the variable type is {@code float} or {@code double} then atomic 4533 * update access modes compare values using their bitwise representation 4534 * (see {@link Float#floatToRawIntBits} and 4535 * {@link Double#doubleToRawLongBits}, respectively). 4536 * @param viewArrayClass the view array class, with a component type of 4537 * type {@code T} 4538 * @param byteOrder the endianness of the view array elements, as 4539 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4540 * endianness of a {@code ByteBuffer}) 4541 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4542 * viewed as if elements corresponding to the components type of the view 4543 * array class 4544 * @throws NullPointerException if viewArrayClass or byteOrder is null 4545 * @throws IllegalArgumentException if viewArrayClass is not an array type 4546 * @throws UnsupportedOperationException if the component type of 4547 * viewArrayClass is not supported as a variable type 4548 * @since 9 4549 */ 4550 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4551 ByteOrder byteOrder) throws IllegalArgumentException { 4552 Objects.requireNonNull(byteOrder); 4553 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4554 byteOrder == ByteOrder.BIG_ENDIAN); 4555 } 4556 4557 4558 /// method handle invocation (reflective style) 4559 4560 /** 4561 * Produces a method handle which will invoke any method handle of the 4562 * given {@code type}, with a given number of trailing arguments replaced by 4563 * a single trailing {@code Object[]} array. 4564 * The resulting invoker will be a method handle with the following 4565 * arguments: 4566 * <ul> 4567 * <li>a single {@code MethodHandle} target 4568 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4569 * <li>an {@code Object[]} array containing trailing arguments 4570 * </ul> 4571 * <p> 4572 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4573 * the indicated {@code type}. 4574 * That is, if the target is exactly of the given {@code type}, it will behave 4575 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4576 * is used to convert the target to the required {@code type}. 4577 * <p> 4578 * The type of the returned invoker will not be the given {@code type}, but rather 4579 * will have all parameters except the first {@code leadingArgCount} 4580 * replaced by a single array of type {@code Object[]}, which will be 4581 * the final parameter. 4582 * <p> 4583 * Before invoking its target, the invoker will spread the final array, apply 4584 * reference casts as necessary, and unbox and widen primitive arguments. 4585 * If, when the invoker is called, the supplied array argument does 4586 * not have the correct number of elements, the invoker will throw 4587 * an {@link IllegalArgumentException} instead of invoking the target. 4588 * <p> 4589 * This method is equivalent to the following code (though it may be more efficient): 4590 * {@snippet lang="java" : 4591 MethodHandle invoker = MethodHandles.invoker(type); 4592 int spreadArgCount = type.parameterCount() - leadingArgCount; 4593 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4594 return invoker; 4595 * } 4596 * This method throws no reflective or security exceptions. 4597 * @param type the desired target type 4598 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4599 * @return a method handle suitable for invoking any method handle of the given type 4600 * @throws NullPointerException if {@code type} is null 4601 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4602 * the range from 0 to {@code type.parameterCount()} inclusive, 4603 * or if the resulting method handle's type would have 4604 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4605 */ 4606 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4607 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4608 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4609 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4610 return type.invokers().spreadInvoker(leadingArgCount); 4611 } 4612 4613 /** 4614 * Produces a special <em>invoker method handle</em> which can be used to 4615 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4616 * The resulting invoker will have a type which is 4617 * exactly equal to the desired type, except that it will accept 4618 * an additional leading argument of type {@code MethodHandle}. 4619 * <p> 4620 * This method is equivalent to the following code (though it may be more efficient): 4621 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4622 * 4623 * <p style="font-size:smaller;"> 4624 * <em>Discussion:</em> 4625 * Invoker method handles can be useful when working with variable method handles 4626 * of unknown types. 4627 * For example, to emulate an {@code invokeExact} call to a variable method 4628 * handle {@code M}, extract its type {@code T}, 4629 * look up the invoker method {@code X} for {@code T}, 4630 * and call the invoker method, as {@code X.invoke(T, A...)}. 4631 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4632 * is unknown.) 4633 * If spreading, collecting, or other argument transformations are required, 4634 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4635 * method handle values, as long as they are compatible with the type of {@code X}. 4636 * <p style="font-size:smaller;"> 4637 * <em>(Note: The invoker method is not available via the Core Reflection API. 4638 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4639 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4640 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4641 * <p> 4642 * This method throws no reflective or security exceptions. 4643 * @param type the desired target type 4644 * @return a method handle suitable for invoking any method handle of the given type 4645 * @throws IllegalArgumentException if the resulting method handle's type would have 4646 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4647 */ 4648 public static MethodHandle exactInvoker(MethodType type) { 4649 return type.invokers().exactInvoker(); 4650 } 4651 4652 /** 4653 * Produces a special <em>invoker method handle</em> which can be used to 4654 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4655 * The resulting invoker will have a type which is 4656 * exactly equal to the desired type, except that it will accept 4657 * an additional leading argument of type {@code MethodHandle}. 4658 * <p> 4659 * Before invoking its target, if the target differs from the expected type, 4660 * the invoker will apply reference casts as 4661 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4662 * Similarly, the return value will be converted as necessary. 4663 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4664 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4665 * <p> 4666 * This method is equivalent to the following code (though it may be more efficient): 4667 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4668 * <p style="font-size:smaller;"> 4669 * <em>Discussion:</em> 4670 * A {@linkplain MethodType#genericMethodType general method type} is one which 4671 * mentions only {@code Object} arguments and return values. 4672 * An invoker for such a type is capable of calling any method handle 4673 * of the same arity as the general type. 4674 * <p style="font-size:smaller;"> 4675 * <em>(Note: The invoker method is not available via the Core Reflection API. 4676 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4677 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4678 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4679 * <p> 4680 * This method throws no reflective or security exceptions. 4681 * @param type the desired target type 4682 * @return a method handle suitable for invoking any method handle convertible to the given type 4683 * @throws IllegalArgumentException if the resulting method handle's type would have 4684 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4685 */ 4686 public static MethodHandle invoker(MethodType type) { 4687 return type.invokers().genericInvoker(); 4688 } 4689 4690 /** 4691 * Produces a special <em>invoker method handle</em> which can be used to 4692 * invoke a signature-polymorphic access mode method on any VarHandle whose 4693 * associated access mode type is compatible with the given type. 4694 * The resulting invoker will have a type which is exactly equal to the 4695 * desired given type, except that it will accept an additional leading 4696 * argument of type {@code VarHandle}. 4697 * 4698 * @param accessMode the VarHandle access mode 4699 * @param type the desired target type 4700 * @return a method handle suitable for invoking an access mode method of 4701 * any VarHandle whose access mode type is of the given type. 4702 * @since 9 4703 */ 4704 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4705 return type.invokers().varHandleMethodExactInvoker(accessMode); 4706 } 4707 4708 /** 4709 * Produces a special <em>invoker method handle</em> which can be used to 4710 * invoke a signature-polymorphic access mode method on any VarHandle whose 4711 * associated access mode type is compatible with the given type. 4712 * The resulting invoker will have a type which is exactly equal to the 4713 * desired given type, except that it will accept an additional leading 4714 * argument of type {@code VarHandle}. 4715 * <p> 4716 * Before invoking its target, if the access mode type differs from the 4717 * desired given type, the invoker will apply reference casts as necessary 4718 * and box, unbox, or widen primitive values, as if by 4719 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4720 * converted as necessary. 4721 * <p> 4722 * This method is equivalent to the following code (though it may be more 4723 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4724 * 4725 * @param accessMode the VarHandle access mode 4726 * @param type the desired target type 4727 * @return a method handle suitable for invoking an access mode method of 4728 * any VarHandle whose access mode type is convertible to the given 4729 * type. 4730 * @since 9 4731 */ 4732 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4733 return type.invokers().varHandleMethodInvoker(accessMode); 4734 } 4735 4736 /*non-public*/ 4737 static MethodHandle basicInvoker(MethodType type) { 4738 return type.invokers().basicInvoker(); 4739 } 4740 4741 /// method handle modification (creation from other method handles) 4742 4743 /** 4744 * Produces a method handle which adapts the type of the 4745 * given method handle to a new type by pairwise argument and return type conversion. 4746 * The original type and new type must have the same number of arguments. 4747 * The resulting method handle is guaranteed to report a type 4748 * which is equal to the desired new type. 4749 * <p> 4750 * If the original type and new type are equal, returns target. 4751 * <p> 4752 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4753 * and some additional conversions are also applied if those conversions fail. 4754 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4755 * if possible, before or instead of any conversions done by {@code asType}: 4756 * <ul> 4757 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4758 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4759 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4760 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4761 * the boolean is converted to a byte value, 1 for true, 0 for false. 4762 * (This treatment follows the usage of the bytecode verifier.) 4763 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4764 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4765 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4766 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4767 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4768 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4769 * widening and/or narrowing.) 4770 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4771 * conversion will be applied at runtime, possibly followed 4772 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4773 * possibly followed by a conversion from byte to boolean by testing 4774 * the low-order bit. 4775 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4776 * and if the reference is null at runtime, a zero value is introduced. 4777 * </ul> 4778 * @param target the method handle to invoke after arguments are retyped 4779 * @param newType the expected type of the new method handle 4780 * @return a method handle which delegates to the target after performing 4781 * any necessary argument conversions, and arranges for any 4782 * necessary return value conversions 4783 * @throws NullPointerException if either argument is null 4784 * @throws WrongMethodTypeException if the conversion cannot be made 4785 * @see MethodHandle#asType 4786 */ 4787 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4788 explicitCastArgumentsChecks(target, newType); 4789 // use the asTypeCache when possible: 4790 MethodType oldType = target.type(); 4791 if (oldType == newType) return target; 4792 if (oldType.explicitCastEquivalentToAsType(newType)) { 4793 return target.asFixedArity().asType(newType); 4794 } 4795 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4796 } 4797 4798 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4799 if (target.type().parameterCount() != newType.parameterCount()) { 4800 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4801 } 4802 } 4803 4804 /** 4805 * Produces a method handle which adapts the calling sequence of the 4806 * given method handle to a new type, by reordering the arguments. 4807 * The resulting method handle is guaranteed to report a type 4808 * which is equal to the desired new type. 4809 * <p> 4810 * The given array controls the reordering. 4811 * Call {@code #I} the number of incoming parameters (the value 4812 * {@code newType.parameterCount()}, and call {@code #O} the number 4813 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4814 * Then the length of the reordering array must be {@code #O}, 4815 * and each element must be a non-negative number less than {@code #I}. 4816 * For every {@code N} less than {@code #O}, the {@code N}-th 4817 * outgoing argument will be taken from the {@code I}-th incoming 4818 * argument, where {@code I} is {@code reorder[N]}. 4819 * <p> 4820 * No argument or return value conversions are applied. 4821 * The type of each incoming argument, as determined by {@code newType}, 4822 * must be identical to the type of the corresponding outgoing parameter 4823 * or parameters in the target method handle. 4824 * The return type of {@code newType} must be identical to the return 4825 * type of the original target. 4826 * <p> 4827 * The reordering array need not specify an actual permutation. 4828 * An incoming argument will be duplicated if its index appears 4829 * more than once in the array, and an incoming argument will be dropped 4830 * if its index does not appear in the array. 4831 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4832 * incoming arguments which are not mentioned in the reordering array 4833 * may be of any type, as determined only by {@code newType}. 4834 * {@snippet lang="java" : 4835 import static java.lang.invoke.MethodHandles.*; 4836 import static java.lang.invoke.MethodType.*; 4837 ... 4838 MethodType intfn1 = methodType(int.class, int.class); 4839 MethodType intfn2 = methodType(int.class, int.class, int.class); 4840 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4841 assert(sub.type().equals(intfn2)); 4842 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4843 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4844 assert((int)rsub.invokeExact(1, 100) == 99); 4845 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4846 assert(add.type().equals(intfn2)); 4847 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4848 assert(twice.type().equals(intfn1)); 4849 assert((int)twice.invokeExact(21) == 42); 4850 * } 4851 * <p> 4852 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4853 * variable-arity method handle}, even if the original target method handle was. 4854 * @param target the method handle to invoke after arguments are reordered 4855 * @param newType the expected type of the new method handle 4856 * @param reorder an index array which controls the reordering 4857 * @return a method handle which delegates to the target after it 4858 * drops unused arguments and moves and/or duplicates the other arguments 4859 * @throws NullPointerException if any argument is null 4860 * @throws IllegalArgumentException if the index array length is not equal to 4861 * the arity of the target, or if any index array element 4862 * not a valid index for a parameter of {@code newType}, 4863 * or if two corresponding parameter types in 4864 * {@code target.type()} and {@code newType} are not identical, 4865 */ 4866 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4867 reorder = reorder.clone(); // get a private copy 4868 MethodType oldType = target.type(); 4869 permuteArgumentChecks(reorder, newType, oldType); 4870 // first detect dropped arguments and handle them separately 4871 int[] originalReorder = reorder; 4872 BoundMethodHandle result = target.rebind(); 4873 LambdaForm form = result.form; 4874 int newArity = newType.parameterCount(); 4875 // Normalize the reordering into a real permutation, 4876 // by removing duplicates and adding dropped elements. 4877 // This somewhat improves lambda form caching, as well 4878 // as simplifying the transform by breaking it up into steps. 4879 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4880 if (ddIdx > 0) { 4881 // We found a duplicated entry at reorder[ddIdx]. 4882 // Example: (x,y,z)->asList(x,y,z) 4883 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4884 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4885 // The starred element corresponds to the argument 4886 // deleted by the dupArgumentForm transform. 4887 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4888 boolean killFirst = false; 4889 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4890 // Set killFirst if the dup is larger than an intervening position. 4891 // This will remove at least one inversion from the permutation. 4892 if (dupVal > val) killFirst = true; 4893 } 4894 if (!killFirst) { 4895 srcPos = dstPos; 4896 dstPos = ddIdx; 4897 } 4898 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4899 assert (reorder[srcPos] == reorder[dstPos]); 4900 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4901 // contract the reordering by removing the element at dstPos 4902 int tailPos = dstPos + 1; 4903 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4904 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4905 } else { 4906 int dropVal = ~ddIdx, insPos = 0; 4907 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4908 // Find first element of reorder larger than dropVal. 4909 // This is where we will insert the dropVal. 4910 insPos += 1; 4911 } 4912 Class<?> ptype = newType.parameterType(dropVal); 4913 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4914 oldType = oldType.insertParameterTypes(insPos, ptype); 4915 // expand the reordering by inserting an element at insPos 4916 int tailPos = insPos + 1; 4917 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4918 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4919 reorder[insPos] = dropVal; 4920 } 4921 assert (permuteArgumentChecks(reorder, newType, oldType)); 4922 } 4923 assert (reorder.length == newArity); // a perfect permutation 4924 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4925 form = form.editor().permuteArgumentsForm(1, reorder); 4926 if (newType == result.type() && form == result.internalForm()) 4927 return result; 4928 return result.copyWith(newType, form); 4929 } 4930 4931 /** 4932 * Return an indication of any duplicate or omission in reorder. 4933 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4934 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4935 * Otherwise, return zero. 4936 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4937 */ 4938 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4939 final int BIT_LIMIT = 63; // max number of bits in bit mask 4940 if (newArity < BIT_LIMIT) { 4941 long mask = 0; 4942 for (int i = 0; i < reorder.length; i++) { 4943 int arg = reorder[i]; 4944 if (arg >= newArity) { 4945 return reorder.length; 4946 } 4947 long bit = 1L << arg; 4948 if ((mask & bit) != 0) { 4949 return i; // >0 indicates a dup 4950 } 4951 mask |= bit; 4952 } 4953 if (mask == (1L << newArity) - 1) { 4954 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4955 return 0; 4956 } 4957 // find first zero 4958 long zeroBit = Long.lowestOneBit(~mask); 4959 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4960 assert(zeroPos <= newArity); 4961 if (zeroPos == newArity) { 4962 return 0; 4963 } 4964 return ~zeroPos; 4965 } else { 4966 // same algorithm, different bit set 4967 BitSet mask = new BitSet(newArity); 4968 for (int i = 0; i < reorder.length; i++) { 4969 int arg = reorder[i]; 4970 if (arg >= newArity) { 4971 return reorder.length; 4972 } 4973 if (mask.get(arg)) { 4974 return i; // >0 indicates a dup 4975 } 4976 mask.set(arg); 4977 } 4978 int zeroPos = mask.nextClearBit(0); 4979 assert(zeroPos <= newArity); 4980 if (zeroPos == newArity) { 4981 return 0; 4982 } 4983 return ~zeroPos; 4984 } 4985 } 4986 4987 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4988 if (newType.returnType() != oldType.returnType()) 4989 throw newIllegalArgumentException("return types do not match", 4990 oldType, newType); 4991 if (reorder.length != oldType.parameterCount()) 4992 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 4993 oldType, Arrays.toString(reorder)); 4994 4995 int limit = newType.parameterCount(); 4996 for (int j = 0; j < reorder.length; j++) { 4997 int i = reorder[j]; 4998 if (i < 0 || i >= limit) { 4999 throw newIllegalArgumentException("index is out of bounds for new type", 5000 i, newType); 5001 } 5002 Class<?> src = newType.parameterType(i); 5003 Class<?> dst = oldType.parameterType(j); 5004 if (src != dst) 5005 throw newIllegalArgumentException("parameter types do not match after reorder", 5006 oldType, newType); 5007 } 5008 return true; 5009 } 5010 5011 /** 5012 * Produces a method handle of the requested return type which returns the given 5013 * constant value every time it is invoked. 5014 * <p> 5015 * Before the method handle is returned, the passed-in value is converted to the requested type. 5016 * If the requested type is primitive, widening primitive conversions are attempted, 5017 * else reference conversions are attempted. 5018 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5019 * @param type the return type of the desired method handle 5020 * @param value the value to return 5021 * @return a method handle of the given return type and no arguments, which always returns the given value 5022 * @throws NullPointerException if the {@code type} argument is null 5023 * @throws ClassCastException if the value cannot be converted to the required return type 5024 * @throws IllegalArgumentException if the given type is {@code void.class} 5025 */ 5026 public static MethodHandle constant(Class<?> type, Object value) { 5027 if (type.isPrimitive()) { 5028 if (type == void.class) 5029 throw newIllegalArgumentException("void type"); 5030 Wrapper w = Wrapper.forPrimitiveType(type); 5031 value = w.convert(value, type); 5032 if (w.zero().equals(value)) 5033 return zero(w, type); 5034 return insertArguments(identity(type), 0, value); 5035 } else { 5036 if (value == null) 5037 return zero(Wrapper.OBJECT, type); 5038 return identity(type).bindTo(value); 5039 } 5040 } 5041 5042 /** 5043 * Produces a method handle which returns its sole argument when invoked. 5044 * @param type the type of the sole parameter and return value of the desired method handle 5045 * @return a unary method handle which accepts and returns the given type 5046 * @throws NullPointerException if the argument is null 5047 * @throws IllegalArgumentException if the given type is {@code void.class} 5048 */ 5049 public static MethodHandle identity(Class<?> type) { 5050 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5051 int pos = btw.ordinal(); 5052 MethodHandle ident = IDENTITY_MHS[pos]; 5053 if (ident == null) { 5054 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5055 } 5056 if (ident.type().returnType() == type) 5057 return ident; 5058 // something like identity(Foo.class); do not bother to intern these 5059 assert (btw == Wrapper.OBJECT); 5060 return makeIdentity(type); 5061 } 5062 5063 /** 5064 * Produces a constant method handle of the requested return type which 5065 * returns the default value for that type every time it is invoked. 5066 * The resulting constant method handle will have no side effects. 5067 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5068 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5069 * since {@code explicitCastArguments} converts {@code null} to default values. 5070 * @param type the expected return type of the desired method handle 5071 * @return a constant method handle that takes no arguments 5072 * and returns the default value of the given type (or void, if the type is void) 5073 * @throws NullPointerException if the argument is null 5074 * @see MethodHandles#constant 5075 * @see MethodHandles#empty 5076 * @see MethodHandles#explicitCastArguments 5077 * @since 9 5078 */ 5079 public static MethodHandle zero(Class<?> type) { 5080 Objects.requireNonNull(type); 5081 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5082 } 5083 5084 private static MethodHandle identityOrVoid(Class<?> type) { 5085 return type == void.class ? zero(type) : identity(type); 5086 } 5087 5088 /** 5089 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5090 * and returns a suitable default depending on the return type. 5091 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5092 * <p>The returned method handle is equivalent to 5093 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5094 * 5095 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5096 * {@code guardWithTest(pred, target, empty(target.type())}. 5097 * @param type the type of the desired method handle 5098 * @return a constant method handle of the given type, which returns a default value of the given return type 5099 * @throws NullPointerException if the argument is null 5100 * @see MethodHandles#zero 5101 * @see MethodHandles#constant 5102 * @since 9 5103 */ 5104 public static MethodHandle empty(MethodType type) { 5105 Objects.requireNonNull(type); 5106 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5107 } 5108 5109 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5110 private static MethodHandle makeIdentity(Class<?> ptype) { 5111 MethodType mtype = methodType(ptype, ptype); 5112 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5113 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5114 } 5115 5116 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5117 int pos = btw.ordinal(); 5118 MethodHandle zero = ZERO_MHS[pos]; 5119 if (zero == null) { 5120 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5121 } 5122 if (zero.type().returnType() == rtype) 5123 return zero; 5124 assert(btw == Wrapper.OBJECT); 5125 return makeZero(rtype); 5126 } 5127 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5128 private static MethodHandle makeZero(Class<?> rtype) { 5129 MethodType mtype = methodType(rtype); 5130 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5131 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5132 } 5133 5134 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5135 // Simulate a CAS, to avoid racy duplication of results. 5136 MethodHandle prev = cache[pos]; 5137 if (prev != null) return prev; 5138 return cache[pos] = value; 5139 } 5140 5141 /** 5142 * Provides a target method handle with one or more <em>bound arguments</em> 5143 * in advance of the method handle's invocation. 5144 * The formal parameters to the target corresponding to the bound 5145 * arguments are called <em>bound parameters</em>. 5146 * Returns a new method handle which saves away the bound arguments. 5147 * When it is invoked, it receives arguments for any non-bound parameters, 5148 * binds the saved arguments to their corresponding parameters, 5149 * and calls the original target. 5150 * <p> 5151 * The type of the new method handle will drop the types for the bound 5152 * parameters from the original target type, since the new method handle 5153 * will no longer require those arguments to be supplied by its callers. 5154 * <p> 5155 * Each given argument object must match the corresponding bound parameter type. 5156 * If a bound parameter type is a primitive, the argument object 5157 * must be a wrapper, and will be unboxed to produce the primitive value. 5158 * <p> 5159 * The {@code pos} argument selects which parameters are to be bound. 5160 * It may range between zero and <i>N-L</i> (inclusively), 5161 * where <i>N</i> is the arity of the target method handle 5162 * and <i>L</i> is the length of the values array. 5163 * <p> 5164 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5165 * variable-arity method handle}, even if the original target method handle was. 5166 * @param target the method handle to invoke after the argument is inserted 5167 * @param pos where to insert the argument (zero for the first) 5168 * @param values the series of arguments to insert 5169 * @return a method handle which inserts an additional argument, 5170 * before calling the original method handle 5171 * @throws NullPointerException if the target or the {@code values} array is null 5172 * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than 5173 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5174 * is the length of the values array. 5175 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5176 * type. 5177 * @see MethodHandle#bindTo 5178 */ 5179 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5180 int insCount = values.length; 5181 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5182 if (insCount == 0) return target; 5183 BoundMethodHandle result = target.rebind(); 5184 for (int i = 0; i < insCount; i++) { 5185 Object value = values[i]; 5186 Class<?> ptype = ptypes[pos+i]; 5187 if (ptype.isPrimitive()) { 5188 result = insertArgumentPrimitive(result, pos, ptype, value); 5189 } else { 5190 value = ptype.cast(value); // throw CCE if needed 5191 result = result.bindArgumentL(pos, value); 5192 } 5193 } 5194 return result; 5195 } 5196 5197 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5198 Class<?> ptype, Object value) { 5199 Wrapper w = Wrapper.forPrimitiveType(ptype); 5200 // perform unboxing and/or primitive conversion 5201 value = w.convert(value, ptype); 5202 return switch (w) { 5203 case INT -> result.bindArgumentI(pos, (int) value); 5204 case LONG -> result.bindArgumentJ(pos, (long) value); 5205 case FLOAT -> result.bindArgumentF(pos, (float) value); 5206 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5207 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5208 }; 5209 } 5210 5211 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5212 MethodType oldType = target.type(); 5213 int outargs = oldType.parameterCount(); 5214 int inargs = outargs - insCount; 5215 if (inargs < 0) 5216 throw newIllegalArgumentException("too many values to insert"); 5217 if (pos < 0 || pos > inargs) 5218 throw newIllegalArgumentException("no argument type to append"); 5219 return oldType.ptypes(); 5220 } 5221 5222 /** 5223 * Produces a method handle which will discard some dummy arguments 5224 * before calling some other specified <i>target</i> method handle. 5225 * The type of the new method handle will be the same as the target's type, 5226 * except it will also include the dummy argument types, 5227 * at some given position. 5228 * <p> 5229 * The {@code pos} argument may range between zero and <i>N</i>, 5230 * where <i>N</i> is the arity of the target. 5231 * If {@code pos} is zero, the dummy arguments will precede 5232 * the target's real arguments; if {@code pos} is <i>N</i> 5233 * they will come after. 5234 * <p> 5235 * <b>Example:</b> 5236 * {@snippet lang="java" : 5237 import static java.lang.invoke.MethodHandles.*; 5238 import static java.lang.invoke.MethodType.*; 5239 ... 5240 MethodHandle cat = lookup().findVirtual(String.class, 5241 "concat", methodType(String.class, String.class)); 5242 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5243 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5244 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5245 assertEquals(bigType, d0.type()); 5246 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5247 * } 5248 * <p> 5249 * This method is also equivalent to the following code: 5250 * <blockquote><pre> 5251 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5252 * </pre></blockquote> 5253 * @param target the method handle to invoke after the arguments are dropped 5254 * @param pos position of first argument to drop (zero for the leftmost) 5255 * @param valueTypes the type(s) of the argument(s) to drop 5256 * @return a method handle which drops arguments of the given types, 5257 * before calling the original method handle 5258 * @throws NullPointerException if the target is null, 5259 * or if the {@code valueTypes} list or any of its elements is null 5260 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5261 * or if {@code pos} is negative or greater than the arity of the target, 5262 * or if the new method handle's type would have too many parameters 5263 */ 5264 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5265 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5266 } 5267 5268 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5269 MethodType oldType = target.type(); // get NPE 5270 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5271 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5272 if (dropped == 0) return target; 5273 BoundMethodHandle result = target.rebind(); 5274 LambdaForm lform = result.form; 5275 int insertFormArg = 1 + pos; 5276 for (Class<?> ptype : valueTypes) { 5277 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5278 } 5279 result = result.copyWith(newType, lform); 5280 return result; 5281 } 5282 5283 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5284 int dropped = valueTypes.length; 5285 MethodType.checkSlotCount(dropped); 5286 int outargs = oldType.parameterCount(); 5287 int inargs = outargs + dropped; 5288 if (pos < 0 || pos > outargs) 5289 throw newIllegalArgumentException("no argument type to remove" 5290 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5291 ); 5292 return dropped; 5293 } 5294 5295 /** 5296 * Produces a method handle which will discard some dummy arguments 5297 * before calling some other specified <i>target</i> method handle. 5298 * The type of the new method handle will be the same as the target's type, 5299 * except it will also include the dummy argument types, 5300 * at some given position. 5301 * <p> 5302 * The {@code pos} argument may range between zero and <i>N</i>, 5303 * where <i>N</i> is the arity of the target. 5304 * If {@code pos} is zero, the dummy arguments will precede 5305 * the target's real arguments; if {@code pos} is <i>N</i> 5306 * they will come after. 5307 * @apiNote 5308 * {@snippet lang="java" : 5309 import static java.lang.invoke.MethodHandles.*; 5310 import static java.lang.invoke.MethodType.*; 5311 ... 5312 MethodHandle cat = lookup().findVirtual(String.class, 5313 "concat", methodType(String.class, String.class)); 5314 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5315 MethodHandle d0 = dropArguments(cat, 0, String.class); 5316 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5317 MethodHandle d1 = dropArguments(cat, 1, String.class); 5318 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5319 MethodHandle d2 = dropArguments(cat, 2, String.class); 5320 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5321 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5322 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5323 * } 5324 * <p> 5325 * This method is also equivalent to the following code: 5326 * <blockquote><pre> 5327 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5328 * </pre></blockquote> 5329 * @param target the method handle to invoke after the arguments are dropped 5330 * @param pos position of first argument to drop (zero for the leftmost) 5331 * @param valueTypes the type(s) of the argument(s) to drop 5332 * @return a method handle which drops arguments of the given types, 5333 * before calling the original method handle 5334 * @throws NullPointerException if the target is null, 5335 * or if the {@code valueTypes} array or any of its elements is null 5336 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5337 * or if {@code pos} is negative or greater than the arity of the target, 5338 * or if the new method handle's type would have 5339 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5340 */ 5341 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5342 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5343 } 5344 5345 /* Convenience overloads for trusting internal low-arity call-sites */ 5346 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5347 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5348 } 5349 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5350 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5351 } 5352 5353 // private version which allows caller some freedom with error handling 5354 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5355 boolean nullOnFailure) { 5356 Class<?>[] oldTypes = target.type().ptypes(); 5357 int match = oldTypes.length; 5358 if (skip != 0) { 5359 if (skip < 0 || skip > match) { 5360 throw newIllegalArgumentException("illegal skip", skip, target); 5361 } 5362 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5363 match -= skip; 5364 } 5365 Class<?>[] addTypes = newTypes; 5366 int add = addTypes.length; 5367 if (pos != 0) { 5368 if (pos < 0 || pos > add) { 5369 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5370 } 5371 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5372 add -= pos; 5373 assert(addTypes.length == add); 5374 } 5375 // Do not add types which already match the existing arguments. 5376 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5377 if (nullOnFailure) { 5378 return null; 5379 } 5380 throw newIllegalArgumentException("argument lists do not match", 5381 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5382 } 5383 addTypes = Arrays.copyOfRange(addTypes, match, add); 5384 add -= match; 5385 assert(addTypes.length == add); 5386 // newTypes: ( P*[pos], M*[match], A*[add] ) 5387 // target: ( S*[skip], M*[match] ) 5388 MethodHandle adapter = target; 5389 if (add > 0) { 5390 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5391 } 5392 // adapter: (S*[skip], M*[match], A*[add] ) 5393 if (pos > 0) { 5394 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5395 } 5396 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5397 return adapter; 5398 } 5399 5400 /** 5401 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5402 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5403 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5404 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5405 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5406 * {@link #dropArguments(MethodHandle, int, Class[])}. 5407 * <p> 5408 * The resulting handle will have the same return type as the target handle. 5409 * <p> 5410 * In more formal terms, assume these two type lists:<ul> 5411 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5412 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5413 * {@code newTypes}. 5414 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5415 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5416 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5417 * sub-list. 5418 * </ul> 5419 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5420 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5421 * {@link #dropArguments(MethodHandle, int, Class[])}. 5422 * 5423 * @apiNote 5424 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5425 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5426 * {@snippet lang="java" : 5427 import static java.lang.invoke.MethodHandles.*; 5428 import static java.lang.invoke.MethodType.*; 5429 ... 5430 ... 5431 MethodHandle h0 = constant(boolean.class, true); 5432 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5433 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5434 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5435 if (h1.type().parameterCount() < h2.type().parameterCount()) 5436 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5437 else 5438 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5439 MethodHandle h3 = guardWithTest(h0, h1, h2); 5440 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5441 * } 5442 * @param target the method handle to adapt 5443 * @param skip number of targets parameters to disregard (they will be unchanged) 5444 * @param newTypes the list of types to match {@code target}'s parameter type list to 5445 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5446 * @return a possibly adapted method handle 5447 * @throws NullPointerException if either argument is null 5448 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5449 * or if {@code skip} is negative or greater than the arity of the target, 5450 * or if {@code pos} is negative or greater than the newTypes list size, 5451 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5452 * {@code pos}. 5453 * @since 9 5454 */ 5455 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5456 Objects.requireNonNull(target); 5457 Objects.requireNonNull(newTypes); 5458 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5459 } 5460 5461 /** 5462 * Drop the return value of the target handle (if any). 5463 * The returned method handle will have a {@code void} return type. 5464 * 5465 * @param target the method handle to adapt 5466 * @return a possibly adapted method handle 5467 * @throws NullPointerException if {@code target} is null 5468 * @since 16 5469 */ 5470 public static MethodHandle dropReturn(MethodHandle target) { 5471 Objects.requireNonNull(target); 5472 MethodType oldType = target.type(); 5473 Class<?> oldReturnType = oldType.returnType(); 5474 if (oldReturnType == void.class) 5475 return target; 5476 MethodType newType = oldType.changeReturnType(void.class); 5477 BoundMethodHandle result = target.rebind(); 5478 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5479 result = result.copyWith(newType, lform); 5480 return result; 5481 } 5482 5483 /** 5484 * Adapts a target method handle by pre-processing 5485 * one or more of its arguments, each with its own unary filter function, 5486 * and then calling the target with each pre-processed argument 5487 * replaced by the result of its corresponding filter function. 5488 * <p> 5489 * The pre-processing is performed by one or more method handles, 5490 * specified in the elements of the {@code filters} array. 5491 * The first element of the filter array corresponds to the {@code pos} 5492 * argument of the target, and so on in sequence. 5493 * The filter functions are invoked in left to right order. 5494 * <p> 5495 * Null arguments in the array are treated as identity functions, 5496 * and the corresponding arguments left unchanged. 5497 * (If there are no non-null elements in the array, the original target is returned.) 5498 * Each filter is applied to the corresponding argument of the adapter. 5499 * <p> 5500 * If a filter {@code F} applies to the {@code N}th argument of 5501 * the target, then {@code F} must be a method handle which 5502 * takes exactly one argument. The type of {@code F}'s sole argument 5503 * replaces the corresponding argument type of the target 5504 * in the resulting adapted method handle. 5505 * The return type of {@code F} must be identical to the corresponding 5506 * parameter type of the target. 5507 * <p> 5508 * It is an error if there are elements of {@code filters} 5509 * (null or not) 5510 * which do not correspond to argument positions in the target. 5511 * <p><b>Example:</b> 5512 * {@snippet lang="java" : 5513 import static java.lang.invoke.MethodHandles.*; 5514 import static java.lang.invoke.MethodType.*; 5515 ... 5516 MethodHandle cat = lookup().findVirtual(String.class, 5517 "concat", methodType(String.class, String.class)); 5518 MethodHandle upcase = lookup().findVirtual(String.class, 5519 "toUpperCase", methodType(String.class)); 5520 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5521 MethodHandle f0 = filterArguments(cat, 0, upcase); 5522 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5523 MethodHandle f1 = filterArguments(cat, 1, upcase); 5524 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5525 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5526 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5527 * } 5528 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5529 * denotes the return type of both the {@code target} and resulting adapter. 5530 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5531 * of the parameters and arguments that precede and follow the filter position 5532 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5533 * values of the filtered parameters and arguments; they also represent the 5534 * return types of the {@code filter[i]} handles. The latter accept arguments 5535 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5536 * the resulting adapter. 5537 * {@snippet lang="java" : 5538 * T target(P... p, A[i]... a[i], B... b); 5539 * A[i] filter[i](V[i]); 5540 * T adapter(P... p, V[i]... v[i], B... b) { 5541 * return target(p..., filter[i](v[i])..., b...); 5542 * } 5543 * } 5544 * <p> 5545 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5546 * variable-arity method handle}, even if the original target method handle was. 5547 * 5548 * @param target the method handle to invoke after arguments are filtered 5549 * @param pos the position of the first argument to filter 5550 * @param filters method handles to call initially on filtered arguments 5551 * @return method handle which incorporates the specified argument filtering logic 5552 * @throws NullPointerException if the target is null 5553 * or if the {@code filters} array is null 5554 * @throws IllegalArgumentException if a non-null element of {@code filters} 5555 * does not match a corresponding argument type of target as described above, 5556 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5557 * or if the resulting method handle's type would have 5558 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5559 */ 5560 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5561 // In method types arguments start at index 0, while the LF 5562 // editor have the MH receiver at position 0 - adjust appropriately. 5563 final int MH_RECEIVER_OFFSET = 1; 5564 filterArgumentsCheckArity(target, pos, filters); 5565 MethodHandle adapter = target; 5566 5567 // keep track of currently matched filters, as to optimize repeated filters 5568 int index = 0; 5569 int[] positions = new int[filters.length]; 5570 MethodHandle filter = null; 5571 5572 // process filters in reverse order so that the invocation of 5573 // the resulting adapter will invoke the filters in left-to-right order 5574 for (int i = filters.length - 1; i >= 0; --i) { 5575 MethodHandle newFilter = filters[i]; 5576 if (newFilter == null) continue; // ignore null elements of filters 5577 5578 // flush changes on update 5579 if (filter != newFilter) { 5580 if (filter != null) { 5581 if (index > 1) { 5582 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5583 } else { 5584 adapter = filterArgument(adapter, positions[0] - 1, filter); 5585 } 5586 } 5587 filter = newFilter; 5588 index = 0; 5589 } 5590 5591 filterArgumentChecks(target, pos + i, newFilter); 5592 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5593 } 5594 if (index > 1) { 5595 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5596 } else if (index == 1) { 5597 adapter = filterArgument(adapter, positions[0] - 1, filter); 5598 } 5599 return adapter; 5600 } 5601 5602 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5603 MethodType targetType = adapter.type(); 5604 MethodType filterType = filter.type(); 5605 BoundMethodHandle result = adapter.rebind(); 5606 Class<?> newParamType = filterType.parameterType(0); 5607 5608 Class<?>[] ptypes = targetType.ptypes().clone(); 5609 for (int pos : positions) { 5610 ptypes[pos - 1] = newParamType; 5611 } 5612 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5613 5614 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5615 return result.copyWithExtendL(newType, lform, filter); 5616 } 5617 5618 /*non-public*/ 5619 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5620 filterArgumentChecks(target, pos, filter); 5621 MethodType targetType = target.type(); 5622 MethodType filterType = filter.type(); 5623 BoundMethodHandle result = target.rebind(); 5624 Class<?> newParamType = filterType.parameterType(0); 5625 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5626 MethodType newType = targetType.changeParameterType(pos, newParamType); 5627 result = result.copyWithExtendL(newType, lform, filter); 5628 return result; 5629 } 5630 5631 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5632 MethodType targetType = target.type(); 5633 int maxPos = targetType.parameterCount(); 5634 if (pos + filters.length > maxPos) 5635 throw newIllegalArgumentException("too many filters"); 5636 } 5637 5638 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5639 MethodType targetType = target.type(); 5640 MethodType filterType = filter.type(); 5641 if (filterType.parameterCount() != 1 5642 || filterType.returnType() != targetType.parameterType(pos)) 5643 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5644 } 5645 5646 /** 5647 * Adapts a target method handle by pre-processing 5648 * a sub-sequence of its arguments with a filter (another method handle). 5649 * The pre-processed arguments are replaced by the result (if any) of the 5650 * filter function. 5651 * The target is then called on the modified (usually shortened) argument list. 5652 * <p> 5653 * If the filter returns a value, the target must accept that value as 5654 * its argument in position {@code pos}, preceded and/or followed by 5655 * any arguments not passed to the filter. 5656 * If the filter returns void, the target must accept all arguments 5657 * not passed to the filter. 5658 * No arguments are reordered, and a result returned from the filter 5659 * replaces (in order) the whole subsequence of arguments originally 5660 * passed to the adapter. 5661 * <p> 5662 * The argument types (if any) of the filter 5663 * replace zero or one argument types of the target, at position {@code pos}, 5664 * in the resulting adapted method handle. 5665 * The return type of the filter (if any) must be identical to the 5666 * argument type of the target at position {@code pos}, and that target argument 5667 * is supplied by the return value of the filter. 5668 * <p> 5669 * In all cases, {@code pos} must be greater than or equal to zero, and 5670 * {@code pos} must also be less than or equal to the target's arity. 5671 * <p><b>Example:</b> 5672 * {@snippet lang="java" : 5673 import static java.lang.invoke.MethodHandles.*; 5674 import static java.lang.invoke.MethodType.*; 5675 ... 5676 MethodHandle deepToString = publicLookup() 5677 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5678 5679 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5680 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5681 5682 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5683 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5684 5685 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5686 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5687 assertEquals("[top, [up, down], strange]", 5688 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5689 5690 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5691 assertEquals("[top, [up, down], [strange]]", 5692 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5693 5694 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5695 assertEquals("[top, [[up, down, strange], charm], bottom]", 5696 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5697 * } 5698 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5699 * represents the return type of the {@code target} and resulting adapter. 5700 * {@code V}/{@code v} stand for the return type and value of the 5701 * {@code filter}, which are also found in the signature and arguments of 5702 * the {@code target}, respectively, unless {@code V} is {@code void}. 5703 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5704 * and values preceding and following the collection position, {@code pos}, 5705 * in the {@code target}'s signature. They also turn up in the resulting 5706 * adapter's signature and arguments, where they surround 5707 * {@code B}/{@code b}, which represent the parameter types and arguments 5708 * to the {@code filter} (if any). 5709 * {@snippet lang="java" : 5710 * T target(A...,V,C...); 5711 * V filter(B...); 5712 * T adapter(A... a,B... b,C... c) { 5713 * V v = filter(b...); 5714 * return target(a...,v,c...); 5715 * } 5716 * // and if the filter has no arguments: 5717 * T target2(A...,V,C...); 5718 * V filter2(); 5719 * T adapter2(A... a,C... c) { 5720 * V v = filter2(); 5721 * return target2(a...,v,c...); 5722 * } 5723 * // and if the filter has a void return: 5724 * T target3(A...,C...); 5725 * void filter3(B...); 5726 * T adapter3(A... a,B... b,C... c) { 5727 * filter3(b...); 5728 * return target3(a...,c...); 5729 * } 5730 * } 5731 * <p> 5732 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5733 * one which first "folds" the affected arguments, and then drops them, in separate 5734 * steps as follows: 5735 * {@snippet lang="java" : 5736 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5737 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5738 * } 5739 * If the target method handle consumes no arguments besides than the result 5740 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5741 * is equivalent to {@code filterReturnValue(coll, mh)}. 5742 * If the filter method handle {@code coll} consumes one argument and produces 5743 * a non-void result, then {@code collectArguments(mh, N, coll)} 5744 * is equivalent to {@code filterArguments(mh, N, coll)}. 5745 * Other equivalences are possible but would require argument permutation. 5746 * <p> 5747 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5748 * variable-arity method handle}, even if the original target method handle was. 5749 * 5750 * @param target the method handle to invoke after filtering the subsequence of arguments 5751 * @param pos the position of the first adapter argument to pass to the filter, 5752 * and/or the target argument which receives the result of the filter 5753 * @param filter method handle to call on the subsequence of arguments 5754 * @return method handle which incorporates the specified argument subsequence filtering logic 5755 * @throws NullPointerException if either argument is null 5756 * @throws IllegalArgumentException if the return type of {@code filter} 5757 * is non-void and is not the same as the {@code pos} argument of the target, 5758 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5759 * or if the resulting method handle's type would have 5760 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5761 * @see MethodHandles#foldArguments 5762 * @see MethodHandles#filterArguments 5763 * @see MethodHandles#filterReturnValue 5764 */ 5765 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5766 MethodType newType = collectArgumentsChecks(target, pos, filter); 5767 MethodType collectorType = filter.type(); 5768 BoundMethodHandle result = target.rebind(); 5769 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5770 return result.copyWithExtendL(newType, lform, filter); 5771 } 5772 5773 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5774 MethodType targetType = target.type(); 5775 MethodType filterType = filter.type(); 5776 Class<?> rtype = filterType.returnType(); 5777 Class<?>[] filterArgs = filterType.ptypes(); 5778 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5779 (rtype != void.class && pos >= targetType.parameterCount())) { 5780 throw newIllegalArgumentException("position is out of range for target", target, pos); 5781 } 5782 if (rtype == void.class) { 5783 return targetType.insertParameterTypes(pos, filterArgs); 5784 } 5785 if (rtype != targetType.parameterType(pos)) { 5786 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5787 } 5788 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5789 } 5790 5791 /** 5792 * Adapts a target method handle by post-processing 5793 * its return value (if any) with a filter (another method handle). 5794 * The result of the filter is returned from the adapter. 5795 * <p> 5796 * If the target returns a value, the filter must accept that value as 5797 * its only argument. 5798 * If the target returns void, the filter must accept no arguments. 5799 * <p> 5800 * The return type of the filter 5801 * replaces the return type of the target 5802 * in the resulting adapted method handle. 5803 * The argument type of the filter (if any) must be identical to the 5804 * return type of the target. 5805 * <p><b>Example:</b> 5806 * {@snippet lang="java" : 5807 import static java.lang.invoke.MethodHandles.*; 5808 import static java.lang.invoke.MethodType.*; 5809 ... 5810 MethodHandle cat = lookup().findVirtual(String.class, 5811 "concat", methodType(String.class, String.class)); 5812 MethodHandle length = lookup().findVirtual(String.class, 5813 "length", methodType(int.class)); 5814 System.out.println((String) cat.invokeExact("x", "y")); // xy 5815 MethodHandle f0 = filterReturnValue(cat, length); 5816 System.out.println((int) f0.invokeExact("x", "y")); // 2 5817 * } 5818 * <p>Here is pseudocode for the resulting adapter. In the code, 5819 * {@code T}/{@code t} represent the result type and value of the 5820 * {@code target}; {@code V}, the result type of the {@code filter}; and 5821 * {@code A}/{@code a}, the types and values of the parameters and arguments 5822 * of the {@code target} as well as the resulting adapter. 5823 * {@snippet lang="java" : 5824 * T target(A...); 5825 * V filter(T); 5826 * V adapter(A... a) { 5827 * T t = target(a...); 5828 * return filter(t); 5829 * } 5830 * // and if the target has a void return: 5831 * void target2(A...); 5832 * V filter2(); 5833 * V adapter2(A... a) { 5834 * target2(a...); 5835 * return filter2(); 5836 * } 5837 * // and if the filter has a void return: 5838 * T target3(A...); 5839 * void filter3(V); 5840 * void adapter3(A... a) { 5841 * T t = target3(a...); 5842 * filter3(t); 5843 * } 5844 * } 5845 * <p> 5846 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5847 * variable-arity method handle}, even if the original target method handle was. 5848 * @param target the method handle to invoke before filtering the return value 5849 * @param filter method handle to call on the return value 5850 * @return method handle which incorporates the specified return value filtering logic 5851 * @throws NullPointerException if either argument is null 5852 * @throws IllegalArgumentException if the argument list of {@code filter} 5853 * does not match the return type of target as described above 5854 */ 5855 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5856 MethodType targetType = target.type(); 5857 MethodType filterType = filter.type(); 5858 filterReturnValueChecks(targetType, filterType); 5859 BoundMethodHandle result = target.rebind(); 5860 BasicType rtype = BasicType.basicType(filterType.returnType()); 5861 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5862 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5863 result = result.copyWithExtendL(newType, lform, filter); 5864 return result; 5865 } 5866 5867 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5868 Class<?> rtype = targetType.returnType(); 5869 int filterValues = filterType.parameterCount(); 5870 if (filterValues == 0 5871 ? (rtype != void.class) 5872 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5873 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5874 } 5875 5876 /** 5877 * Filter the return value of a target method handle with a filter function. The filter function is 5878 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5879 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5880 * as follows: 5881 * {@snippet lang="java" : 5882 * T target(A...) 5883 * V filter(B... , T) 5884 * V adapter(A... a, B... b) { 5885 * T t = target(a...); 5886 * return filter(b..., t); 5887 * } 5888 * } 5889 * <p> 5890 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5891 * 5892 * @param target the target method handle 5893 * @param filter the filter method handle 5894 * @return the adapter method handle 5895 */ 5896 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5897 MethodType targetType = target.type(); 5898 MethodType filterType = filter.type(); 5899 BoundMethodHandle result = target.rebind(); 5900 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5901 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5902 if (filterType.parameterCount() > 1) { 5903 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5904 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5905 } 5906 } 5907 result = result.copyWithExtendL(newType, lform, filter); 5908 return result; 5909 } 5910 5911 /** 5912 * Adapts a target method handle by pre-processing 5913 * some of its arguments, and then calling the target with 5914 * the result of the pre-processing, inserted into the original 5915 * sequence of arguments. 5916 * <p> 5917 * The pre-processing is performed by {@code combiner}, a second method handle. 5918 * Of the arguments passed to the adapter, the first {@code N} arguments 5919 * are copied to the combiner, which is then called. 5920 * (Here, {@code N} is defined as the parameter count of the combiner.) 5921 * After this, control passes to the target, with any result 5922 * from the combiner inserted before the original {@code N} incoming 5923 * arguments. 5924 * <p> 5925 * If the combiner returns a value, the first parameter type of the target 5926 * must be identical with the return type of the combiner, and the next 5927 * {@code N} parameter types of the target must exactly match the parameters 5928 * of the combiner. 5929 * <p> 5930 * If the combiner has a void return, no result will be inserted, 5931 * and the first {@code N} parameter types of the target 5932 * must exactly match the parameters of the combiner. 5933 * <p> 5934 * The resulting adapter is the same type as the target, except that the 5935 * first parameter type is dropped, 5936 * if it corresponds to the result of the combiner. 5937 * <p> 5938 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5939 * that either the combiner or the target does not wish to receive. 5940 * If some of the incoming arguments are destined only for the combiner, 5941 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5942 * arguments will not need to be live on the stack on entry to the 5943 * target.) 5944 * <p><b>Example:</b> 5945 * {@snippet lang="java" : 5946 import static java.lang.invoke.MethodHandles.*; 5947 import static java.lang.invoke.MethodType.*; 5948 ... 5949 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5950 "println", methodType(void.class, String.class)) 5951 .bindTo(System.out); 5952 MethodHandle cat = lookup().findVirtual(String.class, 5953 "concat", methodType(String.class, String.class)); 5954 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5955 MethodHandle catTrace = foldArguments(cat, trace); 5956 // also prints "boo": 5957 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5958 * } 5959 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5960 * represents the result type of the {@code target} and resulting adapter. 5961 * {@code V}/{@code v} represent the type and value of the parameter and argument 5962 * of {@code target} that precedes the folding position; {@code V} also is 5963 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5964 * types and values of the {@code N} parameters and arguments at the folding 5965 * position. {@code B}/{@code b} represent the types and values of the 5966 * {@code target} parameters and arguments that follow the folded parameters 5967 * and arguments. 5968 * {@snippet lang="java" : 5969 * // there are N arguments in A... 5970 * T target(V, A[N]..., B...); 5971 * V combiner(A...); 5972 * T adapter(A... a, B... b) { 5973 * V v = combiner(a...); 5974 * return target(v, a..., b...); 5975 * } 5976 * // and if the combiner has a void return: 5977 * T target2(A[N]..., B...); 5978 * void combiner2(A...); 5979 * T adapter2(A... a, B... b) { 5980 * combiner2(a...); 5981 * return target2(a..., b...); 5982 * } 5983 * } 5984 * <p> 5985 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5986 * variable-arity method handle}, even if the original target method handle was. 5987 * @param target the method handle to invoke after arguments are combined 5988 * @param combiner method handle to call initially on the incoming arguments 5989 * @return method handle which incorporates the specified argument folding logic 5990 * @throws NullPointerException if either argument is null 5991 * @throws IllegalArgumentException if {@code combiner}'s return type 5992 * is non-void and not the same as the first argument type of 5993 * the target, or if the initial {@code N} argument types 5994 * of the target 5995 * (skipping one matching the {@code combiner}'s return type) 5996 * are not identical with the argument types of {@code combiner} 5997 */ 5998 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5999 return foldArguments(target, 0, combiner); 6000 } 6001 6002 /** 6003 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6004 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6005 * before the folded arguments. 6006 * <p> 6007 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6008 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6009 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6010 * 0. 6011 * 6012 * @apiNote Example: 6013 * {@snippet lang="java" : 6014 import static java.lang.invoke.MethodHandles.*; 6015 import static java.lang.invoke.MethodType.*; 6016 ... 6017 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6018 "println", methodType(void.class, String.class)) 6019 .bindTo(System.out); 6020 MethodHandle cat = lookup().findVirtual(String.class, 6021 "concat", methodType(String.class, String.class)); 6022 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6023 MethodHandle catTrace = foldArguments(cat, 1, trace); 6024 // also prints "jum": 6025 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6026 * } 6027 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6028 * represents the result type of the {@code target} and resulting adapter. 6029 * {@code V}/{@code v} represent the type and value of the parameter and argument 6030 * of {@code target} that precedes the folding position; {@code V} also is 6031 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6032 * types and values of the {@code N} parameters and arguments at the folding 6033 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6034 * and values of the {@code target} parameters and arguments that precede and 6035 * follow the folded parameters and arguments starting at {@code pos}, 6036 * respectively. 6037 * {@snippet lang="java" : 6038 * // there are N arguments in A... 6039 * T target(Z..., V, A[N]..., B...); 6040 * V combiner(A...); 6041 * T adapter(Z... z, A... a, B... b) { 6042 * V v = combiner(a...); 6043 * return target(z..., v, a..., b...); 6044 * } 6045 * // and if the combiner has a void return: 6046 * T target2(Z..., A[N]..., B...); 6047 * void combiner2(A...); 6048 * T adapter2(Z... z, A... a, B... b) { 6049 * combiner2(a...); 6050 * return target2(z..., a..., b...); 6051 * } 6052 * } 6053 * <p> 6054 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6055 * variable-arity method handle}, even if the original target method handle was. 6056 * 6057 * @param target the method handle to invoke after arguments are combined 6058 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6059 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6060 * @param combiner method handle to call initially on the incoming arguments 6061 * @return method handle which incorporates the specified argument folding logic 6062 * @throws NullPointerException if either argument is null 6063 * @throws IllegalArgumentException if either of the following two conditions holds: 6064 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6065 * {@code pos} of the target signature; 6066 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6067 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6068 * 6069 * @see #foldArguments(MethodHandle, MethodHandle) 6070 * @since 9 6071 */ 6072 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6073 MethodType targetType = target.type(); 6074 MethodType combinerType = combiner.type(); 6075 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6076 BoundMethodHandle result = target.rebind(); 6077 boolean dropResult = rtype == void.class; 6078 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6079 MethodType newType = targetType; 6080 if (!dropResult) { 6081 newType = newType.dropParameterTypes(pos, pos + 1); 6082 } 6083 result = result.copyWithExtendL(newType, lform, combiner); 6084 return result; 6085 } 6086 6087 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6088 int foldArgs = combinerType.parameterCount(); 6089 Class<?> rtype = combinerType.returnType(); 6090 int foldVals = rtype == void.class ? 0 : 1; 6091 int afterInsertPos = foldPos + foldVals; 6092 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6093 if (ok) { 6094 for (int i = 0; i < foldArgs; i++) { 6095 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6096 ok = false; 6097 break; 6098 } 6099 } 6100 } 6101 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6102 ok = false; 6103 if (!ok) 6104 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6105 return rtype; 6106 } 6107 6108 /** 6109 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6110 * of the pre-processing replacing the argument at the given position. 6111 * 6112 * @param target the method handle to invoke after arguments are combined 6113 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6114 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6115 * @param combiner method handle to call initially on the incoming arguments 6116 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6117 * @return method handle which incorporates the specified argument folding logic 6118 * @throws NullPointerException if either argument is null 6119 * @throws IllegalArgumentException if either of the following two conditions holds: 6120 * (1) {@code combiner}'s return type is not the same as the argument type at position 6121 * {@code pos} of the target signature; 6122 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6123 * not identical with the argument types of {@code combiner}. 6124 */ 6125 /*non-public*/ 6126 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6127 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6128 } 6129 6130 /** 6131 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6132 * the pre-processing inserted into the original sequence of arguments at the given position. 6133 * 6134 * @param target the method handle to invoke after arguments are combined 6135 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6136 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6137 * @param combiner method handle to call initially on the incoming arguments 6138 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6139 * @return method handle which incorporates the specified argument folding logic 6140 * @throws NullPointerException if either argument is null 6141 * @throws IllegalArgumentException if either of the following two conditions holds: 6142 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6143 * {@code pos} of the target signature; 6144 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6145 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6146 * with the argument types of {@code combiner}. 6147 */ 6148 /*non-public*/ 6149 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6150 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6151 } 6152 6153 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6154 MethodType targetType = target.type(); 6155 MethodType combinerType = combiner.type(); 6156 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6157 BoundMethodHandle result = target.rebind(); 6158 6159 MethodType newType = targetType; 6160 LambdaForm lform; 6161 if (filter) { 6162 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6163 } else { 6164 boolean dropResult = rtype == void.class; 6165 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6166 if (!dropResult) { 6167 newType = newType.dropParameterTypes(position, position + 1); 6168 } 6169 } 6170 result = result.copyWithExtendL(newType, lform, combiner); 6171 return result; 6172 } 6173 6174 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6175 int combinerArgs = combinerType.parameterCount(); 6176 if (argPos.length != combinerArgs) { 6177 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6178 } 6179 Class<?> rtype = combinerType.returnType(); 6180 6181 for (int i = 0; i < combinerArgs; i++) { 6182 int arg = argPos[i]; 6183 if (arg < 0 || arg > targetType.parameterCount()) { 6184 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6185 } 6186 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6187 throw newIllegalArgumentException("target argument type at position " + arg 6188 + " must match combiner argument type at index " + i + ": " + targetType 6189 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6190 } 6191 } 6192 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6193 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6194 } 6195 return rtype; 6196 } 6197 6198 /** 6199 * Makes a method handle which adapts a target method handle, 6200 * by guarding it with a test, a boolean-valued method handle. 6201 * If the guard fails, a fallback handle is called instead. 6202 * All three method handles must have the same corresponding 6203 * argument and return types, except that the return type 6204 * of the test must be boolean, and the test is allowed 6205 * to have fewer arguments than the other two method handles. 6206 * <p> 6207 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6208 * represents the uniform result type of the three involved handles; 6209 * {@code A}/{@code a}, the types and values of the {@code target} 6210 * parameters and arguments that are consumed by the {@code test}; and 6211 * {@code B}/{@code b}, those types and values of the {@code target} 6212 * parameters and arguments that are not consumed by the {@code test}. 6213 * {@snippet lang="java" : 6214 * boolean test(A...); 6215 * T target(A...,B...); 6216 * T fallback(A...,B...); 6217 * T adapter(A... a,B... b) { 6218 * if (test(a...)) 6219 * return target(a..., b...); 6220 * else 6221 * return fallback(a..., b...); 6222 * } 6223 * } 6224 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6225 * be modified by execution of the test, and so are passed unchanged 6226 * from the caller to the target or fallback as appropriate. 6227 * @param test method handle used for test, must return boolean 6228 * @param target method handle to call if test passes 6229 * @param fallback method handle to call if test fails 6230 * @return method handle which incorporates the specified if/then/else logic 6231 * @throws NullPointerException if any argument is null 6232 * @throws IllegalArgumentException if {@code test} does not return boolean, 6233 * or if all three method types do not match (with the return 6234 * type of {@code test} changed to match that of the target). 6235 */ 6236 public static MethodHandle guardWithTest(MethodHandle test, 6237 MethodHandle target, 6238 MethodHandle fallback) { 6239 MethodType gtype = test.type(); 6240 MethodType ttype = target.type(); 6241 MethodType ftype = fallback.type(); 6242 if (!ttype.equals(ftype)) 6243 throw misMatchedTypes("target and fallback types", ttype, ftype); 6244 if (gtype.returnType() != boolean.class) 6245 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6246 6247 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6248 if (test == null) { 6249 throw misMatchedTypes("target and test types", ttype, gtype); 6250 } 6251 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6252 } 6253 6254 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6255 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6256 } 6257 6258 /** 6259 * Makes a method handle which adapts a target method handle, 6260 * by running it inside an exception handler. 6261 * If the target returns normally, the adapter returns that value. 6262 * If an exception matching the specified type is thrown, the fallback 6263 * handle is called instead on the exception, plus the original arguments. 6264 * <p> 6265 * The target and handler must have the same corresponding 6266 * argument and return types, except that handler may omit trailing arguments 6267 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6268 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6269 * <p> 6270 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6271 * represents the return type of the {@code target} and {@code handler}, 6272 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6273 * the types and values of arguments to the resulting handle consumed by 6274 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6275 * resulting handle discarded by {@code handler}. 6276 * {@snippet lang="java" : 6277 * T target(A..., B...); 6278 * T handler(ExType, A...); 6279 * T adapter(A... a, B... b) { 6280 * try { 6281 * return target(a..., b...); 6282 * } catch (ExType ex) { 6283 * return handler(ex, a...); 6284 * } 6285 * } 6286 * } 6287 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6288 * be modified by execution of the target, and so are passed unchanged 6289 * from the caller to the handler, if the handler is invoked. 6290 * <p> 6291 * The target and handler must return the same type, even if the handler 6292 * always throws. (This might happen, for instance, because the handler 6293 * is simulating a {@code finally} clause). 6294 * To create such a throwing handler, compose the handler creation logic 6295 * with {@link #throwException throwException}, 6296 * in order to create a method handle of the correct return type. 6297 * @param target method handle to call 6298 * @param exType the type of exception which the handler will catch 6299 * @param handler method handle to call if a matching exception is thrown 6300 * @return method handle which incorporates the specified try/catch logic 6301 * @throws NullPointerException if any argument is null 6302 * @throws IllegalArgumentException if {@code handler} does not accept 6303 * the given exception type, or if the method handle types do 6304 * not match in their return types and their 6305 * corresponding parameters 6306 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6307 */ 6308 public static MethodHandle catchException(MethodHandle target, 6309 Class<? extends Throwable> exType, 6310 MethodHandle handler) { 6311 MethodType ttype = target.type(); 6312 MethodType htype = handler.type(); 6313 if (!Throwable.class.isAssignableFrom(exType)) 6314 throw new ClassCastException(exType.getName()); 6315 if (htype.parameterCount() < 1 || 6316 !htype.parameterType(0).isAssignableFrom(exType)) 6317 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6318 if (htype.returnType() != ttype.returnType()) 6319 throw misMatchedTypes("target and handler return types", ttype, htype); 6320 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6321 if (handler == null) { 6322 throw misMatchedTypes("target and handler types", ttype, htype); 6323 } 6324 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6325 } 6326 6327 /** 6328 * Produces a method handle which will throw exceptions of the given {@code exType}. 6329 * The method handle will accept a single argument of {@code exType}, 6330 * and immediately throw it as an exception. 6331 * The method type will nominally specify a return of {@code returnType}. 6332 * The return type may be anything convenient: It doesn't matter to the 6333 * method handle's behavior, since it will never return normally. 6334 * @param returnType the return type of the desired method handle 6335 * @param exType the parameter type of the desired method handle 6336 * @return method handle which can throw the given exceptions 6337 * @throws NullPointerException if either argument is null 6338 */ 6339 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6340 if (!Throwable.class.isAssignableFrom(exType)) 6341 throw new ClassCastException(exType.getName()); 6342 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6343 } 6344 6345 /** 6346 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6347 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6348 * delivers the loop's result, which is the return value of the resulting handle. 6349 * <p> 6350 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6351 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6352 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6353 * terms of method handles, each clause will specify up to four independent actions:<ul> 6354 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6355 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6356 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6357 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6358 * </ul> 6359 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6360 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6361 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6362 * <p> 6363 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6364 * this case. See below for a detailed description. 6365 * <p> 6366 * <em>Parameters optional everywhere:</em> 6367 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6368 * As an exception, the init functions cannot take any {@code v} parameters, 6369 * because those values are not yet computed when the init functions are executed. 6370 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6371 * In fact, any clause function may take no arguments at all. 6372 * <p> 6373 * <em>Loop parameters:</em> 6374 * A clause function may take all the iteration variable values it is entitled to, in which case 6375 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6376 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6377 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6378 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6379 * init function is automatically a loop parameter {@code a}.) 6380 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6381 * These loop parameters act as loop-invariant values visible across the whole loop. 6382 * <p> 6383 * <em>Parameters visible everywhere:</em> 6384 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6385 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6386 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6387 * Most clause functions will not need all of this information, but they will be formally connected to it 6388 * as if by {@link #dropArguments}. 6389 * <a id="astar"></a> 6390 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6391 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6392 * In that notation, the general form of an init function parameter list 6393 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6394 * <p> 6395 * <em>Checking clause structure:</em> 6396 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6397 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6398 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6399 * met by the inputs to the loop combinator. 6400 * <p> 6401 * <em>Effectively identical sequences:</em> 6402 * <a id="effid"></a> 6403 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6404 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6405 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6406 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6407 * that longest list. 6408 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6409 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6410 * <p> 6411 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6412 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6413 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6414 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6415 * four. Padding takes place by appending elements to the array. 6416 * <li>Clauses with all {@code null}s are disregarded. 6417 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6418 * </ol> 6419 * <p> 6420 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6421 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6422 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6423 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6424 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6425 * iteration variable type. 6426 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6427 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6428 * </ol> 6429 * <p> 6430 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6431 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6432 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6433 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6434 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6435 * (These types will be checked in step 2, along with all the clause function types.) 6436 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6437 * <li>All of the collected parameter lists must be effectively identical. 6438 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6439 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6440 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6441 * the "internal parameter list". 6442 * </ul> 6443 * <p> 6444 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6445 * <li>Examine fini function return types, disregarding omitted fini functions. 6446 * <li>If there are no fini functions, the loop return type is {@code void}. 6447 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6448 * type. 6449 * </ol> 6450 * <p> 6451 * <em>Step 1D: Check other types.</em><ol type="a"> 6452 * <li>There must be at least one non-omitted pred function. 6453 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6454 * </ol> 6455 * <p> 6456 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6457 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6458 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6459 * (Note that their parameter lists are already effectively identical to this list.) 6460 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6461 * effectively identical to the internal parameter list {@code (V... A...)}. 6462 * </ol> 6463 * <p> 6464 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6465 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6466 * type. 6467 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6468 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6469 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6470 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6471 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6472 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6473 * loop return type. 6474 * </ol> 6475 * <p> 6476 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6477 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6478 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6479 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6480 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6481 * pad out the end of the list. 6482 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6483 * </ol> 6484 * <p> 6485 * <em>Final observations.</em><ol type="a"> 6486 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6487 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6488 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6489 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6490 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6491 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6492 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6493 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6494 * </ol> 6495 * <p> 6496 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6497 * <ul> 6498 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6499 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6500 * (Only one {@code Pn} has to be non-{@code null}.) 6501 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6502 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6503 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6504 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6505 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6506 * the resulting loop handle's parameter types {@code (A...)}. 6507 * </ul> 6508 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6509 * which is natural if most of the loop computation happens in the steps. For some loops, 6510 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6511 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6512 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6513 * where the init functions will need the extra parameters. For such reasons, the rules for 6514 * determining these parameters are as symmetric as possible, across all clause parts. 6515 * In general, the loop parameters function as common invariant values across the whole 6516 * loop, while the iteration variables function as common variant values, or (if there is 6517 * no step function) as internal loop invariant temporaries. 6518 * <p> 6519 * <em>Loop execution.</em><ol type="a"> 6520 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6521 * every clause function. These locals are loop invariant. 6522 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6523 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6524 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6525 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6526 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6527 * (in argument order). 6528 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6529 * returns {@code false}. 6530 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6531 * sequence {@code (v...)} of loop variables. 6532 * The updated value is immediately visible to all subsequent function calls. 6533 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6534 * (of type {@code R}) is returned from the loop as a whole. 6535 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6536 * except by throwing an exception. 6537 * </ol> 6538 * <p> 6539 * <em>Usage tips.</em> 6540 * <ul> 6541 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6542 * sometimes a step function only needs to observe the current value of its own variable. 6543 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6544 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6545 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6546 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6547 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6548 * <li>If some of the clause functions are virtual methods on an instance, the instance 6549 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6550 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6551 * will be the first iteration variable value, and it will be easy to use virtual 6552 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6553 * </ul> 6554 * <p> 6555 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6556 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6557 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6558 * {@snippet lang="java" : 6559 * V... init...(A...); 6560 * boolean pred...(V..., A...); 6561 * V... step...(V..., A...); 6562 * R fini...(V..., A...); 6563 * R loop(A... a) { 6564 * V... v... = init...(a...); 6565 * for (;;) { 6566 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6567 * v = s(v..., a...); 6568 * if (!p(v..., a...)) { 6569 * return f(v..., a...); 6570 * } 6571 * } 6572 * } 6573 * } 6574 * } 6575 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6576 * to their full length, even though individual clause functions may neglect to take them all. 6577 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6578 * 6579 * @apiNote Example: 6580 * {@snippet lang="java" : 6581 * // iterative implementation of the factorial function as a loop handle 6582 * static int one(int k) { return 1; } 6583 * static int inc(int i, int acc, int k) { return i + 1; } 6584 * static int mult(int i, int acc, int k) { return i * acc; } 6585 * static boolean pred(int i, int acc, int k) { return i < k; } 6586 * static int fin(int i, int acc, int k) { return acc; } 6587 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6588 * // null initializer for counter, should initialize to 0 6589 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6590 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6591 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6592 * assertEquals(120, loop.invoke(5)); 6593 * } 6594 * The same example, dropping arguments and using combinators: 6595 * {@snippet lang="java" : 6596 * // simplified implementation of the factorial function as a loop handle 6597 * static int inc(int i) { return i + 1; } // drop acc, k 6598 * static int mult(int i, int acc) { return i * acc; } //drop k 6599 * static boolean cmp(int i, int k) { return i < k; } 6600 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6601 * // null initializer for counter, should initialize to 0 6602 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6603 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6604 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6605 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6606 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6607 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6608 * assertEquals(720, loop.invoke(6)); 6609 * } 6610 * A similar example, using a helper object to hold a loop parameter: 6611 * {@snippet lang="java" : 6612 * // instance-based implementation of the factorial function as a loop handle 6613 * static class FacLoop { 6614 * final int k; 6615 * FacLoop(int k) { this.k = k; } 6616 * int inc(int i) { return i + 1; } 6617 * int mult(int i, int acc) { return i * acc; } 6618 * boolean pred(int i) { return i < k; } 6619 * int fin(int i, int acc) { return acc; } 6620 * } 6621 * // assume MH_FacLoop is a handle to the constructor 6622 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6623 * // null initializer for counter, should initialize to 0 6624 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6625 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6626 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6627 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6628 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6629 * assertEquals(5040, loop.invoke(7)); 6630 * } 6631 * 6632 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6633 * 6634 * @return a method handle embodying the looping behavior as defined by the arguments. 6635 * 6636 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6637 * 6638 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6639 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6640 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6641 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6642 * @since 9 6643 */ 6644 public static MethodHandle loop(MethodHandle[]... clauses) { 6645 // Step 0: determine clause structure. 6646 loopChecks0(clauses); 6647 6648 List<MethodHandle> init = new ArrayList<>(); 6649 List<MethodHandle> step = new ArrayList<>(); 6650 List<MethodHandle> pred = new ArrayList<>(); 6651 List<MethodHandle> fini = new ArrayList<>(); 6652 6653 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6654 init.add(clause[0]); // all clauses have at least length 1 6655 step.add(clause.length <= 1 ? null : clause[1]); 6656 pred.add(clause.length <= 2 ? null : clause[2]); 6657 fini.add(clause.length <= 3 ? null : clause[3]); 6658 }); 6659 6660 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6661 final int nclauses = init.size(); 6662 6663 // Step 1A: determine iteration variables (V...). 6664 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6665 for (int i = 0; i < nclauses; ++i) { 6666 MethodHandle in = init.get(i); 6667 MethodHandle st = step.get(i); 6668 if (in == null && st == null) { 6669 iterationVariableTypes.add(void.class); 6670 } else if (in != null && st != null) { 6671 loopChecks1a(i, in, st); 6672 iterationVariableTypes.add(in.type().returnType()); 6673 } else { 6674 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6675 } 6676 } 6677 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6678 6679 // Step 1B: determine loop parameters (A...). 6680 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6681 loopChecks1b(init, commonSuffix); 6682 6683 // Step 1C: determine loop return type. 6684 // Step 1D: check other types. 6685 // local variable required here; see JDK-8223553 6686 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6687 .map(MethodType::returnType); 6688 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6689 loopChecks1cd(pred, fini, loopReturnType); 6690 6691 // Step 2: determine parameter lists. 6692 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6693 commonParameterSequence.addAll(commonSuffix); 6694 loopChecks2(step, pred, fini, commonParameterSequence); 6695 // Step 3: fill in omitted functions. 6696 for (int i = 0; i < nclauses; ++i) { 6697 Class<?> t = iterationVariableTypes.get(i); 6698 if (init.get(i) == null) { 6699 init.set(i, empty(methodType(t, commonSuffix))); 6700 } 6701 if (step.get(i) == null) { 6702 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6703 } 6704 if (pred.get(i) == null) { 6705 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6706 } 6707 if (fini.get(i) == null) { 6708 fini.set(i, empty(methodType(t, commonParameterSequence))); 6709 } 6710 } 6711 6712 // Step 4: fill in missing parameter types. 6713 // Also convert all handles to fixed-arity handles. 6714 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6715 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6716 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6717 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6718 6719 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6720 allMatch(pl -> pl.equals(commonSuffix)); 6721 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6722 allMatch(pl -> pl.equals(commonParameterSequence)); 6723 6724 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6725 } 6726 6727 private static void loopChecks0(MethodHandle[][] clauses) { 6728 if (clauses == null || clauses.length == 0) { 6729 throw newIllegalArgumentException("null or no clauses passed"); 6730 } 6731 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6732 throw newIllegalArgumentException("null clauses are not allowed"); 6733 } 6734 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6735 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6736 } 6737 } 6738 6739 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6740 if (in.type().returnType() != st.type().returnType()) { 6741 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6742 st.type().returnType()); 6743 } 6744 } 6745 6746 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6747 final List<Class<?>> empty = List.of(); 6748 final List<Class<?>> longest = mhs.filter(Objects::nonNull). 6749 // take only those that can contribute to a common suffix because they are longer than the prefix 6750 map(MethodHandle::type). 6751 filter(t -> t.parameterCount() > skipSize). 6752 map(MethodType::parameterList). 6753 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 6754 return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size()); 6755 } 6756 6757 private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) { 6758 final List<Class<?>> empty = List.of(); 6759 return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 6760 } 6761 6762 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6763 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6764 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6765 return longestParameterList(List.of(longest1, longest2)); 6766 } 6767 6768 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6769 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6770 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6771 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6772 " (common suffix: " + commonSuffix + ")"); 6773 } 6774 } 6775 6776 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6777 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6778 anyMatch(t -> t != loopReturnType)) { 6779 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6780 loopReturnType + ")"); 6781 } 6782 6783 if (pred.stream().noneMatch(Objects::nonNull)) { 6784 throw newIllegalArgumentException("no predicate found", pred); 6785 } 6786 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6787 anyMatch(t -> t != boolean.class)) { 6788 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6789 } 6790 } 6791 6792 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6793 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6794 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6795 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6796 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6797 } 6798 } 6799 6800 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6801 return hs.stream().map(h -> { 6802 int pc = h.type().parameterCount(); 6803 int tpsize = targetParams.size(); 6804 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6805 }).toList(); 6806 } 6807 6808 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6809 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6810 } 6811 6812 /** 6813 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6814 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6815 * <p> 6816 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6817 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6818 * evaluates to {@code true}). 6819 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6820 * <p> 6821 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6822 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6823 * and updated with the value returned from its invocation. The result of loop execution will be 6824 * the final value of the additional loop-local variable (if present). 6825 * <p> 6826 * The following rules hold for these argument handles:<ul> 6827 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6828 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6829 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6830 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6831 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6832 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6833 * It will constrain the parameter lists of the other loop parts. 6834 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6835 * list {@code (A...)} is called the <em>external parameter list</em>. 6836 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6837 * additional state variable of the loop. 6838 * The body must both accept and return a value of this type {@code V}. 6839 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6840 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6841 * <a href="MethodHandles.html#effid">effectively identical</a> 6842 * to the external parameter list {@code (A...)}. 6843 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6844 * {@linkplain #empty default value}. 6845 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6846 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6847 * effectively identical to the internal parameter list. 6848 * </ul> 6849 * <p> 6850 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6851 * <li>The loop handle's result type is the result type {@code V} of the body. 6852 * <li>The loop handle's parameter types are the types {@code (A...)}, 6853 * from the external parameter list. 6854 * </ul> 6855 * <p> 6856 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6857 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6858 * passed to the loop. 6859 * {@snippet lang="java" : 6860 * V init(A...); 6861 * boolean pred(V, A...); 6862 * V body(V, A...); 6863 * V whileLoop(A... a...) { 6864 * V v = init(a...); 6865 * while (pred(v, a...)) { 6866 * v = body(v, a...); 6867 * } 6868 * return v; 6869 * } 6870 * } 6871 * 6872 * @apiNote Example: 6873 * {@snippet lang="java" : 6874 * // implement the zip function for lists as a loop handle 6875 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6876 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6877 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6878 * zip.add(a.next()); 6879 * zip.add(b.next()); 6880 * return zip; 6881 * } 6882 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6883 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6884 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6885 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6886 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6887 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6888 * } 6889 * 6890 * 6891 * @apiNote The implementation of this method can be expressed as follows: 6892 * {@snippet lang="java" : 6893 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6894 * MethodHandle fini = (body.type().returnType() == void.class 6895 * ? null : identity(body.type().returnType())); 6896 * MethodHandle[] 6897 * checkExit = { null, null, pred, fini }, 6898 * varBody = { init, body }; 6899 * return loop(checkExit, varBody); 6900 * } 6901 * } 6902 * 6903 * @param init optional initializer, providing the initial value of the loop variable. 6904 * May be {@code null}, implying a default initial value. See above for other constraints. 6905 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6906 * above for other constraints. 6907 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6908 * See above for other constraints. 6909 * 6910 * @return a method handle implementing the {@code while} loop as described by the arguments. 6911 * @throws IllegalArgumentException if the rules for the arguments are violated. 6912 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6913 * 6914 * @see #loop(MethodHandle[][]) 6915 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6916 * @since 9 6917 */ 6918 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6919 whileLoopChecks(init, pred, body); 6920 MethodHandle fini = identityOrVoid(body.type().returnType()); 6921 MethodHandle[] checkExit = { null, null, pred, fini }; 6922 MethodHandle[] varBody = { init, body }; 6923 return loop(checkExit, varBody); 6924 } 6925 6926 /** 6927 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6928 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6929 * <p> 6930 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6931 * method will, in each iteration, first execute its body and then evaluate the predicate. 6932 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6933 * <p> 6934 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6935 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6936 * and updated with the value returned from its invocation. The result of loop execution will be 6937 * the final value of the additional loop-local variable (if present). 6938 * <p> 6939 * The following rules hold for these argument handles:<ul> 6940 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6941 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6942 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6943 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6944 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6945 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6946 * It will constrain the parameter lists of the other loop parts. 6947 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6948 * list {@code (A...)} is called the <em>external parameter list</em>. 6949 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6950 * additional state variable of the loop. 6951 * The body must both accept and return a value of this type {@code V}. 6952 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6953 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6954 * <a href="MethodHandles.html#effid">effectively identical</a> 6955 * to the external parameter list {@code (A...)}. 6956 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6957 * {@linkplain #empty default value}. 6958 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6959 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6960 * effectively identical to the internal parameter list. 6961 * </ul> 6962 * <p> 6963 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6964 * <li>The loop handle's result type is the result type {@code V} of the body. 6965 * <li>The loop handle's parameter types are the types {@code (A...)}, 6966 * from the external parameter list. 6967 * </ul> 6968 * <p> 6969 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6970 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6971 * passed to the loop. 6972 * {@snippet lang="java" : 6973 * V init(A...); 6974 * boolean pred(V, A...); 6975 * V body(V, A...); 6976 * V doWhileLoop(A... a...) { 6977 * V v = init(a...); 6978 * do { 6979 * v = body(v, a...); 6980 * } while (pred(v, a...)); 6981 * return v; 6982 * } 6983 * } 6984 * 6985 * @apiNote Example: 6986 * {@snippet lang="java" : 6987 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6988 * static int zero(int limit) { return 0; } 6989 * static int step(int i, int limit) { return i + 1; } 6990 * static boolean pred(int i, int limit) { return i < limit; } 6991 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6992 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6993 * assertEquals(23, loop.invoke(23)); 6994 * } 6995 * 6996 * 6997 * @apiNote The implementation of this method can be expressed as follows: 6998 * {@snippet lang="java" : 6999 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7000 * MethodHandle fini = (body.type().returnType() == void.class 7001 * ? null : identity(body.type().returnType())); 7002 * MethodHandle[] clause = { init, body, pred, fini }; 7003 * return loop(clause); 7004 * } 7005 * } 7006 * 7007 * @param init optional initializer, providing the initial value of the loop variable. 7008 * May be {@code null}, implying a default initial value. See above for other constraints. 7009 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7010 * See above for other constraints. 7011 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7012 * above for other constraints. 7013 * 7014 * @return a method handle implementing the {@code while} loop as described by the arguments. 7015 * @throws IllegalArgumentException if the rules for the arguments are violated. 7016 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7017 * 7018 * @see #loop(MethodHandle[][]) 7019 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7020 * @since 9 7021 */ 7022 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7023 whileLoopChecks(init, pred, body); 7024 MethodHandle fini = identityOrVoid(body.type().returnType()); 7025 MethodHandle[] clause = {init, body, pred, fini }; 7026 return loop(clause); 7027 } 7028 7029 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7030 Objects.requireNonNull(pred); 7031 Objects.requireNonNull(body); 7032 MethodType bodyType = body.type(); 7033 Class<?> returnType = bodyType.returnType(); 7034 List<Class<?>> innerList = bodyType.parameterList(); 7035 List<Class<?>> outerList = innerList; 7036 if (returnType == void.class) { 7037 // OK 7038 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7039 // leading V argument missing => error 7040 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7041 throw misMatchedTypes("body function", bodyType, expected); 7042 } else { 7043 outerList = innerList.subList(1, innerList.size()); 7044 } 7045 MethodType predType = pred.type(); 7046 if (predType.returnType() != boolean.class || 7047 !predType.effectivelyIdenticalParameters(0, innerList)) { 7048 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7049 } 7050 if (init != null) { 7051 MethodType initType = init.type(); 7052 if (initType.returnType() != returnType || 7053 !initType.effectivelyIdenticalParameters(0, outerList)) { 7054 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7055 } 7056 } 7057 } 7058 7059 /** 7060 * Constructs a loop that runs a given number of iterations. 7061 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7062 * <p> 7063 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7064 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7065 * It will be initialized to 0 and incremented by 1 in each iteration. 7066 * <p> 7067 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7068 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7069 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7070 * <p> 7071 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7072 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7073 * iteration variable. 7074 * The result of the loop handle execution will be the final {@code V} value of that variable 7075 * (or {@code void} if there is no {@code V} variable). 7076 * <p> 7077 * The following rules hold for the argument handles:<ul> 7078 * <li>The {@code iterations} handle must not be {@code null}, and must return 7079 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7080 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7081 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7082 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7083 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7084 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7085 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7086 * of types called the <em>internal parameter list</em>. 7087 * It will constrain the parameter lists of the other loop parts. 7088 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7089 * with no additional {@code A} types, then the internal parameter list is extended by 7090 * the argument types {@code A...} of the {@code iterations} handle. 7091 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7092 * list {@code (A...)} is called the <em>external parameter list</em>. 7093 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7094 * additional state variable of the loop. 7095 * The body must both accept a leading parameter and return a value of this type {@code V}. 7096 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7097 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7098 * <a href="MethodHandles.html#effid">effectively identical</a> 7099 * to the external parameter list {@code (A...)}. 7100 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7101 * {@linkplain #empty default value}. 7102 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7103 * effectively identical to the external parameter list {@code (A...)}. 7104 * </ul> 7105 * <p> 7106 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7107 * <li>The loop handle's result type is the result type {@code V} of the body. 7108 * <li>The loop handle's parameter types are the types {@code (A...)}, 7109 * from the external parameter list. 7110 * </ul> 7111 * <p> 7112 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7113 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7114 * arguments passed to the loop. 7115 * {@snippet lang="java" : 7116 * int iterations(A...); 7117 * V init(A...); 7118 * V body(V, int, A...); 7119 * V countedLoop(A... a...) { 7120 * int end = iterations(a...); 7121 * V v = init(a...); 7122 * for (int i = 0; i < end; ++i) { 7123 * v = body(v, i, a...); 7124 * } 7125 * return v; 7126 * } 7127 * } 7128 * 7129 * @apiNote Example with a fully conformant body method: 7130 * {@snippet lang="java" : 7131 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7132 * // => a variation on a well known theme 7133 * static String step(String v, int counter, String init) { return "na " + v; } 7134 * // assume MH_step is a handle to the method above 7135 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7136 * MethodHandle start = MethodHandles.identity(String.class); 7137 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7138 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7139 * } 7140 * 7141 * @apiNote Example with the simplest possible body method type, 7142 * and passing the number of iterations to the loop invocation: 7143 * {@snippet lang="java" : 7144 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7145 * // => a variation on a well known theme 7146 * static String step(String v, int counter ) { return "na " + v; } 7147 * // assume MH_step is a handle to the method above 7148 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7149 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7150 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7151 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7152 * } 7153 * 7154 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7155 * as loop parameters: 7156 * {@snippet lang="java" : 7157 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7158 * // => a variation on a well known theme 7159 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 7160 * // assume MH_step is a handle to the method above 7161 * MethodHandle count = MethodHandles.identity(int.class); 7162 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7163 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7164 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7165 * } 7166 * 7167 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7168 * to enforce a loop type: 7169 * {@snippet lang="java" : 7170 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7171 * // => a variation on a well known theme 7172 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7173 * // assume MH_step is a handle to the method above 7174 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7175 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7176 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7177 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7178 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7179 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7180 * } 7181 * 7182 * @apiNote The implementation of this method can be expressed as follows: 7183 * {@snippet lang="java" : 7184 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7185 * return countedLoop(empty(iterations.type()), iterations, init, body); 7186 * } 7187 * } 7188 * 7189 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7190 * result type must be {@code int}. See above for other constraints. 7191 * @param init optional initializer, providing the initial value of the loop variable. 7192 * May be {@code null}, implying a default initial value. See above for other constraints. 7193 * @param body body of the loop, which may not be {@code null}. 7194 * It controls the loop parameters and result type in the standard case (see above for details). 7195 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7196 * and may accept any number of additional types. 7197 * See above for other constraints. 7198 * 7199 * @return a method handle representing the loop. 7200 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7201 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7202 * 7203 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7204 * @since 9 7205 */ 7206 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7207 return countedLoop(empty(iterations.type()), iterations, init, body); 7208 } 7209 7210 /** 7211 * Constructs a loop that counts over a range of numbers. 7212 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7213 * <p> 7214 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7215 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7216 * values of the loop counter. 7217 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7218 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7219 * <p> 7220 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7221 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7222 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7223 * <p> 7224 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7225 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7226 * iteration variable. 7227 * The result of the loop handle execution will be the final {@code V} value of that variable 7228 * (or {@code void} if there is no {@code V} variable). 7229 * <p> 7230 * The following rules hold for the argument handles:<ul> 7231 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7232 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7233 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7234 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7235 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7236 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7237 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7238 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7239 * of types called the <em>internal parameter list</em>. 7240 * It will constrain the parameter lists of the other loop parts. 7241 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7242 * with no additional {@code A} types, then the internal parameter list is extended by 7243 * the argument types {@code A...} of the {@code end} handle. 7244 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7245 * list {@code (A...)} is called the <em>external parameter list</em>. 7246 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7247 * additional state variable of the loop. 7248 * The body must both accept a leading parameter and return a value of this type {@code V}. 7249 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7250 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7251 * <a href="MethodHandles.html#effid">effectively identical</a> 7252 * to the external parameter list {@code (A...)}. 7253 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7254 * {@linkplain #empty default value}. 7255 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7256 * effectively identical to the external parameter list {@code (A...)}. 7257 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7258 * to the external parameter list. 7259 * </ul> 7260 * <p> 7261 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7262 * <li>The loop handle's result type is the result type {@code V} of the body. 7263 * <li>The loop handle's parameter types are the types {@code (A...)}, 7264 * from the external parameter list. 7265 * </ul> 7266 * <p> 7267 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7268 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7269 * arguments passed to the loop. 7270 * {@snippet lang="java" : 7271 * int start(A...); 7272 * int end(A...); 7273 * V init(A...); 7274 * V body(V, int, A...); 7275 * V countedLoop(A... a...) { 7276 * int e = end(a...); 7277 * int s = start(a...); 7278 * V v = init(a...); 7279 * for (int i = s; i < e; ++i) { 7280 * v = body(v, i, a...); 7281 * } 7282 * return v; 7283 * } 7284 * } 7285 * 7286 * @apiNote The implementation of this method can be expressed as follows: 7287 * {@snippet lang="java" : 7288 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7289 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7290 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7291 * // the following semantics: 7292 * // MH_increment: (int limit, int counter) -> counter + 1 7293 * // MH_predicate: (int limit, int counter) -> counter < limit 7294 * Class<?> counterType = start.type().returnType(); // int 7295 * Class<?> returnType = body.type().returnType(); 7296 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7297 * if (returnType != void.class) { // ignore the V variable 7298 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7299 * pred = dropArguments(pred, 1, returnType); // ditto 7300 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7301 * } 7302 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7303 * MethodHandle[] 7304 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7305 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7306 * indexVar = { start, incr }; // i = start(); i = i + 1 7307 * return loop(loopLimit, bodyClause, indexVar); 7308 * } 7309 * } 7310 * 7311 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7312 * See above for other constraints. 7313 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7314 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7315 * @param init optional initializer, providing the initial value of the loop variable. 7316 * May be {@code null}, implying a default initial value. See above for other constraints. 7317 * @param body body of the loop, which may not be {@code null}. 7318 * It controls the loop parameters and result type in the standard case (see above for details). 7319 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7320 * and may accept any number of additional types. 7321 * See above for other constraints. 7322 * 7323 * @return a method handle representing the loop. 7324 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7325 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7326 * 7327 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7328 * @since 9 7329 */ 7330 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7331 countedLoopChecks(start, end, init, body); 7332 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7333 Class<?> limitType = end.type().returnType(); // yes, int again 7334 Class<?> returnType = body.type().returnType(); 7335 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7336 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7337 MethodHandle retv = null; 7338 if (returnType != void.class) { 7339 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7340 pred = dropArguments(pred, 1, returnType); // ditto 7341 retv = dropArguments(identity(returnType), 0, counterType); 7342 } 7343 body = dropArguments(body, 0, counterType); // ignore the limit variable 7344 MethodHandle[] 7345 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7346 bodyClause = { init, body }, // v = init(); v = body(v, i) 7347 indexVar = { start, incr }; // i = start(); i = i + 1 7348 return loop(loopLimit, bodyClause, indexVar); 7349 } 7350 7351 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7352 Objects.requireNonNull(start); 7353 Objects.requireNonNull(end); 7354 Objects.requireNonNull(body); 7355 Class<?> counterType = start.type().returnType(); 7356 if (counterType != int.class) { 7357 MethodType expected = start.type().changeReturnType(int.class); 7358 throw misMatchedTypes("start function", start.type(), expected); 7359 } else if (end.type().returnType() != counterType) { 7360 MethodType expected = end.type().changeReturnType(counterType); 7361 throw misMatchedTypes("end function", end.type(), expected); 7362 } 7363 MethodType bodyType = body.type(); 7364 Class<?> returnType = bodyType.returnType(); 7365 List<Class<?>> innerList = bodyType.parameterList(); 7366 // strip leading V value if present 7367 int vsize = (returnType == void.class ? 0 : 1); 7368 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7369 // argument list has no "V" => error 7370 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7371 throw misMatchedTypes("body function", bodyType, expected); 7372 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7373 // missing I type => error 7374 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7375 throw misMatchedTypes("body function", bodyType, expected); 7376 } 7377 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7378 if (outerList.isEmpty()) { 7379 // special case; take lists from end handle 7380 outerList = end.type().parameterList(); 7381 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7382 } 7383 MethodType expected = methodType(counterType, outerList); 7384 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7385 throw misMatchedTypes("start parameter types", start.type(), expected); 7386 } 7387 if (end.type() != start.type() && 7388 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7389 throw misMatchedTypes("end parameter types", end.type(), expected); 7390 } 7391 if (init != null) { 7392 MethodType initType = init.type(); 7393 if (initType.returnType() != returnType || 7394 !initType.effectivelyIdenticalParameters(0, outerList)) { 7395 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7396 } 7397 } 7398 } 7399 7400 /** 7401 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7402 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7403 * <p> 7404 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7405 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7406 * <p> 7407 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7408 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7409 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7410 * <p> 7411 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7412 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7413 * iteration variable. 7414 * The result of the loop handle execution will be the final {@code V} value of that variable 7415 * (or {@code void} if there is no {@code V} variable). 7416 * <p> 7417 * The following rules hold for the argument handles:<ul> 7418 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7419 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7420 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7421 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7422 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7423 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7424 * of types called the <em>internal parameter list</em>. 7425 * It will constrain the parameter lists of the other loop parts. 7426 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7427 * with no additional {@code A} types, then the internal parameter list is extended by 7428 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7429 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7430 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7431 * list {@code (A...)} is called the <em>external parameter list</em>. 7432 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7433 * additional state variable of the loop. 7434 * The body must both accept a leading parameter and return a value of this type {@code V}. 7435 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7436 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7437 * <a href="MethodHandles.html#effid">effectively identical</a> 7438 * to the external parameter list {@code (A...)}. 7439 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7440 * {@linkplain #empty default value}. 7441 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7442 * type {@code java.util.Iterator} or a subtype thereof. 7443 * The iterator it produces when the loop is executed will be assumed 7444 * to yield values which can be converted to type {@code T}. 7445 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7446 * effectively identical to the external parameter list {@code (A...)}. 7447 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7448 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7449 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7450 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7451 * the {@link MethodHandle#asType asType} conversion method. 7452 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7453 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7454 * </ul> 7455 * <p> 7456 * The type {@code T} may be either a primitive or reference. 7457 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7458 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7459 * as if by the {@link MethodHandle#asType asType} conversion method. 7460 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7461 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7462 * <p> 7463 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7464 * <li>The loop handle's result type is the result type {@code V} of the body. 7465 * <li>The loop handle's parameter types are the types {@code (A...)}, 7466 * from the external parameter list. 7467 * </ul> 7468 * <p> 7469 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7470 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7471 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7472 * {@snippet lang="java" : 7473 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7474 * V init(A...); 7475 * V body(V,T,A...); 7476 * V iteratedLoop(A... a...) { 7477 * Iterator<T> it = iterator(a...); 7478 * V v = init(a...); 7479 * while (it.hasNext()) { 7480 * T t = it.next(); 7481 * v = body(v, t, a...); 7482 * } 7483 * return v; 7484 * } 7485 * } 7486 * 7487 * @apiNote Example: 7488 * {@snippet lang="java" : 7489 * // get an iterator from a list 7490 * static List<String> reverseStep(List<String> r, String e) { 7491 * r.add(0, e); 7492 * return r; 7493 * } 7494 * static List<String> newArrayList() { return new ArrayList<>(); } 7495 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7496 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7497 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7498 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7499 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7500 * } 7501 * 7502 * @apiNote The implementation of this method can be expressed approximately as follows: 7503 * {@snippet lang="java" : 7504 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7505 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7506 * Class<?> returnType = body.type().returnType(); 7507 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7508 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7509 * MethodHandle retv = null, step = body, startIter = iterator; 7510 * if (returnType != void.class) { 7511 * // the simple thing first: in (I V A...), drop the I to get V 7512 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7513 * // body type signature (V T A...), internal loop types (I V A...) 7514 * step = swapArguments(body, 0, 1); // swap V <-> T 7515 * } 7516 * if (startIter == null) startIter = MH_getIter; 7517 * MethodHandle[] 7518 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7519 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7520 * return loop(iterVar, bodyClause); 7521 * } 7522 * } 7523 * 7524 * @param iterator an optional handle to return the iterator to start the loop. 7525 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7526 * See above for other constraints. 7527 * @param init optional initializer, providing the initial value of the loop variable. 7528 * May be {@code null}, implying a default initial value. See above for other constraints. 7529 * @param body body of the loop, which may not be {@code null}. 7530 * It controls the loop parameters and result type in the standard case (see above for details). 7531 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7532 * and may accept any number of additional types. 7533 * See above for other constraints. 7534 * 7535 * @return a method handle embodying the iteration loop functionality. 7536 * @throws NullPointerException if the {@code body} handle is {@code null}. 7537 * @throws IllegalArgumentException if any argument violates the above requirements. 7538 * 7539 * @since 9 7540 */ 7541 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7542 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7543 Class<?> returnType = body.type().returnType(); 7544 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7545 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7546 MethodHandle startIter; 7547 MethodHandle nextVal; 7548 { 7549 MethodType iteratorType; 7550 if (iterator == null) { 7551 // derive argument type from body, if available, else use Iterable 7552 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7553 iteratorType = startIter.type().changeParameterType(0, iterableType); 7554 } else { 7555 // force return type to the internal iterator class 7556 iteratorType = iterator.type().changeReturnType(Iterator.class); 7557 startIter = iterator; 7558 } 7559 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7560 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7561 7562 // perform the asType transforms under an exception transformer, as per spec.: 7563 try { 7564 startIter = startIter.asType(iteratorType); 7565 nextVal = nextRaw.asType(nextValType); 7566 } catch (WrongMethodTypeException ex) { 7567 throw new IllegalArgumentException(ex); 7568 } 7569 } 7570 7571 MethodHandle retv = null, step = body; 7572 if (returnType != void.class) { 7573 // the simple thing first: in (I V A...), drop the I to get V 7574 retv = dropArguments(identity(returnType), 0, Iterator.class); 7575 // body type signature (V T A...), internal loop types (I V A...) 7576 step = swapArguments(body, 0, 1); // swap V <-> T 7577 } 7578 7579 MethodHandle[] 7580 iterVar = { startIter, null, hasNext, retv }, 7581 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7582 return loop(iterVar, bodyClause); 7583 } 7584 7585 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7586 Objects.requireNonNull(body); 7587 MethodType bodyType = body.type(); 7588 Class<?> returnType = bodyType.returnType(); 7589 List<Class<?>> internalParamList = bodyType.parameterList(); 7590 // strip leading V value if present 7591 int vsize = (returnType == void.class ? 0 : 1); 7592 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7593 // argument list has no "V" => error 7594 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7595 throw misMatchedTypes("body function", bodyType, expected); 7596 } else if (internalParamList.size() <= vsize) { 7597 // missing T type => error 7598 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7599 throw misMatchedTypes("body function", bodyType, expected); 7600 } 7601 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7602 Class<?> iterableType = null; 7603 if (iterator != null) { 7604 // special case; if the body handle only declares V and T then 7605 // the external parameter list is obtained from iterator handle 7606 if (externalParamList.isEmpty()) { 7607 externalParamList = iterator.type().parameterList(); 7608 } 7609 MethodType itype = iterator.type(); 7610 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7611 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7612 } 7613 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7614 MethodType expected = methodType(itype.returnType(), externalParamList); 7615 throw misMatchedTypes("iterator parameters", itype, expected); 7616 } 7617 } else { 7618 if (externalParamList.isEmpty()) { 7619 // special case; if the iterator handle is null and the body handle 7620 // only declares V and T then the external parameter list consists 7621 // of Iterable 7622 externalParamList = List.of(Iterable.class); 7623 iterableType = Iterable.class; 7624 } else { 7625 // special case; if the iterator handle is null and the external 7626 // parameter list is not empty then the first parameter must be 7627 // assignable to Iterable 7628 iterableType = externalParamList.get(0); 7629 if (!Iterable.class.isAssignableFrom(iterableType)) { 7630 throw newIllegalArgumentException( 7631 "inferred first loop argument must inherit from Iterable: " + iterableType); 7632 } 7633 } 7634 } 7635 if (init != null) { 7636 MethodType initType = init.type(); 7637 if (initType.returnType() != returnType || 7638 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7639 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7640 } 7641 } 7642 return iterableType; // help the caller a bit 7643 } 7644 7645 /*non-public*/ 7646 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7647 // there should be a better way to uncross my wires 7648 int arity = mh.type().parameterCount(); 7649 int[] order = new int[arity]; 7650 for (int k = 0; k < arity; k++) order[k] = k; 7651 order[i] = j; order[j] = i; 7652 Class<?>[] types = mh.type().parameterArray(); 7653 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7654 MethodType swapType = methodType(mh.type().returnType(), types); 7655 return permuteArguments(mh, swapType, order); 7656 } 7657 7658 /** 7659 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7660 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7661 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7662 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7663 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7664 * {@code try-finally} handle. 7665 * <p> 7666 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7667 * The first is the exception thrown during the 7668 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7669 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7670 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7671 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7672 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7673 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7674 * <p> 7675 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7676 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7677 * two extra leading parameters:<ul> 7678 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7679 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7680 * the result from the execution of the {@code target} handle. 7681 * This parameter is not present if the {@code target} returns {@code void}. 7682 * </ul> 7683 * <p> 7684 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7685 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7686 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7687 * the cleanup. 7688 * {@snippet lang="java" : 7689 * V target(A..., B...); 7690 * V cleanup(Throwable, V, A...); 7691 * V adapter(A... a, B... b) { 7692 * V result = (zero value for V); 7693 * Throwable throwable = null; 7694 * try { 7695 * result = target(a..., b...); 7696 * } catch (Throwable t) { 7697 * throwable = t; 7698 * throw t; 7699 * } finally { 7700 * result = cleanup(throwable, result, a...); 7701 * } 7702 * return result; 7703 * } 7704 * } 7705 * <p> 7706 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7707 * be modified by execution of the target, and so are passed unchanged 7708 * from the caller to the cleanup, if it is invoked. 7709 * <p> 7710 * The target and cleanup must return the same type, even if the cleanup 7711 * always throws. 7712 * To create such a throwing cleanup, compose the cleanup logic 7713 * with {@link #throwException throwException}, 7714 * in order to create a method handle of the correct return type. 7715 * <p> 7716 * Note that {@code tryFinally} never converts exceptions into normal returns. 7717 * In rare cases where exceptions must be converted in that way, first wrap 7718 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7719 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7720 * <p> 7721 * It is recommended that the first parameter type of {@code cleanup} be 7722 * declared {@code Throwable} rather than a narrower subtype. This ensures 7723 * {@code cleanup} will always be invoked with whatever exception that 7724 * {@code target} throws. Declaring a narrower type may result in a 7725 * {@code ClassCastException} being thrown by the {@code try-finally} 7726 * handle if the type of the exception thrown by {@code target} is not 7727 * assignable to the first parameter type of {@code cleanup}. Note that 7728 * various exception types of {@code VirtualMachineError}, 7729 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7730 * thrown by almost any kind of Java code, and a finally clause that 7731 * catches (say) only {@code IOException} would mask any of the others 7732 * behind a {@code ClassCastException}. 7733 * 7734 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7735 * @param cleanup the handle that is invoked in the finally block. 7736 * 7737 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7738 * @throws NullPointerException if any argument is null 7739 * @throws IllegalArgumentException if {@code cleanup} does not accept 7740 * the required leading arguments, or if the method handle types do 7741 * not match in their return types and their 7742 * corresponding trailing parameters 7743 * 7744 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7745 * @since 9 7746 */ 7747 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7748 Class<?>[] targetParamTypes = target.type().ptypes(); 7749 Class<?> rtype = target.type().returnType(); 7750 7751 tryFinallyChecks(target, cleanup); 7752 7753 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7754 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7755 // target parameter list. 7756 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7757 7758 // Ensure that the intrinsic type checks the instance thrown by the 7759 // target against the first parameter of cleanup 7760 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7761 7762 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7763 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7764 } 7765 7766 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7767 Class<?> rtype = target.type().returnType(); 7768 if (rtype != cleanup.type().returnType()) { 7769 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7770 } 7771 MethodType cleanupType = cleanup.type(); 7772 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7773 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7774 } 7775 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7776 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7777 } 7778 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7779 // target parameter list. 7780 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7781 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7782 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7783 cleanup.type(), target.type()); 7784 } 7785 } 7786 7787 /** 7788 * Creates a table switch method handle, which can be used to switch over a set of target 7789 * method handles, based on a given target index, called selector. 7790 * <p> 7791 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7792 * and where {@code N} is the number of target method handles, the table switch method 7793 * handle will invoke the n-th target method handle from the list of target method handles. 7794 * <p> 7795 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7796 * method handle will invoke the given fallback method handle. 7797 * <p> 7798 * All method handles passed to this method must have the same type, with the additional 7799 * requirement that the leading parameter be of type {@code int}. The leading parameter 7800 * represents the selector. 7801 * <p> 7802 * Any trailing parameters present in the type will appear on the returned table switch 7803 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7804 * together with the selector value, to the selected method handle when invoking it. 7805 * 7806 * @apiNote Example: 7807 * The cases each drop the {@code selector} value they are given, and take an additional 7808 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7809 * to a specific constant label string for each case: 7810 * {@snippet lang="java" : 7811 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7812 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7813 * MethodType.methodType(String.class, String.class)); 7814 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7815 * 7816 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7817 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7818 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7819 * 7820 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7821 * caseDefault, 7822 * case0, 7823 * case1 7824 * ); 7825 * 7826 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7827 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7828 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7829 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7830 * } 7831 * 7832 * @param fallback the fallback method handle that is called when the selector is not 7833 * within the range {@code [0, N)}. 7834 * @param targets array of target method handles. 7835 * @return the table switch method handle. 7836 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7837 * any of the elements of the {@code targets} array are 7838 * {@code null}. 7839 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7840 * parameter of the fallback handle or any of the target 7841 * handles is not {@code int}, or if the types of 7842 * the fallback handle and all of target handles are 7843 * not the same. 7844 */ 7845 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7846 Objects.requireNonNull(fallback); 7847 Objects.requireNonNull(targets); 7848 targets = targets.clone(); 7849 MethodType type = tableSwitchChecks(fallback, targets); 7850 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7851 } 7852 7853 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7854 if (caseActions.length == 0) 7855 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7856 7857 MethodType expectedType = defaultCase.type(); 7858 7859 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7860 throw new IllegalArgumentException( 7861 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7862 7863 for (MethodHandle mh : caseActions) { 7864 Objects.requireNonNull(mh); 7865 if (mh.type() != expectedType) 7866 throw new IllegalArgumentException( 7867 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7868 } 7869 7870 return expectedType; 7871 } 7872 7873 /** 7874 * Creates a var handle object, which can be used to dereference a {@linkplain java.lang.foreign.MemorySegment memory segment} 7875 * by viewing its contents as a sequence of the provided value layout. 7876 * 7877 * <p>The provided layout specifies the {@linkplain ValueLayout#carrier() carrier type}, 7878 * the {@linkplain ValueLayout#byteSize() byte size}, 7879 * the {@linkplain ValueLayout#byteAlignment() byte alignment} and the {@linkplain ValueLayout#order() byte order} 7880 * associated with the returned var handle. 7881 * 7882 * <p>The returned var handle's type is {@code carrier} and the list of coordinate types is 7883 * {@code (MemorySegment, long)}, where the {@code long} coordinate type corresponds to byte offset into 7884 * a given memory segment. The returned var handle accesses bytes at an offset in a given 7885 * memory segment, composing bytes to or from a value of the type {@code carrier} according to the given endianness; 7886 * the alignment constraint (in bytes) for the resulting var handle is given by {@code alignmentBytes}. 7887 * 7888 * <p>As an example, consider the memory layout expressed by a {@link GroupLayout} instance constructed as follows: 7889 * {@snippet lang="java" : 7890 * GroupLayout seq = java.lang.foreign.MemoryLayout.structLayout( 7891 * MemoryLayout.paddingLayout(32), 7892 * ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).withName("value") 7893 * ); 7894 * } 7895 * To access the member layout named {@code value}, we can construct a memory segment view var handle as follows: 7896 * {@snippet lang="java" : 7897 * VarHandle handle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN)); //(MemorySegment, long) -> int 7898 * handle = MethodHandles.insertCoordinates(handle, 1, 4); //(MemorySegment) -> int 7899 * } 7900 * 7901 * @apiNote The resulting var handle features certain <i>access mode restrictions</i>, 7902 * which are common to all memory segment view var handles. A memory segment view var handle is associated 7903 * with an access size {@code S} and an alignment constraint {@code B} 7904 * (both expressed in bytes). We say that a memory access operation is <em>fully aligned</em> if it occurs 7905 * at a memory address {@code A} which is compatible with both alignment constraints {@code S} and {@code B}. 7906 * If access is fully aligned then following access modes are supported and are 7907 * guaranteed to support atomic access: 7908 * <ul> 7909 * <li>read write access modes for all {@code T}, with the exception of 7910 * access modes {@code get} and {@code set} for {@code long} and 7911 * {@code double} on 32-bit platforms. 7912 * <li>atomic update access modes for {@code int}, {@code long}, 7913 * {@code float}, {@code double} or {@link MemorySegment}. 7914 * (Future major platform releases of the JDK may support additional 7915 * types for certain currently unsupported access modes.) 7916 * <li>numeric atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}. 7917 * (Future major platform releases of the JDK may support additional 7918 * numeric types for certain currently unsupported access modes.) 7919 * <li>bitwise atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}. 7920 * (Future major platform releases of the JDK may support additional 7921 * numeric types for certain currently unsupported access modes.) 7922 * </ul> 7923 * 7924 * If {@code T} is {@code float}, {@code double} or {@link MemorySegment} then atomic 7925 * update access modes compare values using their bitwise representation 7926 * (see {@link Float#floatToRawIntBits}, 7927 * {@link Double#doubleToRawLongBits} and {@link MemorySegment#address()}, respectively). 7928 * <p> 7929 * Alternatively, a memory access operation is <em>partially aligned</em> if it occurs at a memory address {@code A} 7930 * which is only compatible with the alignment constraint {@code B}; in such cases, access for anything other than the 7931 * {@code get} and {@code set} access modes will result in an {@code IllegalStateException}. If access is partially aligned, 7932 * atomic access is only guaranteed with respect to the largest power of two that divides the GCD of {@code A} and {@code S}. 7933 * <p> 7934 * In all other cases, we say that a memory access operation is <em>misaligned</em>; in such cases an 7935 * {@code IllegalStateException} is thrown, irrespective of the access mode being used. 7936 * <p> 7937 * Finally, if {@code T} is {@code MemorySegment} all write access modes throw {@link IllegalArgumentException} 7938 * unless the value to be written is a {@linkplain MemorySegment#isNative() native} memory segment. 7939 * 7940 * @param layout the value layout for which a memory access handle is to be obtained. 7941 * @return the new memory segment view var handle. 7942 * @throws IllegalArgumentException if an illegal carrier type is used, or if {@code alignmentBytes} is not a power of two. 7943 * @throws NullPointerException if {@code layout} is {@code null}. 7944 * @see MemoryLayout#varHandle(MemoryLayout.PathElement...) 7945 * @since 19 7946 */ 7947 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 7948 public static VarHandle memorySegmentViewVarHandle(ValueLayout layout) { 7949 Objects.requireNonNull(layout); 7950 return Utils.makeSegmentViewVarHandle(layout); 7951 } 7952 7953 /** 7954 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7955 * <p> 7956 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7957 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7958 * to the target var handle. 7959 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7960 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7961 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7962 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7963 * <p> 7964 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7965 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7966 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7967 * will be appended to the coordinates of the target var handle). 7968 * <p> 7969 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7970 * throw an {@link IllegalStateException}. 7971 * <p> 7972 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7973 * atomic access guarantees as those featured by the target var handle. 7974 * 7975 * @param target the target var handle 7976 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7977 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7978 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7979 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7980 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7981 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7982 * @throws NullPointerException if any of the arguments is {@code null}. 7983 * @since 19 7984 */ 7985 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 7986 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7987 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7988 } 7989 7990 /** 7991 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7992 * <p> 7993 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7994 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7995 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7996 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7997 * by the adaptation) to the target var handle. 7998 * <p> 7999 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 8000 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8001 * <p> 8002 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8003 * throw an {@link IllegalStateException}. 8004 * <p> 8005 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8006 * atomic access guarantees as those featured by the target var handle. 8007 * 8008 * @param target the target var handle 8009 * @param pos the position of the first coordinate to be transformed 8010 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 8011 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 8012 * to the new coordinate values. 8013 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 8014 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 8015 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8016 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 8017 * or if it's determined that any of the filters throws any checked exceptions. 8018 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 8019 * @since 19 8020 */ 8021 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 8022 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8023 return VarHandles.filterCoordinates(target, pos, filters); 8024 } 8025 8026 /** 8027 * Provides a target var handle with one or more <em>bound coordinates</em> 8028 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8029 * coordinate types than the target var handle. 8030 * <p> 8031 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8032 * are joined with bound coordinate values, and then passed to the target var handle. 8033 * <p> 8034 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8035 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8036 * <p> 8037 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8038 * atomic access guarantees as those featured by the target var handle. 8039 * 8040 * @param target the var handle to invoke after the bound coordinates are inserted 8041 * @param pos the position of the first coordinate to be inserted 8042 * @param values the series of bound coordinates to insert 8043 * @return an adapter var handle which inserts additional coordinates, 8044 * before calling the target var handle 8045 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8046 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8047 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8048 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8049 * of the target var handle. 8050 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8051 * @since 19 8052 */ 8053 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 8054 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8055 return VarHandles.insertCoordinates(target, pos, values); 8056 } 8057 8058 /** 8059 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8060 * so that the new coordinates match the provided ones. 8061 * <p> 8062 * The given array controls the reordering. 8063 * Call {@code #I} the number of incoming coordinates (the value 8064 * {@code newCoordinates.size()}), and call {@code #O} the number 8065 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8066 * Then the length of the reordering array must be {@code #O}, 8067 * and each element must be a non-negative number less than {@code #I}. 8068 * For every {@code N} less than {@code #O}, the {@code N}-th 8069 * outgoing coordinate will be taken from the {@code I}-th incoming 8070 * coordinate, where {@code I} is {@code reorder[N]}. 8071 * <p> 8072 * No coordinate value conversions are applied. 8073 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8074 * must be identical to the type of the corresponding outgoing coordinate 8075 * in the target var handle. 8076 * <p> 8077 * The reordering array need not specify an actual permutation. 8078 * An incoming coordinate will be duplicated if its index appears 8079 * more than once in the array, and an incoming coordinate will be dropped 8080 * if its index does not appear in the array. 8081 * <p> 8082 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8083 * atomic access guarantees as those featured by the target var handle. 8084 * @param target the var handle to invoke after the coordinates have been reordered 8085 * @param newCoordinates the new coordinate types 8086 * @param reorder an index array which controls the reordering 8087 * @return an adapter var handle which re-arranges the incoming coordinate values, 8088 * before calling the target var handle 8089 * @throws IllegalArgumentException if the index array length is not equal to 8090 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8091 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8092 * the target var handle and in {@code newCoordinates} are not identical. 8093 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8094 * @since 19 8095 */ 8096 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 8097 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8098 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8099 } 8100 8101 /** 8102 * Adapts a target var handle by pre-processing 8103 * a sub-sequence of its coordinate values with a filter (a method handle). 8104 * The pre-processed coordinates are replaced by the result (if any) of the 8105 * filter function and the target var handle is then called on the modified (usually shortened) 8106 * coordinate list. 8107 * <p> 8108 * If {@code R} is the return type of the filter (which cannot be void), the target var handle must accept a value of 8109 * type {@code R} as its coordinate in position {@code pos}, preceded and/or followed by 8110 * any coordinate not passed to the filter. 8111 * No coordinates are reordered, and the result returned from the filter 8112 * replaces (in order) the whole subsequence of coordinates originally 8113 * passed to the adapter. 8114 * <p> 8115 * The argument types (if any) of the filter 8116 * replace zero or one coordinate types of the target var handle, at position {@code pos}, 8117 * in the resulting adapted var handle. 8118 * The return type of the filter must be identical to the 8119 * coordinate type of the target var handle at position {@code pos}, and that target var handle 8120 * coordinate is supplied by the return value of the filter. 8121 * <p> 8122 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8123 * throw an {@link IllegalStateException}. 8124 * <p> 8125 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8126 * atomic access guarantees as those featured by the target var handle. 8127 * 8128 * @param target the var handle to invoke after the coordinates have been filtered 8129 * @param pos the position of the coordinate to be filtered 8130 * @param filter the filter method handle 8131 * @return an adapter var handle which filters the incoming coordinate values, 8132 * before calling the target var handle 8133 * @throws IllegalArgumentException if the return type of {@code filter} 8134 * is void, or it is not the same as the {@code pos} coordinate of the target var handle, 8135 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8136 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8137 * or if it's determined that {@code filter} throws any checked exceptions. 8138 * @throws NullPointerException if any of the arguments is {@code null}. 8139 * @since 19 8140 */ 8141 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 8142 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8143 return VarHandles.collectCoordinates(target, pos, filter); 8144 } 8145 8146 /** 8147 * Returns a var handle which will discard some dummy coordinates before delegating to the 8148 * target var handle. As a consequence, the resulting var handle will feature more 8149 * coordinate types than the target var handle. 8150 * <p> 8151 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8152 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8153 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8154 * <p> 8155 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8156 * atomic access guarantees as those featured by the target var handle. 8157 * 8158 * @param target the var handle to invoke after the dummy coordinates are dropped 8159 * @param pos position of the first coordinate to drop (zero for the leftmost) 8160 * @param valueTypes the type(s) of the coordinate(s) to drop 8161 * @return an adapter var handle which drops some dummy coordinates, 8162 * before calling the target var handle 8163 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8164 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8165 * @since 19 8166 */ 8167 @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN) 8168 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8169 return VarHandles.dropCoordinates(target, pos, valueTypes); 8170 } 8171 }