1 /* 2 * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.access.SharedSecrets; 29 import jdk.internal.misc.Unsafe; 30 import jdk.internal.misc.VM; 31 import jdk.internal.org.objectweb.asm.ClassReader; 32 import jdk.internal.org.objectweb.asm.Opcodes; 33 import jdk.internal.org.objectweb.asm.Type; 34 import jdk.internal.reflect.CallerSensitive; 35 import jdk.internal.reflect.CallerSensitiveAdapter; 36 import jdk.internal.reflect.Reflection; 37 import jdk.internal.util.ClassFileDumper; 38 import jdk.internal.vm.annotation.ForceInline; 39 import sun.invoke.util.ValueConversions; 40 import sun.invoke.util.VerifyAccess; 41 import sun.invoke.util.Wrapper; 42 import sun.reflect.misc.ReflectUtil; 43 import sun.security.util.SecurityConstants; 44 45 import java.lang.constant.ConstantDescs; 46 import java.lang.invoke.LambdaForm.BasicType; 47 import java.lang.reflect.Constructor; 48 import java.lang.reflect.Field; 49 import java.lang.reflect.Member; 50 import java.lang.reflect.Method; 51 import java.lang.reflect.Modifier; 52 import java.nio.ByteOrder; 53 import java.security.ProtectionDomain; 54 import java.util.ArrayList; 55 import java.util.Arrays; 56 import java.util.BitSet; 57 import java.util.Comparator; 58 import java.util.Iterator; 59 import java.util.List; 60 import java.util.Objects; 61 import java.util.Set; 62 import java.util.concurrent.ConcurrentHashMap; 63 import java.util.stream.Stream; 64 65 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 66 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 67 import static java.lang.invoke.MethodHandleNatives.Constants.*; 68 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 69 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 70 import static java.lang.invoke.MethodHandleStatics.newInternalError; 71 import static java.lang.invoke.MethodType.methodType; 72 73 /** 74 * This class consists exclusively of static methods that operate on or return 75 * method handles. They fall into several categories: 76 * <ul> 77 * <li>Lookup methods which help create method handles for methods and fields. 78 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 79 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 80 * </ul> 81 * A lookup, combinator, or factory method will fail and throw an 82 * {@code IllegalArgumentException} if the created method handle's type 83 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 84 * 85 * @author John Rose, JSR 292 EG 86 * @since 1.7 87 */ 88 public class MethodHandles { 89 90 private MethodHandles() { } // do not instantiate 91 92 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 93 94 // See IMPL_LOOKUP below. 95 96 //// Method handle creation from ordinary methods. 97 98 /** 99 * Returns a {@link Lookup lookup object} with 100 * full capabilities to emulate all supported bytecode behaviors of the caller. 101 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 102 * Factory methods on the lookup object can create 103 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 104 * for any member that the caller has access to via bytecodes, 105 * including protected and private fields and methods. 106 * This lookup object is created by the original lookup class 107 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 108 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 109 * Do not store it in place where untrusted code can access it. 110 * <p> 111 * This method is caller sensitive, which means that it may return different 112 * values to different callers. 113 * In cases where {@code MethodHandles.lookup} is called from a context where 114 * there is no caller frame on the stack (e.g. when called directly 115 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 116 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 117 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 118 * to obtain a low-privileged lookup instead. 119 * @return a lookup object for the caller of this method, with 120 * {@linkplain Lookup#ORIGINAL original} and 121 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 122 * @throws IllegalCallerException if there is no caller frame on the stack. 123 */ 124 @CallerSensitive 125 @ForceInline // to ensure Reflection.getCallerClass optimization 126 public static Lookup lookup() { 127 final Class<?> c = Reflection.getCallerClass(); 128 if (c == null) { 129 throw new IllegalCallerException("no caller frame"); 130 } 131 return new Lookup(c); 132 } 133 134 /** 135 * This lookup method is the alternate implementation of 136 * the lookup method with a leading caller class argument which is 137 * non-caller-sensitive. This method is only invoked by reflection 138 * and method handle. 139 */ 140 @CallerSensitiveAdapter 141 private static Lookup lookup(Class<?> caller) { 142 if (caller.getClassLoader() == null) { 143 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 144 } 145 return new Lookup(caller); 146 } 147 148 /** 149 * Returns a {@link Lookup lookup object} which is trusted minimally. 150 * The lookup has the {@code UNCONDITIONAL} mode. 151 * It can only be used to create method handles to public members of 152 * public classes in packages that are exported unconditionally. 153 * <p> 154 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 155 * of this lookup object will be {@link java.lang.Object}. 156 * 157 * @apiNote The use of Object is conventional, and because the lookup modes are 158 * limited, there is no special access provided to the internals of Object, its package 159 * or its module. This public lookup object or other lookup object with 160 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 161 * is not used to determine the lookup context. 162 * 163 * <p style="font-size:smaller;"> 164 * <em>Discussion:</em> 165 * The lookup class can be changed to any other class {@code C} using an expression of the form 166 * {@link Lookup#in publicLookup().in(C.class)}. 167 * A public lookup object is always subject to 168 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 169 * Also, it cannot access 170 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 171 * @return a lookup object which is trusted minimally 172 */ 173 public static Lookup publicLookup() { 174 return Lookup.PUBLIC_LOOKUP; 175 } 176 177 /** 178 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 179 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 180 * The returned lookup object can provide access to classes in modules and packages, 181 * and members of those classes, outside the normal rules of Java access control, 182 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 183 * <p> 184 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 185 * allowed to do deep reflection on module {@code M2} and package of the target class 186 * if and only if all of the following conditions are {@code true}: 187 * <ul> 188 * <li>If there is a security manager, its {@code checkPermission} method is 189 * called to check {@code ReflectPermission("suppressAccessChecks")} and 190 * that must return normally. 191 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 192 * full privilege access}. Specifically: 193 * <ul> 194 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 195 * (This is because otherwise there would be no way to ensure the original lookup 196 * creator was a member of any particular module, and so any subsequent checks 197 * for readability and qualified exports would become ineffective.) 198 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 199 * (This is because an application intending to share intra-module access 200 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 201 * deep reflection to its own module.) 202 * </ul> 203 * <li>The target class must be a proper class, not a primitive or array class. 204 * (Thus, {@code M2} is well-defined.) 205 * <li>If the caller module {@code M1} differs from 206 * the target module {@code M2} then both of the following must be true: 207 * <ul> 208 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 209 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 210 * containing the target class to at least {@code M1}.</li> 211 * </ul> 212 * </ul> 213 * <p> 214 * If any of the above checks is violated, this method fails with an 215 * exception. 216 * <p> 217 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 218 * returns a {@code Lookup} on {@code targetClass} with 219 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 220 * with {@code null} previous lookup class. 221 * <p> 222 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 223 * returns a {@code Lookup} on {@code targetClass} that records 224 * the lookup class of the caller as the new previous lookup class with 225 * {@code PRIVATE} access but no {@code MODULE} access. 226 * <p> 227 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 228 * 229 * @apiNote The {@code Lookup} object returned by this method is allowed to 230 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 231 * of {@code targetClass}. Extreme caution should be taken when opening a package 232 * to another module as such defined classes have the same full privilege 233 * access as other members in {@code targetClass}'s module. 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 ({@value ConstantDescs#INIT_NAME} and {@value 709 * ConstantDescs#CLASS_INIT_NAME}). 710 * The internal syntax of invocation instructions allows them to refer to such internal 711 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 712 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 713 * <p> 714 * If the relationship between nested types is expressed directly through the 715 * {@code NestHost} and {@code NestMembers} attributes 716 * (see the Java Virtual Machine Specification, sections {@jvms 717 * 4.7.28} and {@jvms 4.7.29}), 718 * then the associated {@code Lookup} object provides direct access to 719 * the lookup class and all of its nestmates 720 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 721 * Otherwise, access between nested classes is obtained by the Java compiler creating 722 * a wrapper method to access a private method of another class in the same nest. 723 * For example, a nested class {@code C.D} 724 * can access private members within other related classes such as 725 * {@code C}, {@code C.D.E}, or {@code C.B}, 726 * but the Java compiler may need to generate wrapper methods in 727 * those related classes. In such cases, a {@code Lookup} object on 728 * {@code C.E} would be unable to access those private members. 729 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 730 * which can transform a lookup on {@code C.E} into one on any of those other 731 * classes, without special elevation of privilege. 732 * <p> 733 * The accesses permitted to a given lookup object may be limited, 734 * according to its set of {@link #lookupModes lookupModes}, 735 * to a subset of members normally accessible to the lookup class. 736 * For example, the {@link MethodHandles#publicLookup publicLookup} 737 * method produces a lookup object which is only allowed to access 738 * public members in public classes of exported packages. 739 * The caller sensitive method {@link MethodHandles#lookup lookup} 740 * produces a lookup object with full capabilities relative to 741 * its caller class, to emulate all supported bytecode behaviors. 742 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 743 * with fewer access modes than the original lookup object. 744 * 745 * <p style="font-size:smaller;"> 746 * <a id="privacc"></a> 747 * <em>Discussion of private and module access:</em> 748 * We say that a lookup has <em>private access</em> 749 * if its {@linkplain #lookupModes lookup modes} 750 * include the possibility of accessing {@code private} members 751 * (which includes the private members of nestmates). 752 * As documented in the relevant methods elsewhere, 753 * only lookups with private access possess the following capabilities: 754 * <ul style="font-size:smaller;"> 755 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 756 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 757 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 758 * for classes accessible to the lookup class 759 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 760 * within the same package member 761 * </ul> 762 * <p style="font-size:smaller;"> 763 * Similarly, a lookup with module access ensures that the original lookup creator was 764 * a member in the same module as the lookup class. 765 * <p style="font-size:smaller;"> 766 * Private and module access are independently determined modes; a lookup may have 767 * either or both or neither. A lookup which possesses both access modes is said to 768 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 769 * <p style="font-size:smaller;"> 770 * A lookup with <em>original access</em> ensures that this lookup is created by 771 * the original lookup class and the bootstrap method invoked by the VM. 772 * Such a lookup with original access also has private and module access 773 * which has the following additional capability: 774 * <ul style="font-size:smaller;"> 775 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 776 * such as {@code Class.forName} 777 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 778 * class data} associated with the lookup class</li> 779 * </ul> 780 * <p style="font-size:smaller;"> 781 * Each of these permissions is a consequence of the fact that a lookup object 782 * with private access can be securely traced back to an originating class, 783 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 784 * can be reliably determined and emulated by method handles. 785 * 786 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 787 * When a lookup class in one module {@code M1} accesses a class in another module 788 * {@code M2}, extra access checking is performed beyond the access mode bits. 789 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 790 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 791 * and when the type is in a package of {@code M2} that is exported to 792 * at least {@code M1}. 793 * <p> 794 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 795 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 796 * MethodHandles.privateLookupIn} methods. 797 * Teleporting across modules will always record the original lookup class as 798 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 799 * and drops {@link Lookup#MODULE MODULE} access. 800 * If the target class is in the same module as the lookup class {@code C}, 801 * then the target class becomes the new lookup class 802 * and there is no change to the previous lookup class. 803 * If the target class is in a different module from {@code M1} ({@code C}'s module), 804 * {@code C} becomes the new previous lookup class 805 * and the target class becomes the new lookup class. 806 * In that case, if there was already a previous lookup class in {@code M0}, 807 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 808 * drops all privileges. 809 * For example, 810 * {@snippet lang="java" : 811 * Lookup lookup = MethodHandles.lookup(); // in class C 812 * Lookup lookup2 = lookup.in(D.class); 813 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 814 * } 815 * <p> 816 * The {@link #lookup()} factory method produces a {@code Lookup} object 817 * with {@code null} previous lookup class. 818 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 819 * to class {@code D} without elevation of privileges. 820 * If {@code C} and {@code D} are in the same module, 821 * {@code lookup2} records {@code D} as the new lookup class and keeps the 822 * same previous lookup class as the original {@code lookup}, or 823 * {@code null} if not present. 824 * <p> 825 * When a {@code Lookup} teleports from a class 826 * in one nest to another nest, {@code PRIVATE} access is dropped. 827 * When a {@code Lookup} teleports from a class in one package to 828 * another package, {@code PACKAGE} access is dropped. 829 * When a {@code Lookup} teleports from a class in one module to another module, 830 * {@code MODULE} access is dropped. 831 * Teleporting across modules drops the ability to access non-exported classes 832 * in both the module of the new lookup class and the module of the old lookup class 833 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 834 * A {@code Lookup} can teleport back and forth to a class in the module of 835 * the lookup class and the module of the previous class lookup. 836 * Teleporting across modules can only decrease access but cannot increase it. 837 * Teleporting to some third module drops all accesses. 838 * <p> 839 * In the above example, if {@code C} and {@code D} are in different modules, 840 * {@code lookup2} records {@code D} as its lookup class and 841 * {@code C} as its previous lookup class and {@code lookup2} has only 842 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 843 * {@code C}'s module and {@code D}'s module. 844 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 845 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 846 * class {@code D} is recorded as its previous lookup class. 847 * <p> 848 * Teleporting across modules restricts access to the public types that 849 * both the lookup class and the previous lookup class can equally access 850 * (see below). 851 * <p> 852 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 853 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 854 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 855 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 856 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 857 * to call {@code privateLookupIn}. 858 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 859 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 860 * produces a new {@code Lookup} on {@code T} with full capabilities. 861 * A {@code lookup} on {@code C} is also allowed 862 * to do deep reflection on {@code T} in another module {@code M2} if 863 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 864 * the package containing {@code T} to at least {@code M1}. 865 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 866 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 867 * The resulting {@code Lookup} can be used to do member lookup or teleport 868 * to another lookup class by calling {@link #in Lookup::in}. But 869 * it cannot be used to obtain another private {@code Lookup} by calling 870 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 871 * because it has no {@code MODULE} access. 872 * <p> 873 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 874 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 875 * of {@code T}. Extreme caution should be taken when opening a package 876 * to another module as such defined classes have the same full privilege 877 * access as other members in {@code M2}. 878 * 879 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 880 * 881 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 882 * allows cross-module access. The access checking is performed with respect 883 * to both the lookup class and the previous lookup class if present. 884 * <p> 885 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 886 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 887 * exported unconditionally}. 888 * <p> 889 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 890 * the lookup with {@link #PUBLIC} mode can access all public types in modules 891 * that are readable to {@code M1} and the type is in a package that is exported 892 * at least to {@code M1}. 893 * <p> 894 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 895 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 896 * the intersection of all public types that are accessible to {@code M1} 897 * with all public types that are accessible to {@code M0}. {@code M0} 898 * reads {@code M1} and hence the set of accessible types includes: 899 * 900 * <ul> 901 * <li>unconditional-exported packages from {@code M1}</li> 902 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 903 * <li> 904 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 905 * and {@code M1} read {@code M2} 906 * </li> 907 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 908 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 909 * <li> 910 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 911 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 912 * </li> 913 * </ul> 914 * 915 * <h2><a id="access-modes"></a>Access modes</h2> 916 * 917 * The table below shows the access modes of a {@code Lookup} produced by 918 * any of the following factory or transformation methods: 919 * <ul> 920 * <li>{@link #lookup() MethodHandles::lookup}</li> 921 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 922 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 923 * <li>{@link Lookup#in Lookup::in}</li> 924 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 925 * </ul> 926 * 927 * <table class="striped"> 928 * <caption style="display:none"> 929 * Access mode summary 930 * </caption> 931 * <thead> 932 * <tr> 933 * <th scope="col">Lookup object</th> 934 * <th style="text-align:center">original</th> 935 * <th style="text-align:center">protected</th> 936 * <th style="text-align:center">private</th> 937 * <th style="text-align:center">package</th> 938 * <th style="text-align:center">module</th> 939 * <th style="text-align:center">public</th> 940 * </tr> 941 * </thead> 942 * <tbody> 943 * <tr> 944 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 945 * <td style="text-align:center">ORI</td> 946 * <td style="text-align:center">PRO</td> 947 * <td style="text-align:center">PRI</td> 948 * <td style="text-align:center">PAC</td> 949 * <td style="text-align:center">MOD</td> 950 * <td style="text-align:center">1R</td> 951 * </tr> 952 * <tr> 953 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 954 * <td></td> 955 * <td></td> 956 * <td></td> 957 * <td style="text-align:center">PAC</td> 958 * <td style="text-align:center">MOD</td> 959 * <td style="text-align:center">1R</td> 960 * </tr> 961 * <tr> 962 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 963 * <td></td> 964 * <td></td> 965 * <td></td> 966 * <td></td> 967 * <td style="text-align:center">MOD</td> 968 * <td style="text-align:center">1R</td> 969 * </tr> 970 * <tr> 971 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 972 * <td></td> 973 * <td></td> 974 * <td></td> 975 * <td></td> 976 * <td></td> 977 * <td style="text-align:center">2R</td> 978 * </tr> 979 * <tr> 980 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 981 * <td></td> 982 * <td></td> 983 * <td></td> 984 * <td></td> 985 * <td></td> 986 * <td style="text-align:center">2R</td> 987 * </tr> 988 * <tr> 989 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 990 * <td></td> 991 * <td style="text-align:center">PRO</td> 992 * <td style="text-align:center">PRI</td> 993 * <td style="text-align:center">PAC</td> 994 * <td style="text-align:center">MOD</td> 995 * <td style="text-align:center">1R</td> 996 * </tr> 997 * <tr> 998 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 999 * <td></td> 1000 * <td style="text-align:center">PRO</td> 1001 * <td style="text-align:center">PRI</td> 1002 * <td style="text-align:center">PAC</td> 1003 * <td style="text-align:center">MOD</td> 1004 * <td style="text-align:center">1R</td> 1005 * </tr> 1006 * <tr> 1007 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1008 * <td></td> 1009 * <td></td> 1010 * <td></td> 1011 * <td style="text-align:center">PAC</td> 1012 * <td style="text-align:center">MOD</td> 1013 * <td style="text-align:center">1R</td> 1014 * </tr> 1015 * <tr> 1016 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1017 * <td></td> 1018 * <td></td> 1019 * <td></td> 1020 * <td></td> 1021 * <td style="text-align:center">MOD</td> 1022 * <td style="text-align:center">1R</td> 1023 * </tr> 1024 * <tr> 1025 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1026 * <td></td> 1027 * <td></td> 1028 * <td></td> 1029 * <td></td> 1030 * <td></td> 1031 * <td style="text-align:center">2R</td> 1032 * </tr> 1033 * <tr> 1034 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1035 * <td></td> 1036 * <td></td> 1037 * <td style="text-align:center">PRI</td> 1038 * <td style="text-align:center">PAC</td> 1039 * <td style="text-align:center">MOD</td> 1040 * <td style="text-align:center">1R</td> 1041 * </tr> 1042 * <tr> 1043 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1044 * <td></td> 1045 * <td></td> 1046 * <td></td> 1047 * <td style="text-align:center">PAC</td> 1048 * <td style="text-align:center">MOD</td> 1049 * <td style="text-align:center">1R</td> 1050 * </tr> 1051 * <tr> 1052 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1053 * <td></td> 1054 * <td></td> 1055 * <td></td> 1056 * <td></td> 1057 * <td style="text-align:center">MOD</td> 1058 * <td style="text-align:center">1R</td> 1059 * </tr> 1060 * <tr> 1061 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1062 * <td></td> 1063 * <td></td> 1064 * <td></td> 1065 * <td></td> 1066 * <td></td> 1067 * <td style="text-align:center">1R</td> 1068 * </tr> 1069 * <tr> 1070 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1071 * <td></td> 1072 * <td></td> 1073 * <td></td> 1074 * <td></td> 1075 * <td></td> 1076 * <td style="text-align:center">none</td> 1077 * <tr> 1078 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1079 * <td></td> 1080 * <td style="text-align:center">PRO</td> 1081 * <td style="text-align:center">PRI</td> 1082 * <td style="text-align:center">PAC</td> 1083 * <td></td> 1084 * <td style="text-align:center">2R</td> 1085 * </tr> 1086 * <tr> 1087 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1088 * <td></td> 1089 * <td style="text-align:center">PRO</td> 1090 * <td style="text-align:center">PRI</td> 1091 * <td style="text-align:center">PAC</td> 1092 * <td></td> 1093 * <td style="text-align:center">2R</td> 1094 * </tr> 1095 * <tr> 1096 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1097 * <td></td> 1098 * <td></td> 1099 * <td></td> 1100 * <td></td> 1101 * <td></td> 1102 * <td style="text-align:center">IAE</td> 1103 * </tr> 1104 * <tr> 1105 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1106 * <td></td> 1107 * <td></td> 1108 * <td></td> 1109 * <td style="text-align:center">PAC</td> 1110 * <td></td> 1111 * <td style="text-align:center">2R</td> 1112 * </tr> 1113 * <tr> 1114 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1115 * <td></td> 1116 * <td></td> 1117 * <td></td> 1118 * <td></td> 1119 * <td></td> 1120 * <td style="text-align:center">2R</td> 1121 * </tr> 1122 * <tr> 1123 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1124 * <td></td> 1125 * <td></td> 1126 * <td></td> 1127 * <td></td> 1128 * <td></td> 1129 * <td style="text-align:center">2R</td> 1130 * </tr> 1131 * <tr> 1132 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1133 * <td></td> 1134 * <td></td> 1135 * <td></td> 1136 * <td></td> 1137 * <td></td> 1138 * <td style="text-align:center">none</td> 1139 * </tr> 1140 * <tr> 1141 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1142 * <td></td> 1143 * <td></td> 1144 * <td style="text-align:center">PRI</td> 1145 * <td style="text-align:center">PAC</td> 1146 * <td></td> 1147 * <td style="text-align:center">2R</td> 1148 * </tr> 1149 * <tr> 1150 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1151 * <td></td> 1152 * <td></td> 1153 * <td></td> 1154 * <td style="text-align:center">PAC</td> 1155 * <td></td> 1156 * <td style="text-align:center">2R</td> 1157 * </tr> 1158 * <tr> 1159 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1160 * <td></td> 1161 * <td></td> 1162 * <td></td> 1163 * <td></td> 1164 * <td></td> 1165 * <td style="text-align:center">2R</td> 1166 * </tr> 1167 * <tr> 1168 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1169 * <td></td> 1170 * <td></td> 1171 * <td></td> 1172 * <td></td> 1173 * <td></td> 1174 * <td style="text-align:center">2R</td> 1175 * </tr> 1176 * <tr> 1177 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1178 * <td></td> 1179 * <td></td> 1180 * <td></td> 1181 * <td></td> 1182 * <td></td> 1183 * <td style="text-align:center">none</td> 1184 * </tr> 1185 * <tr> 1186 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1187 * <td></td> 1188 * <td></td> 1189 * <td style="text-align:center">PRI</td> 1190 * <td style="text-align:center">PAC</td> 1191 * <td style="text-align:center">MOD</td> 1192 * <td style="text-align:center">1R</td> 1193 * </tr> 1194 * <tr> 1195 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1196 * <td></td> 1197 * <td></td> 1198 * <td></td> 1199 * <td style="text-align:center">PAC</td> 1200 * <td style="text-align:center">MOD</td> 1201 * <td style="text-align:center">1R</td> 1202 * </tr> 1203 * <tr> 1204 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1205 * <td></td> 1206 * <td></td> 1207 * <td></td> 1208 * <td></td> 1209 * <td style="text-align:center">MOD</td> 1210 * <td style="text-align:center">1R</td> 1211 * </tr> 1212 * <tr> 1213 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1214 * <td></td> 1215 * <td></td> 1216 * <td></td> 1217 * <td></td> 1218 * <td></td> 1219 * <td style="text-align:center">1R</td> 1220 * </tr> 1221 * <tr> 1222 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1223 * <td></td> 1224 * <td></td> 1225 * <td></td> 1226 * <td></td> 1227 * <td></td> 1228 * <td style="text-align:center">none</td> 1229 * </tr> 1230 * <tr> 1231 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1232 * <td></td> 1233 * <td></td> 1234 * <td></td> 1235 * <td></td> 1236 * <td></td> 1237 * <td style="text-align:center">U</td> 1238 * </tr> 1239 * <tr> 1240 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1241 * <td></td> 1242 * <td></td> 1243 * <td></td> 1244 * <td></td> 1245 * <td></td> 1246 * <td style="text-align:center">U</td> 1247 * </tr> 1248 * <tr> 1249 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1250 * <td></td> 1251 * <td></td> 1252 * <td></td> 1253 * <td></td> 1254 * <td></td> 1255 * <td style="text-align:center">U</td> 1256 * </tr> 1257 * <tr> 1258 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1259 * <td></td> 1260 * <td></td> 1261 * <td></td> 1262 * <td></td> 1263 * <td></td> 1264 * <td style="text-align:center">none</td> 1265 * </tr> 1266 * <tr> 1267 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1268 * <td></td> 1269 * <td></td> 1270 * <td></td> 1271 * <td></td> 1272 * <td></td> 1273 * <td style="text-align:center">IAE</td> 1274 * </tr> 1275 * <tr> 1276 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1277 * <td></td> 1278 * <td></td> 1279 * <td></td> 1280 * <td></td> 1281 * <td></td> 1282 * <td style="text-align:center">none</td> 1283 * </tr> 1284 * </tbody> 1285 * </table> 1286 * 1287 * <p> 1288 * Notes: 1289 * <ul> 1290 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1291 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1292 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1293 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1294 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1295 * {@code PRO} indicates {@link #PROTECTED} bit set, 1296 * {@code PRI} indicates {@link #PRIVATE} bit set, 1297 * {@code PAC} indicates {@link #PACKAGE} bit set, 1298 * {@code MOD} indicates {@link #MODULE} bit set, 1299 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1300 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1301 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1302 * <li>Public access comes in three kinds: 1303 * <ul> 1304 * <li>unconditional ({@code U}): the lookup assumes readability. 1305 * The lookup has {@code null} previous lookup class. 1306 * <li>one-module-reads ({@code 1R}): the module access checking is 1307 * performed with respect to the lookup class. The lookup has {@code null} 1308 * previous lookup class. 1309 * <li>two-module-reads ({@code 2R}): the module access checking is 1310 * performed with respect to the lookup class and the previous lookup class. 1311 * The lookup has a non-null previous lookup class which is in a 1312 * different module from the current lookup class. 1313 * </ul> 1314 * <li>Any attempt to reach a third module loses all access.</li> 1315 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1316 * all access modes are dropped.</li> 1317 * </ul> 1318 * 1319 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1320 * Although bytecode instructions can only refer to classes in 1321 * a related class loader, this API can search for methods in any 1322 * class, as long as a reference to its {@code Class} object is 1323 * available. Such cross-loader references are also possible with the 1324 * Core Reflection API, and are impossible to bytecode instructions 1325 * such as {@code invokestatic} or {@code getfield}. 1326 * There is a {@linkplain java.lang.SecurityManager security manager API} 1327 * to allow applications to check such cross-loader references. 1328 * These checks apply to both the {@code MethodHandles.Lookup} API 1329 * and the Core Reflection API 1330 * (as found on {@link java.lang.Class Class}). 1331 * <p> 1332 * If a security manager is present, member and class lookups are subject to 1333 * additional checks. 1334 * From one to three calls are made to the security manager. 1335 * Any of these calls can refuse access by throwing a 1336 * {@link java.lang.SecurityException SecurityException}. 1337 * Define {@code smgr} as the security manager, 1338 * {@code lookc} as the lookup class of the current lookup object, 1339 * {@code refc} as the containing class in which the member 1340 * is being sought, and {@code defc} as the class in which the 1341 * member is actually defined. 1342 * (If a class or other type is being accessed, 1343 * the {@code refc} and {@code defc} values are the class itself.) 1344 * The value {@code lookc} is defined as <em>not present</em> 1345 * if the current lookup object does not have 1346 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1347 * The calls are made according to the following rules: 1348 * <ul> 1349 * <li><b>Step 1:</b> 1350 * If {@code lookc} is not present, or if its class loader is not 1351 * the same as or an ancestor of the class loader of {@code refc}, 1352 * then {@link SecurityManager#checkPackageAccess 1353 * smgr.checkPackageAccess(refcPkg)} is called, 1354 * where {@code refcPkg} is the package of {@code refc}. 1355 * <li><b>Step 2a:</b> 1356 * If the retrieved member is not public and 1357 * {@code lookc} is not present, then 1358 * {@link SecurityManager#checkPermission smgr.checkPermission} 1359 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1360 * <li><b>Step 2b:</b> 1361 * If the retrieved class has a {@code null} class loader, 1362 * and {@code lookc} is not present, then 1363 * {@link SecurityManager#checkPermission smgr.checkPermission} 1364 * with {@code RuntimePermission("getClassLoader")} is called. 1365 * <li><b>Step 3:</b> 1366 * If the retrieved member is not public, 1367 * and if {@code lookc} is not present, 1368 * and if {@code defc} and {@code refc} are different, 1369 * then {@link SecurityManager#checkPackageAccess 1370 * smgr.checkPackageAccess(defcPkg)} is called, 1371 * where {@code defcPkg} is the package of {@code defc}. 1372 * </ul> 1373 * Security checks are performed after other access checks have passed. 1374 * Therefore, the above rules presuppose a member or class that is public, 1375 * or else that is being accessed from a lookup class that has 1376 * rights to access the member or class. 1377 * <p> 1378 * If a security manager is present and the current lookup object does not have 1379 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1380 * {@link #defineClass(byte[]) defineClass}, 1381 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1382 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1383 * defineHiddenClassWithClassData} 1384 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1385 * with {@code RuntimePermission("defineClass")}. 1386 * 1387 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1388 * A small number of Java methods have a special property called caller sensitivity. 1389 * A <em>caller-sensitive</em> method can behave differently depending on the 1390 * identity of its immediate caller. 1391 * <p> 1392 * If a method handle for a caller-sensitive method is requested, 1393 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1394 * but they take account of the lookup class in a special way. 1395 * The resulting method handle behaves as if it were called 1396 * from an instruction contained in the lookup class, 1397 * so that the caller-sensitive method detects the lookup class. 1398 * (By contrast, the invoker of the method handle is disregarded.) 1399 * Thus, in the case of caller-sensitive methods, 1400 * different lookup classes may give rise to 1401 * differently behaving method handles. 1402 * <p> 1403 * In cases where the lookup object is 1404 * {@link MethodHandles#publicLookup() publicLookup()}, 1405 * or some other lookup object without the 1406 * {@linkplain #ORIGINAL original access}, 1407 * the lookup class is disregarded. 1408 * In such cases, no caller-sensitive method handle can be created, 1409 * access is forbidden, and the lookup fails with an 1410 * {@code IllegalAccessException}. 1411 * <p style="font-size:smaller;"> 1412 * <em>Discussion:</em> 1413 * For example, the caller-sensitive method 1414 * {@link java.lang.Class#forName(String) Class.forName(x)} 1415 * can return varying classes or throw varying exceptions, 1416 * depending on the class loader of the class that calls it. 1417 * A public lookup of {@code Class.forName} will fail, because 1418 * there is no reasonable way to determine its bytecode behavior. 1419 * <p style="font-size:smaller;"> 1420 * If an application caches method handles for broad sharing, 1421 * it should use {@code publicLookup()} to create them. 1422 * If there is a lookup of {@code Class.forName}, it will fail, 1423 * and the application must take appropriate action in that case. 1424 * It may be that a later lookup, perhaps during the invocation of a 1425 * bootstrap method, can incorporate the specific identity 1426 * of the caller, making the method accessible. 1427 * <p style="font-size:smaller;"> 1428 * The function {@code MethodHandles.lookup} is caller sensitive 1429 * so that there can be a secure foundation for lookups. 1430 * Nearly all other methods in the JSR 292 API rely on lookup 1431 * objects to check access requests. 1432 */ 1433 public static final 1434 class Lookup { 1435 /** The class on behalf of whom the lookup is being performed. */ 1436 private final Class<?> lookupClass; 1437 1438 /** previous lookup class */ 1439 private final Class<?> prevLookupClass; 1440 1441 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1442 private final int allowedModes; 1443 1444 static { 1445 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1446 } 1447 1448 /** A single-bit mask representing {@code public} access, 1449 * which may contribute to the result of {@link #lookupModes lookupModes}. 1450 * The value, {@code 0x01}, happens to be the same as the value of the 1451 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1452 * <p> 1453 * A {@code Lookup} with this lookup mode performs cross-module access check 1454 * with respect to the {@linkplain #lookupClass() lookup class} and 1455 * {@linkplain #previousLookupClass() previous lookup class} if present. 1456 */ 1457 public static final int PUBLIC = Modifier.PUBLIC; 1458 1459 /** A single-bit mask representing {@code private} access, 1460 * which may contribute to the result of {@link #lookupModes lookupModes}. 1461 * The value, {@code 0x02}, happens to be the same as the value of the 1462 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1463 */ 1464 public static final int PRIVATE = Modifier.PRIVATE; 1465 1466 /** A single-bit mask representing {@code protected} access, 1467 * which may contribute to the result of {@link #lookupModes lookupModes}. 1468 * The value, {@code 0x04}, happens to be the same as the value of the 1469 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1470 */ 1471 public static final int PROTECTED = Modifier.PROTECTED; 1472 1473 /** A single-bit mask representing {@code package} access (default access), 1474 * which may contribute to the result of {@link #lookupModes lookupModes}. 1475 * The value is {@code 0x08}, which does not correspond meaningfully to 1476 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1477 */ 1478 public static final int PACKAGE = Modifier.STATIC; 1479 1480 /** A single-bit mask representing {@code module} access, 1481 * which may contribute to the result of {@link #lookupModes lookupModes}. 1482 * The value is {@code 0x10}, which does not correspond meaningfully to 1483 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1484 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1485 * with this lookup mode can access all public types in the module of the 1486 * lookup class and public types in packages exported by other modules 1487 * to the module of the lookup class. 1488 * <p> 1489 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1490 * previous lookup class} is always {@code null}. 1491 * 1492 * @since 9 1493 */ 1494 public static final int MODULE = PACKAGE << 1; 1495 1496 /** A single-bit mask representing {@code unconditional} access 1497 * which may contribute to the result of {@link #lookupModes lookupModes}. 1498 * The value is {@code 0x20}, which does not correspond meaningfully to 1499 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1500 * A {@code Lookup} with this lookup mode assumes {@linkplain 1501 * java.lang.Module#canRead(java.lang.Module) readability}. 1502 * This lookup mode can access all public members of public types 1503 * of all modules when the type is in a package that is {@link 1504 * java.lang.Module#isExported(String) exported unconditionally}. 1505 * 1506 * <p> 1507 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1508 * previous lookup class} is always {@code null}. 1509 * 1510 * @since 9 1511 * @see #publicLookup() 1512 */ 1513 public static final int UNCONDITIONAL = PACKAGE << 2; 1514 1515 /** A single-bit mask representing {@code original} access 1516 * which may contribute to the result of {@link #lookupModes lookupModes}. 1517 * The value is {@code 0x40}, which does not correspond meaningfully to 1518 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1519 * 1520 * <p> 1521 * If this lookup mode is set, the {@code Lookup} object must be 1522 * created by the original lookup class by calling 1523 * {@link MethodHandles#lookup()} method or by a bootstrap method 1524 * invoked by the VM. The {@code Lookup} object with this lookup 1525 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1526 * 1527 * @since 16 1528 */ 1529 public static final int ORIGINAL = PACKAGE << 3; 1530 1531 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1532 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1533 private static final int TRUSTED = -1; 1534 1535 /* 1536 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1537 * Adjust 0 => PACKAGE 1538 */ 1539 private static int fixmods(int mods) { 1540 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1541 if (Modifier.isPublic(mods)) 1542 mods |= UNCONDITIONAL; 1543 return (mods != 0) ? mods : PACKAGE; 1544 } 1545 1546 /** Tells which class is performing the lookup. It is this class against 1547 * which checks are performed for visibility and access permissions. 1548 * <p> 1549 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1550 * access checks are performed against both the lookup class and the previous lookup class. 1551 * <p> 1552 * The class implies a maximum level of access permission, 1553 * but the permissions may be additionally limited by the bitmask 1554 * {@link #lookupModes lookupModes}, which controls whether non-public members 1555 * can be accessed. 1556 * @return the lookup class, on behalf of which this lookup object finds members 1557 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1558 */ 1559 public Class<?> lookupClass() { 1560 return lookupClass; 1561 } 1562 1563 /** Reports a lookup class in another module that this lookup object 1564 * was previously teleported from, or {@code null}. 1565 * <p> 1566 * A {@code Lookup} object produced by the factory methods, such as the 1567 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1568 * has {@code null} previous lookup class. 1569 * A {@code Lookup} object has a non-null previous lookup class 1570 * when this lookup was teleported from an old lookup class 1571 * in one module to a new lookup class in another module. 1572 * 1573 * @return the lookup class in another module that this lookup object was 1574 * previously teleported from, or {@code null} 1575 * @since 14 1576 * @see #in(Class) 1577 * @see MethodHandles#privateLookupIn(Class, Lookup) 1578 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1579 */ 1580 public Class<?> previousLookupClass() { 1581 return prevLookupClass; 1582 } 1583 1584 // This is just for calling out to MethodHandleImpl. 1585 private Class<?> lookupClassOrNull() { 1586 return (allowedModes == TRUSTED) ? null : lookupClass; 1587 } 1588 1589 /** Tells which access-protection classes of members this lookup object can produce. 1590 * The result is a bit-mask of the bits 1591 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1592 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1593 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1594 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1595 * {@linkplain #MODULE MODULE (0x10)}, 1596 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1597 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1598 * <p> 1599 * A freshly-created lookup object 1600 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1601 * all possible bits set, except {@code UNCONDITIONAL}. 1602 * A lookup object on a new lookup class 1603 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1604 * may have some mode bits set to zero. 1605 * Mode bits can also be 1606 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1607 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1608 * The purpose of this is to restrict access via the new lookup object, 1609 * so that it can access only names which can be reached by the original 1610 * lookup object, and also by the new lookup class. 1611 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1612 * @see #in 1613 * @see #dropLookupMode 1614 */ 1615 public int lookupModes() { 1616 return allowedModes & ALL_MODES; 1617 } 1618 1619 /** Embody the current class (the lookupClass) as a lookup class 1620 * for method handle creation. 1621 * Must be called by from a method in this package, 1622 * which in turn is called by a method not in this package. 1623 */ 1624 Lookup(Class<?> lookupClass) { 1625 this(lookupClass, null, FULL_POWER_MODES); 1626 } 1627 1628 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1629 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1630 && prevLookupClass.getModule() != lookupClass.getModule()); 1631 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1632 this.lookupClass = lookupClass; 1633 this.prevLookupClass = prevLookupClass; 1634 this.allowedModes = allowedModes; 1635 } 1636 1637 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1638 // make sure we haven't accidentally picked up a privileged class: 1639 checkUnprivilegedlookupClass(lookupClass); 1640 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1641 } 1642 1643 /** 1644 * Creates a lookup on the specified new lookup class. 1645 * The resulting object will report the specified 1646 * class as its own {@link #lookupClass() lookupClass}. 1647 * 1648 * <p> 1649 * However, the resulting {@code Lookup} object is guaranteed 1650 * to have no more access capabilities than the original. 1651 * In particular, access capabilities can be lost as follows:<ul> 1652 * <li>If the new lookup class is different from the old lookup class, 1653 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1654 * <li>If the new lookup class is in a different module from the old one, 1655 * i.e. {@link #MODULE MODULE} access is lost. 1656 * <li>If the new lookup class is in a different package 1657 * than the old one, protected and default (package) members will not be accessible, 1658 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1659 * <li>If the new lookup class is not within the same package member 1660 * as the old one, private members will not be accessible, and protected members 1661 * will not be accessible by virtue of inheritance, 1662 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1663 * (Protected members may continue to be accessible because of package sharing.) 1664 * <li>If the new lookup class is not 1665 * {@linkplain #accessClass(Class) accessible} to this lookup, 1666 * then no members, not even public members, will be accessible 1667 * i.e. all access modes are lost. 1668 * <li>If the new lookup class, the old lookup class and the previous lookup class 1669 * are all in different modules i.e. teleporting to a third module, 1670 * all access modes are lost. 1671 * </ul> 1672 * <p> 1673 * The new previous lookup class is chosen as follows: 1674 * <ul> 1675 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1676 * the new previous lookup class is {@code null}. 1677 * <li>If the new lookup class is in the same module as the old lookup class, 1678 * the new previous lookup class is the old previous lookup class. 1679 * <li>If the new lookup class is in a different module from the old lookup class, 1680 * the new previous lookup class is the old lookup class. 1681 *</ul> 1682 * <p> 1683 * The resulting lookup's capabilities for loading classes 1684 * (used during {@link #findClass} invocations) 1685 * are determined by the lookup class' loader, 1686 * which may change due to this operation. 1687 * 1688 * @param requestedLookupClass the desired lookup class for the new lookup object 1689 * @return a lookup object which reports the desired lookup class, or the same object 1690 * if there is no change 1691 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1692 * @throws NullPointerException if the argument is null 1693 * 1694 * @see #accessClass(Class) 1695 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1696 */ 1697 public Lookup in(Class<?> requestedLookupClass) { 1698 Objects.requireNonNull(requestedLookupClass); 1699 if (requestedLookupClass.isPrimitive()) 1700 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1701 if (requestedLookupClass.isArray()) 1702 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1703 1704 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1705 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1706 if (requestedLookupClass == this.lookupClass) 1707 return this; // keep same capabilities 1708 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1709 Module fromModule = this.lookupClass.getModule(); 1710 Module targetModule = requestedLookupClass.getModule(); 1711 Class<?> plc = this.previousLookupClass(); 1712 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1713 assert plc == null; 1714 newModes = UNCONDITIONAL; 1715 } else if (fromModule != targetModule) { 1716 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1717 // allow hopping back and forth between fromModule and plc's module 1718 // but not the third module 1719 newModes = 0; 1720 } 1721 // drop MODULE access 1722 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1723 // teleport from this lookup class 1724 plc = this.lookupClass; 1725 } 1726 if ((newModes & PACKAGE) != 0 1727 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1728 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1729 } 1730 // Allow nestmate lookups to be created without special privilege: 1731 if ((newModes & PRIVATE) != 0 1732 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1733 newModes &= ~(PRIVATE|PROTECTED); 1734 } 1735 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1736 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1737 // The requested class it not accessible from the lookup class. 1738 // No permissions. 1739 newModes = 0; 1740 } 1741 return newLookup(requestedLookupClass, plc, newModes); 1742 } 1743 1744 /** 1745 * Creates a lookup on the same lookup class which this lookup object 1746 * finds members, but with a lookup mode that has lost the given lookup mode. 1747 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1748 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1749 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1750 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1751 * 1752 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1753 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1754 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1755 * lookup has no access. 1756 * 1757 * <p> If this lookup is not a public lookup, then the following applies 1758 * regardless of its {@linkplain #lookupModes() lookup modes}. 1759 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1760 * dropped and so the resulting lookup mode will never have these access 1761 * capabilities. When dropping {@code PACKAGE} 1762 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1763 * access. When dropping {@code MODULE} then the resulting lookup will not 1764 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1765 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1766 * 1767 * @apiNote 1768 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1769 * delegate non-public access within the package of the lookup class without 1770 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1771 * A lookup with {@code MODULE} but not 1772 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1773 * the module of the lookup class without conferring package access. 1774 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1775 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1776 * to public classes accessible to both the module of the lookup class 1777 * and the module of the previous lookup class. 1778 * 1779 * @param modeToDrop the lookup mode to drop 1780 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1781 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1782 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1783 * or {@code UNCONDITIONAL} 1784 * @see MethodHandles#privateLookupIn 1785 * @since 9 1786 */ 1787 public Lookup dropLookupMode(int modeToDrop) { 1788 int oldModes = lookupModes(); 1789 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1790 switch (modeToDrop) { 1791 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1792 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1793 case PACKAGE: newModes &= ~(PRIVATE); break; 1794 case PROTECTED: 1795 case PRIVATE: 1796 case ORIGINAL: 1797 case UNCONDITIONAL: break; 1798 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1799 } 1800 if (newModes == oldModes) return this; // return self if no change 1801 return newLookup(lookupClass(), previousLookupClass(), newModes); 1802 } 1803 1804 /** 1805 * Creates and links a class or interface from {@code bytes} 1806 * with the same class loader and in the same runtime package and 1807 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1808 * {@linkplain #lookupClass() lookup class} as if calling 1809 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1810 * ClassLoader::defineClass}. 1811 * 1812 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1813 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1814 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1815 * that the lookup object was created by a caller in the runtime package (or derived 1816 * from a lookup originally created by suitably privileged code to a target class in 1817 * the runtime package). </p> 1818 * 1819 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1820 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1821 * same package as the lookup class. </p> 1822 * 1823 * <p> This method does not run the class initializer. The class initializer may 1824 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1825 * Specification</em>. </p> 1826 * 1827 * <p> If there is a security manager and this lookup does not have {@linkplain 1828 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1829 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1830 * 1831 * @param bytes the class bytes 1832 * @return the {@code Class} object for the class 1833 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1834 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1835 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1836 * than the lookup class or {@code bytes} is not a class or interface 1837 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1838 * @throws VerifyError if the newly created class cannot be verified 1839 * @throws LinkageError if the newly created class cannot be linked for any other reason 1840 * @throws SecurityException if a security manager is present and it 1841 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1842 * @throws NullPointerException if {@code bytes} is {@code null} 1843 * @since 9 1844 * @see Lookup#privateLookupIn 1845 * @see Lookup#dropLookupMode 1846 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1847 */ 1848 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1849 ensureDefineClassPermission(); 1850 if ((lookupModes() & PACKAGE) == 0) 1851 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1852 return makeClassDefiner(bytes.clone()).defineClass(false); 1853 } 1854 1855 private void ensureDefineClassPermission() { 1856 if (allowedModes == TRUSTED) return; 1857 1858 if (!hasFullPrivilegeAccess()) { 1859 @SuppressWarnings("removal") 1860 SecurityManager sm = System.getSecurityManager(); 1861 if (sm != null) 1862 sm.checkPermission(new RuntimePermission("defineClass")); 1863 } 1864 } 1865 1866 /** 1867 * The set of class options that specify whether a hidden class created by 1868 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1869 * Lookup::defineHiddenClass} method is dynamically added as a new member 1870 * to the nest of a lookup class and/or whether a hidden class has 1871 * a strong relationship with the class loader marked as its defining loader. 1872 * 1873 * @since 15 1874 */ 1875 public enum ClassOption { 1876 /** 1877 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1878 * of a lookup class as a nestmate. 1879 * 1880 * <p> A hidden nestmate class has access to the private members of all 1881 * classes and interfaces in the same nest. 1882 * 1883 * @see Class#getNestHost() 1884 */ 1885 NESTMATE(NESTMATE_CLASS), 1886 1887 /** 1888 * Specifies that a hidden class has a <em>strong</em> 1889 * relationship with the class loader marked as its defining loader, 1890 * as a normal class or interface has with its own defining loader. 1891 * This means that the hidden class may be unloaded if and only if 1892 * its defining loader is not reachable and thus may be reclaimed 1893 * by a garbage collector (JLS {@jls 12.7}). 1894 * 1895 * <p> By default, a hidden class or interface may be unloaded 1896 * even if the class loader that is marked as its defining loader is 1897 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1898 1899 * 1900 * @jls 12.7 Unloading of Classes and Interfaces 1901 */ 1902 STRONG(STRONG_LOADER_LINK); 1903 1904 /* the flag value is used by VM at define class time */ 1905 private final int flag; 1906 ClassOption(int flag) { 1907 this.flag = flag; 1908 } 1909 1910 static int optionsToFlag(Set<ClassOption> options) { 1911 int flags = 0; 1912 for (ClassOption cp : options) { 1913 flags |= cp.flag; 1914 } 1915 return flags; 1916 } 1917 } 1918 1919 /** 1920 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1921 * returning a {@code Lookup} on the newly created class or interface. 1922 * 1923 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1924 * which either defines {@code C} directly or delegates to another class loader. 1925 * A class loader defines {@code C} directly by invoking 1926 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1927 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1928 * to derive {@code C} from a purported representation in {@code class} file format. 1929 * In situations where use of a class loader is undesirable, a class or interface 1930 * {@code C} can be created by this method instead. This method is capable of 1931 * defining {@code C}, and thereby creating it, without invoking 1932 * {@code ClassLoader::defineClass}. 1933 * Instead, this method defines {@code C} as if by arranging for 1934 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1935 * from a purported representation in {@code class} file format 1936 * using the following rules: 1937 * 1938 * <ol> 1939 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1940 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1941 * This level of access is needed to create {@code C} in the module 1942 * of the lookup class of this {@code Lookup}.</li> 1943 * 1944 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1945 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1946 * The major and minor version may differ from the {@code class} file version 1947 * of the lookup class of this {@code Lookup}.</li> 1948 * 1949 * <li> The value of {@code this_class} must be a valid index in the 1950 * {@code constant_pool} table, and the entry at that index must be a valid 1951 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1952 * encoded in internal form that is specified by this structure. {@code N} must 1953 * denote a class or interface in the same package as the lookup class.</li> 1954 * 1955 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1956 * where {@code <suffix>} is an unqualified name. 1957 * 1958 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1959 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1960 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1961 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1962 * refers to the new {@code CONSTANT_Utf8_info} structure. 1963 * 1964 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1965 * 1966 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1967 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1968 * with the following adjustments: 1969 * <ul> 1970 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1971 * that includes a single {@code "."} character, even though this is not a valid 1972 * binary class or interface name in internal form.</li> 1973 * 1974 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1975 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1976 * 1977 * <li> {@code C} is considered to have the same runtime 1978 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1979 * and {@linkplain java.security.ProtectionDomain protection domain} 1980 * as the lookup class of this {@code Lookup}. 1981 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1982 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1983 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1984 * <ul> 1985 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1986 * even though this is not a valid binary class or interface name.</li> 1987 * <li> {@link Class#descriptorString()} returns the string 1988 * {@code "L" + N + "." + <suffix> + ";"}, 1989 * even though this is not a valid type descriptor name.</li> 1990 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1991 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1992 * </ul> 1993 * </ul> 1994 * </li> 1995 * </ol> 1996 * 1997 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1998 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1999 * <ul> 2000 * <li> During verification, whenever it is necessary to load the class named 2001 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2002 * made of any class loader.</li> 2003 * 2004 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2005 * by {@code this_class}, the symbolic reference is considered to be resolved to 2006 * {@code C} and resolution always succeeds immediately.</li> 2007 * </ul> 2008 * 2009 * <p> If the {@code initialize} parameter is {@code true}, 2010 * then {@code C} is initialized by the Java Virtual Machine. 2011 * 2012 * <p> The newly created class or interface {@code C} serves as the 2013 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2014 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2015 * no other class or interface can refer to {@code C} via a constant pool entry. 2016 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2017 * a method parameter type, or a method return type by any other class. 2018 * This is because a hidden class or interface does not have a binary name, so 2019 * there is no internal form available to record in any class's constant pool. 2020 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2021 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2022 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2023 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2024 * JVM Tool Interface</a>. 2025 * 2026 * <p> A class or interface created by 2027 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2028 * a class loader} has a strong relationship with that class loader. 2029 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2030 * that {@linkplain Class#getClassLoader() defined it}. 2031 * This means that a class created by a class loader may be unloaded if and 2032 * only if its defining loader is not reachable and thus may be reclaimed 2033 * by a garbage collector (JLS {@jls 12.7}). 2034 * 2035 * By default, however, a hidden class or interface may be unloaded even if 2036 * the class loader that is marked as its defining loader is 2037 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2038 * This behavior is useful when a hidden class or interface serves multiple 2039 * classes defined by arbitrary class loaders. In other cases, a hidden 2040 * class or interface may be linked to a single class (or a small number of classes) 2041 * with the same defining loader as the hidden class or interface. 2042 * In such cases, where the hidden class or interface must be coterminous 2043 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2044 * option may be passed in {@code options}. 2045 * This arranges for a hidden class to have the same strong relationship 2046 * with the class loader marked as its defining loader, 2047 * as a normal class or interface has with its own defining loader. 2048 * 2049 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2050 * may still prevent a hidden class or interface from being 2051 * unloaded by ensuring that the {@code Class} object is reachable. 2052 * 2053 * <p> The unloading characteristics are set for each hidden class when it is 2054 * defined, and cannot be changed later. An advantage of allowing hidden classes 2055 * to be unloaded independently of the class loader marked as their defining loader 2056 * is that a very large number of hidden classes may be created by an application. 2057 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2058 * just as if normal classes were created by class loaders. 2059 * 2060 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2061 * their private members. The nest relationship is determined by 2062 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2063 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2064 * By default, a hidden class belongs to a nest consisting only of itself 2065 * because a hidden class has no binary name. 2066 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2067 * to create a hidden class or interface {@code C} as a member of a nest. 2068 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2069 * in the {@code ClassFile} structure from which {@code C} was derived. 2070 * Instead, the following rules determine the nest host of {@code C}: 2071 * <ul> 2072 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2073 * been determined, then let {@code H} be the nest host of the lookup class. 2074 * Otherwise, the nest host of the lookup class is determined using the 2075 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2076 * <li>The nest host of {@code C} is determined to be {@code H}, 2077 * the nest host of the lookup class.</li> 2078 * </ul> 2079 * 2080 * <p> A hidden class or interface may be serializable, but this requires a custom 2081 * serialization mechanism in order to ensure that instances are properly serialized 2082 * and deserialized. The default serialization mechanism supports only classes and 2083 * interfaces that are discoverable by their class name. 2084 * 2085 * @param bytes the bytes that make up the class data, 2086 * in the format of a valid {@code class} file as defined by 2087 * <cite>The Java Virtual Machine Specification</cite>. 2088 * @param initialize if {@code true} the class will be initialized. 2089 * @param options {@linkplain ClassOption class options} 2090 * @return the {@code Lookup} object on the hidden class, 2091 * with {@linkplain #ORIGINAL original} and 2092 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2093 * 2094 * @throws IllegalAccessException if this {@code Lookup} does not have 2095 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2096 * @throws SecurityException if a security manager is present and it 2097 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2098 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2099 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2100 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2101 * than the lookup class or {@code bytes} is not a class or interface 2102 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2103 * @throws IncompatibleClassChangeError if the class or interface named as 2104 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2105 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2106 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2107 * {@code C} is {@code C} itself 2108 * @throws VerifyError if the newly created class cannot be verified 2109 * @throws LinkageError if the newly created class cannot be linked for any other reason 2110 * @throws NullPointerException if any parameter is {@code null} 2111 * 2112 * @since 15 2113 * @see Class#isHidden() 2114 * @jvms 4.2.1 Binary Class and Interface Names 2115 * @jvms 4.2.2 Unqualified Names 2116 * @jvms 4.7.28 The {@code NestHost} Attribute 2117 * @jvms 4.7.29 The {@code NestMembers} Attribute 2118 * @jvms 5.4.3.1 Class and Interface Resolution 2119 * @jvms 5.4.4 Access Control 2120 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2121 * @jvms 5.4 Linking 2122 * @jvms 5.5 Initialization 2123 * @jls 12.7 Unloading of Classes and Interfaces 2124 */ 2125 @SuppressWarnings("doclint:reference") // cross-module links 2126 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2127 throws IllegalAccessException 2128 { 2129 Objects.requireNonNull(bytes); 2130 Objects.requireNonNull(options); 2131 2132 ensureDefineClassPermission(); 2133 if (!hasFullPrivilegeAccess()) { 2134 throw new IllegalAccessException(this + " does not have full privilege access"); 2135 } 2136 2137 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize); 2138 } 2139 2140 /** 2141 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2142 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2143 * returning a {@code Lookup} on the newly created class or interface. 2144 * 2145 * <p> This method is equivalent to calling 2146 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2147 * as if the hidden class is injected with a private static final <i>unnamed</i> 2148 * field which is initialized with the given {@code classData} at 2149 * the first instruction of the class initializer. 2150 * The newly created class is linked by the Java Virtual Machine. 2151 * 2152 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2153 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2154 * methods can be used to retrieve the {@code classData}. 2155 * 2156 * @apiNote 2157 * A framework can create a hidden class with class data with one or more 2158 * objects and load the class data as dynamically-computed constant(s) 2159 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2160 * Class data} is accessible only to the lookup object created by the newly 2161 * defined hidden class but inaccessible to other members in the same nest 2162 * (unlike private static fields that are accessible to nestmates). 2163 * Care should be taken w.r.t. mutability for example when passing 2164 * an array or other mutable structure through the class data. 2165 * Changing any value stored in the class data at runtime may lead to 2166 * unpredictable behavior. 2167 * If the class data is a {@code List}, it is good practice to make it 2168 * unmodifiable for example via {@link List#of List::of}. 2169 * 2170 * @param bytes the class bytes 2171 * @param classData pre-initialized class data 2172 * @param initialize if {@code true} the class will be initialized. 2173 * @param options {@linkplain ClassOption class options} 2174 * @return the {@code Lookup} object on the hidden class, 2175 * with {@linkplain #ORIGINAL original} and 2176 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2177 * 2178 * @throws IllegalAccessException if this {@code Lookup} does not have 2179 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2180 * @throws SecurityException if a security manager is present and it 2181 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2182 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2183 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2184 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2185 * than the lookup class or {@code bytes} is not a class or interface 2186 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2187 * @throws IncompatibleClassChangeError if the class or interface named as 2188 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2189 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2190 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2191 * {@code C} is {@code C} itself 2192 * @throws VerifyError if the newly created class cannot be verified 2193 * @throws LinkageError if the newly created class cannot be linked for any other reason 2194 * @throws NullPointerException if any parameter is {@code null} 2195 * 2196 * @since 16 2197 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2198 * @see Class#isHidden() 2199 * @see MethodHandles#classData(Lookup, String, Class) 2200 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2201 * @jvms 4.2.1 Binary Class and Interface Names 2202 * @jvms 4.2.2 Unqualified Names 2203 * @jvms 4.7.28 The {@code NestHost} Attribute 2204 * @jvms 4.7.29 The {@code NestMembers} Attribute 2205 * @jvms 5.4.3.1 Class and Interface Resolution 2206 * @jvms 5.4.4 Access Control 2207 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2208 * @jvms 5.4 Linking 2209 * @jvms 5.5 Initialization 2210 * @jls 12.7 Unloading of Classes and Interface 2211 */ 2212 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2213 throws IllegalAccessException 2214 { 2215 Objects.requireNonNull(bytes); 2216 Objects.requireNonNull(classData); 2217 Objects.requireNonNull(options); 2218 2219 ensureDefineClassPermission(); 2220 if (!hasFullPrivilegeAccess()) { 2221 throw new IllegalAccessException(this + " does not have full privilege access"); 2222 } 2223 2224 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false) 2225 .defineClassAsLookup(initialize, classData); 2226 } 2227 2228 // A default dumper for writing class files passed to Lookup::defineClass 2229 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2230 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2231 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2232 // 2233 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2234 // and LambdaForms and method handle internals. They are dumped via 2235 // different ClassFileDumpers. 2236 private static ClassFileDumper defaultDumper() { 2237 return DEFAULT_DUMPER; 2238 } 2239 2240 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2241 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2242 2243 static class ClassFile { 2244 final String name; // internal name 2245 final int accessFlags; 2246 final byte[] bytes; 2247 ClassFile(String name, int accessFlags, byte[] bytes) { 2248 this.name = name; 2249 this.accessFlags = accessFlags; 2250 this.bytes = bytes; 2251 } 2252 2253 static ClassFile newInstanceNoCheck(String name, byte[] bytes) { 2254 return new ClassFile(name, 0, bytes); 2255 } 2256 2257 /** 2258 * This method checks the class file version and the structure of `this_class`. 2259 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2260 * that is in the named package. 2261 * 2262 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2263 * or the class is not in the given package name. 2264 */ 2265 static ClassFile newInstance(byte[] bytes, String pkgName) { 2266 var cf = readClassFile(bytes); 2267 2268 // check if it's in the named package 2269 int index = cf.name.lastIndexOf('/'); 2270 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.'); 2271 if (!pn.equals(pkgName)) { 2272 throw newIllegalArgumentException(cf.name + " not in same package as lookup class"); 2273 } 2274 return cf; 2275 } 2276 2277 private static ClassFile readClassFile(byte[] bytes) { 2278 int magic = readInt(bytes, 0); 2279 if (magic != 0xCAFEBABE) { 2280 throw new ClassFormatError("Incompatible magic value: " + magic); 2281 } 2282 int minor = readUnsignedShort(bytes, 4); 2283 int major = readUnsignedShort(bytes, 6); 2284 if (!VM.isSupportedClassFileVersion(major, minor)) { 2285 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2286 } 2287 2288 String name; 2289 int accessFlags; 2290 try { 2291 ClassReader reader = new ClassReader(bytes); 2292 // ClassReader does not check if `this_class` is CONSTANT_Class_info 2293 // workaround to read `this_class` using readConst and validate the value 2294 int thisClass = reader.readUnsignedShort(reader.header + 2); 2295 Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]); 2296 if (!(constant instanceof Type type)) { 2297 throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info"); 2298 } 2299 if (!type.getDescriptor().startsWith("L")) { 2300 throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info"); 2301 } 2302 name = type.getInternalName(); 2303 accessFlags = reader.readUnsignedShort(reader.header); 2304 } catch (RuntimeException e) { 2305 // ASM exceptions are poorly specified 2306 ClassFormatError cfe = new ClassFormatError(); 2307 cfe.initCause(e); 2308 throw cfe; 2309 } 2310 // must be a class or interface 2311 if ((accessFlags & Opcodes.ACC_MODULE) != 0) { 2312 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2313 } 2314 return new ClassFile(name, accessFlags, bytes); 2315 } 2316 2317 private static int readInt(byte[] bytes, int offset) { 2318 if ((offset+4) > bytes.length) { 2319 throw new ClassFormatError("Invalid ClassFile structure"); 2320 } 2321 return ((bytes[offset] & 0xFF) << 24) 2322 | ((bytes[offset + 1] & 0xFF) << 16) 2323 | ((bytes[offset + 2] & 0xFF) << 8) 2324 | (bytes[offset + 3] & 0xFF); 2325 } 2326 2327 private static int readUnsignedShort(byte[] bytes, int offset) { 2328 if ((offset+2) > bytes.length) { 2329 throw new ClassFormatError("Invalid ClassFile structure"); 2330 } 2331 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2332 } 2333 } 2334 2335 /* 2336 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2337 * from the given bytes. 2338 * 2339 * Caller should make a defensive copy of the arguments if needed 2340 * before calling this factory method. 2341 * 2342 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2343 * {@code bytes} denotes a class in a different package than the lookup class 2344 */ 2345 private ClassDefiner makeClassDefiner(byte[] bytes) { 2346 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2347 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper()); 2348 } 2349 2350 /** 2351 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2352 * from the given bytes. No package name check on the given bytes. 2353 * 2354 * @param name internal name 2355 * @param bytes class bytes 2356 * @param dumper dumper to write the given bytes to the dumper's output directory 2357 * @return ClassDefiner that defines a normal class of the given bytes. 2358 */ 2359 ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) { 2360 // skip package name validation 2361 ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes); 2362 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper); 2363 } 2364 2365 /** 2366 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2367 * from the given bytes. The name must be in the same package as the lookup class. 2368 * 2369 * Caller should make a defensive copy of the arguments if needed 2370 * before calling this factory method. 2371 * 2372 * @param bytes class bytes 2373 * @param dumper dumper to write the given bytes to the dumper's output directory 2374 * @return ClassDefiner that defines a hidden class of the given bytes. 2375 * 2376 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2377 * {@code bytes} denotes a class in a different package than the lookup class 2378 */ 2379 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2380 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2381 return makeHiddenClassDefiner(cf, Set.of(), false, dumper); 2382 } 2383 2384 /** 2385 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2386 * from the given bytes and options. 2387 * The name must be in the same package as the lookup class. 2388 * 2389 * Caller should make a defensive copy of the arguments if needed 2390 * before calling this factory method. 2391 * 2392 * @param bytes class bytes 2393 * @param options class options 2394 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2395 * @return ClassDefiner that defines a hidden class of the given bytes and options 2396 * 2397 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2398 * {@code bytes} denotes a class in a different package than the lookup class 2399 */ 2400 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2401 Set<ClassOption> options, 2402 boolean accessVmAnnotations) { 2403 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2404 return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper()); 2405 } 2406 2407 /** 2408 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2409 * from the given bytes and the given options. No package name check on the given bytes. 2410 * 2411 * @param name internal name that specifies the prefix of the hidden class 2412 * @param bytes class bytes 2413 * @param options class options 2414 * @param dumper dumper to write the given bytes to the dumper's output directory 2415 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2416 */ 2417 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) { 2418 Objects.requireNonNull(dumper); 2419 // skip name and access flags validation 2420 return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper); 2421 } 2422 2423 /** 2424 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2425 * from the given class file and options. 2426 * 2427 * @param cf ClassFile 2428 * @param options class options 2429 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2430 * @param dumper dumper to write the given bytes to the dumper's output directory 2431 */ 2432 private ClassDefiner makeHiddenClassDefiner(ClassFile cf, 2433 Set<ClassOption> options, 2434 boolean accessVmAnnotations, 2435 ClassFileDumper dumper) { 2436 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options); 2437 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2438 // jdk.internal.vm.annotations are permitted for classes 2439 // defined to boot loader and platform loader 2440 flags |= ACCESS_VM_ANNOTATIONS; 2441 } 2442 2443 return new ClassDefiner(this, cf, flags, dumper); 2444 } 2445 2446 static class ClassDefiner { 2447 private final Lookup lookup; 2448 private final String name; // internal name 2449 private final byte[] bytes; 2450 private final int classFlags; 2451 private final ClassFileDumper dumper; 2452 2453 private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) { 2454 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2455 this.lookup = lookup; 2456 this.bytes = cf.bytes; 2457 this.name = cf.name; 2458 this.classFlags = flags; 2459 this.dumper = dumper; 2460 } 2461 2462 String internalName() { 2463 return name; 2464 } 2465 2466 Class<?> defineClass(boolean initialize) { 2467 return defineClass(initialize, null); 2468 } 2469 2470 Lookup defineClassAsLookup(boolean initialize) { 2471 Class<?> c = defineClass(initialize, null); 2472 return new Lookup(c, null, FULL_POWER_MODES); 2473 } 2474 2475 /** 2476 * Defines the class of the given bytes and the given classData. 2477 * If {@code initialize} parameter is true, then the class will be initialized. 2478 * 2479 * @param initialize true if the class to be initialized 2480 * @param classData classData or null 2481 * @return the class 2482 * 2483 * @throws LinkageError linkage error 2484 */ 2485 Class<?> defineClass(boolean initialize, Object classData) { 2486 Class<?> lookupClass = lookup.lookupClass(); 2487 ClassLoader loader = lookupClass.getClassLoader(); 2488 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2489 Class<?> c = null; 2490 try { 2491 c = SharedSecrets.getJavaLangAccess() 2492 .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData); 2493 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2494 return c; 2495 } finally { 2496 // dump the classfile for debugging 2497 if (dumper.isEnabled()) { 2498 String name = internalName(); 2499 if (c != null) { 2500 dumper.dumpClass(name, c, bytes); 2501 } else { 2502 dumper.dumpFailedClass(name, bytes); 2503 } 2504 } 2505 } 2506 } 2507 2508 /** 2509 * Defines the class of the given bytes and the given classData. 2510 * If {@code initialize} parameter is true, then the class will be initialized. 2511 * 2512 * @param initialize true if the class to be initialized 2513 * @param classData classData or null 2514 * @return a Lookup for the defined class 2515 * 2516 * @throws LinkageError linkage error 2517 */ 2518 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2519 Class<?> c = defineClass(initialize, classData); 2520 return new Lookup(c, null, FULL_POWER_MODES); 2521 } 2522 2523 private boolean isNestmate() { 2524 return (classFlags & NESTMATE_CLASS) != 0; 2525 } 2526 } 2527 2528 private ProtectionDomain lookupClassProtectionDomain() { 2529 ProtectionDomain pd = cachedProtectionDomain; 2530 if (pd == null) { 2531 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2532 } 2533 return pd; 2534 } 2535 2536 // cached protection domain 2537 private volatile ProtectionDomain cachedProtectionDomain; 2538 2539 // Make sure outer class is initialized first. 2540 static { IMPL_NAMES.getClass(); } 2541 2542 /** Package-private version of lookup which is trusted. */ 2543 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2544 2545 /** Version of lookup which is trusted minimally. 2546 * It can only be used to create method handles to publicly accessible 2547 * members in packages that are exported unconditionally. 2548 */ 2549 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2550 2551 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2552 String name = lookupClass.getName(); 2553 if (name.startsWith("java.lang.invoke.")) 2554 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2555 } 2556 2557 /** 2558 * Displays the name of the class from which lookups are to be made, 2559 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2560 * previous lookup class} if present. 2561 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2562 * If there are restrictions on the access permitted to this lookup, 2563 * this is indicated by adding a suffix to the class name, consisting 2564 * of a slash and a keyword. The keyword represents the strongest 2565 * allowed access, and is chosen as follows: 2566 * <ul> 2567 * <li>If no access is allowed, the suffix is "/noaccess". 2568 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2569 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2570 * <li>If only public and module access are allowed, the suffix is "/module". 2571 * <li>If public and package access are allowed, the suffix is "/package". 2572 * <li>If public, package, and private access are allowed, the suffix is "/private". 2573 * </ul> 2574 * If none of the above cases apply, it is the case that 2575 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2576 * (public, module, package, private, and protected) is allowed. 2577 * In this case, no suffix is added. 2578 * This is true only of an object obtained originally from 2579 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2580 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2581 * always have restricted access, and will display a suffix. 2582 * <p> 2583 * (It may seem strange that protected access should be 2584 * stronger than private access. Viewed independently from 2585 * package access, protected access is the first to be lost, 2586 * because it requires a direct subclass relationship between 2587 * caller and callee.) 2588 * @see #in 2589 */ 2590 @Override 2591 public String toString() { 2592 String cname = lookupClass.getName(); 2593 if (prevLookupClass != null) 2594 cname += "/" + prevLookupClass.getName(); 2595 switch (allowedModes) { 2596 case 0: // no privileges 2597 return cname + "/noaccess"; 2598 case UNCONDITIONAL: 2599 return cname + "/publicLookup"; 2600 case PUBLIC: 2601 return cname + "/public"; 2602 case PUBLIC|MODULE: 2603 return cname + "/module"; 2604 case PUBLIC|PACKAGE: 2605 case PUBLIC|MODULE|PACKAGE: 2606 return cname + "/package"; 2607 case PUBLIC|PACKAGE|PRIVATE: 2608 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2609 return cname + "/private"; 2610 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2611 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2612 case FULL_POWER_MODES: 2613 return cname; 2614 case TRUSTED: 2615 return "/trusted"; // internal only; not exported 2616 default: // Should not happen, but it's a bitfield... 2617 cname = cname + "/" + Integer.toHexString(allowedModes); 2618 assert(false) : cname; 2619 return cname; 2620 } 2621 } 2622 2623 /** 2624 * Produces a method handle for a static method. 2625 * The type of the method handle will be that of the method. 2626 * (Since static methods do not take receivers, there is no 2627 * additional receiver argument inserted into the method handle type, 2628 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2629 * The method and all its argument types must be accessible to the lookup object. 2630 * <p> 2631 * The returned method handle will have 2632 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2633 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2634 * <p> 2635 * If the returned method handle is invoked, the method's class will 2636 * be initialized, if it has not already been initialized. 2637 * <p><b>Example:</b> 2638 * {@snippet lang="java" : 2639 import static java.lang.invoke.MethodHandles.*; 2640 import static java.lang.invoke.MethodType.*; 2641 ... 2642 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2643 "asList", methodType(List.class, Object[].class)); 2644 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2645 * } 2646 * @param refc the class from which the method is accessed 2647 * @param name the name of the method 2648 * @param type the type of the method 2649 * @return the desired method handle 2650 * @throws NoSuchMethodException if the method does not exist 2651 * @throws IllegalAccessException if access checking fails, 2652 * or if the method is not {@code static}, 2653 * or if the method's variable arity modifier bit 2654 * is set and {@code asVarargsCollector} fails 2655 * @throws SecurityException if a security manager is present and it 2656 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2657 * @throws NullPointerException if any argument is null 2658 */ 2659 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2660 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2661 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2662 } 2663 2664 /** 2665 * Produces a method handle for a virtual method. 2666 * The type of the method handle will be that of the method, 2667 * with the receiver type (usually {@code refc}) prepended. 2668 * The method and all its argument types must be accessible to the lookup object. 2669 * <p> 2670 * When called, the handle will treat the first argument as a receiver 2671 * and, for non-private methods, dispatch on the receiver's type to determine which method 2672 * implementation to enter. 2673 * For private methods the named method in {@code refc} will be invoked on the receiver. 2674 * (The dispatching action is identical with that performed by an 2675 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2676 * <p> 2677 * The first argument will be of type {@code refc} if the lookup 2678 * class has full privileges to access the member. Otherwise 2679 * the member must be {@code protected} and the first argument 2680 * will be restricted in type to the lookup class. 2681 * <p> 2682 * The returned method handle will have 2683 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2684 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2685 * <p> 2686 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2687 * instructions and method handles produced by {@code findVirtual}, 2688 * if the class is {@code MethodHandle} and the name string is 2689 * {@code invokeExact} or {@code invoke}, the resulting 2690 * method handle is equivalent to one produced by 2691 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2692 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2693 * with the same {@code type} argument. 2694 * <p> 2695 * If the class is {@code VarHandle} and the name string corresponds to 2696 * the name of a signature-polymorphic access mode method, the resulting 2697 * method handle is equivalent to one produced by 2698 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2699 * the access mode corresponding to the name string and with the same 2700 * {@code type} arguments. 2701 * <p> 2702 * <b>Example:</b> 2703 * {@snippet lang="java" : 2704 import static java.lang.invoke.MethodHandles.*; 2705 import static java.lang.invoke.MethodType.*; 2706 ... 2707 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2708 "concat", methodType(String.class, String.class)); 2709 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2710 "hashCode", methodType(int.class)); 2711 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2712 "hashCode", methodType(int.class)); 2713 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2714 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2715 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2716 // interface method: 2717 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2718 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2719 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2720 // constructor "internal method" must be accessed differently: 2721 MethodType MT_newString = methodType(void.class); //()V for new String() 2722 try { assertEquals("impossible", lookup() 2723 .findVirtual(String.class, "<init>", MT_newString)); 2724 } catch (NoSuchMethodException ex) { } // OK 2725 MethodHandle MH_newString = publicLookup() 2726 .findConstructor(String.class, MT_newString); 2727 assertEquals("", (String) MH_newString.invokeExact()); 2728 * } 2729 * 2730 * @param refc the class or interface from which the method is accessed 2731 * @param name the name of the method 2732 * @param type the type of the method, with the receiver argument omitted 2733 * @return the desired method handle 2734 * @throws NoSuchMethodException if the method does not exist 2735 * @throws IllegalAccessException if access checking fails, 2736 * or if the method is {@code static}, 2737 * or if the method's variable arity modifier bit 2738 * is set and {@code asVarargsCollector} fails 2739 * @throws SecurityException if a security manager is present and it 2740 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2741 * @throws NullPointerException if any argument is null 2742 */ 2743 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2744 if (refc == MethodHandle.class) { 2745 MethodHandle mh = findVirtualForMH(name, type); 2746 if (mh != null) return mh; 2747 } else if (refc == VarHandle.class) { 2748 MethodHandle mh = findVirtualForVH(name, type); 2749 if (mh != null) return mh; 2750 } 2751 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2752 MemberName method = resolveOrFail(refKind, refc, name, type); 2753 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2754 } 2755 private MethodHandle findVirtualForMH(String name, MethodType type) { 2756 // these names require special lookups because of the implicit MethodType argument 2757 if ("invoke".equals(name)) 2758 return invoker(type); 2759 if ("invokeExact".equals(name)) 2760 return exactInvoker(type); 2761 assert(!MemberName.isMethodHandleInvokeName(name)); 2762 return null; 2763 } 2764 private MethodHandle findVirtualForVH(String name, MethodType type) { 2765 try { 2766 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2767 } catch (IllegalArgumentException e) { 2768 return null; 2769 } 2770 } 2771 2772 /** 2773 * Produces a method handle which creates an object and initializes it, using 2774 * the constructor of the specified type. 2775 * The parameter types of the method handle will be those of the constructor, 2776 * while the return type will be a reference to the constructor's class. 2777 * The constructor and all its argument types must be accessible to the lookup object. 2778 * <p> 2779 * The requested type must have a return type of {@code void}. 2780 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2781 * <p> 2782 * The returned method handle will have 2783 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2784 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2785 * <p> 2786 * If the returned method handle is invoked, the constructor's class will 2787 * be initialized, if it has not already been initialized. 2788 * <p><b>Example:</b> 2789 * {@snippet lang="java" : 2790 import static java.lang.invoke.MethodHandles.*; 2791 import static java.lang.invoke.MethodType.*; 2792 ... 2793 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2794 ArrayList.class, methodType(void.class, Collection.class)); 2795 Collection orig = Arrays.asList("x", "y"); 2796 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2797 assert(orig != copy); 2798 assertEquals(orig, copy); 2799 // a variable-arity constructor: 2800 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2801 ProcessBuilder.class, methodType(void.class, String[].class)); 2802 ProcessBuilder pb = (ProcessBuilder) 2803 MH_newProcessBuilder.invoke("x", "y", "z"); 2804 assertEquals("[x, y, z]", pb.command().toString()); 2805 * } 2806 * @param refc the class or interface from which the method is accessed 2807 * @param type the type of the method, with the receiver argument omitted, and a void return type 2808 * @return the desired method handle 2809 * @throws NoSuchMethodException if the constructor does not exist 2810 * @throws IllegalAccessException if access checking fails 2811 * or if the method's variable arity modifier bit 2812 * is set and {@code asVarargsCollector} fails 2813 * @throws SecurityException if a security manager is present and it 2814 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2815 * @throws NullPointerException if any argument is null 2816 */ 2817 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2818 if (refc.isArray()) { 2819 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2820 } 2821 String name = ConstantDescs.INIT_NAME; 2822 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2823 return getDirectConstructor(refc, ctor); 2824 } 2825 2826 /** 2827 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2828 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2829 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2830 * and then determines whether the class is accessible to this lookup object. 2831 * <p> 2832 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2833 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2834 * of {@code '['} and followed by the element type as encoded in the 2835 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2836 * <p> 2837 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2838 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2839 * 2840 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2841 * or the string representing an array class 2842 * @return the requested class. 2843 * @throws SecurityException if a security manager is present and it 2844 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2845 * @throws LinkageError if the linkage fails 2846 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2847 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2848 * modes. 2849 * @throws NullPointerException if {@code targetName} is null 2850 * @since 9 2851 * @jvms 5.4.3.1 Class and Interface Resolution 2852 */ 2853 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2854 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2855 return accessClass(targetClass); 2856 } 2857 2858 /** 2859 * Ensures that {@code targetClass} has been initialized. The class 2860 * to be initialized must be {@linkplain #accessClass accessible} 2861 * to this {@code Lookup} object. This method causes {@code targetClass} 2862 * to be initialized if it has not been already initialized, 2863 * as specified in JVMS {@jvms 5.5}. 2864 * 2865 * <p> 2866 * This method returns when {@code targetClass} is fully initialized, or 2867 * when {@code targetClass} is being initialized by the current thread. 2868 * 2869 * @param <T> the type of the class to be initialized 2870 * @param targetClass the class to be initialized 2871 * @return {@code targetClass} that has been initialized, or that is being 2872 * initialized by the current thread. 2873 * 2874 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2875 * or array class 2876 * @throws IllegalAccessException if {@code targetClass} is not 2877 * {@linkplain #accessClass accessible} to this lookup 2878 * @throws ExceptionInInitializerError if the class initialization provoked 2879 * by this method fails 2880 * @throws SecurityException if a security manager is present and it 2881 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2882 * @since 15 2883 * @jvms 5.5 Initialization 2884 */ 2885 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2886 if (targetClass.isPrimitive()) 2887 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2888 if (targetClass.isArray()) 2889 throw new IllegalArgumentException(targetClass + " is an array class"); 2890 2891 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2892 throw makeAccessException(targetClass); 2893 } 2894 checkSecurityManager(targetClass); 2895 2896 // ensure class initialization 2897 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2898 return targetClass; 2899 } 2900 2901 /* 2902 * Returns IllegalAccessException due to access violation to the given targetClass. 2903 * 2904 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2905 * which verifies access to a class rather a member. 2906 */ 2907 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2908 String message = "access violation: "+ targetClass; 2909 if (this == MethodHandles.publicLookup()) { 2910 message += ", from public Lookup"; 2911 } else { 2912 Module m = lookupClass().getModule(); 2913 message += ", from " + lookupClass() + " (" + m + ")"; 2914 if (prevLookupClass != null) { 2915 message += ", previous lookup " + 2916 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2917 } 2918 } 2919 return new IllegalAccessException(message); 2920 } 2921 2922 /** 2923 * Determines if a class can be accessed from the lookup context defined by 2924 * this {@code Lookup} object. The static initializer of the class is not run. 2925 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2926 * if the element type of the array class is accessible. Otherwise, 2927 * {@code targetClass} is determined as accessible as follows. 2928 * 2929 * <p> 2930 * If {@code targetClass} is in the same module as the lookup class, 2931 * the lookup class is {@code LC} in module {@code M1} and 2932 * the previous lookup class is in module {@code M0} or 2933 * {@code null} if not present, 2934 * {@code targetClass} is accessible if and only if one of the following is true: 2935 * <ul> 2936 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2937 * {@code LC} or other class in the same nest of {@code LC}.</li> 2938 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2939 * in the same runtime package of {@code LC}.</li> 2940 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2941 * a public type in {@code M1}.</li> 2942 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2943 * a public type in a package exported by {@code M1} to at least {@code M0} 2944 * if the previous lookup class is present; otherwise, {@code targetClass} 2945 * is a public type in a package exported by {@code M1} unconditionally.</li> 2946 * </ul> 2947 * 2948 * <p> 2949 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2950 * can access public types in all modules when the type is in a package 2951 * that is exported unconditionally. 2952 * <p> 2953 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2954 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2955 * is inaccessible. 2956 * <p> 2957 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2958 * {@code M1} is the module containing {@code lookupClass} and 2959 * {@code M2} is the module containing {@code targetClass}, 2960 * then {@code targetClass} is accessible if and only if 2961 * <ul> 2962 * <li>{@code M1} reads {@code M2}, and 2963 * <li>{@code targetClass} is public and in a package exported by 2964 * {@code M2} at least to {@code M1}. 2965 * </ul> 2966 * <p> 2967 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2968 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2969 * containing the previous lookup class, then {@code targetClass} is accessible 2970 * if and only if one of the following is true: 2971 * <ul> 2972 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2973 * {@linkplain Module#reads reads} {@code M0} and the type is 2974 * in a package that is exported to at least {@code M1}. 2975 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2976 * {@linkplain Module#reads reads} {@code M1} and the type is 2977 * in a package that is exported to at least {@code M0}. 2978 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2979 * and {@code M1} reads {@code M2} and the type is in a package 2980 * that is exported to at least both {@code M0} and {@code M2}. 2981 * </ul> 2982 * <p> 2983 * Otherwise, {@code targetClass} is not accessible. 2984 * 2985 * @param <T> the type of the class to be access-checked 2986 * @param targetClass the class to be access-checked 2987 * @return {@code targetClass} that has been access-checked 2988 * @throws IllegalAccessException if the class is not accessible from the lookup class 2989 * and previous lookup class, if present, using the allowed access modes. 2990 * @throws SecurityException if a security manager is present and it 2991 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2992 * @throws NullPointerException if {@code targetClass} is {@code null} 2993 * @since 9 2994 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2995 */ 2996 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2997 if (!isClassAccessible(targetClass)) { 2998 throw makeAccessException(targetClass); 2999 } 3000 checkSecurityManager(targetClass); 3001 return targetClass; 3002 } 3003 3004 /** 3005 * Produces an early-bound method handle for a virtual method. 3006 * It will bypass checks for overriding methods on the receiver, 3007 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3008 * instruction from within the explicitly specified {@code specialCaller}. 3009 * The type of the method handle will be that of the method, 3010 * with a suitably restricted receiver type prepended. 3011 * (The receiver type will be {@code specialCaller} or a subtype.) 3012 * The method and all its argument types must be accessible 3013 * to the lookup object. 3014 * <p> 3015 * Before method resolution, 3016 * if the explicitly specified caller class is not identical with the 3017 * lookup class, or if this lookup object does not have 3018 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3019 * privileges, the access fails. 3020 * <p> 3021 * The returned method handle will have 3022 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3023 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3024 * <p style="font-size:smaller;"> 3025 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 3026 * are not visible to this API, 3027 * even though the {@code invokespecial} instruction can refer to them 3028 * in special circumstances. Use {@link #findConstructor findConstructor} 3029 * to access instance initialization methods in a safe manner.)</em> 3030 * <p><b>Example:</b> 3031 * {@snippet lang="java" : 3032 import static java.lang.invoke.MethodHandles.*; 3033 import static java.lang.invoke.MethodType.*; 3034 ... 3035 static class Listie extends ArrayList { 3036 public String toString() { return "[wee Listie]"; } 3037 static Lookup lookup() { return MethodHandles.lookup(); } 3038 } 3039 ... 3040 // no access to constructor via invokeSpecial: 3041 MethodHandle MH_newListie = Listie.lookup() 3042 .findConstructor(Listie.class, methodType(void.class)); 3043 Listie l = (Listie) MH_newListie.invokeExact(); 3044 try { assertEquals("impossible", Listie.lookup().findSpecial( 3045 Listie.class, "<init>", methodType(void.class), Listie.class)); 3046 } catch (NoSuchMethodException ex) { } // OK 3047 // access to super and self methods via invokeSpecial: 3048 MethodHandle MH_super = Listie.lookup().findSpecial( 3049 ArrayList.class, "toString" , methodType(String.class), Listie.class); 3050 MethodHandle MH_this = Listie.lookup().findSpecial( 3051 Listie.class, "toString" , methodType(String.class), Listie.class); 3052 MethodHandle MH_duper = Listie.lookup().findSpecial( 3053 Object.class, "toString" , methodType(String.class), Listie.class); 3054 assertEquals("[]", (String) MH_super.invokeExact(l)); 3055 assertEquals(""+l, (String) MH_this.invokeExact(l)); 3056 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 3057 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 3058 String.class, "toString", methodType(String.class), Listie.class)); 3059 } catch (IllegalAccessException ex) { } // OK 3060 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 3061 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 3062 * } 3063 * 3064 * @param refc the class or interface from which the method is accessed 3065 * @param name the name of the method (which must not be "<init>") 3066 * @param type the type of the method, with the receiver argument omitted 3067 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 3068 * @return the desired method handle 3069 * @throws NoSuchMethodException if the method does not exist 3070 * @throws IllegalAccessException if access checking fails, 3071 * or if the method is {@code static}, 3072 * or if the method's variable arity modifier bit 3073 * is set and {@code asVarargsCollector} fails 3074 * @throws SecurityException if a security manager is present and it 3075 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3076 * @throws NullPointerException if any argument is null 3077 */ 3078 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3079 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3080 checkSpecialCaller(specialCaller, refc); 3081 Lookup specialLookup = this.in(specialCaller); 3082 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3083 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3084 } 3085 3086 /** 3087 * Produces a method handle giving read access to a non-static field. 3088 * The type of the method handle will have a return type of the field's 3089 * value type. 3090 * The method handle's single argument will be the instance containing 3091 * the field. 3092 * Access checking is performed immediately on behalf of the lookup class. 3093 * @param refc the class or interface from which the method is accessed 3094 * @param name the field's name 3095 * @param type the field's type 3096 * @return a method handle which can load values from the field 3097 * @throws NoSuchFieldException if the field does not exist 3098 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3099 * @throws SecurityException if a security manager is present and it 3100 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3101 * @throws NullPointerException if any argument is null 3102 * @see #findVarHandle(Class, String, Class) 3103 */ 3104 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3105 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3106 return getDirectField(REF_getField, refc, field); 3107 } 3108 3109 /** 3110 * Produces a method handle giving write access to a non-static field. 3111 * The type of the method handle will have a void return type. 3112 * The method handle will take two arguments, the instance containing 3113 * the field, and the value to be stored. 3114 * The second argument will be of the field's value type. 3115 * Access checking is performed immediately on behalf of the lookup class. 3116 * @param refc the class or interface from which the method is accessed 3117 * @param name the field's name 3118 * @param type the field's type 3119 * @return a method handle which can store values into the field 3120 * @throws NoSuchFieldException if the field does not exist 3121 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3122 * or {@code final} 3123 * @throws SecurityException if a security manager is present and it 3124 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3125 * @throws NullPointerException if any argument is null 3126 * @see #findVarHandle(Class, String, Class) 3127 */ 3128 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3129 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3130 return getDirectField(REF_putField, refc, field); 3131 } 3132 3133 /** 3134 * Produces a VarHandle giving access to a non-static field {@code name} 3135 * of type {@code type} declared in a class of type {@code recv}. 3136 * The VarHandle's variable type is {@code type} and it has one 3137 * coordinate type, {@code recv}. 3138 * <p> 3139 * Access checking is performed immediately on behalf of the lookup 3140 * class. 3141 * <p> 3142 * Certain access modes of the returned VarHandle are unsupported under 3143 * the following conditions: 3144 * <ul> 3145 * <li>if the field is declared {@code final}, then the write, atomic 3146 * update, numeric atomic update, and bitwise atomic update access 3147 * modes are unsupported. 3148 * <li>if the field type is anything other than {@code byte}, 3149 * {@code short}, {@code char}, {@code int}, {@code long}, 3150 * {@code float}, or {@code double} then numeric atomic update 3151 * access modes are unsupported. 3152 * <li>if the field type is anything other than {@code boolean}, 3153 * {@code byte}, {@code short}, {@code char}, {@code int} or 3154 * {@code long} then bitwise atomic update access modes are 3155 * unsupported. 3156 * </ul> 3157 * <p> 3158 * If the field is declared {@code volatile} then the returned VarHandle 3159 * will override access to the field (effectively ignore the 3160 * {@code volatile} declaration) in accordance to its specified 3161 * access modes. 3162 * <p> 3163 * If the field type is {@code float} or {@code double} then numeric 3164 * and atomic update access modes compare values using their bitwise 3165 * representation (see {@link Float#floatToRawIntBits} and 3166 * {@link Double#doubleToRawLongBits}, respectively). 3167 * @apiNote 3168 * Bitwise comparison of {@code float} values or {@code double} values, 3169 * as performed by the numeric and atomic update access modes, differ 3170 * from the primitive {@code ==} operator and the {@link Float#equals} 3171 * and {@link Double#equals} methods, specifically with respect to 3172 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3173 * Care should be taken when performing a compare and set or a compare 3174 * and exchange operation with such values since the operation may 3175 * unexpectedly fail. 3176 * There are many possible NaN values that are considered to be 3177 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3178 * provided by Java can distinguish between them. Operation failure can 3179 * occur if the expected or witness value is a NaN value and it is 3180 * transformed (perhaps in a platform specific manner) into another NaN 3181 * value, and thus has a different bitwise representation (see 3182 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3183 * details). 3184 * The values {@code -0.0} and {@code +0.0} have different bitwise 3185 * representations but are considered equal when using the primitive 3186 * {@code ==} operator. Operation failure can occur if, for example, a 3187 * numeric algorithm computes an expected value to be say {@code -0.0} 3188 * and previously computed the witness value to be say {@code +0.0}. 3189 * @param recv the receiver class, of type {@code R}, that declares the 3190 * non-static field 3191 * @param name the field's name 3192 * @param type the field's type, of type {@code T} 3193 * @return a VarHandle giving access to non-static fields. 3194 * @throws NoSuchFieldException if the field does not exist 3195 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3196 * @throws SecurityException if a security manager is present and it 3197 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3198 * @throws NullPointerException if any argument is null 3199 * @since 9 3200 */ 3201 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3202 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3203 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3204 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3205 } 3206 3207 /** 3208 * Produces a method handle giving read access to a static field. 3209 * The type of the method handle will have a return type of the field's 3210 * value type. 3211 * The method handle will take no arguments. 3212 * Access checking is performed immediately on behalf of the lookup class. 3213 * <p> 3214 * If the returned method handle is invoked, the field's class will 3215 * be initialized, if it has not already been initialized. 3216 * @param refc the class or interface from which the method is accessed 3217 * @param name the field's name 3218 * @param type the field's type 3219 * @return a method handle which can load values from the field 3220 * @throws NoSuchFieldException if the field does not exist 3221 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3222 * @throws SecurityException if a security manager is present and it 3223 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3224 * @throws NullPointerException if any argument is null 3225 */ 3226 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3227 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3228 return getDirectField(REF_getStatic, refc, field); 3229 } 3230 3231 /** 3232 * Produces a method handle giving write access to a static field. 3233 * The type of the method handle will have a void return type. 3234 * The method handle will take a single 3235 * argument, of the field's value type, the value to be stored. 3236 * Access checking is performed immediately on behalf of the lookup class. 3237 * <p> 3238 * If the returned method handle is invoked, the field's class will 3239 * be initialized, if it has not already been initialized. 3240 * @param refc the class or interface from which the method is accessed 3241 * @param name the field's name 3242 * @param type the field's type 3243 * @return a method handle which can store values into the field 3244 * @throws NoSuchFieldException if the field does not exist 3245 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3246 * or is {@code final} 3247 * @throws SecurityException if a security manager is present and it 3248 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3249 * @throws NullPointerException if any argument is null 3250 */ 3251 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3252 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3253 return getDirectField(REF_putStatic, refc, field); 3254 } 3255 3256 /** 3257 * Produces a VarHandle giving access to a static field {@code name} of 3258 * type {@code type} declared in a class of type {@code decl}. 3259 * The VarHandle's variable type is {@code type} and it has no 3260 * coordinate types. 3261 * <p> 3262 * Access checking is performed immediately on behalf of the lookup 3263 * class. 3264 * <p> 3265 * If the returned VarHandle is operated on, the declaring class will be 3266 * initialized, if it has not already been initialized. 3267 * <p> 3268 * Certain access modes of the returned VarHandle are unsupported under 3269 * the following conditions: 3270 * <ul> 3271 * <li>if the field is declared {@code final}, then the write, atomic 3272 * update, numeric atomic update, and bitwise atomic update access 3273 * modes are unsupported. 3274 * <li>if the field type is anything other than {@code byte}, 3275 * {@code short}, {@code char}, {@code int}, {@code long}, 3276 * {@code float}, or {@code double}, then numeric atomic update 3277 * access modes are unsupported. 3278 * <li>if the field type is anything other than {@code boolean}, 3279 * {@code byte}, {@code short}, {@code char}, {@code int} or 3280 * {@code long} then bitwise atomic update access modes are 3281 * unsupported. 3282 * </ul> 3283 * <p> 3284 * If the field is declared {@code volatile} then the returned VarHandle 3285 * will override access to the field (effectively ignore the 3286 * {@code volatile} declaration) in accordance to its specified 3287 * access modes. 3288 * <p> 3289 * If the field type is {@code float} or {@code double} then numeric 3290 * and atomic update access modes compare values using their bitwise 3291 * representation (see {@link Float#floatToRawIntBits} and 3292 * {@link Double#doubleToRawLongBits}, respectively). 3293 * @apiNote 3294 * Bitwise comparison of {@code float} values or {@code double} values, 3295 * as performed by the numeric and atomic update access modes, differ 3296 * from the primitive {@code ==} operator and the {@link Float#equals} 3297 * and {@link Double#equals} methods, specifically with respect to 3298 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3299 * Care should be taken when performing a compare and set or a compare 3300 * and exchange operation with such values since the operation may 3301 * unexpectedly fail. 3302 * There are many possible NaN values that are considered to be 3303 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3304 * provided by Java can distinguish between them. Operation failure can 3305 * occur if the expected or witness value is a NaN value and it is 3306 * transformed (perhaps in a platform specific manner) into another NaN 3307 * value, and thus has a different bitwise representation (see 3308 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3309 * details). 3310 * The values {@code -0.0} and {@code +0.0} have different bitwise 3311 * representations but are considered equal when using the primitive 3312 * {@code ==} operator. Operation failure can occur if, for example, a 3313 * numeric algorithm computes an expected value to be say {@code -0.0} 3314 * and previously computed the witness value to be say {@code +0.0}. 3315 * @param decl the class that declares the static field 3316 * @param name the field's name 3317 * @param type the field's type, of type {@code T} 3318 * @return a VarHandle giving access to a static field 3319 * @throws NoSuchFieldException if the field does not exist 3320 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3321 * @throws SecurityException if a security manager is present and it 3322 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3323 * @throws NullPointerException if any argument is null 3324 * @since 9 3325 */ 3326 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3327 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3328 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3329 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3330 } 3331 3332 /** 3333 * Produces an early-bound method handle for a non-static method. 3334 * The receiver must have a supertype {@code defc} in which a method 3335 * of the given name and type is accessible to the lookup class. 3336 * The method and all its argument types must be accessible to the lookup object. 3337 * The type of the method handle will be that of the method, 3338 * without any insertion of an additional receiver parameter. 3339 * The given receiver will be bound into the method handle, 3340 * so that every call to the method handle will invoke the 3341 * requested method on the given receiver. 3342 * <p> 3343 * The returned method handle will have 3344 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3345 * the method's variable arity modifier bit ({@code 0x0080}) is set 3346 * <em>and</em> the trailing array argument is not the only argument. 3347 * (If the trailing array argument is the only argument, 3348 * the given receiver value will be bound to it.) 3349 * <p> 3350 * This is almost equivalent to the following code, with some differences noted below: 3351 * {@snippet lang="java" : 3352 import static java.lang.invoke.MethodHandles.*; 3353 import static java.lang.invoke.MethodType.*; 3354 ... 3355 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3356 MethodHandle mh1 = mh0.bindTo(receiver); 3357 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3358 return mh1; 3359 * } 3360 * where {@code defc} is either {@code receiver.getClass()} or a super 3361 * type of that class, in which the requested method is accessible 3362 * to the lookup class. 3363 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3364 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3365 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3366 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3367 * @param receiver the object from which the method is accessed 3368 * @param name the name of the method 3369 * @param type the type of the method, with the receiver argument omitted 3370 * @return the desired method handle 3371 * @throws NoSuchMethodException if the method does not exist 3372 * @throws IllegalAccessException if access checking fails 3373 * or if the method's variable arity modifier bit 3374 * is set and {@code asVarargsCollector} fails 3375 * @throws SecurityException if a security manager is present and it 3376 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3377 * @throws NullPointerException if any argument is null 3378 * @see MethodHandle#bindTo 3379 * @see #findVirtual 3380 */ 3381 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3382 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3383 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3384 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3385 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3386 throw new IllegalAccessException("The restricted defining class " + 3387 mh.type().leadingReferenceParameter().getName() + 3388 " is not assignable from receiver class " + 3389 receiver.getClass().getName()); 3390 } 3391 return mh.bindArgumentL(0, receiver).setVarargs(method); 3392 } 3393 3394 /** 3395 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3396 * to <i>m</i>, if the lookup class has permission. 3397 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3398 * If <i>m</i> is virtual, overriding is respected on every call. 3399 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3400 * The type of the method handle will be that of the method, 3401 * with the receiver type prepended (but only if it is non-static). 3402 * If the method's {@code accessible} flag is not set, 3403 * access checking is performed immediately on behalf of the lookup class. 3404 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3405 * <p> 3406 * The returned method handle will have 3407 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3408 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3409 * <p> 3410 * If <i>m</i> is static, and 3411 * if the returned method handle is invoked, the method's class will 3412 * be initialized, if it has not already been initialized. 3413 * @param m the reflected method 3414 * @return a method handle which can invoke the reflected method 3415 * @throws IllegalAccessException if access checking fails 3416 * or if the method's variable arity modifier bit 3417 * is set and {@code asVarargsCollector} fails 3418 * @throws NullPointerException if the argument is null 3419 */ 3420 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3421 if (m.getDeclaringClass() == MethodHandle.class) { 3422 MethodHandle mh = unreflectForMH(m); 3423 if (mh != null) return mh; 3424 } 3425 if (m.getDeclaringClass() == VarHandle.class) { 3426 MethodHandle mh = unreflectForVH(m); 3427 if (mh != null) return mh; 3428 } 3429 MemberName method = new MemberName(m); 3430 byte refKind = method.getReferenceKind(); 3431 if (refKind == REF_invokeSpecial) 3432 refKind = REF_invokeVirtual; 3433 assert(method.isMethod()); 3434 @SuppressWarnings("deprecation") 3435 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3436 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3437 } 3438 private MethodHandle unreflectForMH(Method m) { 3439 // these names require special lookups because they throw UnsupportedOperationException 3440 if (MemberName.isMethodHandleInvokeName(m.getName())) 3441 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3442 return null; 3443 } 3444 private MethodHandle unreflectForVH(Method m) { 3445 // these names require special lookups because they throw UnsupportedOperationException 3446 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3447 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3448 return null; 3449 } 3450 3451 /** 3452 * Produces a method handle for a reflected method. 3453 * It will bypass checks for overriding methods on the receiver, 3454 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3455 * instruction from within the explicitly specified {@code specialCaller}. 3456 * The type of the method handle will be that of the method, 3457 * with a suitably restricted receiver type prepended. 3458 * (The receiver type will be {@code specialCaller} or a subtype.) 3459 * If the method's {@code accessible} flag is not set, 3460 * access checking is performed immediately on behalf of the lookup class, 3461 * as if {@code invokespecial} instruction were being linked. 3462 * <p> 3463 * Before method resolution, 3464 * if the explicitly specified caller class is not identical with the 3465 * lookup class, or if this lookup object does not have 3466 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3467 * privileges, the access fails. 3468 * <p> 3469 * The returned method handle will have 3470 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3471 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3472 * @param m the reflected method 3473 * @param specialCaller the class nominally calling the method 3474 * @return a method handle which can invoke the reflected method 3475 * @throws IllegalAccessException if access checking fails, 3476 * or if the method is {@code static}, 3477 * or if the method's variable arity modifier bit 3478 * is set and {@code asVarargsCollector} fails 3479 * @throws NullPointerException if any argument is null 3480 */ 3481 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3482 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3483 Lookup specialLookup = this.in(specialCaller); 3484 MemberName method = new MemberName(m, true); 3485 assert(method.isMethod()); 3486 // ignore m.isAccessible: this is a new kind of access 3487 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3488 } 3489 3490 /** 3491 * Produces a method handle for a reflected constructor. 3492 * The type of the method handle will be that of the constructor, 3493 * with the return type changed to the declaring class. 3494 * The method handle will perform a {@code newInstance} operation, 3495 * creating a new instance of the constructor's class on the 3496 * arguments passed to the method handle. 3497 * <p> 3498 * If the constructor's {@code accessible} flag is not set, 3499 * access checking is performed immediately on behalf of the lookup class. 3500 * <p> 3501 * The returned method handle will have 3502 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3503 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3504 * <p> 3505 * If the returned method handle is invoked, the constructor's class will 3506 * be initialized, if it has not already been initialized. 3507 * @param c the reflected constructor 3508 * @return a method handle which can invoke the reflected constructor 3509 * @throws IllegalAccessException if access checking fails 3510 * or if the method's variable arity modifier bit 3511 * is set and {@code asVarargsCollector} fails 3512 * @throws NullPointerException if the argument is null 3513 */ 3514 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3515 MemberName ctor = new MemberName(c); 3516 assert(ctor.isConstructor()); 3517 @SuppressWarnings("deprecation") 3518 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3519 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3520 } 3521 3522 /* 3523 * Produces a method handle that is capable of creating instances of the given class 3524 * and instantiated by the given constructor. No security manager check. 3525 * 3526 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3527 */ 3528 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3529 MemberName ctor = new MemberName(c); 3530 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3531 checkAccess(REF_newInvokeSpecial, decl, ctor); 3532 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3533 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3534 } 3535 3536 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3537 if (decl == ctor.getDeclaringClass()) 3538 return true; 3539 3540 Class<?> cl = decl; 3541 while ((cl = cl.getSuperclass()) != null) { 3542 if (cl == ctor.getDeclaringClass()) { 3543 return true; 3544 } 3545 } 3546 return false; 3547 } 3548 3549 /** 3550 * Produces a method handle giving read access to a reflected field. 3551 * The type of the method handle will have a return type of the field's 3552 * value type. 3553 * If the field is {@code static}, the method handle will take no arguments. 3554 * Otherwise, its single argument will be the instance containing 3555 * the field. 3556 * If the {@code Field} object's {@code accessible} flag is not set, 3557 * access checking is performed immediately on behalf of the lookup class. 3558 * <p> 3559 * If the field is static, and 3560 * if the returned method handle is invoked, the field's class will 3561 * be initialized, if it has not already been initialized. 3562 * @param f the reflected field 3563 * @return a method handle which can load values from the reflected field 3564 * @throws IllegalAccessException if access checking fails 3565 * @throws NullPointerException if the argument is null 3566 */ 3567 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3568 return unreflectField(f, false); 3569 } 3570 3571 /** 3572 * Produces a method handle giving write access to a reflected field. 3573 * The type of the method handle will have a void return type. 3574 * If the field is {@code static}, the method handle will take a single 3575 * argument, of the field's value type, the value to be stored. 3576 * Otherwise, the two arguments will be the instance containing 3577 * the field, and the value to be stored. 3578 * If the {@code Field} object's {@code accessible} flag is not set, 3579 * access checking is performed immediately on behalf of the lookup class. 3580 * <p> 3581 * If the field is {@code final}, write access will not be 3582 * allowed and access checking will fail, except under certain 3583 * narrow circumstances documented for {@link Field#set Field.set}. 3584 * A method handle is returned only if a corresponding call to 3585 * the {@code Field} object's {@code set} method could return 3586 * normally. In particular, fields which are both {@code static} 3587 * and {@code final} may never be set. 3588 * <p> 3589 * If the field is {@code static}, and 3590 * if the returned method handle is invoked, the field's class will 3591 * be initialized, if it has not already been initialized. 3592 * @param f the reflected field 3593 * @return a method handle which can store values into the reflected field 3594 * @throws IllegalAccessException if access checking fails, 3595 * or if the field is {@code final} and write access 3596 * is not enabled on the {@code Field} object 3597 * @throws NullPointerException if the argument is null 3598 */ 3599 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3600 return unreflectField(f, true); 3601 } 3602 3603 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3604 MemberName field = new MemberName(f, isSetter); 3605 if (isSetter && field.isFinal()) { 3606 if (field.isTrustedFinalField()) { 3607 String msg = field.isStatic() ? "static final field has no write access" 3608 : "final field has no write access"; 3609 throw field.makeAccessException(msg, this); 3610 } 3611 } 3612 assert(isSetter 3613 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3614 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3615 @SuppressWarnings("deprecation") 3616 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3617 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3618 } 3619 3620 /** 3621 * Produces a VarHandle giving access to a reflected field {@code f} 3622 * of type {@code T} declared in a class of type {@code R}. 3623 * The VarHandle's variable type is {@code T}. 3624 * If the field is non-static the VarHandle has one coordinate type, 3625 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3626 * coordinate types. 3627 * <p> 3628 * Access checking is performed immediately on behalf of the lookup 3629 * class, regardless of the value of the field's {@code accessible} 3630 * flag. 3631 * <p> 3632 * If the field is static, and if the returned VarHandle is operated 3633 * on, the field's declaring class will be initialized, if it has not 3634 * already been initialized. 3635 * <p> 3636 * Certain access modes of the returned VarHandle are unsupported under 3637 * the following conditions: 3638 * <ul> 3639 * <li>if the field is declared {@code final}, then the write, atomic 3640 * update, numeric atomic update, and bitwise atomic update access 3641 * modes are unsupported. 3642 * <li>if the field type is anything other than {@code byte}, 3643 * {@code short}, {@code char}, {@code int}, {@code long}, 3644 * {@code float}, or {@code double} then numeric atomic update 3645 * access modes are unsupported. 3646 * <li>if the field type is anything other than {@code boolean}, 3647 * {@code byte}, {@code short}, {@code char}, {@code int} or 3648 * {@code long} then bitwise atomic update access modes are 3649 * unsupported. 3650 * </ul> 3651 * <p> 3652 * If the field is declared {@code volatile} then the returned VarHandle 3653 * will override access to the field (effectively ignore the 3654 * {@code volatile} declaration) in accordance to its specified 3655 * access modes. 3656 * <p> 3657 * If the field type is {@code float} or {@code double} then numeric 3658 * and atomic update access modes compare values using their bitwise 3659 * representation (see {@link Float#floatToRawIntBits} and 3660 * {@link Double#doubleToRawLongBits}, respectively). 3661 * @apiNote 3662 * Bitwise comparison of {@code float} values or {@code double} values, 3663 * as performed by the numeric and atomic update access modes, differ 3664 * from the primitive {@code ==} operator and the {@link Float#equals} 3665 * and {@link Double#equals} methods, specifically with respect to 3666 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3667 * Care should be taken when performing a compare and set or a compare 3668 * and exchange operation with such values since the operation may 3669 * unexpectedly fail. 3670 * There are many possible NaN values that are considered to be 3671 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3672 * provided by Java can distinguish between them. Operation failure can 3673 * occur if the expected or witness value is a NaN value and it is 3674 * transformed (perhaps in a platform specific manner) into another NaN 3675 * value, and thus has a different bitwise representation (see 3676 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3677 * details). 3678 * The values {@code -0.0} and {@code +0.0} have different bitwise 3679 * representations but are considered equal when using the primitive 3680 * {@code ==} operator. Operation failure can occur if, for example, a 3681 * numeric algorithm computes an expected value to be say {@code -0.0} 3682 * and previously computed the witness value to be say {@code +0.0}. 3683 * @param f the reflected field, with a field of type {@code T}, and 3684 * a declaring class of type {@code R} 3685 * @return a VarHandle giving access to non-static fields or a static 3686 * field 3687 * @throws IllegalAccessException if access checking fails 3688 * @throws NullPointerException if the argument is null 3689 * @since 9 3690 */ 3691 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3692 MemberName getField = new MemberName(f, false); 3693 MemberName putField = new MemberName(f, true); 3694 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3695 f.getDeclaringClass(), getField, putField); 3696 } 3697 3698 /** 3699 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3700 * created by this lookup object or a similar one. 3701 * Security and access checks are performed to ensure that this lookup object 3702 * is capable of reproducing the target method handle. 3703 * This means that the cracking may fail if target is a direct method handle 3704 * but was created by an unrelated lookup object. 3705 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3706 * and was created by a lookup object for a different class. 3707 * @param target a direct method handle to crack into symbolic reference components 3708 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3709 * @throws SecurityException if a security manager is present and it 3710 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3711 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3712 * @throws NullPointerException if the target is {@code null} 3713 * @see MethodHandleInfo 3714 * @since 1.8 3715 */ 3716 public MethodHandleInfo revealDirect(MethodHandle target) { 3717 if (!target.isCrackable()) { 3718 throw newIllegalArgumentException("not a direct method handle"); 3719 } 3720 MemberName member = target.internalMemberName(); 3721 Class<?> defc = member.getDeclaringClass(); 3722 byte refKind = member.getReferenceKind(); 3723 assert(MethodHandleNatives.refKindIsValid(refKind)); 3724 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3725 // Devirtualized method invocation is usually formally virtual. 3726 // To avoid creating extra MemberName objects for this common case, 3727 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3728 refKind = REF_invokeVirtual; 3729 if (refKind == REF_invokeVirtual && defc.isInterface()) 3730 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3731 refKind = REF_invokeInterface; 3732 // Check SM permissions and member access before cracking. 3733 try { 3734 checkAccess(refKind, defc, member); 3735 checkSecurityManager(defc, member); 3736 } catch (IllegalAccessException ex) { 3737 throw new IllegalArgumentException(ex); 3738 } 3739 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3740 Class<?> callerClass = target.internalCallerClass(); 3741 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3742 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3743 } 3744 // Produce the handle to the results. 3745 return new InfoFromMemberName(this, member, refKind); 3746 } 3747 3748 /// Helper methods, all package-private. 3749 3750 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3751 checkSymbolicClass(refc); // do this before attempting to resolve 3752 Objects.requireNonNull(name); 3753 Objects.requireNonNull(type); 3754 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3755 NoSuchFieldException.class); 3756 } 3757 3758 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3759 checkSymbolicClass(refc); // do this before attempting to resolve 3760 Objects.requireNonNull(type); 3761 checkMethodName(refKind, name); // implicit null-check of name 3762 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3763 NoSuchMethodException.class); 3764 } 3765 3766 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3767 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3768 Objects.requireNonNull(member.getName()); 3769 Objects.requireNonNull(member.getType()); 3770 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3771 ReflectiveOperationException.class); 3772 } 3773 3774 MemberName resolveOrNull(byte refKind, MemberName member) { 3775 // do this before attempting to resolve 3776 if (!isClassAccessible(member.getDeclaringClass())) { 3777 return null; 3778 } 3779 Objects.requireNonNull(member.getName()); 3780 Objects.requireNonNull(member.getType()); 3781 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3782 } 3783 3784 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3785 // do this before attempting to resolve 3786 if (!isClassAccessible(refc)) { 3787 return null; 3788 } 3789 Objects.requireNonNull(type); 3790 // implicit null-check of name 3791 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3792 return null; 3793 } 3794 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3795 } 3796 3797 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3798 if (!isClassAccessible(refc)) { 3799 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3800 } 3801 } 3802 3803 boolean isClassAccessible(Class<?> refc) { 3804 Objects.requireNonNull(refc); 3805 Class<?> caller = lookupClassOrNull(); 3806 Class<?> type = refc; 3807 while (type.isArray()) { 3808 type = type.getComponentType(); 3809 } 3810 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3811 } 3812 3813 /** Check name for an illegal leading "<" character. */ 3814 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3815 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3816 throw new NoSuchMethodException("illegal method name: "+name); 3817 } 3818 3819 /** 3820 * Find my trustable caller class if m is a caller sensitive method. 3821 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3822 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3823 */ 3824 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3825 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3826 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3827 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3828 } 3829 return this; 3830 } 3831 3832 /** 3833 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3834 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3835 * 3836 * @deprecated This method was originally designed to test {@code PRIVATE} access 3837 * that implies full privilege access but {@code MODULE} access has since become 3838 * independent of {@code PRIVATE} access. It is recommended to call 3839 * {@link #hasFullPrivilegeAccess()} instead. 3840 * @since 9 3841 */ 3842 @Deprecated(since="14") 3843 public boolean hasPrivateAccess() { 3844 return hasFullPrivilegeAccess(); 3845 } 3846 3847 /** 3848 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3849 * i.e. {@code PRIVATE} and {@code MODULE} access. 3850 * A {@code Lookup} object must have full privilege access in order to 3851 * access all members that are allowed to the 3852 * {@linkplain #lookupClass() lookup class}. 3853 * 3854 * @return {@code true} if this lookup has full privilege access. 3855 * @since 14 3856 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3857 */ 3858 public boolean hasFullPrivilegeAccess() { 3859 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3860 } 3861 3862 /** 3863 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3864 * for ensureInitialized, findClass or accessClass. 3865 */ 3866 void checkSecurityManager(Class<?> refc) { 3867 if (allowedModes == TRUSTED) return; 3868 3869 @SuppressWarnings("removal") 3870 SecurityManager smgr = System.getSecurityManager(); 3871 if (smgr == null) return; 3872 3873 // Step 1: 3874 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3875 if (!fullPrivilegeLookup || 3876 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3877 ReflectUtil.checkPackageAccess(refc); 3878 } 3879 3880 // Step 2b: 3881 if (!fullPrivilegeLookup) { 3882 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3883 } 3884 } 3885 3886 /** 3887 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3888 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3889 * If this lookup object has full privilege access except original access, 3890 * then the caller class is the lookupClass. 3891 * 3892 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3893 * from the same module skips the security permission check. 3894 */ 3895 void checkSecurityManager(Class<?> refc, MemberName m) { 3896 Objects.requireNonNull(refc); 3897 Objects.requireNonNull(m); 3898 3899 if (allowedModes == TRUSTED) return; 3900 3901 @SuppressWarnings("removal") 3902 SecurityManager smgr = System.getSecurityManager(); 3903 if (smgr == null) return; 3904 3905 // Step 1: 3906 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3907 if (!fullPrivilegeLookup || 3908 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3909 ReflectUtil.checkPackageAccess(refc); 3910 } 3911 3912 // Step 2a: 3913 if (m.isPublic()) return; 3914 if (!fullPrivilegeLookup) { 3915 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3916 } 3917 3918 // Step 3: 3919 Class<?> defc = m.getDeclaringClass(); 3920 if (!fullPrivilegeLookup && defc != refc) { 3921 ReflectUtil.checkPackageAccess(defc); 3922 } 3923 } 3924 3925 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3926 boolean wantStatic = (refKind == REF_invokeStatic); 3927 String message; 3928 if (m.isConstructor()) 3929 message = "expected a method, not a constructor"; 3930 else if (!m.isMethod()) 3931 message = "expected a method"; 3932 else if (wantStatic != m.isStatic()) 3933 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3934 else 3935 { checkAccess(refKind, refc, m); return; } 3936 throw m.makeAccessException(message, this); 3937 } 3938 3939 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3940 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3941 String message; 3942 if (wantStatic != m.isStatic()) 3943 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3944 else 3945 { checkAccess(refKind, refc, m); return; } 3946 throw m.makeAccessException(message, this); 3947 } 3948 3949 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3950 return Modifier.isProtected(m.getModifiers()) && 3951 refKind == REF_invokeVirtual && 3952 m.getDeclaringClass() == Object.class && 3953 m.getName().equals("clone") && 3954 refc.isArray(); 3955 } 3956 3957 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3958 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3959 assert(m.referenceKindIsConsistentWith(refKind) && 3960 MethodHandleNatives.refKindIsValid(refKind) && 3961 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3962 int allowedModes = this.allowedModes; 3963 if (allowedModes == TRUSTED) return; 3964 int mods = m.getModifiers(); 3965 if (isArrayClone(refKind, refc, m)) { 3966 // The JVM does this hack also. 3967 // (See ClassVerifier::verify_invoke_instructions 3968 // and LinkResolver::check_method_accessability.) 3969 // Because the JVM does not allow separate methods on array types, 3970 // there is no separate method for int[].clone. 3971 // All arrays simply inherit Object.clone. 3972 // But for access checking logic, we make Object.clone 3973 // (normally protected) appear to be public. 3974 // Later on, when the DirectMethodHandle is created, 3975 // its leading argument will be restricted to the 3976 // requested array type. 3977 // N.B. The return type is not adjusted, because 3978 // that is *not* the bytecode behavior. 3979 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3980 } 3981 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3982 // cannot "new" a protected ctor in a different package 3983 mods ^= Modifier.PROTECTED; 3984 } 3985 if (Modifier.isFinal(mods) && 3986 MethodHandleNatives.refKindIsSetter(refKind)) 3987 throw m.makeAccessException("unexpected set of a final field", this); 3988 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3989 if ((requestedModes & allowedModes) != 0) { 3990 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3991 mods, lookupClass(), previousLookupClass(), allowedModes)) 3992 return; 3993 } else { 3994 // Protected members can also be checked as if they were package-private. 3995 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3996 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3997 return; 3998 } 3999 throw m.makeAccessException(accessFailedMessage(refc, m), this); 4000 } 4001 4002 String accessFailedMessage(Class<?> refc, MemberName m) { 4003 Class<?> defc = m.getDeclaringClass(); 4004 int mods = m.getModifiers(); 4005 // check the class first: 4006 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 4007 (defc == refc || 4008 Modifier.isPublic(refc.getModifiers()))); 4009 if (!classOK && (allowedModes & PACKAGE) != 0) { 4010 // ignore previous lookup class to check if default package access 4011 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 4012 (defc == refc || 4013 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 4014 } 4015 if (!classOK) 4016 return "class is not public"; 4017 if (Modifier.isPublic(mods)) 4018 return "access to public member failed"; // (how?, module not readable?) 4019 if (Modifier.isPrivate(mods)) 4020 return "member is private"; 4021 if (Modifier.isProtected(mods)) 4022 return "member is protected"; 4023 return "member is private to package"; 4024 } 4025 4026 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 4027 int allowedModes = this.allowedModes; 4028 if (allowedModes == TRUSTED) return; 4029 if ((lookupModes() & PRIVATE) == 0 4030 || (specialCaller != lookupClass() 4031 // ensure non-abstract methods in superinterfaces can be special-invoked 4032 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 4033 throw new MemberName(specialCaller). 4034 makeAccessException("no private access for invokespecial", this); 4035 } 4036 4037 private boolean restrictProtectedReceiver(MemberName method) { 4038 // The accessing class only has the right to use a protected member 4039 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 4040 if (!method.isProtected() || method.isStatic() 4041 || allowedModes == TRUSTED 4042 || method.getDeclaringClass() == lookupClass() 4043 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 4044 return false; 4045 return true; 4046 } 4047 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 4048 assert(!method.isStatic()); 4049 // receiver type of mh is too wide; narrow to caller 4050 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 4051 throw method.makeAccessException("caller class must be a subclass below the method", caller); 4052 } 4053 MethodType rawType = mh.type(); 4054 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 4055 MethodType narrowType = rawType.changeParameterType(0, caller); 4056 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 4057 assert(mh.viewAsTypeChecks(narrowType, true)); 4058 return mh.copyWith(narrowType, mh.form); 4059 } 4060 4061 /** Check access and get the requested method. */ 4062 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4063 final boolean doRestrict = true; 4064 final boolean checkSecurity = true; 4065 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4066 } 4067 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 4068 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4069 final boolean doRestrict = false; 4070 final boolean checkSecurity = true; 4071 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 4072 } 4073 /** Check access and get the requested method, eliding security manager checks. */ 4074 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4075 final boolean doRestrict = true; 4076 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4077 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4078 } 4079 /** Common code for all methods; do not call directly except from immediately above. */ 4080 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 4081 boolean checkSecurity, 4082 boolean doRestrict, 4083 Lookup boundCaller) throws IllegalAccessException { 4084 checkMethod(refKind, refc, method); 4085 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4086 if (checkSecurity) 4087 checkSecurityManager(refc, method); 4088 assert(!method.isMethodHandleInvoke()); 4089 4090 if (refKind == REF_invokeSpecial && 4091 refc != lookupClass() && 4092 !refc.isInterface() && !lookupClass().isInterface() && 4093 refc != lookupClass().getSuperclass() && 4094 refc.isAssignableFrom(lookupClass())) { 4095 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 4096 4097 // Per JVMS 6.5, desc. of invokespecial instruction: 4098 // If the method is in a superclass of the LC, 4099 // and if our original search was above LC.super, 4100 // repeat the search (symbolic lookup) from LC.super 4101 // and continue with the direct superclass of that class, 4102 // and so forth, until a match is found or no further superclasses exist. 4103 // FIXME: MemberName.resolve should handle this instead. 4104 Class<?> refcAsSuper = lookupClass(); 4105 MemberName m2; 4106 do { 4107 refcAsSuper = refcAsSuper.getSuperclass(); 4108 m2 = new MemberName(refcAsSuper, 4109 method.getName(), 4110 method.getMethodType(), 4111 REF_invokeSpecial); 4112 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4113 } while (m2 == null && // no method is found yet 4114 refc != refcAsSuper); // search up to refc 4115 if (m2 == null) throw new InternalError(method.toString()); 4116 method = m2; 4117 refc = refcAsSuper; 4118 // redo basic checks 4119 checkMethod(refKind, refc, method); 4120 } 4121 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4122 MethodHandle mh = dmh; 4123 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4124 if ((doRestrict && refKind == REF_invokeSpecial) || 4125 (MethodHandleNatives.refKindHasReceiver(refKind) && 4126 restrictProtectedReceiver(method) && 4127 // All arrays simply inherit the protected Object.clone method. 4128 // The leading argument is already restricted to the requested 4129 // array type (not the lookup class). 4130 !isArrayClone(refKind, refc, method))) { 4131 mh = restrictReceiver(method, dmh, lookupClass()); 4132 } 4133 mh = maybeBindCaller(method, mh, boundCaller); 4134 mh = mh.setVarargs(method); 4135 return mh; 4136 } 4137 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4138 throws IllegalAccessException { 4139 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4140 return mh; 4141 4142 // boundCaller must have full privilege access. 4143 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4144 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4145 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4146 4147 assert boundCaller.hasFullPrivilegeAccess(); 4148 4149 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4150 // Note: caller will apply varargs after this step happens. 4151 return cbmh; 4152 } 4153 4154 /** Check access and get the requested field. */ 4155 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4156 final boolean checkSecurity = true; 4157 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4158 } 4159 /** Check access and get the requested field, eliding security manager checks. */ 4160 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4161 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4162 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4163 } 4164 /** Common code for all fields; do not call directly except from immediately above. */ 4165 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4166 boolean checkSecurity) throws IllegalAccessException { 4167 checkField(refKind, refc, field); 4168 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4169 if (checkSecurity) 4170 checkSecurityManager(refc, field); 4171 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4172 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4173 restrictProtectedReceiver(field)); 4174 if (doRestrict) 4175 return restrictReceiver(field, dmh, lookupClass()); 4176 return dmh; 4177 } 4178 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4179 Class<?> refc, MemberName getField, MemberName putField) 4180 throws IllegalAccessException { 4181 final boolean checkSecurity = true; 4182 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4183 } 4184 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4185 Class<?> refc, MemberName getField, MemberName putField) 4186 throws IllegalAccessException { 4187 final boolean checkSecurity = false; 4188 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4189 } 4190 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4191 Class<?> refc, MemberName getField, MemberName putField, 4192 boolean checkSecurity) throws IllegalAccessException { 4193 assert getField.isStatic() == putField.isStatic(); 4194 assert getField.isGetter() && putField.isSetter(); 4195 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4196 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4197 4198 checkField(getRefKind, refc, getField); 4199 if (checkSecurity) 4200 checkSecurityManager(refc, getField); 4201 4202 if (!putField.isFinal()) { 4203 // A VarHandle does not support updates to final fields, any 4204 // such VarHandle to a final field will be read-only and 4205 // therefore the following write-based accessibility checks are 4206 // only required for non-final fields 4207 checkField(putRefKind, refc, putField); 4208 if (checkSecurity) 4209 checkSecurityManager(refc, putField); 4210 } 4211 4212 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4213 restrictProtectedReceiver(getField)); 4214 if (doRestrict) { 4215 assert !getField.isStatic(); 4216 // receiver type of VarHandle is too wide; narrow to caller 4217 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4218 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4219 } 4220 refc = lookupClass(); 4221 } 4222 return VarHandles.makeFieldHandle(getField, refc, 4223 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4224 } 4225 /** Check access and get the requested constructor. */ 4226 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4227 final boolean checkSecurity = true; 4228 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4229 } 4230 /** Check access and get the requested constructor, eliding security manager checks. */ 4231 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4232 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4233 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4234 } 4235 /** Common code for all constructors; do not call directly except from immediately above. */ 4236 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4237 boolean checkSecurity) throws IllegalAccessException { 4238 assert(ctor.isConstructor()); 4239 checkAccess(REF_newInvokeSpecial, refc, ctor); 4240 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4241 if (checkSecurity) 4242 checkSecurityManager(refc, ctor); 4243 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4244 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4245 } 4246 4247 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4248 */ 4249 /*non-public*/ 4250 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4251 throws ReflectiveOperationException { 4252 if (!(type instanceof Class || type instanceof MethodType)) 4253 throw new InternalError("unresolved MemberName"); 4254 MemberName member = new MemberName(refKind, defc, name, type); 4255 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4256 if (mh != null) { 4257 checkSymbolicClass(defc); 4258 return mh; 4259 } 4260 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4261 // Treat MethodHandle.invoke and invokeExact specially. 4262 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4263 if (mh != null) { 4264 return mh; 4265 } 4266 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4267 // Treat signature-polymorphic methods on VarHandle specially. 4268 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4269 if (mh != null) { 4270 return mh; 4271 } 4272 } 4273 MemberName resolved = resolveOrFail(refKind, member); 4274 mh = getDirectMethodForConstant(refKind, defc, resolved); 4275 if (mh instanceof DirectMethodHandle dmh 4276 && canBeCached(refKind, defc, resolved)) { 4277 MemberName key = mh.internalMemberName(); 4278 if (key != null) { 4279 key = key.asNormalOriginal(); 4280 } 4281 if (member.equals(key)) { // better safe than sorry 4282 LOOKASIDE_TABLE.put(key, dmh); 4283 } 4284 } 4285 return mh; 4286 } 4287 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4288 if (refKind == REF_invokeSpecial) { 4289 return false; 4290 } 4291 if (!Modifier.isPublic(defc.getModifiers()) || 4292 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4293 !member.isPublic() || 4294 member.isCallerSensitive()) { 4295 return false; 4296 } 4297 ClassLoader loader = defc.getClassLoader(); 4298 if (loader != null) { 4299 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4300 boolean found = false; 4301 while (sysl != null) { 4302 if (loader == sysl) { found = true; break; } 4303 sysl = sysl.getParent(); 4304 } 4305 if (!found) { 4306 return false; 4307 } 4308 } 4309 try { 4310 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4311 new MemberName(refKind, defc, member.getName(), member.getType())); 4312 if (resolved2 == null) { 4313 return false; 4314 } 4315 checkSecurityManager(defc, resolved2); 4316 } catch (SecurityException ex) { 4317 return false; 4318 } 4319 return true; 4320 } 4321 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4322 throws ReflectiveOperationException { 4323 if (MethodHandleNatives.refKindIsField(refKind)) { 4324 return getDirectFieldNoSecurityManager(refKind, defc, member); 4325 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4326 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4327 } else if (refKind == REF_newInvokeSpecial) { 4328 return getDirectConstructorNoSecurityManager(defc, member); 4329 } 4330 // oops 4331 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4332 } 4333 4334 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4335 } 4336 4337 /** 4338 * Produces a method handle constructing arrays of a desired type, 4339 * as if by the {@code anewarray} bytecode. 4340 * The return type of the method handle will be the array type. 4341 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4342 * 4343 * <p> If the returned method handle is invoked with a negative 4344 * array size, a {@code NegativeArraySizeException} will be thrown. 4345 * 4346 * @param arrayClass an array type 4347 * @return a method handle which can create arrays of the given type 4348 * @throws NullPointerException if the argument is {@code null} 4349 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4350 * @see java.lang.reflect.Array#newInstance(Class, int) 4351 * @jvms 6.5 {@code anewarray} Instruction 4352 * @since 9 4353 */ 4354 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4355 if (!arrayClass.isArray()) { 4356 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4357 } 4358 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4359 bindTo(arrayClass.getComponentType()); 4360 return ani.asType(ani.type().changeReturnType(arrayClass)); 4361 } 4362 4363 /** 4364 * Produces a method handle returning the length of an array, 4365 * as if by the {@code arraylength} bytecode. 4366 * The type of the method handle will have {@code int} as return type, 4367 * and its sole argument will be the array type. 4368 * 4369 * <p> If the returned method handle is invoked with a {@code null} 4370 * array reference, a {@code NullPointerException} will be thrown. 4371 * 4372 * @param arrayClass an array type 4373 * @return a method handle which can retrieve the length of an array of the given array type 4374 * @throws NullPointerException if the argument is {@code null} 4375 * @throws IllegalArgumentException if arrayClass is not an array type 4376 * @jvms 6.5 {@code arraylength} Instruction 4377 * @since 9 4378 */ 4379 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4380 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4381 } 4382 4383 /** 4384 * Produces a method handle giving read access to elements of an array, 4385 * as if by the {@code aaload} bytecode. 4386 * The type of the method handle will have a return type of the array's 4387 * element type. Its first argument will be the array type, 4388 * and the second will be {@code int}. 4389 * 4390 * <p> When the returned method handle is invoked, 4391 * the array reference and array index are checked. 4392 * A {@code NullPointerException} will be thrown if the array reference 4393 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4394 * thrown if the index is negative or if it is greater than or equal to 4395 * the length of the array. 4396 * 4397 * @param arrayClass an array type 4398 * @return a method handle which can load values from the given array type 4399 * @throws NullPointerException if the argument is null 4400 * @throws IllegalArgumentException if arrayClass is not an array type 4401 * @jvms 6.5 {@code aaload} Instruction 4402 */ 4403 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4404 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4405 } 4406 4407 /** 4408 * Produces a method handle giving write access to elements of an array, 4409 * as if by the {@code astore} bytecode. 4410 * The type of the method handle will have a void return type. 4411 * Its last argument will be the array's element type. 4412 * The first and second arguments will be the array type and int. 4413 * 4414 * <p> When the returned method handle is invoked, 4415 * the array reference and array index are checked. 4416 * A {@code NullPointerException} will be thrown if the array reference 4417 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4418 * thrown if the index is negative or if it is greater than or equal to 4419 * the length of the array. 4420 * 4421 * @param arrayClass the class of an array 4422 * @return a method handle which can store values into the array type 4423 * @throws NullPointerException if the argument is null 4424 * @throws IllegalArgumentException if arrayClass is not an array type 4425 * @jvms 6.5 {@code aastore} Instruction 4426 */ 4427 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4428 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4429 } 4430 4431 /** 4432 * Produces a VarHandle giving access to elements of an array of type 4433 * {@code arrayClass}. The VarHandle's variable type is the component type 4434 * of {@code arrayClass} and the list of coordinate types is 4435 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4436 * corresponds to an argument that is an index into an array. 4437 * <p> 4438 * Certain access modes of the returned VarHandle are unsupported under 4439 * the following conditions: 4440 * <ul> 4441 * <li>if the component type is anything other than {@code byte}, 4442 * {@code short}, {@code char}, {@code int}, {@code long}, 4443 * {@code float}, or {@code double} then numeric atomic update access 4444 * modes are unsupported. 4445 * <li>if the component type is anything other than {@code boolean}, 4446 * {@code byte}, {@code short}, {@code char}, {@code int} or 4447 * {@code long} then bitwise atomic update access modes are 4448 * unsupported. 4449 * </ul> 4450 * <p> 4451 * If the component type is {@code float} or {@code double} then numeric 4452 * and atomic update access modes compare values using their bitwise 4453 * representation (see {@link Float#floatToRawIntBits} and 4454 * {@link Double#doubleToRawLongBits}, respectively). 4455 * 4456 * <p> When the returned {@code VarHandle} is invoked, 4457 * the array reference and array index are checked. 4458 * A {@code NullPointerException} will be thrown if the array reference 4459 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4460 * thrown if the index is negative or if it is greater than or equal to 4461 * the length of the array. 4462 * 4463 * @apiNote 4464 * Bitwise comparison of {@code float} values or {@code double} values, 4465 * as performed by the numeric and atomic update access modes, differ 4466 * from the primitive {@code ==} operator and the {@link Float#equals} 4467 * and {@link Double#equals} methods, specifically with respect to 4468 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4469 * Care should be taken when performing a compare and set or a compare 4470 * and exchange operation with such values since the operation may 4471 * unexpectedly fail. 4472 * There are many possible NaN values that are considered to be 4473 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4474 * provided by Java can distinguish between them. Operation failure can 4475 * occur if the expected or witness value is a NaN value and it is 4476 * transformed (perhaps in a platform specific manner) into another NaN 4477 * value, and thus has a different bitwise representation (see 4478 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4479 * details). 4480 * The values {@code -0.0} and {@code +0.0} have different bitwise 4481 * representations but are considered equal when using the primitive 4482 * {@code ==} operator. Operation failure can occur if, for example, a 4483 * numeric algorithm computes an expected value to be say {@code -0.0} 4484 * and previously computed the witness value to be say {@code +0.0}. 4485 * @param arrayClass the class of an array, of type {@code T[]} 4486 * @return a VarHandle giving access to elements of an array 4487 * @throws NullPointerException if the arrayClass is null 4488 * @throws IllegalArgumentException if arrayClass is not an array type 4489 * @since 9 4490 */ 4491 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4492 return VarHandles.makeArrayElementHandle(arrayClass); 4493 } 4494 4495 /** 4496 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4497 * viewed as if it were a different primitive array type, such as 4498 * {@code int[]} or {@code long[]}. 4499 * The VarHandle's variable type is the component type of 4500 * {@code viewArrayClass} and the list of coordinate types is 4501 * {@code (byte[], int)}, where the {@code int} coordinate type 4502 * corresponds to an argument that is an index into a {@code byte[]} array. 4503 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4504 * array, composing bytes to or from a value of the component type of 4505 * {@code viewArrayClass} according to the given endianness. 4506 * <p> 4507 * The supported component types (variables types) are {@code short}, 4508 * {@code char}, {@code int}, {@code long}, {@code float} and 4509 * {@code double}. 4510 * <p> 4511 * Access of bytes at a given index will result in an 4512 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4513 * or greater than the {@code byte[]} array length minus the size (in bytes) 4514 * of {@code T}. 4515 * <p> 4516 * Access of bytes at an index may be aligned or misaligned for {@code T}, 4517 * with respect to the underlying memory address, {@code A} say, associated 4518 * with the array and index. 4519 * If access is misaligned then access for anything other than the 4520 * {@code get} and {@code set} access modes will result in an 4521 * {@code IllegalStateException}. In such cases atomic access is only 4522 * guaranteed with respect to the largest power of two that divides the GCD 4523 * of {@code A} and the size (in bytes) of {@code T}. 4524 * If access is aligned then following access modes are supported and are 4525 * guaranteed to support atomic access: 4526 * <ul> 4527 * <li>read write access modes for all {@code T}, with the exception of 4528 * access modes {@code get} and {@code set} for {@code long} and 4529 * {@code double} on 32-bit platforms. 4530 * <li>atomic update access modes for {@code int}, {@code long}, 4531 * {@code float} or {@code double}. 4532 * (Future major platform releases of the JDK may support additional 4533 * types for certain currently unsupported access modes.) 4534 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4535 * (Future major platform releases of the JDK may support additional 4536 * numeric types for certain currently unsupported access modes.) 4537 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4538 * (Future major platform releases of the JDK may support additional 4539 * numeric types for certain currently unsupported access modes.) 4540 * </ul> 4541 * <p> 4542 * Misaligned access, and therefore atomicity guarantees, may be determined 4543 * for {@code byte[]} arrays without operating on a specific array. Given 4544 * an {@code index}, {@code T} and its corresponding boxed type, 4545 * {@code T_BOX}, misalignment may be determined as follows: 4546 * <pre>{@code 4547 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4548 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 4549 * alignmentOffset(0, sizeOfT); 4550 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 4551 * boolean isMisaligned = misalignedAtIndex != 0; 4552 * }</pre> 4553 * <p> 4554 * If the variable type is {@code float} or {@code double} then atomic 4555 * update access modes compare values using their bitwise representation 4556 * (see {@link Float#floatToRawIntBits} and 4557 * {@link Double#doubleToRawLongBits}, respectively). 4558 * @param viewArrayClass the view array class, with a component type of 4559 * type {@code T} 4560 * @param byteOrder the endianness of the view array elements, as 4561 * stored in the underlying {@code byte} array 4562 * @return a VarHandle giving access to elements of a {@code byte[]} array 4563 * viewed as if elements corresponding to the components type of the view 4564 * array class 4565 * @throws NullPointerException if viewArrayClass or byteOrder is null 4566 * @throws IllegalArgumentException if viewArrayClass is not an array type 4567 * @throws UnsupportedOperationException if the component type of 4568 * viewArrayClass is not supported as a variable type 4569 * @since 9 4570 */ 4571 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4572 ByteOrder byteOrder) throws IllegalArgumentException { 4573 Objects.requireNonNull(byteOrder); 4574 return VarHandles.byteArrayViewHandle(viewArrayClass, 4575 byteOrder == ByteOrder.BIG_ENDIAN); 4576 } 4577 4578 /** 4579 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4580 * viewed as if it were an array of elements of a different primitive 4581 * component type to that of {@code byte}, such as {@code int[]} or 4582 * {@code long[]}. 4583 * The VarHandle's variable type is the component type of 4584 * {@code viewArrayClass} and the list of coordinate types is 4585 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4586 * corresponds to an argument that is an index into a {@code byte[]} array. 4587 * The returned VarHandle accesses bytes at an index in a 4588 * {@code ByteBuffer}, composing bytes to or from a value of the component 4589 * type of {@code viewArrayClass} according to the given endianness. 4590 * <p> 4591 * The supported component types (variables types) are {@code short}, 4592 * {@code char}, {@code int}, {@code long}, {@code float} and 4593 * {@code double}. 4594 * <p> 4595 * Access will result in a {@code ReadOnlyBufferException} for anything 4596 * other than the read access modes if the {@code ByteBuffer} is read-only. 4597 * <p> 4598 * Access of bytes at a given index will result in an 4599 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4600 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4601 * {@code T}. 4602 * <p> 4603 * Access of bytes at an index may be aligned or misaligned for {@code T}, 4604 * with respect to the underlying memory address, {@code A} say, associated 4605 * with the {@code ByteBuffer} and index. 4606 * If access is misaligned then access for anything other than the 4607 * {@code get} and {@code set} access modes will result in an 4608 * {@code IllegalStateException}. In such cases atomic access is only 4609 * guaranteed with respect to the largest power of two that divides the GCD 4610 * of {@code A} and the size (in bytes) of {@code T}. 4611 * If access is aligned then following access modes are supported and are 4612 * guaranteed to support atomic access: 4613 * <ul> 4614 * <li>read write access modes for all {@code T}, with the exception of 4615 * access modes {@code get} and {@code set} for {@code long} and 4616 * {@code double} on 32-bit platforms. 4617 * <li>atomic update access modes for {@code int}, {@code long}, 4618 * {@code float} or {@code double}. 4619 * (Future major platform releases of the JDK may support additional 4620 * types for certain currently unsupported access modes.) 4621 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4622 * (Future major platform releases of the JDK may support additional 4623 * numeric types for certain currently unsupported access modes.) 4624 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4625 * (Future major platform releases of the JDK may support additional 4626 * numeric types for certain currently unsupported access modes.) 4627 * </ul> 4628 * <p> 4629 * Misaligned access, and therefore atomicity guarantees, may be determined 4630 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4631 * {@code index}, {@code T} and its corresponding boxed type, 4632 * {@code T_BOX}, as follows: 4633 * <pre>{@code 4634 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4635 * ByteBuffer bb = ... 4636 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4637 * boolean isMisaligned = misalignedAtIndex != 0; 4638 * }</pre> 4639 * <p> 4640 * If the variable type is {@code float} or {@code double} then atomic 4641 * update access modes compare values using their bitwise representation 4642 * (see {@link Float#floatToRawIntBits} and 4643 * {@link Double#doubleToRawLongBits}, respectively). 4644 * @param viewArrayClass the view array class, with a component type of 4645 * type {@code T} 4646 * @param byteOrder the endianness of the view array elements, as 4647 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4648 * endianness of a {@code ByteBuffer}) 4649 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4650 * viewed as if elements corresponding to the components type of the view 4651 * array class 4652 * @throws NullPointerException if viewArrayClass or byteOrder is null 4653 * @throws IllegalArgumentException if viewArrayClass is not an array type 4654 * @throws UnsupportedOperationException if the component type of 4655 * viewArrayClass is not supported as a variable type 4656 * @since 9 4657 */ 4658 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4659 ByteOrder byteOrder) throws IllegalArgumentException { 4660 Objects.requireNonNull(byteOrder); 4661 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4662 byteOrder == ByteOrder.BIG_ENDIAN); 4663 } 4664 4665 4666 /// method handle invocation (reflective style) 4667 4668 /** 4669 * Produces a method handle which will invoke any method handle of the 4670 * given {@code type}, with a given number of trailing arguments replaced by 4671 * a single trailing {@code Object[]} array. 4672 * The resulting invoker will be a method handle with the following 4673 * arguments: 4674 * <ul> 4675 * <li>a single {@code MethodHandle} target 4676 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4677 * <li>an {@code Object[]} array containing trailing arguments 4678 * </ul> 4679 * <p> 4680 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4681 * the indicated {@code type}. 4682 * That is, if the target is exactly of the given {@code type}, it will behave 4683 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4684 * is used to convert the target to the required {@code type}. 4685 * <p> 4686 * The type of the returned invoker will not be the given {@code type}, but rather 4687 * will have all parameters except the first {@code leadingArgCount} 4688 * replaced by a single array of type {@code Object[]}, which will be 4689 * the final parameter. 4690 * <p> 4691 * Before invoking its target, the invoker will spread the final array, apply 4692 * reference casts as necessary, and unbox and widen primitive arguments. 4693 * If, when the invoker is called, the supplied array argument does 4694 * not have the correct number of elements, the invoker will throw 4695 * an {@link IllegalArgumentException} instead of invoking the target. 4696 * <p> 4697 * This method is equivalent to the following code (though it may be more efficient): 4698 * {@snippet lang="java" : 4699 MethodHandle invoker = MethodHandles.invoker(type); 4700 int spreadArgCount = type.parameterCount() - leadingArgCount; 4701 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4702 return invoker; 4703 * } 4704 * This method throws no reflective or security exceptions. 4705 * @param type the desired target type 4706 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4707 * @return a method handle suitable for invoking any method handle of the given type 4708 * @throws NullPointerException if {@code type} is null 4709 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4710 * the range from 0 to {@code type.parameterCount()} inclusive, 4711 * or if the resulting method handle's type would have 4712 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4713 */ 4714 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4715 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4716 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4717 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4718 return type.invokers().spreadInvoker(leadingArgCount); 4719 } 4720 4721 /** 4722 * Produces a special <em>invoker method handle</em> which can be used to 4723 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4724 * The resulting invoker will have a type which is 4725 * exactly equal to the desired type, except that it will accept 4726 * an additional leading argument of type {@code MethodHandle}. 4727 * <p> 4728 * This method is equivalent to the following code (though it may be more efficient): 4729 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4730 * 4731 * <p style="font-size:smaller;"> 4732 * <em>Discussion:</em> 4733 * Invoker method handles can be useful when working with variable method handles 4734 * of unknown types. 4735 * For example, to emulate an {@code invokeExact} call to a variable method 4736 * handle {@code M}, extract its type {@code T}, 4737 * look up the invoker method {@code X} for {@code T}, 4738 * and call the invoker method, as {@code X.invoke(T, A...)}. 4739 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4740 * is unknown.) 4741 * If spreading, collecting, or other argument transformations are required, 4742 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4743 * method handle values, as long as they are compatible with the type of {@code X}. 4744 * <p style="font-size:smaller;"> 4745 * <em>(Note: The invoker method is not available via the Core Reflection API. 4746 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4747 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4748 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4749 * <p> 4750 * This method throws no reflective or security exceptions. 4751 * @param type the desired target type 4752 * @return a method handle suitable for invoking any method handle of the given type 4753 * @throws IllegalArgumentException if the resulting method handle's type would have 4754 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4755 */ 4756 public static MethodHandle exactInvoker(MethodType type) { 4757 return type.invokers().exactInvoker(); 4758 } 4759 4760 /** 4761 * Produces a special <em>invoker method handle</em> which can be used to 4762 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4763 * The resulting invoker will have a type which is 4764 * exactly equal to the desired type, except that it will accept 4765 * an additional leading argument of type {@code MethodHandle}. 4766 * <p> 4767 * Before invoking its target, if the target differs from the expected type, 4768 * the invoker will apply reference casts as 4769 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4770 * Similarly, the return value will be converted as necessary. 4771 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4772 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4773 * <p> 4774 * This method is equivalent to the following code (though it may be more efficient): 4775 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4776 * <p style="font-size:smaller;"> 4777 * <em>Discussion:</em> 4778 * A {@linkplain MethodType#genericMethodType general method type} is one which 4779 * mentions only {@code Object} arguments and return values. 4780 * An invoker for such a type is capable of calling any method handle 4781 * of the same arity as the general type. 4782 * <p style="font-size:smaller;"> 4783 * <em>(Note: The invoker method is not available via the Core Reflection API. 4784 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4785 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4786 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4787 * <p> 4788 * This method throws no reflective or security exceptions. 4789 * @param type the desired target type 4790 * @return a method handle suitable for invoking any method handle convertible to the given type 4791 * @throws IllegalArgumentException if the resulting method handle's type would have 4792 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4793 */ 4794 public static MethodHandle invoker(MethodType type) { 4795 return type.invokers().genericInvoker(); 4796 } 4797 4798 /** 4799 * Produces a special <em>invoker method handle</em> which can be used to 4800 * invoke a signature-polymorphic access mode method on any VarHandle whose 4801 * associated access mode type is compatible with the given type. 4802 * The resulting invoker will have a type which is exactly equal to the 4803 * desired given type, except that it will accept an additional leading 4804 * argument of type {@code VarHandle}. 4805 * 4806 * @param accessMode the VarHandle access mode 4807 * @param type the desired target type 4808 * @return a method handle suitable for invoking an access mode method of 4809 * any VarHandle whose access mode type is of the given type. 4810 * @since 9 4811 */ 4812 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4813 return type.invokers().varHandleMethodExactInvoker(accessMode); 4814 } 4815 4816 /** 4817 * Produces a special <em>invoker method handle</em> which can be used to 4818 * invoke a signature-polymorphic access mode method on any VarHandle whose 4819 * associated access mode type is compatible with the given type. 4820 * The resulting invoker will have a type which is exactly equal to the 4821 * desired given type, except that it will accept an additional leading 4822 * argument of type {@code VarHandle}. 4823 * <p> 4824 * Before invoking its target, if the access mode type differs from the 4825 * desired given type, the invoker will apply reference casts as necessary 4826 * and box, unbox, or widen primitive values, as if by 4827 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4828 * converted as necessary. 4829 * <p> 4830 * This method is equivalent to the following code (though it may be more 4831 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4832 * 4833 * @param accessMode the VarHandle access mode 4834 * @param type the desired target type 4835 * @return a method handle suitable for invoking an access mode method of 4836 * any VarHandle whose access mode type is convertible to the given 4837 * type. 4838 * @since 9 4839 */ 4840 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4841 return type.invokers().varHandleMethodInvoker(accessMode); 4842 } 4843 4844 /*non-public*/ 4845 static MethodHandle basicInvoker(MethodType type) { 4846 return type.invokers().basicInvoker(); 4847 } 4848 4849 /// method handle modification (creation from other method handles) 4850 4851 /** 4852 * Produces a method handle which adapts the type of the 4853 * given method handle to a new type by pairwise argument and return type conversion. 4854 * The original type and new type must have the same number of arguments. 4855 * The resulting method handle is guaranteed to report a type 4856 * which is equal to the desired new type. 4857 * <p> 4858 * If the original type and new type are equal, returns target. 4859 * <p> 4860 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4861 * and some additional conversions are also applied if those conversions fail. 4862 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4863 * if possible, before or instead of any conversions done by {@code asType}: 4864 * <ul> 4865 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4866 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4867 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4868 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4869 * the boolean is converted to a byte value, 1 for true, 0 for false. 4870 * (This treatment follows the usage of the bytecode verifier.) 4871 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4872 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4873 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4874 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4875 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4876 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4877 * widening and/or narrowing.) 4878 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4879 * conversion will be applied at runtime, possibly followed 4880 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4881 * possibly followed by a conversion from byte to boolean by testing 4882 * the low-order bit. 4883 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4884 * and if the reference is null at runtime, a zero value is introduced. 4885 * </ul> 4886 * @param target the method handle to invoke after arguments are retyped 4887 * @param newType the expected type of the new method handle 4888 * @return a method handle which delegates to the target after performing 4889 * any necessary argument conversions, and arranges for any 4890 * necessary return value conversions 4891 * @throws NullPointerException if either argument is null 4892 * @throws WrongMethodTypeException if the conversion cannot be made 4893 * @see MethodHandle#asType 4894 */ 4895 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4896 explicitCastArgumentsChecks(target, newType); 4897 // use the asTypeCache when possible: 4898 MethodType oldType = target.type(); 4899 if (oldType == newType) return target; 4900 if (oldType.explicitCastEquivalentToAsType(newType)) { 4901 return target.asFixedArity().asType(newType); 4902 } 4903 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4904 } 4905 4906 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4907 if (target.type().parameterCount() != newType.parameterCount()) { 4908 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4909 } 4910 } 4911 4912 /** 4913 * Produces a method handle which adapts the calling sequence of the 4914 * given method handle to a new type, by reordering the arguments. 4915 * The resulting method handle is guaranteed to report a type 4916 * which is equal to the desired new type. 4917 * <p> 4918 * The given array controls the reordering. 4919 * Call {@code #I} the number of incoming parameters (the value 4920 * {@code newType.parameterCount()}, and call {@code #O} the number 4921 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4922 * Then the length of the reordering array must be {@code #O}, 4923 * and each element must be a non-negative number less than {@code #I}. 4924 * For every {@code N} less than {@code #O}, the {@code N}-th 4925 * outgoing argument will be taken from the {@code I}-th incoming 4926 * argument, where {@code I} is {@code reorder[N]}. 4927 * <p> 4928 * No argument or return value conversions are applied. 4929 * The type of each incoming argument, as determined by {@code newType}, 4930 * must be identical to the type of the corresponding outgoing parameter 4931 * or parameters in the target method handle. 4932 * The return type of {@code newType} must be identical to the return 4933 * type of the original target. 4934 * <p> 4935 * The reordering array need not specify an actual permutation. 4936 * An incoming argument will be duplicated if its index appears 4937 * more than once in the array, and an incoming argument will be dropped 4938 * if its index does not appear in the array. 4939 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4940 * incoming arguments which are not mentioned in the reordering array 4941 * may be of any type, as determined only by {@code newType}. 4942 * {@snippet lang="java" : 4943 import static java.lang.invoke.MethodHandles.*; 4944 import static java.lang.invoke.MethodType.*; 4945 ... 4946 MethodType intfn1 = methodType(int.class, int.class); 4947 MethodType intfn2 = methodType(int.class, int.class, int.class); 4948 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4949 assert(sub.type().equals(intfn2)); 4950 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4951 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4952 assert((int)rsub.invokeExact(1, 100) == 99); 4953 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4954 assert(add.type().equals(intfn2)); 4955 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4956 assert(twice.type().equals(intfn1)); 4957 assert((int)twice.invokeExact(21) == 42); 4958 * } 4959 * <p> 4960 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4961 * variable-arity method handle}, even if the original target method handle was. 4962 * @param target the method handle to invoke after arguments are reordered 4963 * @param newType the expected type of the new method handle 4964 * @param reorder an index array which controls the reordering 4965 * @return a method handle which delegates to the target after it 4966 * drops unused arguments and moves and/or duplicates the other arguments 4967 * @throws NullPointerException if any argument is null 4968 * @throws IllegalArgumentException if the index array length is not equal to 4969 * the arity of the target, or if any index array element 4970 * not a valid index for a parameter of {@code newType}, 4971 * or if two corresponding parameter types in 4972 * {@code target.type()} and {@code newType} are not identical, 4973 */ 4974 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4975 reorder = reorder.clone(); // get a private copy 4976 MethodType oldType = target.type(); 4977 permuteArgumentChecks(reorder, newType, oldType); 4978 // first detect dropped arguments and handle them separately 4979 int[] originalReorder = reorder; 4980 BoundMethodHandle result = target.rebind(); 4981 LambdaForm form = result.form; 4982 int newArity = newType.parameterCount(); 4983 // Normalize the reordering into a real permutation, 4984 // by removing duplicates and adding dropped elements. 4985 // This somewhat improves lambda form caching, as well 4986 // as simplifying the transform by breaking it up into steps. 4987 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4988 if (ddIdx > 0) { 4989 // We found a duplicated entry at reorder[ddIdx]. 4990 // Example: (x,y,z)->asList(x,y,z) 4991 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4992 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4993 // The starred element corresponds to the argument 4994 // deleted by the dupArgumentForm transform. 4995 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4996 boolean killFirst = false; 4997 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4998 // Set killFirst if the dup is larger than an intervening position. 4999 // This will remove at least one inversion from the permutation. 5000 if (dupVal > val) killFirst = true; 5001 } 5002 if (!killFirst) { 5003 srcPos = dstPos; 5004 dstPos = ddIdx; 5005 } 5006 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 5007 assert (reorder[srcPos] == reorder[dstPos]); 5008 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 5009 // contract the reordering by removing the element at dstPos 5010 int tailPos = dstPos + 1; 5011 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 5012 reorder = Arrays.copyOf(reorder, reorder.length - 1); 5013 } else { 5014 int dropVal = ~ddIdx, insPos = 0; 5015 while (insPos < reorder.length && reorder[insPos] < dropVal) { 5016 // Find first element of reorder larger than dropVal. 5017 // This is where we will insert the dropVal. 5018 insPos += 1; 5019 } 5020 Class<?> ptype = newType.parameterType(dropVal); 5021 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 5022 oldType = oldType.insertParameterTypes(insPos, ptype); 5023 // expand the reordering by inserting an element at insPos 5024 int tailPos = insPos + 1; 5025 reorder = Arrays.copyOf(reorder, reorder.length + 1); 5026 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 5027 reorder[insPos] = dropVal; 5028 } 5029 assert (permuteArgumentChecks(reorder, newType, oldType)); 5030 } 5031 assert (reorder.length == newArity); // a perfect permutation 5032 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 5033 form = form.editor().permuteArgumentsForm(1, reorder); 5034 if (newType == result.type() && form == result.internalForm()) 5035 return result; 5036 return result.copyWith(newType, form); 5037 } 5038 5039 /** 5040 * Return an indication of any duplicate or omission in reorder. 5041 * If the reorder contains a duplicate entry, return the index of the second occurrence. 5042 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 5043 * Otherwise, return zero. 5044 * If an element not in [0..newArity-1] is encountered, return reorder.length. 5045 */ 5046 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 5047 final int BIT_LIMIT = 63; // max number of bits in bit mask 5048 if (newArity < BIT_LIMIT) { 5049 long mask = 0; 5050 for (int i = 0; i < reorder.length; i++) { 5051 int arg = reorder[i]; 5052 if (arg >= newArity) { 5053 return reorder.length; 5054 } 5055 long bit = 1L << arg; 5056 if ((mask & bit) != 0) { 5057 return i; // >0 indicates a dup 5058 } 5059 mask |= bit; 5060 } 5061 if (mask == (1L << newArity) - 1) { 5062 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 5063 return 0; 5064 } 5065 // find first zero 5066 long zeroBit = Long.lowestOneBit(~mask); 5067 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 5068 assert(zeroPos <= newArity); 5069 if (zeroPos == newArity) { 5070 return 0; 5071 } 5072 return ~zeroPos; 5073 } else { 5074 // same algorithm, different bit set 5075 BitSet mask = new BitSet(newArity); 5076 for (int i = 0; i < reorder.length; i++) { 5077 int arg = reorder[i]; 5078 if (arg >= newArity) { 5079 return reorder.length; 5080 } 5081 if (mask.get(arg)) { 5082 return i; // >0 indicates a dup 5083 } 5084 mask.set(arg); 5085 } 5086 int zeroPos = mask.nextClearBit(0); 5087 assert(zeroPos <= newArity); 5088 if (zeroPos == newArity) { 5089 return 0; 5090 } 5091 return ~zeroPos; 5092 } 5093 } 5094 5095 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 5096 if (newType.returnType() != oldType.returnType()) 5097 throw newIllegalArgumentException("return types do not match", 5098 oldType, newType); 5099 if (reorder.length != oldType.parameterCount()) 5100 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 5101 oldType, Arrays.toString(reorder)); 5102 5103 int limit = newType.parameterCount(); 5104 for (int j = 0; j < reorder.length; j++) { 5105 int i = reorder[j]; 5106 if (i < 0 || i >= limit) { 5107 throw newIllegalArgumentException("index is out of bounds for new type", 5108 i, newType); 5109 } 5110 Class<?> src = newType.parameterType(i); 5111 Class<?> dst = oldType.parameterType(j); 5112 if (src != dst) 5113 throw newIllegalArgumentException("parameter types do not match after reorder", 5114 oldType, newType); 5115 } 5116 return true; 5117 } 5118 5119 /** 5120 * Produces a method handle of the requested return type which returns the given 5121 * constant value every time it is invoked. 5122 * <p> 5123 * Before the method handle is returned, the passed-in value is converted to the requested type. 5124 * If the requested type is primitive, widening primitive conversions are attempted, 5125 * else reference conversions are attempted. 5126 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5127 * @param type the return type of the desired method handle 5128 * @param value the value to return 5129 * @return a method handle of the given return type and no arguments, which always returns the given value 5130 * @throws NullPointerException if the {@code type} argument is null 5131 * @throws ClassCastException if the value cannot be converted to the required return type 5132 * @throws IllegalArgumentException if the given type is {@code void.class} 5133 */ 5134 public static MethodHandle constant(Class<?> type, Object value) { 5135 if (type.isPrimitive()) { 5136 if (type == void.class) 5137 throw newIllegalArgumentException("void type"); 5138 Wrapper w = Wrapper.forPrimitiveType(type); 5139 value = w.convert(value, type); 5140 if (w.zero().equals(value)) 5141 return zero(w, type); 5142 return insertArguments(identity(type), 0, value); 5143 } else { 5144 if (value == null) 5145 return zero(Wrapper.OBJECT, type); 5146 return identity(type).bindTo(value); 5147 } 5148 } 5149 5150 /** 5151 * Produces a method handle which returns its sole argument when invoked. 5152 * @param type the type of the sole parameter and return value of the desired method handle 5153 * @return a unary method handle which accepts and returns the given type 5154 * @throws NullPointerException if the argument is null 5155 * @throws IllegalArgumentException if the given type is {@code void.class} 5156 */ 5157 public static MethodHandle identity(Class<?> type) { 5158 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5159 int pos = btw.ordinal(); 5160 MethodHandle ident = IDENTITY_MHS[pos]; 5161 if (ident == null) { 5162 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5163 } 5164 if (ident.type().returnType() == type) 5165 return ident; 5166 // something like identity(Foo.class); do not bother to intern these 5167 assert (btw == Wrapper.OBJECT); 5168 return makeIdentity(type); 5169 } 5170 5171 /** 5172 * Produces a constant method handle of the requested return type which 5173 * returns the default value for that type every time it is invoked. 5174 * The resulting constant method handle will have no side effects. 5175 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5176 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5177 * since {@code explicitCastArguments} converts {@code null} to default values. 5178 * @param type the expected return type of the desired method handle 5179 * @return a constant method handle that takes no arguments 5180 * and returns the default value of the given type (or void, if the type is void) 5181 * @throws NullPointerException if the argument is null 5182 * @see MethodHandles#constant 5183 * @see MethodHandles#empty 5184 * @see MethodHandles#explicitCastArguments 5185 * @since 9 5186 */ 5187 public static MethodHandle zero(Class<?> type) { 5188 Objects.requireNonNull(type); 5189 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5190 } 5191 5192 private static MethodHandle identityOrVoid(Class<?> type) { 5193 return type == void.class ? zero(type) : identity(type); 5194 } 5195 5196 /** 5197 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5198 * and returns a suitable default depending on the return type. 5199 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5200 * <p>The returned method handle is equivalent to 5201 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5202 * 5203 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5204 * {@code guardWithTest(pred, target, empty(target.type())}. 5205 * @param type the type of the desired method handle 5206 * @return a constant method handle of the given type, which returns a default value of the given return type 5207 * @throws NullPointerException if the argument is null 5208 * @see MethodHandles#zero 5209 * @see MethodHandles#constant 5210 * @since 9 5211 */ 5212 public static MethodHandle empty(MethodType type) { 5213 Objects.requireNonNull(type); 5214 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5215 } 5216 5217 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5218 private static MethodHandle makeIdentity(Class<?> ptype) { 5219 MethodType mtype = methodType(ptype, ptype); 5220 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5221 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5222 } 5223 5224 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5225 int pos = btw.ordinal(); 5226 MethodHandle zero = ZERO_MHS[pos]; 5227 if (zero == null) { 5228 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5229 } 5230 if (zero.type().returnType() == rtype) 5231 return zero; 5232 assert(btw == Wrapper.OBJECT); 5233 return makeZero(rtype); 5234 } 5235 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5236 private static MethodHandle makeZero(Class<?> rtype) { 5237 MethodType mtype = methodType(rtype); 5238 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5239 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5240 } 5241 5242 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5243 // Simulate a CAS, to avoid racy duplication of results. 5244 MethodHandle prev = cache[pos]; 5245 if (prev != null) return prev; 5246 return cache[pos] = value; 5247 } 5248 5249 /** 5250 * Provides a target method handle with one or more <em>bound arguments</em> 5251 * in advance of the method handle's invocation. 5252 * The formal parameters to the target corresponding to the bound 5253 * arguments are called <em>bound parameters</em>. 5254 * Returns a new method handle which saves away the bound arguments. 5255 * When it is invoked, it receives arguments for any non-bound parameters, 5256 * binds the saved arguments to their corresponding parameters, 5257 * and calls the original target. 5258 * <p> 5259 * The type of the new method handle will drop the types for the bound 5260 * parameters from the original target type, since the new method handle 5261 * will no longer require those arguments to be supplied by its callers. 5262 * <p> 5263 * Each given argument object must match the corresponding bound parameter type. 5264 * If a bound parameter type is a primitive, the argument object 5265 * must be a wrapper, and will be unboxed to produce the primitive value. 5266 * <p> 5267 * The {@code pos} argument selects which parameters are to be bound. 5268 * It may range between zero and <i>N-L</i> (inclusively), 5269 * where <i>N</i> is the arity of the target method handle 5270 * and <i>L</i> is the length of the values array. 5271 * <p> 5272 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5273 * variable-arity method handle}, even if the original target method handle was. 5274 * @param target the method handle to invoke after the argument is inserted 5275 * @param pos where to insert the argument (zero for the first) 5276 * @param values the series of arguments to insert 5277 * @return a method handle which inserts an additional argument, 5278 * before calling the original method handle 5279 * @throws NullPointerException if the target or the {@code values} array is null 5280 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 5281 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5282 * is the length of the values array. 5283 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5284 * type. 5285 * @see MethodHandle#bindTo 5286 */ 5287 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5288 int insCount = values.length; 5289 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5290 if (insCount == 0) return target; 5291 BoundMethodHandle result = target.rebind(); 5292 for (int i = 0; i < insCount; i++) { 5293 Object value = values[i]; 5294 Class<?> ptype = ptypes[pos+i]; 5295 if (ptype.isPrimitive()) { 5296 result = insertArgumentPrimitive(result, pos, ptype, value); 5297 } else { 5298 value = ptype.cast(value); // throw CCE if needed 5299 result = result.bindArgumentL(pos, value); 5300 } 5301 } 5302 return result; 5303 } 5304 5305 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5306 Class<?> ptype, Object value) { 5307 Wrapper w = Wrapper.forPrimitiveType(ptype); 5308 // perform unboxing and/or primitive conversion 5309 value = w.convert(value, ptype); 5310 return switch (w) { 5311 case INT -> result.bindArgumentI(pos, (int) value); 5312 case LONG -> result.bindArgumentJ(pos, (long) value); 5313 case FLOAT -> result.bindArgumentF(pos, (float) value); 5314 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5315 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5316 }; 5317 } 5318 5319 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5320 MethodType oldType = target.type(); 5321 int outargs = oldType.parameterCount(); 5322 int inargs = outargs - insCount; 5323 if (inargs < 0) 5324 throw newIllegalArgumentException("too many values to insert"); 5325 if (pos < 0 || pos > inargs) 5326 throw newIllegalArgumentException("no argument type to append"); 5327 return oldType.ptypes(); 5328 } 5329 5330 /** 5331 * Produces a method handle which will discard some dummy arguments 5332 * before calling some other specified <i>target</i> method handle. 5333 * The type of the new method handle will be the same as the target's type, 5334 * except it will also include the dummy argument types, 5335 * at some given position. 5336 * <p> 5337 * The {@code pos} argument may range between zero and <i>N</i>, 5338 * where <i>N</i> is the arity of the target. 5339 * If {@code pos} is zero, the dummy arguments will precede 5340 * the target's real arguments; if {@code pos} is <i>N</i> 5341 * they will come after. 5342 * <p> 5343 * <b>Example:</b> 5344 * {@snippet lang="java" : 5345 import static java.lang.invoke.MethodHandles.*; 5346 import static java.lang.invoke.MethodType.*; 5347 ... 5348 MethodHandle cat = lookup().findVirtual(String.class, 5349 "concat", methodType(String.class, String.class)); 5350 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5351 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5352 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5353 assertEquals(bigType, d0.type()); 5354 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5355 * } 5356 * <p> 5357 * This method is also equivalent to the following code: 5358 * <blockquote><pre> 5359 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5360 * </pre></blockquote> 5361 * @param target the method handle to invoke after the arguments are dropped 5362 * @param pos position of first argument to drop (zero for the leftmost) 5363 * @param valueTypes the type(s) of the argument(s) to drop 5364 * @return a method handle which drops arguments of the given types, 5365 * before calling the original method handle 5366 * @throws NullPointerException if the target is null, 5367 * or if the {@code valueTypes} list or any of its elements is null 5368 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5369 * or if {@code pos} is negative or greater than the arity of the target, 5370 * or if the new method handle's type would have too many parameters 5371 */ 5372 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5373 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5374 } 5375 5376 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5377 MethodType oldType = target.type(); // get NPE 5378 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5379 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5380 if (dropped == 0) return target; 5381 BoundMethodHandle result = target.rebind(); 5382 LambdaForm lform = result.form; 5383 int insertFormArg = 1 + pos; 5384 for (Class<?> ptype : valueTypes) { 5385 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5386 } 5387 result = result.copyWith(newType, lform); 5388 return result; 5389 } 5390 5391 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5392 int dropped = valueTypes.length; 5393 MethodType.checkSlotCount(dropped); 5394 int outargs = oldType.parameterCount(); 5395 int inargs = outargs + dropped; 5396 if (pos < 0 || pos > outargs) 5397 throw newIllegalArgumentException("no argument type to remove" 5398 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5399 ); 5400 return dropped; 5401 } 5402 5403 /** 5404 * Produces a method handle which will discard some dummy arguments 5405 * before calling some other specified <i>target</i> method handle. 5406 * The type of the new method handle will be the same as the target's type, 5407 * except it will also include the dummy argument types, 5408 * at some given position. 5409 * <p> 5410 * The {@code pos} argument may range between zero and <i>N</i>, 5411 * where <i>N</i> is the arity of the target. 5412 * If {@code pos} is zero, the dummy arguments will precede 5413 * the target's real arguments; if {@code pos} is <i>N</i> 5414 * they will come after. 5415 * @apiNote 5416 * {@snippet lang="java" : 5417 import static java.lang.invoke.MethodHandles.*; 5418 import static java.lang.invoke.MethodType.*; 5419 ... 5420 MethodHandle cat = lookup().findVirtual(String.class, 5421 "concat", methodType(String.class, String.class)); 5422 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5423 MethodHandle d0 = dropArguments(cat, 0, String.class); 5424 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5425 MethodHandle d1 = dropArguments(cat, 1, String.class); 5426 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5427 MethodHandle d2 = dropArguments(cat, 2, String.class); 5428 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5429 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5430 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5431 * } 5432 * <p> 5433 * This method is also equivalent to the following code: 5434 * <blockquote><pre> 5435 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5436 * </pre></blockquote> 5437 * @param target the method handle to invoke after the arguments are dropped 5438 * @param pos position of first argument to drop (zero for the leftmost) 5439 * @param valueTypes the type(s) of the argument(s) to drop 5440 * @return a method handle which drops arguments of the given types, 5441 * before calling the original method handle 5442 * @throws NullPointerException if the target is null, 5443 * or if the {@code valueTypes} array or any of its elements is null 5444 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5445 * or if {@code pos} is negative or greater than the arity of the target, 5446 * or if the new method handle's type would have 5447 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5448 */ 5449 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5450 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5451 } 5452 5453 /* Convenience overloads for trusting internal low-arity call-sites */ 5454 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5455 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5456 } 5457 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5458 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5459 } 5460 5461 // private version which allows caller some freedom with error handling 5462 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5463 boolean nullOnFailure) { 5464 Class<?>[] oldTypes = target.type().ptypes(); 5465 int match = oldTypes.length; 5466 if (skip != 0) { 5467 if (skip < 0 || skip > match) { 5468 throw newIllegalArgumentException("illegal skip", skip, target); 5469 } 5470 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5471 match -= skip; 5472 } 5473 Class<?>[] addTypes = newTypes; 5474 int add = addTypes.length; 5475 if (pos != 0) { 5476 if (pos < 0 || pos > add) { 5477 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5478 } 5479 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5480 add -= pos; 5481 assert(addTypes.length == add); 5482 } 5483 // Do not add types which already match the existing arguments. 5484 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5485 if (nullOnFailure) { 5486 return null; 5487 } 5488 throw newIllegalArgumentException("argument lists do not match", 5489 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5490 } 5491 addTypes = Arrays.copyOfRange(addTypes, match, add); 5492 add -= match; 5493 assert(addTypes.length == add); 5494 // newTypes: ( P*[pos], M*[match], A*[add] ) 5495 // target: ( S*[skip], M*[match] ) 5496 MethodHandle adapter = target; 5497 if (add > 0) { 5498 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5499 } 5500 // adapter: (S*[skip], M*[match], A*[add] ) 5501 if (pos > 0) { 5502 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5503 } 5504 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5505 return adapter; 5506 } 5507 5508 /** 5509 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5510 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5511 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5512 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5513 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5514 * {@link #dropArguments(MethodHandle, int, Class[])}. 5515 * <p> 5516 * The resulting handle will have the same return type as the target handle. 5517 * <p> 5518 * In more formal terms, assume these two type lists:<ul> 5519 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5520 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5521 * {@code newTypes}. 5522 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5523 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5524 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5525 * sub-list. 5526 * </ul> 5527 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5528 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5529 * {@link #dropArguments(MethodHandle, int, Class[])}. 5530 * 5531 * @apiNote 5532 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5533 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5534 * {@snippet lang="java" : 5535 import static java.lang.invoke.MethodHandles.*; 5536 import static java.lang.invoke.MethodType.*; 5537 ... 5538 ... 5539 MethodHandle h0 = constant(boolean.class, true); 5540 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5541 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5542 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5543 if (h1.type().parameterCount() < h2.type().parameterCount()) 5544 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5545 else 5546 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5547 MethodHandle h3 = guardWithTest(h0, h1, h2); 5548 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5549 * } 5550 * @param target the method handle to adapt 5551 * @param skip number of targets parameters to disregard (they will be unchanged) 5552 * @param newTypes the list of types to match {@code target}'s parameter type list to 5553 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5554 * @return a possibly adapted method handle 5555 * @throws NullPointerException if either argument is null 5556 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5557 * or if {@code skip} is negative or greater than the arity of the target, 5558 * or if {@code pos} is negative or greater than the newTypes list size, 5559 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5560 * {@code pos}. 5561 * @since 9 5562 */ 5563 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5564 Objects.requireNonNull(target); 5565 Objects.requireNonNull(newTypes); 5566 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5567 } 5568 5569 /** 5570 * Drop the return value of the target handle (if any). 5571 * The returned method handle will have a {@code void} return type. 5572 * 5573 * @param target the method handle to adapt 5574 * @return a possibly adapted method handle 5575 * @throws NullPointerException if {@code target} is null 5576 * @since 16 5577 */ 5578 public static MethodHandle dropReturn(MethodHandle target) { 5579 Objects.requireNonNull(target); 5580 MethodType oldType = target.type(); 5581 Class<?> oldReturnType = oldType.returnType(); 5582 if (oldReturnType == void.class) 5583 return target; 5584 MethodType newType = oldType.changeReturnType(void.class); 5585 BoundMethodHandle result = target.rebind(); 5586 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5587 result = result.copyWith(newType, lform); 5588 return result; 5589 } 5590 5591 /** 5592 * Adapts a target method handle by pre-processing 5593 * one or more of its arguments, each with its own unary filter function, 5594 * and then calling the target with each pre-processed argument 5595 * replaced by the result of its corresponding filter function. 5596 * <p> 5597 * The pre-processing is performed by one or more method handles, 5598 * specified in the elements of the {@code filters} array. 5599 * The first element of the filter array corresponds to the {@code pos} 5600 * argument of the target, and so on in sequence. 5601 * The filter functions are invoked in left to right order. 5602 * <p> 5603 * Null arguments in the array are treated as identity functions, 5604 * and the corresponding arguments left unchanged. 5605 * (If there are no non-null elements in the array, the original target is returned.) 5606 * Each filter is applied to the corresponding argument of the adapter. 5607 * <p> 5608 * If a filter {@code F} applies to the {@code N}th argument of 5609 * the target, then {@code F} must be a method handle which 5610 * takes exactly one argument. The type of {@code F}'s sole argument 5611 * replaces the corresponding argument type of the target 5612 * in the resulting adapted method handle. 5613 * The return type of {@code F} must be identical to the corresponding 5614 * parameter type of the target. 5615 * <p> 5616 * It is an error if there are elements of {@code filters} 5617 * (null or not) 5618 * which do not correspond to argument positions in the target. 5619 * <p><b>Example:</b> 5620 * {@snippet lang="java" : 5621 import static java.lang.invoke.MethodHandles.*; 5622 import static java.lang.invoke.MethodType.*; 5623 ... 5624 MethodHandle cat = lookup().findVirtual(String.class, 5625 "concat", methodType(String.class, String.class)); 5626 MethodHandle upcase = lookup().findVirtual(String.class, 5627 "toUpperCase", methodType(String.class)); 5628 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5629 MethodHandle f0 = filterArguments(cat, 0, upcase); 5630 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5631 MethodHandle f1 = filterArguments(cat, 1, upcase); 5632 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5633 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5634 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5635 * } 5636 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5637 * denotes the return type of both the {@code target} and resulting adapter. 5638 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5639 * of the parameters and arguments that precede and follow the filter position 5640 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5641 * values of the filtered parameters and arguments; they also represent the 5642 * return types of the {@code filter[i]} handles. The latter accept arguments 5643 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5644 * the resulting adapter. 5645 * {@snippet lang="java" : 5646 * T target(P... p, A[i]... a[i], B... b); 5647 * A[i] filter[i](V[i]); 5648 * T adapter(P... p, V[i]... v[i], B... b) { 5649 * return target(p..., filter[i](v[i])..., b...); 5650 * } 5651 * } 5652 * <p> 5653 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5654 * variable-arity method handle}, even if the original target method handle was. 5655 * 5656 * @param target the method handle to invoke after arguments are filtered 5657 * @param pos the position of the first argument to filter 5658 * @param filters method handles to call initially on filtered arguments 5659 * @return method handle which incorporates the specified argument filtering logic 5660 * @throws NullPointerException if the target is null 5661 * or if the {@code filters} array is null 5662 * @throws IllegalArgumentException if a non-null element of {@code filters} 5663 * does not match a corresponding argument type of target as described above, 5664 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5665 * or if the resulting method handle's type would have 5666 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5667 */ 5668 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5669 // In method types arguments start at index 0, while the LF 5670 // editor have the MH receiver at position 0 - adjust appropriately. 5671 final int MH_RECEIVER_OFFSET = 1; 5672 filterArgumentsCheckArity(target, pos, filters); 5673 MethodHandle adapter = target; 5674 5675 // keep track of currently matched filters, as to optimize repeated filters 5676 int index = 0; 5677 int[] positions = new int[filters.length]; 5678 MethodHandle filter = null; 5679 5680 // process filters in reverse order so that the invocation of 5681 // the resulting adapter will invoke the filters in left-to-right order 5682 for (int i = filters.length - 1; i >= 0; --i) { 5683 MethodHandle newFilter = filters[i]; 5684 if (newFilter == null) continue; // ignore null elements of filters 5685 5686 // flush changes on update 5687 if (filter != newFilter) { 5688 if (filter != null) { 5689 if (index > 1) { 5690 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5691 } else { 5692 adapter = filterArgument(adapter, positions[0] - 1, filter); 5693 } 5694 } 5695 filter = newFilter; 5696 index = 0; 5697 } 5698 5699 filterArgumentChecks(target, pos + i, newFilter); 5700 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5701 } 5702 if (index > 1) { 5703 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5704 } else if (index == 1) { 5705 adapter = filterArgument(adapter, positions[0] - 1, filter); 5706 } 5707 return adapter; 5708 } 5709 5710 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5711 MethodType targetType = adapter.type(); 5712 MethodType filterType = filter.type(); 5713 BoundMethodHandle result = adapter.rebind(); 5714 Class<?> newParamType = filterType.parameterType(0); 5715 5716 Class<?>[] ptypes = targetType.ptypes().clone(); 5717 for (int pos : positions) { 5718 ptypes[pos - 1] = newParamType; 5719 } 5720 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5721 5722 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5723 return result.copyWithExtendL(newType, lform, filter); 5724 } 5725 5726 /*non-public*/ 5727 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5728 filterArgumentChecks(target, pos, filter); 5729 MethodType targetType = target.type(); 5730 MethodType filterType = filter.type(); 5731 BoundMethodHandle result = target.rebind(); 5732 Class<?> newParamType = filterType.parameterType(0); 5733 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5734 MethodType newType = targetType.changeParameterType(pos, newParamType); 5735 result = result.copyWithExtendL(newType, lform, filter); 5736 return result; 5737 } 5738 5739 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5740 MethodType targetType = target.type(); 5741 int maxPos = targetType.parameterCount(); 5742 if (pos + filters.length > maxPos) 5743 throw newIllegalArgumentException("too many filters"); 5744 } 5745 5746 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5747 MethodType targetType = target.type(); 5748 MethodType filterType = filter.type(); 5749 if (filterType.parameterCount() != 1 5750 || filterType.returnType() != targetType.parameterType(pos)) 5751 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5752 } 5753 5754 /** 5755 * Adapts a target method handle by pre-processing 5756 * a sub-sequence of its arguments with a filter (another method handle). 5757 * The pre-processed arguments are replaced by the result (if any) of the 5758 * filter function. 5759 * The target is then called on the modified (usually shortened) argument list. 5760 * <p> 5761 * If the filter returns a value, the target must accept that value as 5762 * its argument in position {@code pos}, preceded and/or followed by 5763 * any arguments not passed to the filter. 5764 * If the filter returns void, the target must accept all arguments 5765 * not passed to the filter. 5766 * No arguments are reordered, and a result returned from the filter 5767 * replaces (in order) the whole subsequence of arguments originally 5768 * passed to the adapter. 5769 * <p> 5770 * The argument types (if any) of the filter 5771 * replace zero or one argument types of the target, at position {@code pos}, 5772 * in the resulting adapted method handle. 5773 * The return type of the filter (if any) must be identical to the 5774 * argument type of the target at position {@code pos}, and that target argument 5775 * is supplied by the return value of the filter. 5776 * <p> 5777 * In all cases, {@code pos} must be greater than or equal to zero, and 5778 * {@code pos} must also be less than or equal to the target's arity. 5779 * <p><b>Example:</b> 5780 * {@snippet lang="java" : 5781 import static java.lang.invoke.MethodHandles.*; 5782 import static java.lang.invoke.MethodType.*; 5783 ... 5784 MethodHandle deepToString = publicLookup() 5785 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5786 5787 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5788 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5789 5790 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5791 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5792 5793 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5794 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5795 assertEquals("[top, [up, down], strange]", 5796 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5797 5798 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5799 assertEquals("[top, [up, down], [strange]]", 5800 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5801 5802 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5803 assertEquals("[top, [[up, down, strange], charm], bottom]", 5804 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5805 * } 5806 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5807 * represents the return type of the {@code target} and resulting adapter. 5808 * {@code V}/{@code v} stand for the return type and value of the 5809 * {@code filter}, which are also found in the signature and arguments of 5810 * the {@code target}, respectively, unless {@code V} is {@code void}. 5811 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5812 * and values preceding and following the collection position, {@code pos}, 5813 * in the {@code target}'s signature. They also turn up in the resulting 5814 * adapter's signature and arguments, where they surround 5815 * {@code B}/{@code b}, which represent the parameter types and arguments 5816 * to the {@code filter} (if any). 5817 * {@snippet lang="java" : 5818 * T target(A...,V,C...); 5819 * V filter(B...); 5820 * T adapter(A... a,B... b,C... c) { 5821 * V v = filter(b...); 5822 * return target(a...,v,c...); 5823 * } 5824 * // and if the filter has no arguments: 5825 * T target2(A...,V,C...); 5826 * V filter2(); 5827 * T adapter2(A... a,C... c) { 5828 * V v = filter2(); 5829 * return target2(a...,v,c...); 5830 * } 5831 * // and if the filter has a void return: 5832 * T target3(A...,C...); 5833 * void filter3(B...); 5834 * T adapter3(A... a,B... b,C... c) { 5835 * filter3(b...); 5836 * return target3(a...,c...); 5837 * } 5838 * } 5839 * <p> 5840 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5841 * one which first "folds" the affected arguments, and then drops them, in separate 5842 * steps as follows: 5843 * {@snippet lang="java" : 5844 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5845 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5846 * } 5847 * If the target method handle consumes no arguments besides than the result 5848 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5849 * is equivalent to {@code filterReturnValue(coll, mh)}. 5850 * If the filter method handle {@code coll} consumes one argument and produces 5851 * a non-void result, then {@code collectArguments(mh, N, coll)} 5852 * is equivalent to {@code filterArguments(mh, N, coll)}. 5853 * Other equivalences are possible but would require argument permutation. 5854 * <p> 5855 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5856 * variable-arity method handle}, even if the original target method handle was. 5857 * 5858 * @param target the method handle to invoke after filtering the subsequence of arguments 5859 * @param pos the position of the first adapter argument to pass to the filter, 5860 * and/or the target argument which receives the result of the filter 5861 * @param filter method handle to call on the subsequence of arguments 5862 * @return method handle which incorporates the specified argument subsequence filtering logic 5863 * @throws NullPointerException if either argument is null 5864 * @throws IllegalArgumentException if the return type of {@code filter} 5865 * is non-void and is not the same as the {@code pos} argument of the target, 5866 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5867 * or if the resulting method handle's type would have 5868 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5869 * @see MethodHandles#foldArguments 5870 * @see MethodHandles#filterArguments 5871 * @see MethodHandles#filterReturnValue 5872 */ 5873 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5874 MethodType newType = collectArgumentsChecks(target, pos, filter); 5875 MethodType collectorType = filter.type(); 5876 BoundMethodHandle result = target.rebind(); 5877 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5878 return result.copyWithExtendL(newType, lform, filter); 5879 } 5880 5881 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5882 MethodType targetType = target.type(); 5883 MethodType filterType = filter.type(); 5884 Class<?> rtype = filterType.returnType(); 5885 Class<?>[] filterArgs = filterType.ptypes(); 5886 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5887 (rtype != void.class && pos >= targetType.parameterCount())) { 5888 throw newIllegalArgumentException("position is out of range for target", target, pos); 5889 } 5890 if (rtype == void.class) { 5891 return targetType.insertParameterTypes(pos, filterArgs); 5892 } 5893 if (rtype != targetType.parameterType(pos)) { 5894 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5895 } 5896 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5897 } 5898 5899 /** 5900 * Adapts a target method handle by post-processing 5901 * its return value (if any) with a filter (another method handle). 5902 * The result of the filter is returned from the adapter. 5903 * <p> 5904 * If the target returns a value, the filter must accept that value as 5905 * its only argument. 5906 * If the target returns void, the filter must accept no arguments. 5907 * <p> 5908 * The return type of the filter 5909 * replaces the return type of the target 5910 * in the resulting adapted method handle. 5911 * The argument type of the filter (if any) must be identical to the 5912 * return type of the target. 5913 * <p><b>Example:</b> 5914 * {@snippet lang="java" : 5915 import static java.lang.invoke.MethodHandles.*; 5916 import static java.lang.invoke.MethodType.*; 5917 ... 5918 MethodHandle cat = lookup().findVirtual(String.class, 5919 "concat", methodType(String.class, String.class)); 5920 MethodHandle length = lookup().findVirtual(String.class, 5921 "length", methodType(int.class)); 5922 System.out.println((String) cat.invokeExact("x", "y")); // xy 5923 MethodHandle f0 = filterReturnValue(cat, length); 5924 System.out.println((int) f0.invokeExact("x", "y")); // 2 5925 * } 5926 * <p>Here is pseudocode for the resulting adapter. In the code, 5927 * {@code T}/{@code t} represent the result type and value of the 5928 * {@code target}; {@code V}, the result type of the {@code filter}; and 5929 * {@code A}/{@code a}, the types and values of the parameters and arguments 5930 * of the {@code target} as well as the resulting adapter. 5931 * {@snippet lang="java" : 5932 * T target(A...); 5933 * V filter(T); 5934 * V adapter(A... a) { 5935 * T t = target(a...); 5936 * return filter(t); 5937 * } 5938 * // and if the target has a void return: 5939 * void target2(A...); 5940 * V filter2(); 5941 * V adapter2(A... a) { 5942 * target2(a...); 5943 * return filter2(); 5944 * } 5945 * // and if the filter has a void return: 5946 * T target3(A...); 5947 * void filter3(V); 5948 * void adapter3(A... a) { 5949 * T t = target3(a...); 5950 * filter3(t); 5951 * } 5952 * } 5953 * <p> 5954 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5955 * variable-arity method handle}, even if the original target method handle was. 5956 * @param target the method handle to invoke before filtering the return value 5957 * @param filter method handle to call on the return value 5958 * @return method handle which incorporates the specified return value filtering logic 5959 * @throws NullPointerException if either argument is null 5960 * @throws IllegalArgumentException if the argument list of {@code filter} 5961 * does not match the return type of target as described above 5962 */ 5963 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5964 MethodType targetType = target.type(); 5965 MethodType filterType = filter.type(); 5966 filterReturnValueChecks(targetType, filterType); 5967 BoundMethodHandle result = target.rebind(); 5968 BasicType rtype = BasicType.basicType(filterType.returnType()); 5969 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5970 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5971 result = result.copyWithExtendL(newType, lform, filter); 5972 return result; 5973 } 5974 5975 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5976 Class<?> rtype = targetType.returnType(); 5977 int filterValues = filterType.parameterCount(); 5978 if (filterValues == 0 5979 ? (rtype != void.class) 5980 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5981 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5982 } 5983 5984 /** 5985 * Filter the return value of a target method handle with a filter function. The filter function is 5986 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5987 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5988 * as follows: 5989 * {@snippet lang="java" : 5990 * T target(A...) 5991 * V filter(B... , T) 5992 * V adapter(A... a, B... b) { 5993 * T t = target(a...); 5994 * return filter(b..., t); 5995 * } 5996 * } 5997 * <p> 5998 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5999 * 6000 * @param target the target method handle 6001 * @param filter the filter method handle 6002 * @return the adapter method handle 6003 */ 6004 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 6005 MethodType targetType = target.type(); 6006 MethodType filterType = filter.type(); 6007 BoundMethodHandle result = target.rebind(); 6008 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 6009 MethodType newType = targetType.changeReturnType(filterType.returnType()); 6010 if (filterType.parameterCount() > 1) { 6011 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 6012 newType = newType.appendParameterTypes(filterType.parameterType(i)); 6013 } 6014 } 6015 result = result.copyWithExtendL(newType, lform, filter); 6016 return result; 6017 } 6018 6019 /** 6020 * Adapts a target method handle by pre-processing 6021 * some of its arguments, and then calling the target with 6022 * the result of the pre-processing, inserted into the original 6023 * sequence of arguments. 6024 * <p> 6025 * The pre-processing is performed by {@code combiner}, a second method handle. 6026 * Of the arguments passed to the adapter, the first {@code N} arguments 6027 * are copied to the combiner, which is then called. 6028 * (Here, {@code N} is defined as the parameter count of the combiner.) 6029 * After this, control passes to the target, with any result 6030 * from the combiner inserted before the original {@code N} incoming 6031 * arguments. 6032 * <p> 6033 * If the combiner returns a value, the first parameter type of the target 6034 * must be identical with the return type of the combiner, and the next 6035 * {@code N} parameter types of the target must exactly match the parameters 6036 * of the combiner. 6037 * <p> 6038 * If the combiner has a void return, no result will be inserted, 6039 * and the first {@code N} parameter types of the target 6040 * must exactly match the parameters of the combiner. 6041 * <p> 6042 * The resulting adapter is the same type as the target, except that the 6043 * first parameter type is dropped, 6044 * if it corresponds to the result of the combiner. 6045 * <p> 6046 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 6047 * that either the combiner or the target does not wish to receive. 6048 * If some of the incoming arguments are destined only for the combiner, 6049 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 6050 * arguments will not need to be live on the stack on entry to the 6051 * target.) 6052 * <p><b>Example:</b> 6053 * {@snippet lang="java" : 6054 import static java.lang.invoke.MethodHandles.*; 6055 import static java.lang.invoke.MethodType.*; 6056 ... 6057 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6058 "println", methodType(void.class, String.class)) 6059 .bindTo(System.out); 6060 MethodHandle cat = lookup().findVirtual(String.class, 6061 "concat", methodType(String.class, String.class)); 6062 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6063 MethodHandle catTrace = foldArguments(cat, trace); 6064 // also prints "boo": 6065 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6066 * } 6067 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6068 * represents the result type of the {@code target} and resulting adapter. 6069 * {@code V}/{@code v} represent the type and value of the parameter and argument 6070 * of {@code target} that precedes the folding position; {@code V} also is 6071 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6072 * types and values of the {@code N} parameters and arguments at the folding 6073 * position. {@code B}/{@code b} represent the types and values of the 6074 * {@code target} parameters and arguments that follow the folded parameters 6075 * and arguments. 6076 * {@snippet lang="java" : 6077 * // there are N arguments in A... 6078 * T target(V, A[N]..., B...); 6079 * V combiner(A...); 6080 * T adapter(A... a, B... b) { 6081 * V v = combiner(a...); 6082 * return target(v, a..., b...); 6083 * } 6084 * // and if the combiner has a void return: 6085 * T target2(A[N]..., B...); 6086 * void combiner2(A...); 6087 * T adapter2(A... a, B... b) { 6088 * combiner2(a...); 6089 * return target2(a..., b...); 6090 * } 6091 * } 6092 * <p> 6093 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6094 * variable-arity method handle}, even if the original target method handle was. 6095 * @param target the method handle to invoke after arguments are combined 6096 * @param combiner method handle to call initially on the incoming arguments 6097 * @return method handle which incorporates the specified argument folding logic 6098 * @throws NullPointerException if either argument is null 6099 * @throws IllegalArgumentException if {@code combiner}'s return type 6100 * is non-void and not the same as the first argument type of 6101 * the target, or if the initial {@code N} argument types 6102 * of the target 6103 * (skipping one matching the {@code combiner}'s return type) 6104 * are not identical with the argument types of {@code combiner} 6105 */ 6106 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 6107 return foldArguments(target, 0, combiner); 6108 } 6109 6110 /** 6111 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6112 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6113 * before the folded arguments. 6114 * <p> 6115 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6116 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6117 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6118 * 0. 6119 * 6120 * @apiNote Example: 6121 * {@snippet lang="java" : 6122 import static java.lang.invoke.MethodHandles.*; 6123 import static java.lang.invoke.MethodType.*; 6124 ... 6125 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6126 "println", methodType(void.class, String.class)) 6127 .bindTo(System.out); 6128 MethodHandle cat = lookup().findVirtual(String.class, 6129 "concat", methodType(String.class, String.class)); 6130 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6131 MethodHandle catTrace = foldArguments(cat, 1, trace); 6132 // also prints "jum": 6133 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6134 * } 6135 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6136 * represents the result type of the {@code target} and resulting adapter. 6137 * {@code V}/{@code v} represent the type and value of the parameter and argument 6138 * of {@code target} that precedes the folding position; {@code V} also is 6139 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6140 * types and values of the {@code N} parameters and arguments at the folding 6141 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6142 * and values of the {@code target} parameters and arguments that precede and 6143 * follow the folded parameters and arguments starting at {@code pos}, 6144 * respectively. 6145 * {@snippet lang="java" : 6146 * // there are N arguments in A... 6147 * T target(Z..., V, A[N]..., B...); 6148 * V combiner(A...); 6149 * T adapter(Z... z, A... a, B... b) { 6150 * V v = combiner(a...); 6151 * return target(z..., v, a..., b...); 6152 * } 6153 * // and if the combiner has a void return: 6154 * T target2(Z..., A[N]..., B...); 6155 * void combiner2(A...); 6156 * T adapter2(Z... z, A... a, B... b) { 6157 * combiner2(a...); 6158 * return target2(z..., a..., b...); 6159 * } 6160 * } 6161 * <p> 6162 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6163 * variable-arity method handle}, even if the original target method handle was. 6164 * 6165 * @param target the method handle to invoke after arguments are combined 6166 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6167 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6168 * @param combiner method handle to call initially on the incoming arguments 6169 * @return method handle which incorporates the specified argument folding logic 6170 * @throws NullPointerException if either argument is null 6171 * @throws IllegalArgumentException if either of the following two conditions holds: 6172 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6173 * {@code pos} of the target signature; 6174 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6175 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6176 * 6177 * @see #foldArguments(MethodHandle, MethodHandle) 6178 * @since 9 6179 */ 6180 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6181 MethodType targetType = target.type(); 6182 MethodType combinerType = combiner.type(); 6183 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6184 BoundMethodHandle result = target.rebind(); 6185 boolean dropResult = rtype == void.class; 6186 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6187 MethodType newType = targetType; 6188 if (!dropResult) { 6189 newType = newType.dropParameterTypes(pos, pos + 1); 6190 } 6191 result = result.copyWithExtendL(newType, lform, combiner); 6192 return result; 6193 } 6194 6195 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6196 int foldArgs = combinerType.parameterCount(); 6197 Class<?> rtype = combinerType.returnType(); 6198 int foldVals = rtype == void.class ? 0 : 1; 6199 int afterInsertPos = foldPos + foldVals; 6200 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6201 if (ok) { 6202 for (int i = 0; i < foldArgs; i++) { 6203 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6204 ok = false; 6205 break; 6206 } 6207 } 6208 } 6209 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6210 ok = false; 6211 if (!ok) 6212 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6213 return rtype; 6214 } 6215 6216 /** 6217 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6218 * of the pre-processing replacing the argument at the given position. 6219 * 6220 * @param target the method handle to invoke after arguments are combined 6221 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6222 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6223 * @param combiner method handle to call initially on the incoming arguments 6224 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6225 * @return method handle which incorporates the specified argument folding logic 6226 * @throws NullPointerException if either argument is null 6227 * @throws IllegalArgumentException if either of the following two conditions holds: 6228 * (1) {@code combiner}'s return type is not the same as the argument type at position 6229 * {@code pos} of the target signature; 6230 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6231 * not identical with the argument types of {@code combiner}. 6232 */ 6233 /*non-public*/ 6234 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6235 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6236 } 6237 6238 /** 6239 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6240 * the pre-processing inserted into the original sequence of arguments at the given position. 6241 * 6242 * @param target the method handle to invoke after arguments are combined 6243 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6244 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6245 * @param combiner method handle to call initially on the incoming arguments 6246 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6247 * @return method handle which incorporates the specified argument folding logic 6248 * @throws NullPointerException if either argument is null 6249 * @throws IllegalArgumentException if either of the following two conditions holds: 6250 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6251 * {@code pos} of the target signature; 6252 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6253 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6254 * with the argument types of {@code combiner}. 6255 */ 6256 /*non-public*/ 6257 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6258 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6259 } 6260 6261 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6262 MethodType targetType = target.type(); 6263 MethodType combinerType = combiner.type(); 6264 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6265 BoundMethodHandle result = target.rebind(); 6266 6267 MethodType newType = targetType; 6268 LambdaForm lform; 6269 if (filter) { 6270 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6271 } else { 6272 boolean dropResult = rtype == void.class; 6273 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6274 if (!dropResult) { 6275 newType = newType.dropParameterTypes(position, position + 1); 6276 } 6277 } 6278 result = result.copyWithExtendL(newType, lform, combiner); 6279 return result; 6280 } 6281 6282 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6283 int combinerArgs = combinerType.parameterCount(); 6284 if (argPos.length != combinerArgs) { 6285 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6286 } 6287 Class<?> rtype = combinerType.returnType(); 6288 6289 for (int i = 0; i < combinerArgs; i++) { 6290 int arg = argPos[i]; 6291 if (arg < 0 || arg > targetType.parameterCount()) { 6292 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6293 } 6294 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6295 throw newIllegalArgumentException("target argument type at position " + arg 6296 + " must match combiner argument type at index " + i + ": " + targetType 6297 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6298 } 6299 } 6300 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6301 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6302 } 6303 return rtype; 6304 } 6305 6306 /** 6307 * Makes a method handle which adapts a target method handle, 6308 * by guarding it with a test, a boolean-valued method handle. 6309 * If the guard fails, a fallback handle is called instead. 6310 * All three method handles must have the same corresponding 6311 * argument and return types, except that the return type 6312 * of the test must be boolean, and the test is allowed 6313 * to have fewer arguments than the other two method handles. 6314 * <p> 6315 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6316 * represents the uniform result type of the three involved handles; 6317 * {@code A}/{@code a}, the types and values of the {@code target} 6318 * parameters and arguments that are consumed by the {@code test}; and 6319 * {@code B}/{@code b}, those types and values of the {@code target} 6320 * parameters and arguments that are not consumed by the {@code test}. 6321 * {@snippet lang="java" : 6322 * boolean test(A...); 6323 * T target(A...,B...); 6324 * T fallback(A...,B...); 6325 * T adapter(A... a,B... b) { 6326 * if (test(a...)) 6327 * return target(a..., b...); 6328 * else 6329 * return fallback(a..., b...); 6330 * } 6331 * } 6332 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6333 * be modified by execution of the test, and so are passed unchanged 6334 * from the caller to the target or fallback as appropriate. 6335 * @param test method handle used for test, must return boolean 6336 * @param target method handle to call if test passes 6337 * @param fallback method handle to call if test fails 6338 * @return method handle which incorporates the specified if/then/else logic 6339 * @throws NullPointerException if any argument is null 6340 * @throws IllegalArgumentException if {@code test} does not return boolean, 6341 * or if all three method types do not match (with the return 6342 * type of {@code test} changed to match that of the target). 6343 */ 6344 public static MethodHandle guardWithTest(MethodHandle test, 6345 MethodHandle target, 6346 MethodHandle fallback) { 6347 MethodType gtype = test.type(); 6348 MethodType ttype = target.type(); 6349 MethodType ftype = fallback.type(); 6350 if (!ttype.equals(ftype)) 6351 throw misMatchedTypes("target and fallback types", ttype, ftype); 6352 if (gtype.returnType() != boolean.class) 6353 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6354 6355 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6356 if (test == null) { 6357 throw misMatchedTypes("target and test types", ttype, gtype); 6358 } 6359 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6360 } 6361 6362 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6363 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6364 } 6365 6366 /** 6367 * Makes a method handle which adapts a target method handle, 6368 * by running it inside an exception handler. 6369 * If the target returns normally, the adapter returns that value. 6370 * If an exception matching the specified type is thrown, the fallback 6371 * handle is called instead on the exception, plus the original arguments. 6372 * <p> 6373 * The target and handler must have the same corresponding 6374 * argument and return types, except that handler may omit trailing arguments 6375 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6376 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6377 * <p> 6378 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6379 * represents the return type of the {@code target} and {@code handler}, 6380 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6381 * the types and values of arguments to the resulting handle consumed by 6382 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6383 * resulting handle discarded by {@code handler}. 6384 * {@snippet lang="java" : 6385 * T target(A..., B...); 6386 * T handler(ExType, A...); 6387 * T adapter(A... a, B... b) { 6388 * try { 6389 * return target(a..., b...); 6390 * } catch (ExType ex) { 6391 * return handler(ex, a...); 6392 * } 6393 * } 6394 * } 6395 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6396 * be modified by execution of the target, and so are passed unchanged 6397 * from the caller to the handler, if the handler is invoked. 6398 * <p> 6399 * The target and handler must return the same type, even if the handler 6400 * always throws. (This might happen, for instance, because the handler 6401 * is simulating a {@code finally} clause). 6402 * To create such a throwing handler, compose the handler creation logic 6403 * with {@link #throwException throwException}, 6404 * in order to create a method handle of the correct return type. 6405 * @param target method handle to call 6406 * @param exType the type of exception which the handler will catch 6407 * @param handler method handle to call if a matching exception is thrown 6408 * @return method handle which incorporates the specified try/catch logic 6409 * @throws NullPointerException if any argument is null 6410 * @throws IllegalArgumentException if {@code handler} does not accept 6411 * the given exception type, or if the method handle types do 6412 * not match in their return types and their 6413 * corresponding parameters 6414 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6415 */ 6416 public static MethodHandle catchException(MethodHandle target, 6417 Class<? extends Throwable> exType, 6418 MethodHandle handler) { 6419 MethodType ttype = target.type(); 6420 MethodType htype = handler.type(); 6421 if (!Throwable.class.isAssignableFrom(exType)) 6422 throw new ClassCastException(exType.getName()); 6423 if (htype.parameterCount() < 1 || 6424 !htype.parameterType(0).isAssignableFrom(exType)) 6425 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6426 if (htype.returnType() != ttype.returnType()) 6427 throw misMatchedTypes("target and handler return types", ttype, htype); 6428 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6429 if (handler == null) { 6430 throw misMatchedTypes("target and handler types", ttype, htype); 6431 } 6432 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6433 } 6434 6435 /** 6436 * Produces a method handle which will throw exceptions of the given {@code exType}. 6437 * The method handle will accept a single argument of {@code exType}, 6438 * and immediately throw it as an exception. 6439 * The method type will nominally specify a return of {@code returnType}. 6440 * The return type may be anything convenient: It doesn't matter to the 6441 * method handle's behavior, since it will never return normally. 6442 * @param returnType the return type of the desired method handle 6443 * @param exType the parameter type of the desired method handle 6444 * @return method handle which can throw the given exceptions 6445 * @throws NullPointerException if either argument is null 6446 */ 6447 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6448 if (!Throwable.class.isAssignableFrom(exType)) 6449 throw new ClassCastException(exType.getName()); 6450 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6451 } 6452 6453 /** 6454 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6455 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6456 * delivers the loop's result, which is the return value of the resulting handle. 6457 * <p> 6458 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6459 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6460 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6461 * terms of method handles, each clause will specify up to four independent actions:<ul> 6462 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6463 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6464 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6465 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6466 * </ul> 6467 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6468 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6469 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6470 * <p> 6471 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6472 * this case. See below for a detailed description. 6473 * <p> 6474 * <em>Parameters optional everywhere:</em> 6475 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6476 * As an exception, the init functions cannot take any {@code v} parameters, 6477 * because those values are not yet computed when the init functions are executed. 6478 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6479 * In fact, any clause function may take no arguments at all. 6480 * <p> 6481 * <em>Loop parameters:</em> 6482 * A clause function may take all the iteration variable values it is entitled to, in which case 6483 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6484 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6485 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6486 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6487 * init function is automatically a loop parameter {@code a}.) 6488 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6489 * These loop parameters act as loop-invariant values visible across the whole loop. 6490 * <p> 6491 * <em>Parameters visible everywhere:</em> 6492 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6493 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6494 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6495 * Most clause functions will not need all of this information, but they will be formally connected to it 6496 * as if by {@link #dropArguments}. 6497 * <a id="astar"></a> 6498 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6499 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6500 * In that notation, the general form of an init function parameter list 6501 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6502 * <p> 6503 * <em>Checking clause structure:</em> 6504 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6505 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6506 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6507 * met by the inputs to the loop combinator. 6508 * <p> 6509 * <em>Effectively identical sequences:</em> 6510 * <a id="effid"></a> 6511 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6512 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6513 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6514 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6515 * that longest list. 6516 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6517 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6518 * <p> 6519 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6520 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6521 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6522 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6523 * four. Padding takes place by appending elements to the array. 6524 * <li>Clauses with all {@code null}s are disregarded. 6525 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6526 * </ol> 6527 * <p> 6528 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6529 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6530 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6531 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6532 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6533 * iteration variable type. 6534 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6535 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6536 * </ol> 6537 * <p> 6538 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6539 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6540 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6541 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6542 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6543 * (These types will be checked in step 2, along with all the clause function types.) 6544 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6545 * <li>All of the collected parameter lists must be effectively identical. 6546 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6547 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6548 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6549 * the "internal parameter list". 6550 * </ul> 6551 * <p> 6552 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6553 * <li>Examine fini function return types, disregarding omitted fini functions. 6554 * <li>If there are no fini functions, the loop return type is {@code void}. 6555 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6556 * type. 6557 * </ol> 6558 * <p> 6559 * <em>Step 1D: Check other types.</em><ol type="a"> 6560 * <li>There must be at least one non-omitted pred function. 6561 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6562 * </ol> 6563 * <p> 6564 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6565 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6566 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6567 * (Note that their parameter lists are already effectively identical to this list.) 6568 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6569 * effectively identical to the internal parameter list {@code (V... A...)}. 6570 * </ol> 6571 * <p> 6572 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6573 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6574 * type. 6575 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6576 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6577 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6578 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6579 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6580 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6581 * loop return type. 6582 * </ol> 6583 * <p> 6584 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6585 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6586 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6587 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6588 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6589 * pad out the end of the list. 6590 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6591 * </ol> 6592 * <p> 6593 * <em>Final observations.</em><ol type="a"> 6594 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6595 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6596 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6597 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6598 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6599 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6600 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6601 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6602 * </ol> 6603 * <p> 6604 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6605 * <ul> 6606 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6607 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6608 * (Only one {@code Pn} has to be non-{@code null}.) 6609 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6610 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6611 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6612 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6613 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6614 * the resulting loop handle's parameter types {@code (A...)}. 6615 * </ul> 6616 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6617 * which is natural if most of the loop computation happens in the steps. For some loops, 6618 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6619 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6620 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6621 * where the init functions will need the extra parameters. For such reasons, the rules for 6622 * determining these parameters are as symmetric as possible, across all clause parts. 6623 * In general, the loop parameters function as common invariant values across the whole 6624 * loop, while the iteration variables function as common variant values, or (if there is 6625 * no step function) as internal loop invariant temporaries. 6626 * <p> 6627 * <em>Loop execution.</em><ol type="a"> 6628 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6629 * every clause function. These locals are loop invariant. 6630 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6631 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6632 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6633 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6634 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6635 * (in argument order). 6636 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6637 * returns {@code false}. 6638 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6639 * sequence {@code (v...)} of loop variables. 6640 * The updated value is immediately visible to all subsequent function calls. 6641 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6642 * (of type {@code R}) is returned from the loop as a whole. 6643 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6644 * except by throwing an exception. 6645 * </ol> 6646 * <p> 6647 * <em>Usage tips.</em> 6648 * <ul> 6649 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6650 * sometimes a step function only needs to observe the current value of its own variable. 6651 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6652 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6653 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6654 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6655 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6656 * <li>If some of the clause functions are virtual methods on an instance, the instance 6657 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6658 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6659 * will be the first iteration variable value, and it will be easy to use virtual 6660 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6661 * </ul> 6662 * <p> 6663 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6664 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6665 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6666 * {@snippet lang="java" : 6667 * V... init...(A...); 6668 * boolean pred...(V..., A...); 6669 * V... step...(V..., A...); 6670 * R fini...(V..., A...); 6671 * R loop(A... a) { 6672 * V... v... = init...(a...); 6673 * for (;;) { 6674 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6675 * v = s(v..., a...); 6676 * if (!p(v..., a...)) { 6677 * return f(v..., a...); 6678 * } 6679 * } 6680 * } 6681 * } 6682 * } 6683 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6684 * to their full length, even though individual clause functions may neglect to take them all. 6685 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6686 * 6687 * @apiNote Example: 6688 * {@snippet lang="java" : 6689 * // iterative implementation of the factorial function as a loop handle 6690 * static int one(int k) { return 1; } 6691 * static int inc(int i, int acc, int k) { return i + 1; } 6692 * static int mult(int i, int acc, int k) { return i * acc; } 6693 * static boolean pred(int i, int acc, int k) { return i < k; } 6694 * static int fin(int i, int acc, int k) { return acc; } 6695 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6696 * // null initializer for counter, should initialize to 0 6697 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6698 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6699 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6700 * assertEquals(120, loop.invoke(5)); 6701 * } 6702 * The same example, dropping arguments and using combinators: 6703 * {@snippet lang="java" : 6704 * // simplified implementation of the factorial function as a loop handle 6705 * static int inc(int i) { return i + 1; } // drop acc, k 6706 * static int mult(int i, int acc) { return i * acc; } //drop k 6707 * static boolean cmp(int i, int k) { return i < k; } 6708 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6709 * // null initializer for counter, should initialize to 0 6710 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6711 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6712 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6713 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6714 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6715 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6716 * assertEquals(720, loop.invoke(6)); 6717 * } 6718 * A similar example, using a helper object to hold a loop parameter: 6719 * {@snippet lang="java" : 6720 * // instance-based implementation of the factorial function as a loop handle 6721 * static class FacLoop { 6722 * final int k; 6723 * FacLoop(int k) { this.k = k; } 6724 * int inc(int i) { return i + 1; } 6725 * int mult(int i, int acc) { return i * acc; } 6726 * boolean pred(int i) { return i < k; } 6727 * int fin(int i, int acc) { return acc; } 6728 * } 6729 * // assume MH_FacLoop is a handle to the constructor 6730 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6731 * // null initializer for counter, should initialize to 0 6732 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6733 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6734 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6735 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6736 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6737 * assertEquals(5040, loop.invoke(7)); 6738 * } 6739 * 6740 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6741 * 6742 * @return a method handle embodying the looping behavior as defined by the arguments. 6743 * 6744 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6745 * 6746 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6747 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6748 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6749 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6750 * @since 9 6751 */ 6752 public static MethodHandle loop(MethodHandle[]... clauses) { 6753 // Step 0: determine clause structure. 6754 loopChecks0(clauses); 6755 6756 List<MethodHandle> init = new ArrayList<>(); 6757 List<MethodHandle> step = new ArrayList<>(); 6758 List<MethodHandle> pred = new ArrayList<>(); 6759 List<MethodHandle> fini = new ArrayList<>(); 6760 6761 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6762 init.add(clause[0]); // all clauses have at least length 1 6763 step.add(clause.length <= 1 ? null : clause[1]); 6764 pred.add(clause.length <= 2 ? null : clause[2]); 6765 fini.add(clause.length <= 3 ? null : clause[3]); 6766 }); 6767 6768 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6769 final int nclauses = init.size(); 6770 6771 // Step 1A: determine iteration variables (V...). 6772 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6773 for (int i = 0; i < nclauses; ++i) { 6774 MethodHandle in = init.get(i); 6775 MethodHandle st = step.get(i); 6776 if (in == null && st == null) { 6777 iterationVariableTypes.add(void.class); 6778 } else if (in != null && st != null) { 6779 loopChecks1a(i, in, st); 6780 iterationVariableTypes.add(in.type().returnType()); 6781 } else { 6782 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6783 } 6784 } 6785 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6786 6787 // Step 1B: determine loop parameters (A...). 6788 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6789 loopChecks1b(init, commonSuffix); 6790 6791 // Step 1C: determine loop return type. 6792 // Step 1D: check other types. 6793 // local variable required here; see JDK-8223553 6794 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6795 .map(MethodType::returnType); 6796 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6797 loopChecks1cd(pred, fini, loopReturnType); 6798 6799 // Step 2: determine parameter lists. 6800 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6801 commonParameterSequence.addAll(commonSuffix); 6802 loopChecks2(step, pred, fini, commonParameterSequence); 6803 // Step 3: fill in omitted functions. 6804 for (int i = 0; i < nclauses; ++i) { 6805 Class<?> t = iterationVariableTypes.get(i); 6806 if (init.get(i) == null) { 6807 init.set(i, empty(methodType(t, commonSuffix))); 6808 } 6809 if (step.get(i) == null) { 6810 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6811 } 6812 if (pred.get(i) == null) { 6813 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6814 } 6815 if (fini.get(i) == null) { 6816 fini.set(i, empty(methodType(t, commonParameterSequence))); 6817 } 6818 } 6819 6820 // Step 4: fill in missing parameter types. 6821 // Also convert all handles to fixed-arity handles. 6822 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6823 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6824 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6825 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6826 6827 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6828 allMatch(pl -> pl.equals(commonSuffix)); 6829 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6830 allMatch(pl -> pl.equals(commonParameterSequence)); 6831 6832 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6833 } 6834 6835 private static void loopChecks0(MethodHandle[][] clauses) { 6836 if (clauses == null || clauses.length == 0) { 6837 throw newIllegalArgumentException("null or no clauses passed"); 6838 } 6839 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6840 throw newIllegalArgumentException("null clauses are not allowed"); 6841 } 6842 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6843 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6844 } 6845 } 6846 6847 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6848 if (in.type().returnType() != st.type().returnType()) { 6849 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6850 st.type().returnType()); 6851 } 6852 } 6853 6854 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6855 return mhs.filter(Objects::nonNull) 6856 // take only those that can contribute to a common suffix because they are longer than the prefix 6857 .map(MethodHandle::type) 6858 .filter(t -> t.parameterCount() > skipSize) 6859 .max(Comparator.comparingInt(MethodType::parameterCount)) 6860 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6861 .orElse(List.of()); 6862 } 6863 6864 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6865 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6866 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6867 return longest1.size() >= longest2.size() ? longest1 : longest2; 6868 } 6869 6870 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6871 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6872 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6873 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6874 " (common suffix: " + commonSuffix + ")"); 6875 } 6876 } 6877 6878 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6879 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6880 anyMatch(t -> t != loopReturnType)) { 6881 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6882 loopReturnType + ")"); 6883 } 6884 6885 if (pred.stream().noneMatch(Objects::nonNull)) { 6886 throw newIllegalArgumentException("no predicate found", pred); 6887 } 6888 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6889 anyMatch(t -> t != boolean.class)) { 6890 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6891 } 6892 } 6893 6894 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6895 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6896 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6897 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6898 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6899 } 6900 } 6901 6902 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6903 return hs.stream().map(h -> { 6904 int pc = h.type().parameterCount(); 6905 int tpsize = targetParams.size(); 6906 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6907 }).toList(); 6908 } 6909 6910 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6911 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6912 } 6913 6914 /** 6915 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6916 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6917 * <p> 6918 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6919 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6920 * evaluates to {@code true}). 6921 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6922 * <p> 6923 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6924 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6925 * and updated with the value returned from its invocation. The result of loop execution will be 6926 * the final value of the additional loop-local variable (if present). 6927 * <p> 6928 * The following rules hold for these argument handles:<ul> 6929 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6930 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6931 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6932 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6933 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6934 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6935 * It will constrain the parameter lists of the other loop parts. 6936 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6937 * list {@code (A...)} is called the <em>external parameter list</em>. 6938 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6939 * additional state variable of the loop. 6940 * The body must both accept and return a value of this type {@code V}. 6941 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6942 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6943 * <a href="MethodHandles.html#effid">effectively identical</a> 6944 * to the external parameter list {@code (A...)}. 6945 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6946 * {@linkplain #empty default value}. 6947 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6948 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6949 * effectively identical to the internal parameter list. 6950 * </ul> 6951 * <p> 6952 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6953 * <li>The loop handle's result type is the result type {@code V} of the body. 6954 * <li>The loop handle's parameter types are the types {@code (A...)}, 6955 * from the external parameter list. 6956 * </ul> 6957 * <p> 6958 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6959 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6960 * passed to the loop. 6961 * {@snippet lang="java" : 6962 * V init(A...); 6963 * boolean pred(V, A...); 6964 * V body(V, A...); 6965 * V whileLoop(A... a...) { 6966 * V v = init(a...); 6967 * while (pred(v, a...)) { 6968 * v = body(v, a...); 6969 * } 6970 * return v; 6971 * } 6972 * } 6973 * 6974 * @apiNote Example: 6975 * {@snippet lang="java" : 6976 * // implement the zip function for lists as a loop handle 6977 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6978 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6979 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6980 * zip.add(a.next()); 6981 * zip.add(b.next()); 6982 * return zip; 6983 * } 6984 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6985 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6986 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6987 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6988 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6989 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6990 * } 6991 * 6992 * 6993 * @apiNote The implementation of this method can be expressed as follows: 6994 * {@snippet lang="java" : 6995 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6996 * MethodHandle fini = (body.type().returnType() == void.class 6997 * ? null : identity(body.type().returnType())); 6998 * MethodHandle[] 6999 * checkExit = { null, null, pred, fini }, 7000 * varBody = { init, body }; 7001 * return loop(checkExit, varBody); 7002 * } 7003 * } 7004 * 7005 * @param init optional initializer, providing the initial value of the loop variable. 7006 * May be {@code null}, implying a default initial value. See above for other constraints. 7007 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7008 * 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 * 7012 * @return a method handle implementing the {@code while} loop as described by the arguments. 7013 * @throws IllegalArgumentException if the rules for the arguments are violated. 7014 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7015 * 7016 * @see #loop(MethodHandle[][]) 7017 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 7018 * @since 9 7019 */ 7020 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 7021 whileLoopChecks(init, pred, body); 7022 MethodHandle fini = identityOrVoid(body.type().returnType()); 7023 MethodHandle[] checkExit = { null, null, pred, fini }; 7024 MethodHandle[] varBody = { init, body }; 7025 return loop(checkExit, varBody); 7026 } 7027 7028 /** 7029 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 7030 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7031 * <p> 7032 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 7033 * method will, in each iteration, first execute its body and then evaluate the predicate. 7034 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 7035 * <p> 7036 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 7037 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 7038 * and updated with the value returned from its invocation. The result of loop execution will be 7039 * the final value of the additional loop-local variable (if present). 7040 * <p> 7041 * The following rules hold for these argument handles:<ul> 7042 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7043 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 7044 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7045 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 7046 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 7047 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 7048 * It will constrain the parameter lists of the other loop parts. 7049 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 7050 * list {@code (A...)} is called the <em>external parameter list</em>. 7051 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7052 * additional state variable of the loop. 7053 * The body must both accept and return a value of this type {@code V}. 7054 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7055 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7056 * <a href="MethodHandles.html#effid">effectively identical</a> 7057 * to the external parameter list {@code (A...)}. 7058 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7059 * {@linkplain #empty default value}. 7060 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 7061 * Its parameter list (either empty or of the form {@code (V A*)}) must be 7062 * effectively identical to the internal parameter list. 7063 * </ul> 7064 * <p> 7065 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7066 * <li>The loop handle's result type is the result type {@code V} of the body. 7067 * <li>The loop handle's parameter types are the types {@code (A...)}, 7068 * from the external parameter list. 7069 * </ul> 7070 * <p> 7071 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7072 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 7073 * passed to the loop. 7074 * {@snippet lang="java" : 7075 * V init(A...); 7076 * boolean pred(V, A...); 7077 * V body(V, A...); 7078 * V doWhileLoop(A... a...) { 7079 * V v = init(a...); 7080 * do { 7081 * v = body(v, a...); 7082 * } while (pred(v, a...)); 7083 * return v; 7084 * } 7085 * } 7086 * 7087 * @apiNote Example: 7088 * {@snippet lang="java" : 7089 * // int i = 0; while (i < limit) { ++i; } return i; => limit 7090 * static int zero(int limit) { return 0; } 7091 * static int step(int i, int limit) { return i + 1; } 7092 * static boolean pred(int i, int limit) { return i < limit; } 7093 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 7094 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 7095 * assertEquals(23, loop.invoke(23)); 7096 * } 7097 * 7098 * 7099 * @apiNote The implementation of this method can be expressed as follows: 7100 * {@snippet lang="java" : 7101 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7102 * MethodHandle fini = (body.type().returnType() == void.class 7103 * ? null : identity(body.type().returnType())); 7104 * MethodHandle[] clause = { init, body, pred, fini }; 7105 * return loop(clause); 7106 * } 7107 * } 7108 * 7109 * @param init optional initializer, providing the initial value of the loop variable. 7110 * May be {@code null}, implying a default initial value. See above for other constraints. 7111 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7112 * See above for other constraints. 7113 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7114 * above for other constraints. 7115 * 7116 * @return a method handle implementing the {@code while} loop as described by the arguments. 7117 * @throws IllegalArgumentException if the rules for the arguments are violated. 7118 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7119 * 7120 * @see #loop(MethodHandle[][]) 7121 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7122 * @since 9 7123 */ 7124 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7125 whileLoopChecks(init, pred, body); 7126 MethodHandle fini = identityOrVoid(body.type().returnType()); 7127 MethodHandle[] clause = {init, body, pred, fini }; 7128 return loop(clause); 7129 } 7130 7131 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7132 Objects.requireNonNull(pred); 7133 Objects.requireNonNull(body); 7134 MethodType bodyType = body.type(); 7135 Class<?> returnType = bodyType.returnType(); 7136 List<Class<?>> innerList = bodyType.parameterList(); 7137 List<Class<?>> outerList = innerList; 7138 if (returnType == void.class) { 7139 // OK 7140 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7141 // leading V argument missing => error 7142 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7143 throw misMatchedTypes("body function", bodyType, expected); 7144 } else { 7145 outerList = innerList.subList(1, innerList.size()); 7146 } 7147 MethodType predType = pred.type(); 7148 if (predType.returnType() != boolean.class || 7149 !predType.effectivelyIdenticalParameters(0, innerList)) { 7150 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7151 } 7152 if (init != null) { 7153 MethodType initType = init.type(); 7154 if (initType.returnType() != returnType || 7155 !initType.effectivelyIdenticalParameters(0, outerList)) { 7156 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7157 } 7158 } 7159 } 7160 7161 /** 7162 * Constructs a loop that runs a given number of iterations. 7163 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7164 * <p> 7165 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7166 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7167 * It will be initialized to 0 and incremented by 1 in each iteration. 7168 * <p> 7169 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7170 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7171 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7172 * <p> 7173 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7174 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7175 * iteration variable. 7176 * The result of the loop handle execution will be the final {@code V} value of that variable 7177 * (or {@code void} if there is no {@code V} variable). 7178 * <p> 7179 * The following rules hold for the argument handles:<ul> 7180 * <li>The {@code iterations} handle must not be {@code null}, and must return 7181 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7182 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7183 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7184 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7185 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7186 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7187 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7188 * of types called the <em>internal parameter list</em>. 7189 * It will constrain the parameter lists of the other loop parts. 7190 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7191 * with no additional {@code A} types, then the internal parameter list is extended by 7192 * the argument types {@code A...} of the {@code iterations} handle. 7193 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7194 * list {@code (A...)} is called the <em>external parameter list</em>. 7195 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7196 * additional state variable of the loop. 7197 * The body must both accept a leading parameter and return a value of this type {@code V}. 7198 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7199 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7200 * <a href="MethodHandles.html#effid">effectively identical</a> 7201 * to the external parameter list {@code (A...)}. 7202 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7203 * {@linkplain #empty default value}. 7204 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7205 * effectively identical to the external parameter list {@code (A...)}. 7206 * </ul> 7207 * <p> 7208 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7209 * <li>The loop handle's result type is the result type {@code V} of the body. 7210 * <li>The loop handle's parameter types are the types {@code (A...)}, 7211 * from the external parameter list. 7212 * </ul> 7213 * <p> 7214 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7215 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7216 * arguments passed to the loop. 7217 * {@snippet lang="java" : 7218 * int iterations(A...); 7219 * V init(A...); 7220 * V body(V, int, A...); 7221 * V countedLoop(A... a...) { 7222 * int end = iterations(a...); 7223 * V v = init(a...); 7224 * for (int i = 0; i < end; ++i) { 7225 * v = body(v, i, a...); 7226 * } 7227 * return v; 7228 * } 7229 * } 7230 * 7231 * @apiNote Example with a fully conformant body method: 7232 * {@snippet lang="java" : 7233 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7234 * // => a variation on a well known theme 7235 * static String step(String v, int counter, String init) { return "na " + v; } 7236 * // assume MH_step is a handle to the method above 7237 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7238 * MethodHandle start = MethodHandles.identity(String.class); 7239 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7240 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7241 * } 7242 * 7243 * @apiNote Example with the simplest possible body method type, 7244 * and passing the number of iterations to the loop invocation: 7245 * {@snippet lang="java" : 7246 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7247 * // => a variation on a well known theme 7248 * static String step(String v, int counter ) { return "na " + v; } 7249 * // assume MH_step is a handle to the method above 7250 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7251 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7252 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7253 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7254 * } 7255 * 7256 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7257 * as loop parameters: 7258 * {@snippet lang="java" : 7259 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7260 * // => a variation on a well known theme 7261 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 7262 * // assume MH_step is a handle to the method above 7263 * MethodHandle count = MethodHandles.identity(int.class); 7264 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7265 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7266 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7267 * } 7268 * 7269 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7270 * to enforce a loop type: 7271 * {@snippet lang="java" : 7272 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7273 * // => a variation on a well known theme 7274 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7275 * // assume MH_step is a handle to the method above 7276 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7277 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7278 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7279 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7280 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7281 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7282 * } 7283 * 7284 * @apiNote The implementation of this method can be expressed as follows: 7285 * {@snippet lang="java" : 7286 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7287 * return countedLoop(empty(iterations.type()), iterations, init, body); 7288 * } 7289 * } 7290 * 7291 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7292 * result type must be {@code int}. See above for other constraints. 7293 * @param init optional initializer, providing the initial value of the loop variable. 7294 * May be {@code null}, implying a default initial value. See above for other constraints. 7295 * @param body body of the loop, which may not be {@code null}. 7296 * It controls the loop parameters and result type in the standard case (see above for details). 7297 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7298 * and may accept any number of additional types. 7299 * See above for other constraints. 7300 * 7301 * @return a method handle representing the loop. 7302 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7303 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7304 * 7305 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7306 * @since 9 7307 */ 7308 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7309 return countedLoop(empty(iterations.type()), iterations, init, body); 7310 } 7311 7312 /** 7313 * Constructs a loop that counts over a range of numbers. 7314 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7315 * <p> 7316 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7317 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7318 * values of the loop counter. 7319 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7320 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7321 * <p> 7322 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7323 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7324 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7325 * <p> 7326 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7327 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7328 * iteration variable. 7329 * The result of the loop handle execution will be the final {@code V} value of that variable 7330 * (or {@code void} if there is no {@code V} variable). 7331 * <p> 7332 * The following rules hold for the argument handles:<ul> 7333 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7334 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7335 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7336 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7337 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7338 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7339 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7340 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7341 * of types called the <em>internal parameter list</em>. 7342 * It will constrain the parameter lists of the other loop parts. 7343 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7344 * with no additional {@code A} types, then the internal parameter list is extended by 7345 * the argument types {@code A...} of the {@code end} handle. 7346 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7347 * list {@code (A...)} is called the <em>external parameter list</em>. 7348 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7349 * additional state variable of the loop. 7350 * The body must both accept a leading parameter and return a value of this type {@code V}. 7351 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7352 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7353 * <a href="MethodHandles.html#effid">effectively identical</a> 7354 * to the external parameter list {@code (A...)}. 7355 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7356 * {@linkplain #empty default value}. 7357 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7358 * effectively identical to the external parameter list {@code (A...)}. 7359 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7360 * to the external parameter list. 7361 * </ul> 7362 * <p> 7363 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7364 * <li>The loop handle's result type is the result type {@code V} of the body. 7365 * <li>The loop handle's parameter types are the types {@code (A...)}, 7366 * from the external parameter list. 7367 * </ul> 7368 * <p> 7369 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7370 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7371 * arguments passed to the loop. 7372 * {@snippet lang="java" : 7373 * int start(A...); 7374 * int end(A...); 7375 * V init(A...); 7376 * V body(V, int, A...); 7377 * V countedLoop(A... a...) { 7378 * int e = end(a...); 7379 * int s = start(a...); 7380 * V v = init(a...); 7381 * for (int i = s; i < e; ++i) { 7382 * v = body(v, i, a...); 7383 * } 7384 * return v; 7385 * } 7386 * } 7387 * 7388 * @apiNote The implementation of this method can be expressed as follows: 7389 * {@snippet lang="java" : 7390 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7391 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7392 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7393 * // the following semantics: 7394 * // MH_increment: (int limit, int counter) -> counter + 1 7395 * // MH_predicate: (int limit, int counter) -> counter < limit 7396 * Class<?> counterType = start.type().returnType(); // int 7397 * Class<?> returnType = body.type().returnType(); 7398 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7399 * if (returnType != void.class) { // ignore the V variable 7400 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7401 * pred = dropArguments(pred, 1, returnType); // ditto 7402 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7403 * } 7404 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7405 * MethodHandle[] 7406 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7407 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7408 * indexVar = { start, incr }; // i = start(); i = i + 1 7409 * return loop(loopLimit, bodyClause, indexVar); 7410 * } 7411 * } 7412 * 7413 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7414 * See above for other constraints. 7415 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7416 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7417 * @param init optional initializer, providing the initial value of the loop variable. 7418 * May be {@code null}, implying a default initial value. See above for other constraints. 7419 * @param body body of the loop, which may not be {@code null}. 7420 * It controls the loop parameters and result type in the standard case (see above for details). 7421 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7422 * and may accept any number of additional types. 7423 * See above for other constraints. 7424 * 7425 * @return a method handle representing the loop. 7426 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7427 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7428 * 7429 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7430 * @since 9 7431 */ 7432 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7433 countedLoopChecks(start, end, init, body); 7434 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7435 Class<?> limitType = end.type().returnType(); // yes, int again 7436 Class<?> returnType = body.type().returnType(); 7437 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7438 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7439 MethodHandle retv = null; 7440 if (returnType != void.class) { 7441 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7442 pred = dropArguments(pred, 1, returnType); // ditto 7443 retv = dropArguments(identity(returnType), 0, counterType); 7444 } 7445 body = dropArguments(body, 0, counterType); // ignore the limit variable 7446 MethodHandle[] 7447 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7448 bodyClause = { init, body }, // v = init(); v = body(v, i) 7449 indexVar = { start, incr }; // i = start(); i = i + 1 7450 return loop(loopLimit, bodyClause, indexVar); 7451 } 7452 7453 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7454 Objects.requireNonNull(start); 7455 Objects.requireNonNull(end); 7456 Objects.requireNonNull(body); 7457 Class<?> counterType = start.type().returnType(); 7458 if (counterType != int.class) { 7459 MethodType expected = start.type().changeReturnType(int.class); 7460 throw misMatchedTypes("start function", start.type(), expected); 7461 } else if (end.type().returnType() != counterType) { 7462 MethodType expected = end.type().changeReturnType(counterType); 7463 throw misMatchedTypes("end function", end.type(), expected); 7464 } 7465 MethodType bodyType = body.type(); 7466 Class<?> returnType = bodyType.returnType(); 7467 List<Class<?>> innerList = bodyType.parameterList(); 7468 // strip leading V value if present 7469 int vsize = (returnType == void.class ? 0 : 1); 7470 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7471 // argument list has no "V" => error 7472 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7473 throw misMatchedTypes("body function", bodyType, expected); 7474 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7475 // missing I type => error 7476 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7477 throw misMatchedTypes("body function", bodyType, expected); 7478 } 7479 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7480 if (outerList.isEmpty()) { 7481 // special case; take lists from end handle 7482 outerList = end.type().parameterList(); 7483 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7484 } 7485 MethodType expected = methodType(counterType, outerList); 7486 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7487 throw misMatchedTypes("start parameter types", start.type(), expected); 7488 } 7489 if (end.type() != start.type() && 7490 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7491 throw misMatchedTypes("end parameter types", end.type(), expected); 7492 } 7493 if (init != null) { 7494 MethodType initType = init.type(); 7495 if (initType.returnType() != returnType || 7496 !initType.effectivelyIdenticalParameters(0, outerList)) { 7497 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7498 } 7499 } 7500 } 7501 7502 /** 7503 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7504 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7505 * <p> 7506 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7507 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7508 * <p> 7509 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7510 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7511 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7512 * <p> 7513 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7514 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7515 * iteration variable. 7516 * The result of the loop handle execution will be the final {@code V} value of that variable 7517 * (or {@code void} if there is no {@code V} variable). 7518 * <p> 7519 * The following rules hold for the argument handles:<ul> 7520 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7521 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7522 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7523 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7524 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7525 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7526 * of types called the <em>internal parameter list</em>. 7527 * It will constrain the parameter lists of the other loop parts. 7528 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7529 * with no additional {@code A} types, then the internal parameter list is extended by 7530 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7531 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7532 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7533 * list {@code (A...)} is called the <em>external parameter list</em>. 7534 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7535 * additional state variable of the loop. 7536 * The body must both accept a leading parameter and return a value of this type {@code V}. 7537 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7538 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7539 * <a href="MethodHandles.html#effid">effectively identical</a> 7540 * to the external parameter list {@code (A...)}. 7541 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7542 * {@linkplain #empty default value}. 7543 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7544 * type {@code java.util.Iterator} or a subtype thereof. 7545 * The iterator it produces when the loop is executed will be assumed 7546 * to yield values which can be converted to type {@code T}. 7547 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7548 * effectively identical to the external parameter list {@code (A...)}. 7549 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7550 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7551 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7552 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7553 * the {@link MethodHandle#asType asType} conversion method. 7554 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7555 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7556 * </ul> 7557 * <p> 7558 * The type {@code T} may be either a primitive or reference. 7559 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7560 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7561 * as if by the {@link MethodHandle#asType asType} conversion method. 7562 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7563 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7564 * <p> 7565 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7566 * <li>The loop handle's result type is the result type {@code V} of the body. 7567 * <li>The loop handle's parameter types are the types {@code (A...)}, 7568 * from the external parameter list. 7569 * </ul> 7570 * <p> 7571 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7572 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7573 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7574 * {@snippet lang="java" : 7575 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7576 * V init(A...); 7577 * V body(V,T,A...); 7578 * V iteratedLoop(A... a...) { 7579 * Iterator<T> it = iterator(a...); 7580 * V v = init(a...); 7581 * while (it.hasNext()) { 7582 * T t = it.next(); 7583 * v = body(v, t, a...); 7584 * } 7585 * return v; 7586 * } 7587 * } 7588 * 7589 * @apiNote Example: 7590 * {@snippet lang="java" : 7591 * // get an iterator from a list 7592 * static List<String> reverseStep(List<String> r, String e) { 7593 * r.add(0, e); 7594 * return r; 7595 * } 7596 * static List<String> newArrayList() { return new ArrayList<>(); } 7597 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7598 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7599 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7600 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7601 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7602 * } 7603 * 7604 * @apiNote The implementation of this method can be expressed approximately as follows: 7605 * {@snippet lang="java" : 7606 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7607 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7608 * Class<?> returnType = body.type().returnType(); 7609 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7610 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7611 * MethodHandle retv = null, step = body, startIter = iterator; 7612 * if (returnType != void.class) { 7613 * // the simple thing first: in (I V A...), drop the I to get V 7614 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7615 * // body type signature (V T A...), internal loop types (I V A...) 7616 * step = swapArguments(body, 0, 1); // swap V <-> T 7617 * } 7618 * if (startIter == null) startIter = MH_getIter; 7619 * MethodHandle[] 7620 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7621 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7622 * return loop(iterVar, bodyClause); 7623 * } 7624 * } 7625 * 7626 * @param iterator an optional handle to return the iterator to start the loop. 7627 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7628 * See above for other constraints. 7629 * @param init optional initializer, providing the initial value of the loop variable. 7630 * May be {@code null}, implying a default initial value. See above for other constraints. 7631 * @param body body of the loop, which may not be {@code null}. 7632 * It controls the loop parameters and result type in the standard case (see above for details). 7633 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7634 * and may accept any number of additional types. 7635 * See above for other constraints. 7636 * 7637 * @return a method handle embodying the iteration loop functionality. 7638 * @throws NullPointerException if the {@code body} handle is {@code null}. 7639 * @throws IllegalArgumentException if any argument violates the above requirements. 7640 * 7641 * @since 9 7642 */ 7643 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7644 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7645 Class<?> returnType = body.type().returnType(); 7646 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7647 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7648 MethodHandle startIter; 7649 MethodHandle nextVal; 7650 { 7651 MethodType iteratorType; 7652 if (iterator == null) { 7653 // derive argument type from body, if available, else use Iterable 7654 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7655 iteratorType = startIter.type().changeParameterType(0, iterableType); 7656 } else { 7657 // force return type to the internal iterator class 7658 iteratorType = iterator.type().changeReturnType(Iterator.class); 7659 startIter = iterator; 7660 } 7661 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7662 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7663 7664 // perform the asType transforms under an exception transformer, as per spec.: 7665 try { 7666 startIter = startIter.asType(iteratorType); 7667 nextVal = nextRaw.asType(nextValType); 7668 } catch (WrongMethodTypeException ex) { 7669 throw new IllegalArgumentException(ex); 7670 } 7671 } 7672 7673 MethodHandle retv = null, step = body; 7674 if (returnType != void.class) { 7675 // the simple thing first: in (I V A...), drop the I to get V 7676 retv = dropArguments(identity(returnType), 0, Iterator.class); 7677 // body type signature (V T A...), internal loop types (I V A...) 7678 step = swapArguments(body, 0, 1); // swap V <-> T 7679 } 7680 7681 MethodHandle[] 7682 iterVar = { startIter, null, hasNext, retv }, 7683 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7684 return loop(iterVar, bodyClause); 7685 } 7686 7687 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7688 Objects.requireNonNull(body); 7689 MethodType bodyType = body.type(); 7690 Class<?> returnType = bodyType.returnType(); 7691 List<Class<?>> internalParamList = bodyType.parameterList(); 7692 // strip leading V value if present 7693 int vsize = (returnType == void.class ? 0 : 1); 7694 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7695 // argument list has no "V" => error 7696 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7697 throw misMatchedTypes("body function", bodyType, expected); 7698 } else if (internalParamList.size() <= vsize) { 7699 // missing T type => error 7700 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7701 throw misMatchedTypes("body function", bodyType, expected); 7702 } 7703 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7704 Class<?> iterableType = null; 7705 if (iterator != null) { 7706 // special case; if the body handle only declares V and T then 7707 // the external parameter list is obtained from iterator handle 7708 if (externalParamList.isEmpty()) { 7709 externalParamList = iterator.type().parameterList(); 7710 } 7711 MethodType itype = iterator.type(); 7712 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7713 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7714 } 7715 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7716 MethodType expected = methodType(itype.returnType(), externalParamList); 7717 throw misMatchedTypes("iterator parameters", itype, expected); 7718 } 7719 } else { 7720 if (externalParamList.isEmpty()) { 7721 // special case; if the iterator handle is null and the body handle 7722 // only declares V and T then the external parameter list consists 7723 // of Iterable 7724 externalParamList = List.of(Iterable.class); 7725 iterableType = Iterable.class; 7726 } else { 7727 // special case; if the iterator handle is null and the external 7728 // parameter list is not empty then the first parameter must be 7729 // assignable to Iterable 7730 iterableType = externalParamList.get(0); 7731 if (!Iterable.class.isAssignableFrom(iterableType)) { 7732 throw newIllegalArgumentException( 7733 "inferred first loop argument must inherit from Iterable: " + iterableType); 7734 } 7735 } 7736 } 7737 if (init != null) { 7738 MethodType initType = init.type(); 7739 if (initType.returnType() != returnType || 7740 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7741 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7742 } 7743 } 7744 return iterableType; // help the caller a bit 7745 } 7746 7747 /*non-public*/ 7748 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7749 // there should be a better way to uncross my wires 7750 int arity = mh.type().parameterCount(); 7751 int[] order = new int[arity]; 7752 for (int k = 0; k < arity; k++) order[k] = k; 7753 order[i] = j; order[j] = i; 7754 Class<?>[] types = mh.type().parameterArray(); 7755 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7756 MethodType swapType = methodType(mh.type().returnType(), types); 7757 return permuteArguments(mh, swapType, order); 7758 } 7759 7760 /** 7761 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7762 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7763 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7764 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7765 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7766 * {@code try-finally} handle. 7767 * <p> 7768 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7769 * The first is the exception thrown during the 7770 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7771 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7772 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7773 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7774 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7775 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7776 * <p> 7777 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7778 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7779 * two extra leading parameters:<ul> 7780 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7781 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7782 * the result from the execution of the {@code target} handle. 7783 * This parameter is not present if the {@code target} returns {@code void}. 7784 * </ul> 7785 * <p> 7786 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7787 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7788 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7789 * the cleanup. 7790 * {@snippet lang="java" : 7791 * V target(A..., B...); 7792 * V cleanup(Throwable, V, A...); 7793 * V adapter(A... a, B... b) { 7794 * V result = (zero value for V); 7795 * Throwable throwable = null; 7796 * try { 7797 * result = target(a..., b...); 7798 * } catch (Throwable t) { 7799 * throwable = t; 7800 * throw t; 7801 * } finally { 7802 * result = cleanup(throwable, result, a...); 7803 * } 7804 * return result; 7805 * } 7806 * } 7807 * <p> 7808 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7809 * be modified by execution of the target, and so are passed unchanged 7810 * from the caller to the cleanup, if it is invoked. 7811 * <p> 7812 * The target and cleanup must return the same type, even if the cleanup 7813 * always throws. 7814 * To create such a throwing cleanup, compose the cleanup logic 7815 * with {@link #throwException throwException}, 7816 * in order to create a method handle of the correct return type. 7817 * <p> 7818 * Note that {@code tryFinally} never converts exceptions into normal returns. 7819 * In rare cases where exceptions must be converted in that way, first wrap 7820 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7821 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7822 * <p> 7823 * It is recommended that the first parameter type of {@code cleanup} be 7824 * declared {@code Throwable} rather than a narrower subtype. This ensures 7825 * {@code cleanup} will always be invoked with whatever exception that 7826 * {@code target} throws. Declaring a narrower type may result in a 7827 * {@code ClassCastException} being thrown by the {@code try-finally} 7828 * handle if the type of the exception thrown by {@code target} is not 7829 * assignable to the first parameter type of {@code cleanup}. Note that 7830 * various exception types of {@code VirtualMachineError}, 7831 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7832 * thrown by almost any kind of Java code, and a finally clause that 7833 * catches (say) only {@code IOException} would mask any of the others 7834 * behind a {@code ClassCastException}. 7835 * 7836 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7837 * @param cleanup the handle that is invoked in the finally block. 7838 * 7839 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7840 * @throws NullPointerException if any argument is null 7841 * @throws IllegalArgumentException if {@code cleanup} does not accept 7842 * the required leading arguments, or if the method handle types do 7843 * not match in their return types and their 7844 * corresponding trailing parameters 7845 * 7846 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7847 * @since 9 7848 */ 7849 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7850 Class<?>[] targetParamTypes = target.type().ptypes(); 7851 Class<?> rtype = target.type().returnType(); 7852 7853 tryFinallyChecks(target, cleanup); 7854 7855 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7856 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7857 // target parameter list. 7858 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7859 7860 // Ensure that the intrinsic type checks the instance thrown by the 7861 // target against the first parameter of cleanup 7862 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7863 7864 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7865 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7866 } 7867 7868 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7869 Class<?> rtype = target.type().returnType(); 7870 if (rtype != cleanup.type().returnType()) { 7871 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7872 } 7873 MethodType cleanupType = cleanup.type(); 7874 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7875 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7876 } 7877 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7878 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7879 } 7880 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7881 // target parameter list. 7882 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7883 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7884 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7885 cleanup.type(), target.type()); 7886 } 7887 } 7888 7889 /** 7890 * Creates a table switch method handle, which can be used to switch over a set of target 7891 * method handles, based on a given target index, called selector. 7892 * <p> 7893 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7894 * and where {@code N} is the number of target method handles, the table switch method 7895 * handle will invoke the n-th target method handle from the list of target method handles. 7896 * <p> 7897 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7898 * method handle will invoke the given fallback method handle. 7899 * <p> 7900 * All method handles passed to this method must have the same type, with the additional 7901 * requirement that the leading parameter be of type {@code int}. The leading parameter 7902 * represents the selector. 7903 * <p> 7904 * Any trailing parameters present in the type will appear on the returned table switch 7905 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7906 * together with the selector value, to the selected method handle when invoking it. 7907 * 7908 * @apiNote Example: 7909 * The cases each drop the {@code selector} value they are given, and take an additional 7910 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7911 * to a specific constant label string for each case: 7912 * {@snippet lang="java" : 7913 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7914 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7915 * MethodType.methodType(String.class, String.class)); 7916 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7917 * 7918 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7919 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7920 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7921 * 7922 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7923 * caseDefault, 7924 * case0, 7925 * case1 7926 * ); 7927 * 7928 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7929 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7930 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7931 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7932 * } 7933 * 7934 * @param fallback the fallback method handle that is called when the selector is not 7935 * within the range {@code [0, N)}. 7936 * @param targets array of target method handles. 7937 * @return the table switch method handle. 7938 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7939 * any of the elements of the {@code targets} array are 7940 * {@code null}. 7941 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7942 * parameter of the fallback handle or any of the target 7943 * handles is not {@code int}, or if the types of 7944 * the fallback handle and all of target handles are 7945 * not the same. 7946 */ 7947 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7948 Objects.requireNonNull(fallback); 7949 Objects.requireNonNull(targets); 7950 targets = targets.clone(); 7951 MethodType type = tableSwitchChecks(fallback, targets); 7952 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7953 } 7954 7955 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7956 if (caseActions.length == 0) 7957 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7958 7959 MethodType expectedType = defaultCase.type(); 7960 7961 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7962 throw new IllegalArgumentException( 7963 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7964 7965 for (MethodHandle mh : caseActions) { 7966 Objects.requireNonNull(mh); 7967 if (mh.type() != expectedType) 7968 throw new IllegalArgumentException( 7969 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7970 } 7971 7972 return expectedType; 7973 } 7974 7975 /** 7976 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7977 * <p> 7978 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7979 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7980 * to the target var handle. 7981 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7982 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7983 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7984 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7985 * <p> 7986 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7987 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7988 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7989 * will be appended to the coordinates of the target var handle). 7990 * <p> 7991 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7992 * throw an {@link IllegalStateException}. 7993 * <p> 7994 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7995 * atomic access guarantees as those featured by the target var handle. 7996 * 7997 * @param target the target var handle 7998 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7999 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 8000 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 8001 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 8002 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 8003 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 8004 * @throws NullPointerException if any of the arguments is {@code null}. 8005 * @since 22 8006 */ 8007 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 8008 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 8009 } 8010 8011 /** 8012 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 8013 * <p> 8014 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 8015 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 8016 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 8017 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 8018 * by the adaptation) to the target var handle. 8019 * <p> 8020 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 8021 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8022 * <p> 8023 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8024 * throw an {@link IllegalStateException}. 8025 * <p> 8026 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8027 * atomic access guarantees as those featured by the target var handle. 8028 * 8029 * @param target the target var handle 8030 * @param pos the position of the first coordinate to be transformed 8031 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 8032 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 8033 * to the new coordinate values. 8034 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 8035 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 8036 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8037 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 8038 * or if it's determined that any of the filters throws any checked exceptions. 8039 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 8040 * @since 22 8041 */ 8042 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8043 return VarHandles.filterCoordinates(target, pos, filters); 8044 } 8045 8046 /** 8047 * Provides a target var handle with one or more <em>bound coordinates</em> 8048 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8049 * coordinate types than the target var handle. 8050 * <p> 8051 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8052 * are joined with bound coordinate values, and then passed to the target var handle. 8053 * <p> 8054 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8055 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8056 * <p> 8057 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8058 * atomic access guarantees as those featured by the target var handle. 8059 * 8060 * @param target the var handle to invoke after the bound coordinates are inserted 8061 * @param pos the position of the first coordinate to be inserted 8062 * @param values the series of bound coordinates to insert 8063 * @return an adapter var handle which inserts additional coordinates, 8064 * before calling the target var handle 8065 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8066 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8067 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8068 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8069 * of the target var handle. 8070 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8071 * @since 22 8072 */ 8073 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8074 return VarHandles.insertCoordinates(target, pos, values); 8075 } 8076 8077 /** 8078 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8079 * so that the new coordinates match the provided ones. 8080 * <p> 8081 * The given array controls the reordering. 8082 * Call {@code #I} the number of incoming coordinates (the value 8083 * {@code newCoordinates.size()}), and call {@code #O} the number 8084 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8085 * Then the length of the reordering array must be {@code #O}, 8086 * and each element must be a non-negative number less than {@code #I}. 8087 * For every {@code N} less than {@code #O}, the {@code N}-th 8088 * outgoing coordinate will be taken from the {@code I}-th incoming 8089 * coordinate, where {@code I} is {@code reorder[N]}. 8090 * <p> 8091 * No coordinate value conversions are applied. 8092 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8093 * must be identical to the type of the corresponding outgoing coordinate 8094 * in the target var handle. 8095 * <p> 8096 * The reordering array need not specify an actual permutation. 8097 * An incoming coordinate will be duplicated if its index appears 8098 * more than once in the array, and an incoming coordinate will be dropped 8099 * if its index does not appear in the array. 8100 * <p> 8101 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8102 * atomic access guarantees as those featured by the target var handle. 8103 * @param target the var handle to invoke after the coordinates have been reordered 8104 * @param newCoordinates the new coordinate types 8105 * @param reorder an index array which controls the reordering 8106 * @return an adapter var handle which re-arranges the incoming coordinate values, 8107 * before calling the target var handle 8108 * @throws IllegalArgumentException if the index array length is not equal to 8109 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8110 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8111 * the target var handle and in {@code newCoordinates} are not identical. 8112 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8113 * @since 22 8114 */ 8115 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8116 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8117 } 8118 8119 /** 8120 * Adapts a target var handle by pre-processing 8121 * a sub-sequence of its coordinate values with a filter (a method handle). 8122 * The pre-processed coordinates are replaced by the result (if any) of the 8123 * filter function and the target var handle is then called on the modified (usually shortened) 8124 * coordinate list. 8125 * <p> 8126 * If {@code R} is the return type of the filter, then: 8127 * <ul> 8128 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 8129 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 8130 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 8131 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 8132 * target var handle.</li> 8133 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 8134 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 8135 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 8136 * downstream invocation of the target var handle.</li> 8137 * </ul> 8138 * <p> 8139 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8140 * throw an {@link IllegalStateException}. 8141 * <p> 8142 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8143 * atomic access guarantees as those featured by the target var handle. 8144 * 8145 * @param target the var handle to invoke after the coordinates have been filtered 8146 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 8147 * @param filter the filter method handle 8148 * @return an adapter var handle which filters the incoming coordinate values, 8149 * before calling the target var handle 8150 * @throws IllegalArgumentException if the return type of {@code filter} 8151 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 8152 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8153 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8154 * or if it's determined that {@code filter} throws any checked exceptions. 8155 * @throws NullPointerException if any of the arguments is {@code null}. 8156 * @since 22 8157 */ 8158 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8159 return VarHandles.collectCoordinates(target, pos, filter); 8160 } 8161 8162 /** 8163 * Returns a var handle which will discard some dummy coordinates before delegating to the 8164 * target var handle. As a consequence, the resulting var handle will feature more 8165 * coordinate types than the target var handle. 8166 * <p> 8167 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8168 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8169 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8170 * <p> 8171 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8172 * atomic access guarantees as those featured by the target var handle. 8173 * 8174 * @param target the var handle to invoke after the dummy coordinates are dropped 8175 * @param pos position of the first coordinate to drop (zero for the leftmost) 8176 * @param valueTypes the type(s) of the coordinate(s) to drop 8177 * @return an adapter var handle which drops some dummy coordinates, 8178 * before calling the target var handle 8179 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8180 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8181 * @since 22 8182 */ 8183 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8184 return VarHandles.dropCoordinates(target, pos, valueTypes); 8185 } 8186 }