1 /* 2 * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.access.SharedSecrets; 29 import jdk.internal.misc.Unsafe; 30 import jdk.internal.misc.VM; 31 import jdk.internal.reflect.CallerSensitive; 32 import jdk.internal.reflect.CallerSensitiveAdapter; 33 import jdk.internal.reflect.Reflection; 34 import jdk.internal.util.ClassFileDumper; 35 import jdk.internal.vm.annotation.ForceInline; 36 import sun.invoke.util.ValueConversions; 37 import sun.invoke.util.VerifyAccess; 38 import sun.invoke.util.Wrapper; 39 import sun.reflect.misc.ReflectUtil; 40 import sun.security.util.SecurityConstants; 41 42 import java.lang.classfile.ClassFile; 43 import java.lang.classfile.ClassModel; 44 import java.lang.constant.ClassDesc; 45 import java.lang.constant.ConstantDescs; 46 import java.lang.invoke.LambdaForm.BasicType; 47 import java.lang.invoke.MethodHandleImpl.Intrinsic; 48 import java.lang.reflect.Constructor; 49 import java.lang.reflect.Field; 50 import java.lang.reflect.Member; 51 import java.lang.reflect.Method; 52 import java.lang.reflect.Modifier; 53 import java.nio.ByteOrder; 54 import java.security.ProtectionDomain; 55 import java.util.ArrayList; 56 import java.util.Arrays; 57 import java.util.BitSet; 58 import java.util.Comparator; 59 import java.util.Iterator; 60 import java.util.List; 61 import java.util.Objects; 62 import java.util.Set; 63 import java.util.concurrent.ConcurrentHashMap; 64 import java.util.stream.Stream; 65 66 import static java.lang.classfile.ClassFile.*; 67 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 68 import static java.lang.invoke.MethodHandleNatives.Constants.*; 69 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 70 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 71 import static java.lang.invoke.MethodHandleStatics.newInternalError; 72 import static java.lang.invoke.MethodType.methodType; 73 74 /** 75 * This class consists exclusively of static methods that operate on or return 76 * method handles. They fall into several categories: 77 * <ul> 78 * <li>Lookup methods which help create method handles for methods and fields. 79 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 80 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 81 * </ul> 82 * A lookup, combinator, or factory method will fail and throw an 83 * {@code IllegalArgumentException} if the created method handle's type 84 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 85 * 86 * @author John Rose, JSR 292 EG 87 * @since 1.7 88 */ 89 public class MethodHandles { 90 91 private MethodHandles() { } // do not instantiate 92 93 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 94 95 // See IMPL_LOOKUP below. 96 97 //--- Method handle creation from ordinary methods. 98 99 /** 100 * Returns a {@link Lookup lookup object} with 101 * full capabilities to emulate all supported bytecode behaviors of the caller. 102 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 103 * Factory methods on the lookup object can create 104 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 105 * for any member that the caller has access to via bytecodes, 106 * including protected and private fields and methods. 107 * This lookup object is created by the original lookup class 108 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 109 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 110 * Do not store it in place where untrusted code can access it. 111 * <p> 112 * This method is caller sensitive, which means that it may return different 113 * values to different callers. 114 * In cases where {@code MethodHandles.lookup} is called from a context where 115 * there is no caller frame on the stack (e.g. when called directly 116 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 117 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 118 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 119 * to obtain a low-privileged lookup instead. 120 * @return a lookup object for the caller of this method, with 121 * {@linkplain Lookup#ORIGINAL original} and 122 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 123 * @throws IllegalCallerException if there is no caller frame on the stack. 124 */ 125 @CallerSensitive 126 @ForceInline // to ensure Reflection.getCallerClass optimization 127 public static Lookup lookup() { 128 final Class<?> c = Reflection.getCallerClass(); 129 if (c == null) { 130 throw new IllegalCallerException("no caller frame"); 131 } 132 return new Lookup(c); 133 } 134 135 /** 136 * This lookup method is the alternate implementation of 137 * the lookup method with a leading caller class argument which is 138 * non-caller-sensitive. This method is only invoked by reflection 139 * and method handle. 140 */ 141 @CallerSensitiveAdapter 142 private static Lookup lookup(Class<?> caller) { 143 if (caller.getClassLoader() == null) { 144 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 145 } 146 return new Lookup(caller); 147 } 148 149 /** 150 * Returns a {@link Lookup lookup object} which is trusted minimally. 151 * The lookup has the {@code UNCONDITIONAL} mode. 152 * It can only be used to create method handles to public members of 153 * public classes in packages that are exported unconditionally. 154 * <p> 155 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 156 * of this lookup object will be {@link java.lang.Object}. 157 * 158 * @apiNote The use of Object is conventional, and because the lookup modes are 159 * limited, there is no special access provided to the internals of Object, its package 160 * or its module. This public lookup object or other lookup object with 161 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 162 * is not used to determine the lookup context. 163 * 164 * <p style="font-size:smaller;"> 165 * <em>Discussion:</em> 166 * The lookup class can be changed to any other class {@code C} using an expression of the form 167 * {@link Lookup#in publicLookup().in(C.class)}. 168 * A public lookup object is always subject to 169 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 170 * Also, it cannot access 171 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 172 * @return a lookup object which is trusted minimally 173 */ 174 public static Lookup publicLookup() { 175 return Lookup.PUBLIC_LOOKUP; 176 } 177 178 /** 179 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 180 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 181 * The returned lookup object can provide access to classes in modules and packages, 182 * and members of those classes, outside the normal rules of Java access control, 183 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 184 * <p> 185 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 186 * allowed to do deep reflection on module {@code M2} and package of the target class 187 * if and only if all of the following conditions are {@code true}: 188 * <ul> 189 * <li>If there is a security manager, its {@code checkPermission} method is 190 * called to check {@code ReflectPermission("suppressAccessChecks")} and 191 * that must return normally. 192 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 193 * full privilege access}. Specifically: 194 * <ul> 195 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 196 * (This is because otherwise there would be no way to ensure the original lookup 197 * creator was a member of any particular module, and so any subsequent checks 198 * for readability and qualified exports would become ineffective.) 199 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 200 * (This is because an application intending to share intra-module access 201 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 202 * deep reflection to its own module.) 203 * </ul> 204 * <li>The target class must be a proper class, not a primitive or array class. 205 * (Thus, {@code M2} is well-defined.) 206 * <li>If the caller module {@code M1} differs from 207 * the target module {@code M2} then both of the following must be true: 208 * <ul> 209 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 210 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 211 * containing the target class to at least {@code M1}.</li> 212 * </ul> 213 * </ul> 214 * <p> 215 * If any of the above checks is violated, this method fails with an 216 * exception. 217 * <p> 218 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 219 * returns a {@code Lookup} on {@code targetClass} with 220 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 221 * with {@code null} previous lookup class. 222 * <p> 223 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 224 * returns a {@code Lookup} on {@code targetClass} that records 225 * the lookup class of the caller as the new previous lookup class with 226 * {@code PRIVATE} access but no {@code MODULE} access. 227 * <p> 228 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 229 * 230 * @apiNote The {@code Lookup} object returned by this method is allowed to 231 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 232 * of {@code targetClass}. Extreme caution should be taken when opening a package 233 * to another module as such defined classes have the same full privilege 234 * access as other members in {@code targetClass}'s module. 235 * 236 * @param targetClass the target class 237 * @param caller the caller lookup object 238 * @return a lookup object for the target class, with private access 239 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 240 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 241 * @throws SecurityException if denied by the security manager 242 * @throws IllegalAccessException if any of the other access checks specified above fails 243 * @since 9 244 * @see Lookup#dropLookupMode 245 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 246 */ 247 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 248 if (caller.allowedModes == Lookup.TRUSTED) { 249 return new Lookup(targetClass); 250 } 251 252 @SuppressWarnings("removal") 253 SecurityManager sm = System.getSecurityManager(); 254 if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION); 255 if (targetClass.isPrimitive()) 256 throw new IllegalArgumentException(targetClass + " is a primitive class"); 257 if (targetClass.isArray()) 258 throw new IllegalArgumentException(targetClass + " is an array class"); 259 // Ensure that we can reason accurately about private and module access. 260 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 261 if ((caller.lookupModes() & requireAccess) != requireAccess) 262 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 263 264 // previous lookup class is never set if it has MODULE access 265 assert caller.previousLookupClass() == null; 266 267 Class<?> callerClass = caller.lookupClass(); 268 Module callerModule = callerClass.getModule(); // M1 269 Module targetModule = targetClass.getModule(); // M2 270 Class<?> newPreviousClass = null; 271 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 272 273 if (targetModule != callerModule) { 274 if (!callerModule.canRead(targetModule)) 275 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 276 if (targetModule.isNamed()) { 277 String pn = targetClass.getPackageName(); 278 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 279 if (!targetModule.isOpen(pn, callerModule)) 280 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 281 } 282 283 // M2 != M1, set previous lookup class to M1 and drop MODULE access 284 newPreviousClass = callerClass; 285 newModes &= ~Lookup.MODULE; 286 } 287 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 288 } 289 290 /** 291 * Returns the <em>class data</em> associated with the lookup class 292 * of the given {@code caller} lookup object, or {@code null}. 293 * 294 * <p> A hidden class with class data can be created by calling 295 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 296 * Lookup::defineHiddenClassWithClassData}. 297 * This method will cause the static class initializer of the lookup 298 * class of the given {@code caller} lookup object be executed if 299 * it has not been initialized. 300 * 301 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 302 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 303 * {@code null} is returned if this method is called on the lookup object 304 * on these classes. 305 * 306 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 307 * must have {@linkplain Lookup#ORIGINAL original access} 308 * in order to retrieve the class data. 309 * 310 * @apiNote 311 * This method can be called as a bootstrap method for a dynamically computed 312 * constant. A framework can create a hidden class with class data, for 313 * example that can be {@code Class} or {@code MethodHandle} object. 314 * The class data is accessible only to the lookup object 315 * created by the original caller but inaccessible to other members 316 * in the same nest. If a framework passes security sensitive objects 317 * to a hidden class via class data, it is recommended to load the value 318 * of class data as a dynamically computed constant instead of storing 319 * the class data in private static field(s) which are accessible to 320 * other nestmates. 321 * 322 * @param <T> the type to cast the class data object to 323 * @param caller the lookup context describing the class performing the 324 * operation (normally stacked by the JVM) 325 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 326 * ({@code "_"}) 327 * @param type the type of the class data 328 * @return the value of the class data if present in the lookup class; 329 * otherwise {@code null} 330 * @throws IllegalArgumentException if name is not {@code "_"} 331 * @throws IllegalAccessException if the lookup context does not have 332 * {@linkplain Lookup#ORIGINAL original} access 333 * @throws ClassCastException if the class data cannot be converted to 334 * the given {@code type} 335 * @throws NullPointerException if {@code caller} or {@code type} argument 336 * is {@code null} 337 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 338 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 339 * @since 16 340 * @jvms 5.5 Initialization 341 */ 342 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 343 Objects.requireNonNull(caller); 344 Objects.requireNonNull(type); 345 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 346 throw new IllegalArgumentException("name must be \"_\": " + name); 347 } 348 349 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 350 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 351 } 352 353 Object classdata = classData(caller.lookupClass()); 354 if (classdata == null) return null; 355 356 try { 357 return BootstrapMethodInvoker.widenAndCast(classdata, type); 358 } catch (RuntimeException|Error e) { 359 throw e; // let CCE and other runtime exceptions through 360 } catch (Throwable e) { 361 throw new InternalError(e); 362 } 363 } 364 365 /* 366 * Returns the class data set by the VM in the Class::classData field. 367 * 368 * This is also invoked by LambdaForms as it cannot use condy via 369 * MethodHandles::classData due to bootstrapping issue. 370 */ 371 static Object classData(Class<?> c) { 372 UNSAFE.ensureClassInitialized(c); 373 return SharedSecrets.getJavaLangAccess().classData(c); 374 } 375 376 /** 377 * Returns the element at the specified index in the 378 * {@linkplain #classData(Lookup, String, Class) class data}, 379 * if the class data associated with the lookup class 380 * of the given {@code caller} lookup object is a {@code List}. 381 * If the class data is not present in this lookup class, this method 382 * returns {@code null}. 383 * 384 * <p> A hidden class with class data can be created by calling 385 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 386 * Lookup::defineHiddenClassWithClassData}. 387 * This method will cause the static class initializer of the lookup 388 * class of the given {@code caller} lookup object be executed if 389 * it has not been initialized. 390 * 391 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 392 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 393 * {@code null} is returned if this method is called on the lookup object 394 * on these classes. 395 * 396 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 397 * must have {@linkplain Lookup#ORIGINAL original access} 398 * in order to retrieve the class data. 399 * 400 * @apiNote 401 * This method can be called as a bootstrap method for a dynamically computed 402 * constant. A framework can create a hidden class with class data, for 403 * example that can be {@code List.of(o1, o2, o3....)} containing more than 404 * one object and use this method to load one element at a specific index. 405 * The class data is accessible only to the lookup object 406 * created by the original caller but inaccessible to other members 407 * in the same nest. If a framework passes security sensitive objects 408 * to a hidden class via class data, it is recommended to load the value 409 * of class data as a dynamically computed constant instead of storing 410 * the class data in private static field(s) which are accessible to other 411 * nestmates. 412 * 413 * @param <T> the type to cast the result object to 414 * @param caller the lookup context describing the class performing the 415 * operation (normally stacked by the JVM) 416 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 417 * ({@code "_"}) 418 * @param type the type of the element at the given index in the class data 419 * @param index index of the element in the class data 420 * @return the element at the given index in the class data 421 * if the class data is present; otherwise {@code null} 422 * @throws IllegalArgumentException if name is not {@code "_"} 423 * @throws IllegalAccessException if the lookup context does not have 424 * {@linkplain Lookup#ORIGINAL original} access 425 * @throws ClassCastException if the class data cannot be converted to {@code List} 426 * or the element at the specified index cannot be converted to the given type 427 * @throws IndexOutOfBoundsException if the index is out of range 428 * @throws NullPointerException if {@code caller} or {@code type} argument is 429 * {@code null}; or if unboxing operation fails because 430 * the element at the given index is {@code null} 431 * 432 * @since 16 433 * @see #classData(Lookup, String, Class) 434 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 435 */ 436 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 437 throws IllegalAccessException 438 { 439 @SuppressWarnings("unchecked") 440 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 441 if (classdata == null) return null; 442 443 try { 444 Object element = classdata.get(index); 445 return BootstrapMethodInvoker.widenAndCast(element, type); 446 } catch (RuntimeException|Error e) { 447 throw e; // let specified exceptions and other runtime exceptions/errors through 448 } catch (Throwable e) { 449 throw new InternalError(e); 450 } 451 } 452 453 /** 454 * Performs an unchecked "crack" of a 455 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 456 * The result is as if the user had obtained a lookup object capable enough 457 * to crack the target method handle, called 458 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 459 * on the target to obtain its symbolic reference, and then called 460 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 461 * to resolve the symbolic reference to a member. 462 * <p> 463 * If there is a security manager, its {@code checkPermission} method 464 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 465 * @param <T> the desired type of the result, either {@link Member} or a subtype 466 * @param target a direct method handle to crack into symbolic reference components 467 * @param expected a class object representing the desired result type {@code T} 468 * @return a reference to the method, constructor, or field object 469 * @throws SecurityException if the caller is not privileged to call {@code setAccessible} 470 * @throws NullPointerException if either argument is {@code null} 471 * @throws IllegalArgumentException if the target is not a direct method handle 472 * @throws ClassCastException if the member is not of the expected type 473 * @since 1.8 474 */ 475 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 476 @SuppressWarnings("removal") 477 SecurityManager smgr = System.getSecurityManager(); 478 if (smgr != null) smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION); 479 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 480 return lookup.revealDirect(target).reflectAs(expected, lookup); 481 } 482 483 /** 484 * A <em>lookup object</em> is a factory for creating method handles, 485 * when the creation requires access checking. 486 * Method handles do not perform 487 * access checks when they are called, but rather when they are created. 488 * Therefore, method handle access 489 * restrictions must be enforced when a method handle is created. 490 * The caller class against which those restrictions are enforced 491 * is known as the {@linkplain #lookupClass() lookup class}. 492 * <p> 493 * A lookup class which needs to create method handles will call 494 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 495 * When the {@code Lookup} factory object is created, the identity of the lookup class is 496 * determined, and securely stored in the {@code Lookup} object. 497 * The lookup class (or its delegates) may then use factory methods 498 * on the {@code Lookup} object to create method handles for access-checked members. 499 * This includes all methods, constructors, and fields which are allowed to the lookup class, 500 * even private ones. 501 * 502 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 503 * The factory methods on a {@code Lookup} object correspond to all major 504 * use cases for methods, constructors, and fields. 505 * Each method handle created by a factory method is the functional 506 * equivalent of a particular <em>bytecode behavior</em>. 507 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 508 * the Java Virtual Machine Specification.) 509 * Here is a summary of the correspondence between these factory methods and 510 * the behavior of the resulting method handles: 511 * <table class="striped"> 512 * <caption style="display:none">lookup method behaviors</caption> 513 * <thead> 514 * <tr> 515 * <th scope="col"><a id="equiv"></a>lookup expression</th> 516 * <th scope="col">member</th> 517 * <th scope="col">bytecode behavior</th> 518 * </tr> 519 * </thead> 520 * <tbody> 521 * <tr> 522 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 523 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 524 * </tr> 525 * <tr> 526 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 527 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 528 * </tr> 529 * <tr> 530 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 531 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 532 * </tr> 533 * <tr> 534 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 535 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 536 * </tr> 537 * <tr> 538 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 539 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 540 * </tr> 541 * <tr> 542 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 543 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 544 * </tr> 545 * <tr> 546 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 547 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 548 * </tr> 549 * <tr> 550 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 551 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 552 * </tr> 553 * <tr> 554 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 555 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 556 * </tr> 557 * <tr> 558 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 559 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 560 * </tr> 561 * <tr> 562 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 563 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 564 * </tr> 565 * <tr> 566 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 567 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 568 * </tr> 569 * <tr> 570 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 571 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 572 * </tr> 573 * <tr> 574 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 575 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 576 * </tr> 577 * </tbody> 578 * </table> 579 * 580 * Here, the type {@code C} is the class or interface being searched for a member, 581 * documented as a parameter named {@code refc} in the lookup methods. 582 * The method type {@code MT} is composed from the return type {@code T} 583 * and the sequence of argument types {@code A*}. 584 * The constructor also has a sequence of argument types {@code A*} and 585 * is deemed to return the newly-created object of type {@code C}. 586 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 587 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 588 * if it is present, it is always the leading argument to the method handle invocation. 589 * (In the case of some {@code protected} members, {@code this} may be 590 * restricted in type to the lookup class; see below.) 591 * The name {@code arg} stands for all the other method handle arguments. 592 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 593 * stands for a null reference if the accessed method or field is static, 594 * and {@code this} otherwise. 595 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 596 * for reflective objects corresponding to the given members declared in type {@code C}. 597 * <p> 598 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 599 * as if by {@code ldc CONSTANT_Class}. 600 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 601 * <p> 602 * In cases where the given member is of variable arity (i.e., a method or constructor) 603 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 604 * In all other cases, the returned method handle will be of fixed arity. 605 * <p style="font-size:smaller;"> 606 * <em>Discussion:</em> 607 * The equivalence between looked-up method handles and underlying 608 * class members and bytecode behaviors 609 * can break down in a few ways: 610 * <ul style="font-size:smaller;"> 611 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 612 * the lookup can still succeed, even when there is no equivalent 613 * Java expression or bytecoded constant. 614 * <li>Likewise, if {@code T} or {@code MT} 615 * is not symbolically accessible from the lookup class's loader, 616 * the lookup can still succeed. 617 * For example, lookups for {@code MethodHandle.invokeExact} and 618 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 619 * <li>If there is a security manager installed, it can forbid the lookup 620 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 621 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 622 * constant is not subject to security manager checks. 623 * <li>If the looked-up method has a 624 * <a href="MethodHandle.html#maxarity">very large arity</a>, 625 * the method handle creation may fail with an 626 * {@code IllegalArgumentException}, due to the method handle type having 627 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 628 * </ul> 629 * 630 * <h2><a id="access"></a>Access checking</h2> 631 * Access checks are applied in the factory methods of {@code Lookup}, 632 * when a method handle is created. 633 * This is a key difference from the Core Reflection API, since 634 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 635 * performs access checking against every caller, on every call. 636 * <p> 637 * All access checks start from a {@code Lookup} object, which 638 * compares its recorded lookup class against all requests to 639 * create method handles. 640 * A single {@code Lookup} object can be used to create any number 641 * of access-checked method handles, all checked against a single 642 * lookup class. 643 * <p> 644 * A {@code Lookup} object can be shared with other trusted code, 645 * such as a metaobject protocol. 646 * A shared {@code Lookup} object delegates the capability 647 * to create method handles on private members of the lookup class. 648 * Even if privileged code uses the {@code Lookup} object, 649 * the access checking is confined to the privileges of the 650 * original lookup class. 651 * <p> 652 * A lookup can fail, because 653 * the containing class is not accessible to the lookup class, or 654 * because the desired class member is missing, or because the 655 * desired class member is not accessible to the lookup class, or 656 * because the lookup object is not trusted enough to access the member. 657 * In the case of a field setter function on a {@code final} field, 658 * finality enforcement is treated as a kind of access control, 659 * and the lookup will fail, except in special cases of 660 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 661 * In any of these cases, a {@code ReflectiveOperationException} will be 662 * thrown from the attempted lookup. The exact class will be one of 663 * the following: 664 * <ul> 665 * <li>NoSuchMethodException — if a method is requested but does not exist 666 * <li>NoSuchFieldException — if a field is requested but does not exist 667 * <li>IllegalAccessException — if the member exists but an access check fails 668 * </ul> 669 * <p> 670 * In general, the conditions under which a method handle may be 671 * looked up for a method {@code M} are no more restrictive than the conditions 672 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 673 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 674 * a method handle lookup will generally raise a corresponding 675 * checked exception, such as {@code NoSuchMethodException}. 676 * And the effect of invoking the method handle resulting from the lookup 677 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 678 * to executing the compiled, verified, and resolved call to {@code M}. 679 * The same point is true of fields and constructors. 680 * <p style="font-size:smaller;"> 681 * <em>Discussion:</em> 682 * Access checks only apply to named and reflected methods, 683 * constructors, and fields. 684 * Other method handle creation methods, such as 685 * {@link MethodHandle#asType MethodHandle.asType}, 686 * do not require any access checks, and are used 687 * independently of any {@code Lookup} object. 688 * <p> 689 * If the desired member is {@code protected}, the usual JVM rules apply, 690 * including the requirement that the lookup class must either be in the 691 * same package as the desired member, or must inherit that member. 692 * (See the Java Virtual Machine Specification, sections {@jvms 693 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 694 * In addition, if the desired member is a non-static field or method 695 * in a different package, the resulting method handle may only be applied 696 * to objects of the lookup class or one of its subclasses. 697 * This requirement is enforced by narrowing the type of the leading 698 * {@code this} parameter from {@code C} 699 * (which will necessarily be a superclass of the lookup class) 700 * to the lookup class itself. 701 * <p> 702 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 703 * that the receiver argument must match both the resolved method <em>and</em> 704 * the current class. Again, this requirement is enforced by narrowing the 705 * type of the leading parameter to the resulting method handle. 706 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 707 * <p> 708 * The JVM represents constructors and static initializer blocks as internal methods 709 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 710 * ConstantDescs#CLASS_INIT_NAME}). 711 * The internal syntax of invocation instructions allows them to refer to such internal 712 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 713 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 714 * <p> 715 * If the relationship between nested types is expressed directly through the 716 * {@code NestHost} and {@code NestMembers} attributes 717 * (see the Java Virtual Machine Specification, sections {@jvms 718 * 4.7.28} and {@jvms 4.7.29}), 719 * then the associated {@code Lookup} object provides direct access to 720 * the lookup class and all of its nestmates 721 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 722 * Otherwise, access between nested classes is obtained by the Java compiler creating 723 * a wrapper method to access a private method of another class in the same nest. 724 * For example, a nested class {@code C.D} 725 * can access private members within other related classes such as 726 * {@code C}, {@code C.D.E}, or {@code C.B}, 727 * but the Java compiler may need to generate wrapper methods in 728 * those related classes. In such cases, a {@code Lookup} object on 729 * {@code C.E} would be unable to access those private members. 730 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 731 * which can transform a lookup on {@code C.E} into one on any of those other 732 * classes, without special elevation of privilege. 733 * <p> 734 * The accesses permitted to a given lookup object may be limited, 735 * according to its set of {@link #lookupModes lookupModes}, 736 * to a subset of members normally accessible to the lookup class. 737 * For example, the {@link MethodHandles#publicLookup publicLookup} 738 * method produces a lookup object which is only allowed to access 739 * public members in public classes of exported packages. 740 * The caller sensitive method {@link MethodHandles#lookup lookup} 741 * produces a lookup object with full capabilities relative to 742 * its caller class, to emulate all supported bytecode behaviors. 743 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 744 * with fewer access modes than the original lookup object. 745 * 746 * <p style="font-size:smaller;"> 747 * <a id="privacc"></a> 748 * <em>Discussion of private and module access:</em> 749 * We say that a lookup has <em>private access</em> 750 * if its {@linkplain #lookupModes lookup modes} 751 * include the possibility of accessing {@code private} members 752 * (which includes the private members of nestmates). 753 * As documented in the relevant methods elsewhere, 754 * only lookups with private access possess the following capabilities: 755 * <ul style="font-size:smaller;"> 756 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 757 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 758 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 759 * for classes accessible to the lookup class 760 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 761 * within the same package member 762 * </ul> 763 * <p style="font-size:smaller;"> 764 * Similarly, a lookup with module access ensures that the original lookup creator was 765 * a member in the same module as the lookup class. 766 * <p style="font-size:smaller;"> 767 * Private and module access are independently determined modes; a lookup may have 768 * either or both or neither. A lookup which possesses both access modes is said to 769 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 770 * <p style="font-size:smaller;"> 771 * A lookup with <em>original access</em> ensures that this lookup is created by 772 * the original lookup class and the bootstrap method invoked by the VM. 773 * Such a lookup with original access also has private and module access 774 * which has the following additional capability: 775 * <ul style="font-size:smaller;"> 776 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 777 * such as {@code Class.forName} 778 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 779 * class data} associated with the lookup class</li> 780 * </ul> 781 * <p style="font-size:smaller;"> 782 * Each of these permissions is a consequence of the fact that a lookup object 783 * with private access can be securely traced back to an originating class, 784 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 785 * can be reliably determined and emulated by method handles. 786 * 787 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 788 * When a lookup class in one module {@code M1} accesses a class in another module 789 * {@code M2}, extra access checking is performed beyond the access mode bits. 790 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 791 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 792 * and when the type is in a package of {@code M2} that is exported to 793 * at least {@code M1}. 794 * <p> 795 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 796 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 797 * MethodHandles.privateLookupIn} methods. 798 * Teleporting across modules will always record the original lookup class as 799 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 800 * and drops {@link Lookup#MODULE MODULE} access. 801 * If the target class is in the same module as the lookup class {@code C}, 802 * then the target class becomes the new lookup class 803 * and there is no change to the previous lookup class. 804 * If the target class is in a different module from {@code M1} ({@code C}'s module), 805 * {@code C} becomes the new previous lookup class 806 * and the target class becomes the new lookup class. 807 * In that case, if there was already a previous lookup class in {@code M0}, 808 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 809 * drops all privileges. 810 * For example, 811 * {@snippet lang="java" : 812 * Lookup lookup = MethodHandles.lookup(); // in class C 813 * Lookup lookup2 = lookup.in(D.class); 814 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 815 * } 816 * <p> 817 * The {@link #lookup()} factory method produces a {@code Lookup} object 818 * with {@code null} previous lookup class. 819 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 820 * to class {@code D} without elevation of privileges. 821 * If {@code C} and {@code D} are in the same module, 822 * {@code lookup2} records {@code D} as the new lookup class and keeps the 823 * same previous lookup class as the original {@code lookup}, or 824 * {@code null} if not present. 825 * <p> 826 * When a {@code Lookup} teleports from a class 827 * in one nest to another nest, {@code PRIVATE} access is dropped. 828 * When a {@code Lookup} teleports from a class in one package to 829 * another package, {@code PACKAGE} access is dropped. 830 * When a {@code Lookup} teleports from a class in one module to another module, 831 * {@code MODULE} access is dropped. 832 * Teleporting across modules drops the ability to access non-exported classes 833 * in both the module of the new lookup class and the module of the old lookup class 834 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 835 * A {@code Lookup} can teleport back and forth to a class in the module of 836 * the lookup class and the module of the previous class lookup. 837 * Teleporting across modules can only decrease access but cannot increase it. 838 * Teleporting to some third module drops all accesses. 839 * <p> 840 * In the above example, if {@code C} and {@code D} are in different modules, 841 * {@code lookup2} records {@code D} as its lookup class and 842 * {@code C} as its previous lookup class and {@code lookup2} has only 843 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 844 * {@code C}'s module and {@code D}'s module. 845 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 846 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 847 * class {@code D} is recorded as its previous lookup class. 848 * <p> 849 * Teleporting across modules restricts access to the public types that 850 * both the lookup class and the previous lookup class can equally access 851 * (see below). 852 * <p> 853 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 854 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 855 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 856 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 857 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 858 * to call {@code privateLookupIn}. 859 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 860 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 861 * produces a new {@code Lookup} on {@code T} with full capabilities. 862 * A {@code lookup} on {@code C} is also allowed 863 * to do deep reflection on {@code T} in another module {@code M2} if 864 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 865 * the package containing {@code T} to at least {@code M1}. 866 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 867 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 868 * The resulting {@code Lookup} can be used to do member lookup or teleport 869 * to another lookup class by calling {@link #in Lookup::in}. But 870 * it cannot be used to obtain another private {@code Lookup} by calling 871 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 872 * because it has no {@code MODULE} access. 873 * <p> 874 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 875 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 876 * of {@code T}. Extreme caution should be taken when opening a package 877 * to another module as such defined classes have the same full privilege 878 * access as other members in {@code M2}. 879 * 880 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 881 * 882 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 883 * allows cross-module access. The access checking is performed with respect 884 * to both the lookup class and the previous lookup class if present. 885 * <p> 886 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 887 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 888 * exported unconditionally}. 889 * <p> 890 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 891 * the lookup with {@link #PUBLIC} mode can access all public types in modules 892 * that are readable to {@code M1} and the type is in a package that is exported 893 * at least to {@code M1}. 894 * <p> 895 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 896 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 897 * the intersection of all public types that are accessible to {@code M1} 898 * with all public types that are accessible to {@code M0}. {@code M0} 899 * reads {@code M1} and hence the set of accessible types includes: 900 * 901 * <ul> 902 * <li>unconditional-exported packages from {@code M1}</li> 903 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 904 * <li> 905 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 906 * and {@code M1} read {@code M2} 907 * </li> 908 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 909 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 910 * <li> 911 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 912 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 913 * </li> 914 * </ul> 915 * 916 * <h2><a id="access-modes"></a>Access modes</h2> 917 * 918 * The table below shows the access modes of a {@code Lookup} produced by 919 * any of the following factory or transformation methods: 920 * <ul> 921 * <li>{@link #lookup() MethodHandles::lookup}</li> 922 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 923 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 924 * <li>{@link Lookup#in Lookup::in}</li> 925 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 926 * </ul> 927 * 928 * <table class="striped"> 929 * <caption style="display:none"> 930 * Access mode summary 931 * </caption> 932 * <thead> 933 * <tr> 934 * <th scope="col">Lookup object</th> 935 * <th style="text-align:center">original</th> 936 * <th style="text-align:center">protected</th> 937 * <th style="text-align:center">private</th> 938 * <th style="text-align:center">package</th> 939 * <th style="text-align:center">module</th> 940 * <th style="text-align:center">public</th> 941 * </tr> 942 * </thead> 943 * <tbody> 944 * <tr> 945 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 946 * <td style="text-align:center">ORI</td> 947 * <td style="text-align:center">PRO</td> 948 * <td style="text-align:center">PRI</td> 949 * <td style="text-align:center">PAC</td> 950 * <td style="text-align:center">MOD</td> 951 * <td style="text-align:center">1R</td> 952 * </tr> 953 * <tr> 954 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 955 * <td></td> 956 * <td></td> 957 * <td></td> 958 * <td style="text-align:center">PAC</td> 959 * <td style="text-align:center">MOD</td> 960 * <td style="text-align:center">1R</td> 961 * </tr> 962 * <tr> 963 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 964 * <td></td> 965 * <td></td> 966 * <td></td> 967 * <td></td> 968 * <td style="text-align:center">MOD</td> 969 * <td style="text-align:center">1R</td> 970 * </tr> 971 * <tr> 972 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 973 * <td></td> 974 * <td></td> 975 * <td></td> 976 * <td></td> 977 * <td></td> 978 * <td style="text-align:center">2R</td> 979 * </tr> 980 * <tr> 981 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 982 * <td></td> 983 * <td></td> 984 * <td></td> 985 * <td></td> 986 * <td></td> 987 * <td style="text-align:center">2R</td> 988 * </tr> 989 * <tr> 990 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 991 * <td></td> 992 * <td style="text-align:center">PRO</td> 993 * <td style="text-align:center">PRI</td> 994 * <td style="text-align:center">PAC</td> 995 * <td style="text-align:center">MOD</td> 996 * <td style="text-align:center">1R</td> 997 * </tr> 998 * <tr> 999 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 1000 * <td></td> 1001 * <td style="text-align:center">PRO</td> 1002 * <td style="text-align:center">PRI</td> 1003 * <td style="text-align:center">PAC</td> 1004 * <td style="text-align:center">MOD</td> 1005 * <td style="text-align:center">1R</td> 1006 * </tr> 1007 * <tr> 1008 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1009 * <td></td> 1010 * <td></td> 1011 * <td></td> 1012 * <td style="text-align:center">PAC</td> 1013 * <td style="text-align:center">MOD</td> 1014 * <td style="text-align:center">1R</td> 1015 * </tr> 1016 * <tr> 1017 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1018 * <td></td> 1019 * <td></td> 1020 * <td></td> 1021 * <td></td> 1022 * <td style="text-align:center">MOD</td> 1023 * <td style="text-align:center">1R</td> 1024 * </tr> 1025 * <tr> 1026 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1027 * <td></td> 1028 * <td></td> 1029 * <td></td> 1030 * <td></td> 1031 * <td></td> 1032 * <td style="text-align:center">2R</td> 1033 * </tr> 1034 * <tr> 1035 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1036 * <td></td> 1037 * <td></td> 1038 * <td style="text-align:center">PRI</td> 1039 * <td style="text-align:center">PAC</td> 1040 * <td style="text-align:center">MOD</td> 1041 * <td style="text-align:center">1R</td> 1042 * </tr> 1043 * <tr> 1044 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1045 * <td></td> 1046 * <td></td> 1047 * <td></td> 1048 * <td style="text-align:center">PAC</td> 1049 * <td style="text-align:center">MOD</td> 1050 * <td style="text-align:center">1R</td> 1051 * </tr> 1052 * <tr> 1053 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1054 * <td></td> 1055 * <td></td> 1056 * <td></td> 1057 * <td></td> 1058 * <td style="text-align:center">MOD</td> 1059 * <td style="text-align:center">1R</td> 1060 * </tr> 1061 * <tr> 1062 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1063 * <td></td> 1064 * <td></td> 1065 * <td></td> 1066 * <td></td> 1067 * <td></td> 1068 * <td style="text-align:center">1R</td> 1069 * </tr> 1070 * <tr> 1071 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1072 * <td></td> 1073 * <td></td> 1074 * <td></td> 1075 * <td></td> 1076 * <td></td> 1077 * <td style="text-align:center">none</td> 1078 * <tr> 1079 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1080 * <td></td> 1081 * <td style="text-align:center">PRO</td> 1082 * <td style="text-align:center">PRI</td> 1083 * <td style="text-align:center">PAC</td> 1084 * <td></td> 1085 * <td style="text-align:center">2R</td> 1086 * </tr> 1087 * <tr> 1088 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1089 * <td></td> 1090 * <td style="text-align:center">PRO</td> 1091 * <td style="text-align:center">PRI</td> 1092 * <td style="text-align:center">PAC</td> 1093 * <td></td> 1094 * <td style="text-align:center">2R</td> 1095 * </tr> 1096 * <tr> 1097 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1098 * <td></td> 1099 * <td></td> 1100 * <td></td> 1101 * <td></td> 1102 * <td></td> 1103 * <td style="text-align:center">IAE</td> 1104 * </tr> 1105 * <tr> 1106 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1107 * <td></td> 1108 * <td></td> 1109 * <td></td> 1110 * <td style="text-align:center">PAC</td> 1111 * <td></td> 1112 * <td style="text-align:center">2R</td> 1113 * </tr> 1114 * <tr> 1115 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1116 * <td></td> 1117 * <td></td> 1118 * <td></td> 1119 * <td></td> 1120 * <td></td> 1121 * <td style="text-align:center">2R</td> 1122 * </tr> 1123 * <tr> 1124 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1125 * <td></td> 1126 * <td></td> 1127 * <td></td> 1128 * <td></td> 1129 * <td></td> 1130 * <td style="text-align:center">2R</td> 1131 * </tr> 1132 * <tr> 1133 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1134 * <td></td> 1135 * <td></td> 1136 * <td></td> 1137 * <td></td> 1138 * <td></td> 1139 * <td style="text-align:center">none</td> 1140 * </tr> 1141 * <tr> 1142 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1143 * <td></td> 1144 * <td></td> 1145 * <td style="text-align:center">PRI</td> 1146 * <td style="text-align:center">PAC</td> 1147 * <td></td> 1148 * <td style="text-align:center">2R</td> 1149 * </tr> 1150 * <tr> 1151 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1152 * <td></td> 1153 * <td></td> 1154 * <td></td> 1155 * <td style="text-align:center">PAC</td> 1156 * <td></td> 1157 * <td style="text-align:center">2R</td> 1158 * </tr> 1159 * <tr> 1160 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1161 * <td></td> 1162 * <td></td> 1163 * <td></td> 1164 * <td></td> 1165 * <td></td> 1166 * <td style="text-align:center">2R</td> 1167 * </tr> 1168 * <tr> 1169 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1170 * <td></td> 1171 * <td></td> 1172 * <td></td> 1173 * <td></td> 1174 * <td></td> 1175 * <td style="text-align:center">2R</td> 1176 * </tr> 1177 * <tr> 1178 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1179 * <td></td> 1180 * <td></td> 1181 * <td></td> 1182 * <td></td> 1183 * <td></td> 1184 * <td style="text-align:center">none</td> 1185 * </tr> 1186 * <tr> 1187 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1188 * <td></td> 1189 * <td></td> 1190 * <td style="text-align:center">PRI</td> 1191 * <td style="text-align:center">PAC</td> 1192 * <td style="text-align:center">MOD</td> 1193 * <td style="text-align:center">1R</td> 1194 * </tr> 1195 * <tr> 1196 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1197 * <td></td> 1198 * <td></td> 1199 * <td></td> 1200 * <td style="text-align:center">PAC</td> 1201 * <td style="text-align:center">MOD</td> 1202 * <td style="text-align:center">1R</td> 1203 * </tr> 1204 * <tr> 1205 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1206 * <td></td> 1207 * <td></td> 1208 * <td></td> 1209 * <td></td> 1210 * <td style="text-align:center">MOD</td> 1211 * <td style="text-align:center">1R</td> 1212 * </tr> 1213 * <tr> 1214 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1215 * <td></td> 1216 * <td></td> 1217 * <td></td> 1218 * <td></td> 1219 * <td></td> 1220 * <td style="text-align:center">1R</td> 1221 * </tr> 1222 * <tr> 1223 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1224 * <td></td> 1225 * <td></td> 1226 * <td></td> 1227 * <td></td> 1228 * <td></td> 1229 * <td style="text-align:center">none</td> 1230 * </tr> 1231 * <tr> 1232 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1233 * <td></td> 1234 * <td></td> 1235 * <td></td> 1236 * <td></td> 1237 * <td></td> 1238 * <td style="text-align:center">U</td> 1239 * </tr> 1240 * <tr> 1241 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1242 * <td></td> 1243 * <td></td> 1244 * <td></td> 1245 * <td></td> 1246 * <td></td> 1247 * <td style="text-align:center">U</td> 1248 * </tr> 1249 * <tr> 1250 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1251 * <td></td> 1252 * <td></td> 1253 * <td></td> 1254 * <td></td> 1255 * <td></td> 1256 * <td style="text-align:center">U</td> 1257 * </tr> 1258 * <tr> 1259 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1260 * <td></td> 1261 * <td></td> 1262 * <td></td> 1263 * <td></td> 1264 * <td></td> 1265 * <td style="text-align:center">none</td> 1266 * </tr> 1267 * <tr> 1268 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1269 * <td></td> 1270 * <td></td> 1271 * <td></td> 1272 * <td></td> 1273 * <td></td> 1274 * <td style="text-align:center">IAE</td> 1275 * </tr> 1276 * <tr> 1277 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1278 * <td></td> 1279 * <td></td> 1280 * <td></td> 1281 * <td></td> 1282 * <td></td> 1283 * <td style="text-align:center">none</td> 1284 * </tr> 1285 * </tbody> 1286 * </table> 1287 * 1288 * <p> 1289 * Notes: 1290 * <ul> 1291 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1292 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1293 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1294 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1295 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1296 * {@code PRO} indicates {@link #PROTECTED} bit set, 1297 * {@code PRI} indicates {@link #PRIVATE} bit set, 1298 * {@code PAC} indicates {@link #PACKAGE} bit set, 1299 * {@code MOD} indicates {@link #MODULE} bit set, 1300 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1301 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1302 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1303 * <li>Public access comes in three kinds: 1304 * <ul> 1305 * <li>unconditional ({@code U}): the lookup assumes readability. 1306 * The lookup has {@code null} previous lookup class. 1307 * <li>one-module-reads ({@code 1R}): the module access checking is 1308 * performed with respect to the lookup class. The lookup has {@code null} 1309 * previous lookup class. 1310 * <li>two-module-reads ({@code 2R}): the module access checking is 1311 * performed with respect to the lookup class and the previous lookup class. 1312 * The lookup has a non-null previous lookup class which is in a 1313 * different module from the current lookup class. 1314 * </ul> 1315 * <li>Any attempt to reach a third module loses all access.</li> 1316 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1317 * all access modes are dropped.</li> 1318 * </ul> 1319 * 1320 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1321 * Although bytecode instructions can only refer to classes in 1322 * a related class loader, this API can search for methods in any 1323 * class, as long as a reference to its {@code Class} object is 1324 * available. Such cross-loader references are also possible with the 1325 * Core Reflection API, and are impossible to bytecode instructions 1326 * such as {@code invokestatic} or {@code getfield}. 1327 * There is a {@linkplain java.lang.SecurityManager security manager API} 1328 * to allow applications to check such cross-loader references. 1329 * These checks apply to both the {@code MethodHandles.Lookup} API 1330 * and the Core Reflection API 1331 * (as found on {@link java.lang.Class Class}). 1332 * <p> 1333 * If a security manager is present, member and class lookups are subject to 1334 * additional checks. 1335 * From one to three calls are made to the security manager. 1336 * Any of these calls can refuse access by throwing a 1337 * {@link java.lang.SecurityException SecurityException}. 1338 * Define {@code smgr} as the security manager, 1339 * {@code lookc} as the lookup class of the current lookup object, 1340 * {@code refc} as the containing class in which the member 1341 * is being sought, and {@code defc} as the class in which the 1342 * member is actually defined. 1343 * (If a class or other type is being accessed, 1344 * the {@code refc} and {@code defc} values are the class itself.) 1345 * The value {@code lookc} is defined as <em>not present</em> 1346 * if the current lookup object does not have 1347 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1348 * The calls are made according to the following rules: 1349 * <ul> 1350 * <li><b>Step 1:</b> 1351 * If {@code lookc} is not present, or if its class loader is not 1352 * the same as or an ancestor of the class loader of {@code refc}, 1353 * then {@link SecurityManager#checkPackageAccess 1354 * smgr.checkPackageAccess(refcPkg)} is called, 1355 * where {@code refcPkg} is the package of {@code refc}. 1356 * <li><b>Step 2a:</b> 1357 * If the retrieved member is not public and 1358 * {@code lookc} is not present, then 1359 * {@link SecurityManager#checkPermission smgr.checkPermission} 1360 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1361 * <li><b>Step 2b:</b> 1362 * If the retrieved class has a {@code null} class loader, 1363 * and {@code lookc} is not present, then 1364 * {@link SecurityManager#checkPermission smgr.checkPermission} 1365 * with {@code RuntimePermission("getClassLoader")} is called. 1366 * <li><b>Step 3:</b> 1367 * If the retrieved member is not public, 1368 * and if {@code lookc} is not present, 1369 * and if {@code defc} and {@code refc} are different, 1370 * then {@link SecurityManager#checkPackageAccess 1371 * smgr.checkPackageAccess(defcPkg)} is called, 1372 * where {@code defcPkg} is the package of {@code defc}. 1373 * </ul> 1374 * Security checks are performed after other access checks have passed. 1375 * Therefore, the above rules presuppose a member or class that is public, 1376 * or else that is being accessed from a lookup class that has 1377 * rights to access the member or class. 1378 * <p> 1379 * If a security manager is present and the current lookup object does not have 1380 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1381 * {@link #defineClass(byte[]) defineClass}, 1382 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1383 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1384 * defineHiddenClassWithClassData} 1385 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1386 * with {@code RuntimePermission("defineClass")}. 1387 * 1388 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1389 * A small number of Java methods have a special property called caller sensitivity. 1390 * A <em>caller-sensitive</em> method can behave differently depending on the 1391 * identity of its immediate caller. 1392 * <p> 1393 * If a method handle for a caller-sensitive method is requested, 1394 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1395 * but they take account of the lookup class in a special way. 1396 * The resulting method handle behaves as if it were called 1397 * from an instruction contained in the lookup class, 1398 * so that the caller-sensitive method detects the lookup class. 1399 * (By contrast, the invoker of the method handle is disregarded.) 1400 * Thus, in the case of caller-sensitive methods, 1401 * different lookup classes may give rise to 1402 * differently behaving method handles. 1403 * <p> 1404 * In cases where the lookup object is 1405 * {@link MethodHandles#publicLookup() publicLookup()}, 1406 * or some other lookup object without the 1407 * {@linkplain #ORIGINAL original access}, 1408 * the lookup class is disregarded. 1409 * In such cases, no caller-sensitive method handle can be created, 1410 * access is forbidden, and the lookup fails with an 1411 * {@code IllegalAccessException}. 1412 * <p style="font-size:smaller;"> 1413 * <em>Discussion:</em> 1414 * For example, the caller-sensitive method 1415 * {@link java.lang.Class#forName(String) Class.forName(x)} 1416 * can return varying classes or throw varying exceptions, 1417 * depending on the class loader of the class that calls it. 1418 * A public lookup of {@code Class.forName} will fail, because 1419 * there is no reasonable way to determine its bytecode behavior. 1420 * <p style="font-size:smaller;"> 1421 * If an application caches method handles for broad sharing, 1422 * it should use {@code publicLookup()} to create them. 1423 * If there is a lookup of {@code Class.forName}, it will fail, 1424 * and the application must take appropriate action in that case. 1425 * It may be that a later lookup, perhaps during the invocation of a 1426 * bootstrap method, can incorporate the specific identity 1427 * of the caller, making the method accessible. 1428 * <p style="font-size:smaller;"> 1429 * The function {@code MethodHandles.lookup} is caller sensitive 1430 * so that there can be a secure foundation for lookups. 1431 * Nearly all other methods in the JSR 292 API rely on lookup 1432 * objects to check access requests. 1433 */ 1434 public static final 1435 class Lookup { 1436 /** The class on behalf of whom the lookup is being performed. */ 1437 private final Class<?> lookupClass; 1438 1439 /** previous lookup class */ 1440 private final Class<?> prevLookupClass; 1441 1442 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1443 private final int allowedModes; 1444 1445 static { 1446 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1447 } 1448 1449 /** A single-bit mask representing {@code public} access, 1450 * which may contribute to the result of {@link #lookupModes lookupModes}. 1451 * The value, {@code 0x01}, happens to be the same as the value of the 1452 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1453 * <p> 1454 * A {@code Lookup} with this lookup mode performs cross-module access check 1455 * with respect to the {@linkplain #lookupClass() lookup class} and 1456 * {@linkplain #previousLookupClass() previous lookup class} if present. 1457 */ 1458 public static final int PUBLIC = Modifier.PUBLIC; 1459 1460 /** A single-bit mask representing {@code private} access, 1461 * which may contribute to the result of {@link #lookupModes lookupModes}. 1462 * The value, {@code 0x02}, happens to be the same as the value of the 1463 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1464 */ 1465 public static final int PRIVATE = Modifier.PRIVATE; 1466 1467 /** A single-bit mask representing {@code protected} access, 1468 * which may contribute to the result of {@link #lookupModes lookupModes}. 1469 * The value, {@code 0x04}, happens to be the same as the value of the 1470 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1471 */ 1472 public static final int PROTECTED = Modifier.PROTECTED; 1473 1474 /** A single-bit mask representing {@code package} access (default access), 1475 * which may contribute to the result of {@link #lookupModes lookupModes}. 1476 * The value is {@code 0x08}, which does not correspond meaningfully to 1477 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1478 */ 1479 public static final int PACKAGE = Modifier.STATIC; 1480 1481 /** A single-bit mask representing {@code module} access, 1482 * which may contribute to the result of {@link #lookupModes lookupModes}. 1483 * The value is {@code 0x10}, which does not correspond meaningfully to 1484 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1485 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1486 * with this lookup mode can access all public types in the module of the 1487 * lookup class and public types in packages exported by other modules 1488 * to the module of the lookup class. 1489 * <p> 1490 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1491 * previous lookup class} is always {@code null}. 1492 * 1493 * @since 9 1494 */ 1495 public static final int MODULE = PACKAGE << 1; 1496 1497 /** A single-bit mask representing {@code unconditional} access 1498 * which may contribute to the result of {@link #lookupModes lookupModes}. 1499 * The value is {@code 0x20}, which does not correspond meaningfully to 1500 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1501 * A {@code Lookup} with this lookup mode assumes {@linkplain 1502 * java.lang.Module#canRead(java.lang.Module) readability}. 1503 * This lookup mode can access all public members of public types 1504 * of all modules when the type is in a package that is {@link 1505 * java.lang.Module#isExported(String) exported unconditionally}. 1506 * 1507 * <p> 1508 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1509 * previous lookup class} is always {@code null}. 1510 * 1511 * @since 9 1512 * @see #publicLookup() 1513 */ 1514 public static final int UNCONDITIONAL = PACKAGE << 2; 1515 1516 /** A single-bit mask representing {@code original} access 1517 * which may contribute to the result of {@link #lookupModes lookupModes}. 1518 * The value is {@code 0x40}, which does not correspond meaningfully to 1519 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1520 * 1521 * <p> 1522 * If this lookup mode is set, the {@code Lookup} object must be 1523 * created by the original lookup class by calling 1524 * {@link MethodHandles#lookup()} method or by a bootstrap method 1525 * invoked by the VM. The {@code Lookup} object with this lookup 1526 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1527 * 1528 * @since 16 1529 */ 1530 public static final int ORIGINAL = PACKAGE << 3; 1531 1532 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1533 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1534 private static final int TRUSTED = -1; 1535 1536 /* 1537 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1538 * Adjust 0 => PACKAGE 1539 */ 1540 private static int fixmods(int mods) { 1541 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1542 if (Modifier.isPublic(mods)) 1543 mods |= UNCONDITIONAL; 1544 return (mods != 0) ? mods : PACKAGE; 1545 } 1546 1547 /** Tells which class is performing the lookup. It is this class against 1548 * which checks are performed for visibility and access permissions. 1549 * <p> 1550 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1551 * access checks are performed against both the lookup class and the previous lookup class. 1552 * <p> 1553 * The class implies a maximum level of access permission, 1554 * but the permissions may be additionally limited by the bitmask 1555 * {@link #lookupModes lookupModes}, which controls whether non-public members 1556 * can be accessed. 1557 * @return the lookup class, on behalf of which this lookup object finds members 1558 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1559 */ 1560 public Class<?> lookupClass() { 1561 return lookupClass; 1562 } 1563 1564 /** Reports a lookup class in another module that this lookup object 1565 * was previously teleported from, or {@code null}. 1566 * <p> 1567 * A {@code Lookup} object produced by the factory methods, such as the 1568 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1569 * has {@code null} previous lookup class. 1570 * A {@code Lookup} object has a non-null previous lookup class 1571 * when this lookup was teleported from an old lookup class 1572 * in one module to a new lookup class in another module. 1573 * 1574 * @return the lookup class in another module that this lookup object was 1575 * previously teleported from, or {@code null} 1576 * @since 14 1577 * @see #in(Class) 1578 * @see MethodHandles#privateLookupIn(Class, Lookup) 1579 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1580 */ 1581 public Class<?> previousLookupClass() { 1582 return prevLookupClass; 1583 } 1584 1585 // This is just for calling out to MethodHandleImpl. 1586 private Class<?> lookupClassOrNull() { 1587 return (allowedModes == TRUSTED) ? null : lookupClass; 1588 } 1589 1590 /** Tells which access-protection classes of members this lookup object can produce. 1591 * The result is a bit-mask of the bits 1592 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1593 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1594 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1595 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1596 * {@linkplain #MODULE MODULE (0x10)}, 1597 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1598 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1599 * <p> 1600 * A freshly-created lookup object 1601 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1602 * all possible bits set, except {@code UNCONDITIONAL}. 1603 * A lookup object on a new lookup class 1604 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1605 * may have some mode bits set to zero. 1606 * Mode bits can also be 1607 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1608 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1609 * The purpose of this is to restrict access via the new lookup object, 1610 * so that it can access only names which can be reached by the original 1611 * lookup object, and also by the new lookup class. 1612 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1613 * @see #in 1614 * @see #dropLookupMode 1615 */ 1616 public int lookupModes() { 1617 return allowedModes & ALL_MODES; 1618 } 1619 1620 /** Embody the current class (the lookupClass) as a lookup class 1621 * for method handle creation. 1622 * Must be called by from a method in this package, 1623 * which in turn is called by a method not in this package. 1624 */ 1625 Lookup(Class<?> lookupClass) { 1626 this(lookupClass, null, FULL_POWER_MODES); 1627 } 1628 1629 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1630 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1631 && prevLookupClass.getModule() != lookupClass.getModule()); 1632 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1633 this.lookupClass = lookupClass; 1634 this.prevLookupClass = prevLookupClass; 1635 this.allowedModes = allowedModes; 1636 } 1637 1638 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1639 // make sure we haven't accidentally picked up a privileged class: 1640 checkUnprivilegedlookupClass(lookupClass); 1641 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1642 } 1643 1644 /** 1645 * Creates a lookup on the specified new lookup class. 1646 * The resulting object will report the specified 1647 * class as its own {@link #lookupClass() lookupClass}. 1648 * 1649 * <p> 1650 * However, the resulting {@code Lookup} object is guaranteed 1651 * to have no more access capabilities than the original. 1652 * In particular, access capabilities can be lost as follows:<ul> 1653 * <li>If the new lookup class is different from the old lookup class, 1654 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1655 * <li>If the new lookup class is in a different module from the old one, 1656 * i.e. {@link #MODULE MODULE} access is lost. 1657 * <li>If the new lookup class is in a different package 1658 * than the old one, protected and default (package) members will not be accessible, 1659 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1660 * <li>If the new lookup class is not within the same package member 1661 * as the old one, private members will not be accessible, and protected members 1662 * will not be accessible by virtue of inheritance, 1663 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1664 * (Protected members may continue to be accessible because of package sharing.) 1665 * <li>If the new lookup class is not 1666 * {@linkplain #accessClass(Class) accessible} to this lookup, 1667 * then no members, not even public members, will be accessible 1668 * i.e. all access modes are lost. 1669 * <li>If the new lookup class, the old lookup class and the previous lookup class 1670 * are all in different modules i.e. teleporting to a third module, 1671 * all access modes are lost. 1672 * </ul> 1673 * <p> 1674 * The new previous lookup class is chosen as follows: 1675 * <ul> 1676 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1677 * the new previous lookup class is {@code null}. 1678 * <li>If the new lookup class is in the same module as the old lookup class, 1679 * the new previous lookup class is the old previous lookup class. 1680 * <li>If the new lookup class is in a different module from the old lookup class, 1681 * the new previous lookup class is the old lookup class. 1682 *</ul> 1683 * <p> 1684 * The resulting lookup's capabilities for loading classes 1685 * (used during {@link #findClass} invocations) 1686 * are determined by the lookup class' loader, 1687 * which may change due to this operation. 1688 * 1689 * @param requestedLookupClass the desired lookup class for the new lookup object 1690 * @return a lookup object which reports the desired lookup class, or the same object 1691 * if there is no change 1692 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1693 * @throws NullPointerException if the argument is null 1694 * 1695 * @see #accessClass(Class) 1696 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1697 */ 1698 public Lookup in(Class<?> requestedLookupClass) { 1699 Objects.requireNonNull(requestedLookupClass); 1700 if (requestedLookupClass.isPrimitive()) 1701 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1702 if (requestedLookupClass.isArray()) 1703 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1704 1705 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1706 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1707 if (requestedLookupClass == this.lookupClass) 1708 return this; // keep same capabilities 1709 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1710 Module fromModule = this.lookupClass.getModule(); 1711 Module targetModule = requestedLookupClass.getModule(); 1712 Class<?> plc = this.previousLookupClass(); 1713 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1714 assert plc == null; 1715 newModes = UNCONDITIONAL; 1716 } else if (fromModule != targetModule) { 1717 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1718 // allow hopping back and forth between fromModule and plc's module 1719 // but not the third module 1720 newModes = 0; 1721 } 1722 // drop MODULE access 1723 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1724 // teleport from this lookup class 1725 plc = this.lookupClass; 1726 } 1727 if ((newModes & PACKAGE) != 0 1728 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1729 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1730 } 1731 // Allow nestmate lookups to be created without special privilege: 1732 if ((newModes & PRIVATE) != 0 1733 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1734 newModes &= ~(PRIVATE|PROTECTED); 1735 } 1736 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1737 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1738 // The requested class it not accessible from the lookup class. 1739 // No permissions. 1740 newModes = 0; 1741 } 1742 return newLookup(requestedLookupClass, plc, newModes); 1743 } 1744 1745 /** 1746 * Creates a lookup on the same lookup class which this lookup object 1747 * finds members, but with a lookup mode that has lost the given lookup mode. 1748 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1749 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1750 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1751 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1752 * 1753 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1754 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1755 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1756 * lookup has no access. 1757 * 1758 * <p> If this lookup is not a public lookup, then the following applies 1759 * regardless of its {@linkplain #lookupModes() lookup modes}. 1760 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1761 * dropped and so the resulting lookup mode will never have these access 1762 * capabilities. When dropping {@code PACKAGE} 1763 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1764 * access. When dropping {@code MODULE} then the resulting lookup will not 1765 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1766 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1767 * 1768 * @apiNote 1769 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1770 * delegate non-public access within the package of the lookup class without 1771 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1772 * A lookup with {@code MODULE} but not 1773 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1774 * the module of the lookup class without conferring package access. 1775 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1776 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1777 * to public classes accessible to both the module of the lookup class 1778 * and the module of the previous lookup class. 1779 * 1780 * @param modeToDrop the lookup mode to drop 1781 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1782 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1783 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1784 * or {@code UNCONDITIONAL} 1785 * @see MethodHandles#privateLookupIn 1786 * @since 9 1787 */ 1788 public Lookup dropLookupMode(int modeToDrop) { 1789 int oldModes = lookupModes(); 1790 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1791 switch (modeToDrop) { 1792 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1793 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1794 case PACKAGE: newModes &= ~(PRIVATE); break; 1795 case PROTECTED: 1796 case PRIVATE: 1797 case ORIGINAL: 1798 case UNCONDITIONAL: break; 1799 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1800 } 1801 if (newModes == oldModes) return this; // return self if no change 1802 return newLookup(lookupClass(), previousLookupClass(), newModes); 1803 } 1804 1805 /** 1806 * Creates and links a class or interface from {@code bytes} 1807 * with the same class loader and in the same runtime package and 1808 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1809 * {@linkplain #lookupClass() lookup class} as if calling 1810 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1811 * ClassLoader::defineClass}. 1812 * 1813 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1814 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1815 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1816 * that the lookup object was created by a caller in the runtime package (or derived 1817 * from a lookup originally created by suitably privileged code to a target class in 1818 * the runtime package). </p> 1819 * 1820 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1821 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1822 * same package as the lookup class. </p> 1823 * 1824 * <p> This method does not run the class initializer. The class initializer may 1825 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1826 * Specification</em>. </p> 1827 * 1828 * <p> If there is a security manager and this lookup does not have {@linkplain 1829 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1830 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1831 * 1832 * @param bytes the class bytes 1833 * @return the {@code Class} object for the class 1834 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1835 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1836 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1837 * than the lookup class or {@code bytes} is not a class or interface 1838 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1839 * @throws VerifyError if the newly created class cannot be verified 1840 * @throws LinkageError if the newly created class cannot be linked for any other reason 1841 * @throws SecurityException if a security manager is present and it 1842 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1843 * @throws NullPointerException if {@code bytes} is {@code null} 1844 * @since 9 1845 * @see MethodHandles#privateLookupIn 1846 * @see Lookup#dropLookupMode 1847 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1848 */ 1849 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1850 ensureDefineClassPermission(); 1851 if ((lookupModes() & PACKAGE) == 0) 1852 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1853 return makeClassDefiner(bytes.clone()).defineClass(false); 1854 } 1855 1856 private void ensureDefineClassPermission() { 1857 if (allowedModes == TRUSTED) return; 1858 1859 if (!hasFullPrivilegeAccess()) { 1860 @SuppressWarnings("removal") 1861 SecurityManager sm = System.getSecurityManager(); 1862 if (sm != null) 1863 sm.checkPermission(new RuntimePermission("defineClass")); 1864 } 1865 } 1866 1867 /** 1868 * The set of class options that specify whether a hidden class created by 1869 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1870 * Lookup::defineHiddenClass} method is dynamically added as a new member 1871 * to the nest of a lookup class and/or whether a hidden class has 1872 * a strong relationship with the class loader marked as its defining loader. 1873 * 1874 * @since 15 1875 */ 1876 public enum ClassOption { 1877 /** 1878 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1879 * of a lookup class as a nestmate. 1880 * 1881 * <p> A hidden nestmate class has access to the private members of all 1882 * classes and interfaces in the same nest. 1883 * 1884 * @see Class#getNestHost() 1885 */ 1886 NESTMATE(NESTMATE_CLASS), 1887 1888 /** 1889 * Specifies that a hidden class has a <em>strong</em> 1890 * relationship with the class loader marked as its defining loader, 1891 * as a normal class or interface has with its own defining loader. 1892 * This means that the hidden class may be unloaded if and only if 1893 * its defining loader is not reachable and thus may be reclaimed 1894 * by a garbage collector (JLS {@jls 12.7}). 1895 * 1896 * <p> By default, a hidden class or interface may be unloaded 1897 * even if the class loader that is marked as its defining loader is 1898 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1899 1900 * 1901 * @jls 12.7 Unloading of Classes and Interfaces 1902 */ 1903 STRONG(STRONG_LOADER_LINK); 1904 1905 /* the flag value is used by VM at define class time */ 1906 private final int flag; 1907 ClassOption(int flag) { 1908 this.flag = flag; 1909 } 1910 1911 static int optionsToFlag(ClassOption[] options) { 1912 int flags = 0; 1913 for (ClassOption cp : options) { 1914 if ((flags & cp.flag) != 0) { 1915 throw new IllegalArgumentException("Duplicate ClassOption " + cp); 1916 } 1917 flags |= cp.flag; 1918 } 1919 return flags; 1920 } 1921 } 1922 1923 /** 1924 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1925 * returning a {@code Lookup} on the newly created class or interface. 1926 * 1927 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1928 * which either defines {@code C} directly or delegates to another class loader. 1929 * A class loader defines {@code C} directly by invoking 1930 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1931 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1932 * to derive {@code C} from a purported representation in {@code class} file format. 1933 * In situations where use of a class loader is undesirable, a class or interface 1934 * {@code C} can be created by this method instead. This method is capable of 1935 * defining {@code C}, and thereby creating it, without invoking 1936 * {@code ClassLoader::defineClass}. 1937 * Instead, this method defines {@code C} as if by arranging for 1938 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1939 * from a purported representation in {@code class} file format 1940 * using the following rules: 1941 * 1942 * <ol> 1943 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1944 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1945 * This level of access is needed to create {@code C} in the module 1946 * of the lookup class of this {@code Lookup}.</li> 1947 * 1948 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1949 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1950 * The major and minor version may differ from the {@code class} file version 1951 * of the lookup class of this {@code Lookup}.</li> 1952 * 1953 * <li> The value of {@code this_class} must be a valid index in the 1954 * {@code constant_pool} table, and the entry at that index must be a valid 1955 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1956 * encoded in internal form that is specified by this structure. {@code N} must 1957 * denote a class or interface in the same package as the lookup class.</li> 1958 * 1959 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1960 * where {@code <suffix>} is an unqualified name. 1961 * 1962 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1963 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1964 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1965 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1966 * refers to the new {@code CONSTANT_Utf8_info} structure. 1967 * 1968 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1969 * 1970 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1971 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1972 * with the following adjustments: 1973 * <ul> 1974 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1975 * that includes a single {@code "."} character, even though this is not a valid 1976 * binary class or interface name in internal form.</li> 1977 * 1978 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1979 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1980 * 1981 * <li> {@code C} is considered to have the same runtime 1982 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1983 * and {@linkplain java.security.ProtectionDomain protection domain} 1984 * as the lookup class of this {@code Lookup}. 1985 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1986 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1987 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1988 * <ul> 1989 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1990 * even though this is not a valid binary class or interface name.</li> 1991 * <li> {@link Class#descriptorString()} returns the string 1992 * {@code "L" + N + "." + <suffix> + ";"}, 1993 * even though this is not a valid type descriptor name.</li> 1994 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1995 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1996 * </ul> 1997 * </ul> 1998 * </li> 1999 * </ol> 2000 * 2001 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 2002 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 2003 * <ul> 2004 * <li> During verification, whenever it is necessary to load the class named 2005 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2006 * made of any class loader.</li> 2007 * 2008 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2009 * by {@code this_class}, the symbolic reference is considered to be resolved to 2010 * {@code C} and resolution always succeeds immediately.</li> 2011 * </ul> 2012 * 2013 * <p> If the {@code initialize} parameter is {@code true}, 2014 * then {@code C} is initialized by the Java Virtual Machine. 2015 * 2016 * <p> The newly created class or interface {@code C} serves as the 2017 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2018 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2019 * no other class or interface can refer to {@code C} via a constant pool entry. 2020 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2021 * a method parameter type, or a method return type by any other class. 2022 * This is because a hidden class or interface does not have a binary name, so 2023 * there is no internal form available to record in any class's constant pool. 2024 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2025 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2026 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2027 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2028 * JVM Tool Interface</a>. 2029 * 2030 * <p> A class or interface created by 2031 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2032 * a class loader} has a strong relationship with that class loader. 2033 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2034 * that {@linkplain Class#getClassLoader() defined it}. 2035 * This means that a class created by a class loader may be unloaded if and 2036 * only if its defining loader is not reachable and thus may be reclaimed 2037 * by a garbage collector (JLS {@jls 12.7}). 2038 * 2039 * By default, however, a hidden class or interface may be unloaded even if 2040 * the class loader that is marked as its defining loader is 2041 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2042 * This behavior is useful when a hidden class or interface serves multiple 2043 * classes defined by arbitrary class loaders. In other cases, a hidden 2044 * class or interface may be linked to a single class (or a small number of classes) 2045 * with the same defining loader as the hidden class or interface. 2046 * In such cases, where the hidden class or interface must be coterminous 2047 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2048 * option may be passed in {@code options}. 2049 * This arranges for a hidden class to have the same strong relationship 2050 * with the class loader marked as its defining loader, 2051 * as a normal class or interface has with its own defining loader. 2052 * 2053 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2054 * may still prevent a hidden class or interface from being 2055 * unloaded by ensuring that the {@code Class} object is reachable. 2056 * 2057 * <p> The unloading characteristics are set for each hidden class when it is 2058 * defined, and cannot be changed later. An advantage of allowing hidden classes 2059 * to be unloaded independently of the class loader marked as their defining loader 2060 * is that a very large number of hidden classes may be created by an application. 2061 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2062 * just as if normal classes were created by class loaders. 2063 * 2064 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2065 * their private members. The nest relationship is determined by 2066 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2067 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2068 * By default, a hidden class belongs to a nest consisting only of itself 2069 * because a hidden class has no binary name. 2070 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2071 * to create a hidden class or interface {@code C} as a member of a nest. 2072 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2073 * in the {@code ClassFile} structure from which {@code C} was derived. 2074 * Instead, the following rules determine the nest host of {@code C}: 2075 * <ul> 2076 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2077 * been determined, then let {@code H} be the nest host of the lookup class. 2078 * Otherwise, the nest host of the lookup class is determined using the 2079 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2080 * <li>The nest host of {@code C} is determined to be {@code H}, 2081 * the nest host of the lookup class.</li> 2082 * </ul> 2083 * 2084 * <p> A hidden class or interface may be serializable, but this requires a custom 2085 * serialization mechanism in order to ensure that instances are properly serialized 2086 * and deserialized. The default serialization mechanism supports only classes and 2087 * interfaces that are discoverable by their class name. 2088 * 2089 * @param bytes the bytes that make up the class data, 2090 * in the format of a valid {@code class} file as defined by 2091 * <cite>The Java Virtual Machine Specification</cite>. 2092 * @param initialize if {@code true} the class will be initialized. 2093 * @param options {@linkplain ClassOption class options} 2094 * @return the {@code Lookup} object on the hidden class, 2095 * with {@linkplain #ORIGINAL original} and 2096 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2097 * 2098 * @throws IllegalAccessException if this {@code Lookup} does not have 2099 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2100 * @throws SecurityException if a security manager is present and it 2101 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2102 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2103 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2104 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2105 * than the lookup class or {@code bytes} is not a class or interface 2106 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2107 * @throws IncompatibleClassChangeError if the class or interface named as 2108 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2109 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2110 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2111 * {@code C} is {@code C} itself 2112 * @throws VerifyError if the newly created class cannot be verified 2113 * @throws LinkageError if the newly created class cannot be linked for any other reason 2114 * @throws NullPointerException if any parameter is {@code null} 2115 * 2116 * @since 15 2117 * @see Class#isHidden() 2118 * @jvms 4.2.1 Binary Class and Interface Names 2119 * @jvms 4.2.2 Unqualified Names 2120 * @jvms 4.7.28 The {@code NestHost} Attribute 2121 * @jvms 4.7.29 The {@code NestMembers} Attribute 2122 * @jvms 5.4.3.1 Class and Interface Resolution 2123 * @jvms 5.4.4 Access Control 2124 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2125 * @jvms 5.4 Linking 2126 * @jvms 5.5 Initialization 2127 * @jls 12.7 Unloading of Classes and Interfaces 2128 */ 2129 @SuppressWarnings("doclint:reference") // cross-module links 2130 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2131 throws IllegalAccessException 2132 { 2133 Objects.requireNonNull(bytes); 2134 int flags = ClassOption.optionsToFlag(options); 2135 ensureDefineClassPermission(); 2136 if (!hasFullPrivilegeAccess()) { 2137 throw new IllegalAccessException(this + " does not have full privilege access"); 2138 } 2139 2140 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize); 2141 } 2142 2143 /** 2144 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2145 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2146 * returning a {@code Lookup} on the newly created class or interface. 2147 * 2148 * <p> This method is equivalent to calling 2149 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2150 * as if the hidden class is injected with a private static final <i>unnamed</i> 2151 * field which is initialized with the given {@code classData} at 2152 * the first instruction of the class initializer. 2153 * The newly created class is linked by the Java Virtual Machine. 2154 * 2155 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2156 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2157 * methods can be used to retrieve the {@code classData}. 2158 * 2159 * @apiNote 2160 * A framework can create a hidden class with class data with one or more 2161 * objects and load the class data as dynamically-computed constant(s) 2162 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2163 * Class data} is accessible only to the lookup object created by the newly 2164 * defined hidden class but inaccessible to other members in the same nest 2165 * (unlike private static fields that are accessible to nestmates). 2166 * Care should be taken w.r.t. mutability for example when passing 2167 * an array or other mutable structure through the class data. 2168 * Changing any value stored in the class data at runtime may lead to 2169 * unpredictable behavior. 2170 * If the class data is a {@code List}, it is good practice to make it 2171 * unmodifiable for example via {@link List#of List::of}. 2172 * 2173 * @param bytes the class bytes 2174 * @param classData pre-initialized class data 2175 * @param initialize if {@code true} the class will be initialized. 2176 * @param options {@linkplain ClassOption class options} 2177 * @return the {@code Lookup} object on the hidden class, 2178 * with {@linkplain #ORIGINAL original} and 2179 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2180 * 2181 * @throws IllegalAccessException if this {@code Lookup} does not have 2182 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2183 * @throws SecurityException if a security manager is present and it 2184 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2185 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2186 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2187 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2188 * than the lookup class or {@code bytes} is not a class or interface 2189 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2190 * @throws IncompatibleClassChangeError if the class or interface named as 2191 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2192 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2193 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2194 * {@code C} is {@code C} itself 2195 * @throws VerifyError if the newly created class cannot be verified 2196 * @throws LinkageError if the newly created class cannot be linked for any other reason 2197 * @throws NullPointerException if any parameter is {@code null} 2198 * 2199 * @since 16 2200 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2201 * @see Class#isHidden() 2202 * @see MethodHandles#classData(Lookup, String, Class) 2203 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2204 * @jvms 4.2.1 Binary Class and Interface Names 2205 * @jvms 4.2.2 Unqualified Names 2206 * @jvms 4.7.28 The {@code NestHost} Attribute 2207 * @jvms 4.7.29 The {@code NestMembers} Attribute 2208 * @jvms 5.4.3.1 Class and Interface Resolution 2209 * @jvms 5.4.4 Access Control 2210 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2211 * @jvms 5.4 Linking 2212 * @jvms 5.5 Initialization 2213 * @jls 12.7 Unloading of Classes and Interfaces 2214 */ 2215 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2216 throws IllegalAccessException 2217 { 2218 Objects.requireNonNull(bytes); 2219 Objects.requireNonNull(classData); 2220 2221 int flags = ClassOption.optionsToFlag(options); 2222 2223 ensureDefineClassPermission(); 2224 if (!hasFullPrivilegeAccess()) { 2225 throw new IllegalAccessException(this + " does not have full privilege access"); 2226 } 2227 2228 return makeHiddenClassDefiner(bytes.clone(), false, flags) 2229 .defineClassAsLookup(initialize, classData); 2230 } 2231 2232 // A default dumper for writing class files passed to Lookup::defineClass 2233 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2234 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2235 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2236 // 2237 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2238 // and LambdaForms and method handle internals. They are dumped via 2239 // different ClassFileDumpers. 2240 private static ClassFileDumper defaultDumper() { 2241 return DEFAULT_DUMPER; 2242 } 2243 2244 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2245 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2246 2247 /** 2248 * This method checks the class file version and the structure of `this_class`. 2249 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2250 * that is in the named package. 2251 * 2252 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2253 * or the class is not in the given package name. 2254 */ 2255 static String validateAndFindInternalName(byte[] bytes, String pkgName) { 2256 int magic = readInt(bytes, 0); 2257 if (magic != ClassFile.MAGIC_NUMBER) { 2258 throw new ClassFormatError("Incompatible magic value: " + magic); 2259 } 2260 // We have to read major and minor this way as ClassFile API throws IAE 2261 // yet we want distinct ClassFormatError and UnsupportedClassVersionError 2262 int minor = readUnsignedShort(bytes, 4); 2263 int major = readUnsignedShort(bytes, 6); 2264 2265 if (!VM.isSupportedClassFileVersion(major, minor)) { 2266 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2267 } 2268 2269 String name; 2270 ClassDesc sym; 2271 int accessFlags; 2272 try { 2273 ClassModel cm = ClassFile.of().parse(bytes); 2274 var thisClass = cm.thisClass(); 2275 name = thisClass.asInternalName(); 2276 sym = thisClass.asSymbol(); 2277 accessFlags = cm.flags().flagsMask(); 2278 } catch (IllegalArgumentException e) { 2279 ClassFormatError cfe = new ClassFormatError(); 2280 cfe.initCause(e); 2281 throw cfe; 2282 } 2283 // must be a class or interface 2284 if ((accessFlags & ACC_MODULE) != 0) { 2285 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2286 } 2287 2288 String pn = sym.packageName(); 2289 if (!pn.equals(pkgName)) { 2290 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2291 } 2292 2293 return name; 2294 } 2295 2296 private static int readInt(byte[] bytes, int offset) { 2297 if ((offset + 4) > bytes.length) { 2298 throw new ClassFormatError("Invalid ClassFile structure"); 2299 } 2300 return ((bytes[offset] & 0xFF) << 24) 2301 | ((bytes[offset + 1] & 0xFF) << 16) 2302 | ((bytes[offset + 2] & 0xFF) << 8) 2303 | (bytes[offset + 3] & 0xFF); 2304 } 2305 2306 private static int readUnsignedShort(byte[] bytes, int offset) { 2307 if ((offset+2) > bytes.length) { 2308 throw new ClassFormatError("Invalid ClassFile structure"); 2309 } 2310 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2311 } 2312 2313 /* 2314 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2315 * from the given bytes. 2316 * 2317 * Caller should make a defensive copy of the arguments if needed 2318 * before calling this factory method. 2319 * 2320 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2321 * {@code bytes} denotes a class in a different package than the lookup class 2322 */ 2323 private ClassDefiner makeClassDefiner(byte[] bytes) { 2324 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2325 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper()); 2326 } 2327 2328 /** 2329 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2330 * from the given bytes. No package name check on the given bytes. 2331 * 2332 * @param internalName internal name 2333 * @param bytes class bytes 2334 * @param dumper dumper to write the given bytes to the dumper's output directory 2335 * @return ClassDefiner that defines a normal class of the given bytes. 2336 */ 2337 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2338 // skip package name validation 2339 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper); 2340 } 2341 2342 /** 2343 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2344 * from the given bytes. The name must be in the same package as the lookup class. 2345 * 2346 * Caller should make a defensive copy of the arguments if needed 2347 * before calling this factory method. 2348 * 2349 * @param bytes class bytes 2350 * @param dumper dumper to write the given bytes to the dumper's output directory 2351 * @return ClassDefiner that defines a hidden class of the given bytes. 2352 * 2353 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2354 * {@code bytes} denotes a class in a different package than the lookup class 2355 */ 2356 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2357 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2358 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2359 } 2360 2361 /** 2362 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2363 * from the given bytes and options. 2364 * The name must be in the same package as the lookup class. 2365 * 2366 * Caller should make a defensive copy of the arguments if needed 2367 * before calling this factory method. 2368 * 2369 * @param bytes class bytes 2370 * @param flags class option flag mask 2371 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2372 * @return ClassDefiner that defines a hidden class of the given bytes and options 2373 * 2374 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2375 * {@code bytes} denotes a class in a different package than the lookup class 2376 */ 2377 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2378 boolean accessVmAnnotations, 2379 int flags) { 2380 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2381 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags); 2382 } 2383 2384 /** 2385 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2386 * from the given bytes and the given options. No package name check on the given bytes. 2387 * 2388 * @param internalName internal name that specifies the prefix of the hidden class 2389 * @param bytes class bytes 2390 * @param dumper dumper to write the given bytes to the dumper's output directory 2391 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2392 */ 2393 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2394 Objects.requireNonNull(dumper); 2395 // skip name and access flags validation 2396 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2397 } 2398 2399 /** 2400 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2401 * from the given bytes and the given options. No package name check on the given bytes. 2402 * 2403 * @param internalName internal name that specifies the prefix of the hidden class 2404 * @param bytes class bytes 2405 * @param flags class options flag mask 2406 * @param dumper dumper to write the given bytes to the dumper's output directory 2407 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2408 */ 2409 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) { 2410 Objects.requireNonNull(dumper); 2411 // skip name and access flags validation 2412 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags); 2413 } 2414 2415 /** 2416 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2417 * from the given class file and options. 2418 * 2419 * @param internalName internal name 2420 * @param bytes Class byte array 2421 * @param flags class option flag mask 2422 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2423 * @param dumper dumper to write the given bytes to the dumper's output directory 2424 */ 2425 private ClassDefiner makeHiddenClassDefiner(String internalName, 2426 byte[] bytes, 2427 boolean accessVmAnnotations, 2428 ClassFileDumper dumper, 2429 int flags) { 2430 flags |= HIDDEN_CLASS; 2431 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2432 // jdk.internal.vm.annotations are permitted for classes 2433 // defined to boot loader and platform loader 2434 flags |= ACCESS_VM_ANNOTATIONS; 2435 } 2436 2437 return new ClassDefiner(this, internalName, bytes, flags, dumper); 2438 } 2439 2440 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) { 2441 ClassDefiner { 2442 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2443 } 2444 2445 Class<?> defineClass(boolean initialize) { 2446 return defineClass(initialize, null); 2447 } 2448 2449 Lookup defineClassAsLookup(boolean initialize) { 2450 Class<?> c = defineClass(initialize, null); 2451 return new Lookup(c, null, FULL_POWER_MODES); 2452 } 2453 2454 /** 2455 * Defines the class of the given bytes and the given classData. 2456 * If {@code initialize} parameter is true, then the class will be initialized. 2457 * 2458 * @param initialize true if the class to be initialized 2459 * @param classData classData or null 2460 * @return the class 2461 * 2462 * @throws LinkageError linkage error 2463 */ 2464 Class<?> defineClass(boolean initialize, Object classData) { 2465 Class<?> lookupClass = lookup.lookupClass(); 2466 ClassLoader loader = lookupClass.getClassLoader(); 2467 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2468 Class<?> c = null; 2469 try { 2470 c = SharedSecrets.getJavaLangAccess() 2471 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData); 2472 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2473 return c; 2474 } finally { 2475 // dump the classfile for debugging 2476 if (dumper.isEnabled()) { 2477 String name = internalName(); 2478 if (c != null) { 2479 dumper.dumpClass(name, c, bytes); 2480 } else { 2481 dumper.dumpFailedClass(name, bytes); 2482 } 2483 } 2484 } 2485 } 2486 2487 /** 2488 * Defines the class of the given bytes and the given classData. 2489 * If {@code initialize} parameter is true, then the class will be initialized. 2490 * 2491 * @param initialize true if the class to be initialized 2492 * @param classData classData or null 2493 * @return a Lookup for the defined class 2494 * 2495 * @throws LinkageError linkage error 2496 */ 2497 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2498 Class<?> c = defineClass(initialize, classData); 2499 return new Lookup(c, null, FULL_POWER_MODES); 2500 } 2501 2502 private boolean isNestmate() { 2503 return (classFlags & NESTMATE_CLASS) != 0; 2504 } 2505 } 2506 2507 private ProtectionDomain lookupClassProtectionDomain() { 2508 ProtectionDomain pd = cachedProtectionDomain; 2509 if (pd == null) { 2510 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2511 } 2512 return pd; 2513 } 2514 2515 // cached protection domain 2516 private volatile ProtectionDomain cachedProtectionDomain; 2517 2518 // Make sure outer class is initialized first. 2519 static { IMPL_NAMES.getClass(); } 2520 2521 /** Package-private version of lookup which is trusted. */ 2522 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2523 2524 /** Version of lookup which is trusted minimally. 2525 * It can only be used to create method handles to publicly accessible 2526 * members in packages that are exported unconditionally. 2527 */ 2528 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2529 2530 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2531 String name = lookupClass.getName(); 2532 if (name.startsWith("java.lang.invoke.")) 2533 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2534 } 2535 2536 /** 2537 * Displays the name of the class from which lookups are to be made, 2538 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2539 * previous lookup class} if present. 2540 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2541 * If there are restrictions on the access permitted to this lookup, 2542 * this is indicated by adding a suffix to the class name, consisting 2543 * of a slash and a keyword. The keyword represents the strongest 2544 * allowed access, and is chosen as follows: 2545 * <ul> 2546 * <li>If no access is allowed, the suffix is "/noaccess". 2547 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2548 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2549 * <li>If only public and module access are allowed, the suffix is "/module". 2550 * <li>If public and package access are allowed, the suffix is "/package". 2551 * <li>If public, package, and private access are allowed, the suffix is "/private". 2552 * </ul> 2553 * If none of the above cases apply, it is the case that 2554 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2555 * (public, module, package, private, and protected) is allowed. 2556 * In this case, no suffix is added. 2557 * This is true only of an object obtained originally from 2558 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2559 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2560 * always have restricted access, and will display a suffix. 2561 * <p> 2562 * (It may seem strange that protected access should be 2563 * stronger than private access. Viewed independently from 2564 * package access, protected access is the first to be lost, 2565 * because it requires a direct subclass relationship between 2566 * caller and callee.) 2567 * @see #in 2568 */ 2569 @Override 2570 public String toString() { 2571 String cname = lookupClass.getName(); 2572 if (prevLookupClass != null) 2573 cname += "/" + prevLookupClass.getName(); 2574 switch (allowedModes) { 2575 case 0: // no privileges 2576 return cname + "/noaccess"; 2577 case UNCONDITIONAL: 2578 return cname + "/publicLookup"; 2579 case PUBLIC: 2580 return cname + "/public"; 2581 case PUBLIC|MODULE: 2582 return cname + "/module"; 2583 case PUBLIC|PACKAGE: 2584 case PUBLIC|MODULE|PACKAGE: 2585 return cname + "/package"; 2586 case PUBLIC|PACKAGE|PRIVATE: 2587 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2588 return cname + "/private"; 2589 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2590 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2591 case FULL_POWER_MODES: 2592 return cname; 2593 case TRUSTED: 2594 return "/trusted"; // internal only; not exported 2595 default: // Should not happen, but it's a bitfield... 2596 cname = cname + "/" + Integer.toHexString(allowedModes); 2597 assert(false) : cname; 2598 return cname; 2599 } 2600 } 2601 2602 /** 2603 * Produces a method handle for a static method. 2604 * The type of the method handle will be that of the method. 2605 * (Since static methods do not take receivers, there is no 2606 * additional receiver argument inserted into the method handle type, 2607 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2608 * The method and all its argument types must be accessible to the lookup object. 2609 * <p> 2610 * The returned method handle will have 2611 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2612 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2613 * <p> 2614 * If the returned method handle is invoked, the method's class will 2615 * be initialized, if it has not already been initialized. 2616 * <p><b>Example:</b> 2617 * {@snippet lang="java" : 2618 import static java.lang.invoke.MethodHandles.*; 2619 import static java.lang.invoke.MethodType.*; 2620 ... 2621 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2622 "asList", methodType(List.class, Object[].class)); 2623 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2624 * } 2625 * @param refc the class from which the method is accessed 2626 * @param name the name of the method 2627 * @param type the type of the method 2628 * @return the desired method handle 2629 * @throws NoSuchMethodException if the method does not exist 2630 * @throws IllegalAccessException if access checking fails, 2631 * or if the method is not {@code static}, 2632 * or if the method's variable arity modifier bit 2633 * is set and {@code asVarargsCollector} fails 2634 * @throws SecurityException if a security manager is present and it 2635 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2636 * @throws NullPointerException if any argument is null 2637 */ 2638 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2639 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2640 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2641 } 2642 2643 /** 2644 * Produces a method handle for a virtual method. 2645 * The type of the method handle will be that of the method, 2646 * with the receiver type (usually {@code refc}) prepended. 2647 * The method and all its argument types must be accessible to the lookup object. 2648 * <p> 2649 * When called, the handle will treat the first argument as a receiver 2650 * and, for non-private methods, dispatch on the receiver's type to determine which method 2651 * implementation to enter. 2652 * For private methods the named method in {@code refc} will be invoked on the receiver. 2653 * (The dispatching action is identical with that performed by an 2654 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2655 * <p> 2656 * The first argument will be of type {@code refc} if the lookup 2657 * class has full privileges to access the member. Otherwise 2658 * the member must be {@code protected} and the first argument 2659 * will be restricted in type to the lookup class. 2660 * <p> 2661 * The returned method handle will have 2662 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2663 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2664 * <p> 2665 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2666 * instructions and method handles produced by {@code findVirtual}, 2667 * if the class is {@code MethodHandle} and the name string is 2668 * {@code invokeExact} or {@code invoke}, the resulting 2669 * method handle is equivalent to one produced by 2670 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2671 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2672 * with the same {@code type} argument. 2673 * <p> 2674 * If the class is {@code VarHandle} and the name string corresponds to 2675 * the name of a signature-polymorphic access mode method, the resulting 2676 * method handle is equivalent to one produced by 2677 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2678 * the access mode corresponding to the name string and with the same 2679 * {@code type} arguments. 2680 * <p> 2681 * <b>Example:</b> 2682 * {@snippet lang="java" : 2683 import static java.lang.invoke.MethodHandles.*; 2684 import static java.lang.invoke.MethodType.*; 2685 ... 2686 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2687 "concat", methodType(String.class, String.class)); 2688 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2689 "hashCode", methodType(int.class)); 2690 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2691 "hashCode", methodType(int.class)); 2692 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2693 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2694 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2695 // interface method: 2696 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2697 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2698 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2699 // constructor "internal method" must be accessed differently: 2700 MethodType MT_newString = methodType(void.class); //()V for new String() 2701 try { assertEquals("impossible", lookup() 2702 .findVirtual(String.class, "<init>", MT_newString)); 2703 } catch (NoSuchMethodException ex) { } // OK 2704 MethodHandle MH_newString = publicLookup() 2705 .findConstructor(String.class, MT_newString); 2706 assertEquals("", (String) MH_newString.invokeExact()); 2707 * } 2708 * 2709 * @param refc the class or interface from which the method is accessed 2710 * @param name the name of the method 2711 * @param type the type of the method, with the receiver argument omitted 2712 * @return the desired method handle 2713 * @throws NoSuchMethodException if the method does not exist 2714 * @throws IllegalAccessException if access checking fails, 2715 * or if the method is {@code static}, 2716 * or if the method's variable arity modifier bit 2717 * is set and {@code asVarargsCollector} fails 2718 * @throws SecurityException if a security manager is present and it 2719 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2720 * @throws NullPointerException if any argument is null 2721 */ 2722 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2723 if (refc == MethodHandle.class) { 2724 MethodHandle mh = findVirtualForMH(name, type); 2725 if (mh != null) return mh; 2726 } else if (refc == VarHandle.class) { 2727 MethodHandle mh = findVirtualForVH(name, type); 2728 if (mh != null) return mh; 2729 } 2730 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2731 MemberName method = resolveOrFail(refKind, refc, name, type); 2732 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2733 } 2734 private MethodHandle findVirtualForMH(String name, MethodType type) { 2735 // these names require special lookups because of the implicit MethodType argument 2736 if ("invoke".equals(name)) 2737 return invoker(type); 2738 if ("invokeExact".equals(name)) 2739 return exactInvoker(type); 2740 assert(!MemberName.isMethodHandleInvokeName(name)); 2741 return null; 2742 } 2743 private MethodHandle findVirtualForVH(String name, MethodType type) { 2744 try { 2745 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2746 } catch (IllegalArgumentException e) { 2747 return null; 2748 } 2749 } 2750 2751 /** 2752 * Produces a method handle which creates an object and initializes it, using 2753 * the constructor of the specified type. 2754 * The parameter types of the method handle will be those of the constructor, 2755 * while the return type will be a reference to the constructor's class. 2756 * The constructor and all its argument types must be accessible to the lookup object. 2757 * <p> 2758 * The requested type must have a return type of {@code void}. 2759 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2760 * <p> 2761 * The returned method handle will have 2762 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2763 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2764 * <p> 2765 * If the returned method handle is invoked, the constructor's class will 2766 * be initialized, if it has not already been initialized. 2767 * <p><b>Example:</b> 2768 * {@snippet lang="java" : 2769 import static java.lang.invoke.MethodHandles.*; 2770 import static java.lang.invoke.MethodType.*; 2771 ... 2772 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2773 ArrayList.class, methodType(void.class, Collection.class)); 2774 Collection orig = Arrays.asList("x", "y"); 2775 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2776 assert(orig != copy); 2777 assertEquals(orig, copy); 2778 // a variable-arity constructor: 2779 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2780 ProcessBuilder.class, methodType(void.class, String[].class)); 2781 ProcessBuilder pb = (ProcessBuilder) 2782 MH_newProcessBuilder.invoke("x", "y", "z"); 2783 assertEquals("[x, y, z]", pb.command().toString()); 2784 * } 2785 * @param refc the class or interface from which the method is accessed 2786 * @param type the type of the method, with the receiver argument omitted, and a void return type 2787 * @return the desired method handle 2788 * @throws NoSuchMethodException if the constructor does not exist 2789 * @throws IllegalAccessException if access checking fails 2790 * or if the method's variable arity modifier bit 2791 * is set and {@code asVarargsCollector} fails 2792 * @throws SecurityException if a security manager is present and it 2793 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2794 * @throws NullPointerException if any argument is null 2795 */ 2796 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2797 if (refc.isArray()) { 2798 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2799 } 2800 String name = ConstantDescs.INIT_NAME; 2801 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2802 return getDirectConstructor(refc, ctor); 2803 } 2804 2805 /** 2806 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2807 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2808 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2809 * and then determines whether the class is accessible to this lookup object. 2810 * <p> 2811 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2812 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2813 * of {@code '['} and followed by the element type as encoded in the 2814 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2815 * <p> 2816 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2817 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2818 * 2819 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2820 * or the string representing an array class 2821 * @return the requested class. 2822 * @throws SecurityException if a security manager is present and it 2823 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2824 * @throws LinkageError if the linkage fails 2825 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2826 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2827 * modes. 2828 * @throws NullPointerException if {@code targetName} is null 2829 * @since 9 2830 * @jvms 5.4.3.1 Class and Interface Resolution 2831 */ 2832 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2833 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2834 return accessClass(targetClass); 2835 } 2836 2837 /** 2838 * Ensures that {@code targetClass} has been initialized. The class 2839 * to be initialized must be {@linkplain #accessClass accessible} 2840 * to this {@code Lookup} object. This method causes {@code targetClass} 2841 * to be initialized if it has not been already initialized, 2842 * as specified in JVMS {@jvms 5.5}. 2843 * 2844 * <p> 2845 * This method returns when {@code targetClass} is fully initialized, or 2846 * when {@code targetClass} is being initialized by the current thread. 2847 * 2848 * @param <T> the type of the class to be initialized 2849 * @param targetClass the class to be initialized 2850 * @return {@code targetClass} that has been initialized, or that is being 2851 * initialized by the current thread. 2852 * 2853 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2854 * or array class 2855 * @throws IllegalAccessException if {@code targetClass} is not 2856 * {@linkplain #accessClass accessible} to this lookup 2857 * @throws ExceptionInInitializerError if the class initialization provoked 2858 * by this method fails 2859 * @throws SecurityException if a security manager is present and it 2860 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2861 * @since 15 2862 * @jvms 5.5 Initialization 2863 */ 2864 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2865 if (targetClass.isPrimitive()) 2866 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2867 if (targetClass.isArray()) 2868 throw new IllegalArgumentException(targetClass + " is an array class"); 2869 2870 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2871 throw makeAccessException(targetClass); 2872 } 2873 checkSecurityManager(targetClass); 2874 2875 // ensure class initialization 2876 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2877 return targetClass; 2878 } 2879 2880 /* 2881 * Returns IllegalAccessException due to access violation to the given targetClass. 2882 * 2883 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2884 * which verifies access to a class rather a member. 2885 */ 2886 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2887 String message = "access violation: "+ targetClass; 2888 if (this == MethodHandles.publicLookup()) { 2889 message += ", from public Lookup"; 2890 } else { 2891 Module m = lookupClass().getModule(); 2892 message += ", from " + lookupClass() + " (" + m + ")"; 2893 if (prevLookupClass != null) { 2894 message += ", previous lookup " + 2895 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2896 } 2897 } 2898 return new IllegalAccessException(message); 2899 } 2900 2901 /** 2902 * Determines if a class can be accessed from the lookup context defined by 2903 * this {@code Lookup} object. The static initializer of the class is not run. 2904 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2905 * if the element type of the array class is accessible. Otherwise, 2906 * {@code targetClass} is determined as accessible as follows. 2907 * 2908 * <p> 2909 * If {@code targetClass} is in the same module as the lookup class, 2910 * the lookup class is {@code LC} in module {@code M1} and 2911 * the previous lookup class is in module {@code M0} or 2912 * {@code null} if not present, 2913 * {@code targetClass} is accessible if and only if one of the following is true: 2914 * <ul> 2915 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2916 * {@code LC} or other class in the same nest of {@code LC}.</li> 2917 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2918 * in the same runtime package of {@code LC}.</li> 2919 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2920 * a public type in {@code M1}.</li> 2921 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2922 * a public type in a package exported by {@code M1} to at least {@code M0} 2923 * if the previous lookup class is present; otherwise, {@code targetClass} 2924 * is a public type in a package exported by {@code M1} unconditionally.</li> 2925 * </ul> 2926 * 2927 * <p> 2928 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2929 * can access public types in all modules when the type is in a package 2930 * that is exported unconditionally. 2931 * <p> 2932 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2933 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2934 * is inaccessible. 2935 * <p> 2936 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2937 * {@code M1} is the module containing {@code lookupClass} and 2938 * {@code M2} is the module containing {@code targetClass}, 2939 * then {@code targetClass} is accessible if and only if 2940 * <ul> 2941 * <li>{@code M1} reads {@code M2}, and 2942 * <li>{@code targetClass} is public and in a package exported by 2943 * {@code M2} at least to {@code M1}. 2944 * </ul> 2945 * <p> 2946 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2947 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2948 * containing the previous lookup class, then {@code targetClass} is accessible 2949 * if and only if one of the following is true: 2950 * <ul> 2951 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2952 * {@linkplain Module#reads reads} {@code M0} and the type is 2953 * in a package that is exported to at least {@code M1}. 2954 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2955 * {@linkplain Module#reads reads} {@code M1} and the type is 2956 * in a package that is exported to at least {@code M0}. 2957 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2958 * and {@code M1} reads {@code M2} and the type is in a package 2959 * that is exported to at least both {@code M0} and {@code M2}. 2960 * </ul> 2961 * <p> 2962 * Otherwise, {@code targetClass} is not accessible. 2963 * 2964 * @param <T> the type of the class to be access-checked 2965 * @param targetClass the class to be access-checked 2966 * @return {@code targetClass} that has been access-checked 2967 * @throws IllegalAccessException if the class is not accessible from the lookup class 2968 * and previous lookup class, if present, using the allowed access modes. 2969 * @throws SecurityException if a security manager is present and it 2970 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2971 * @throws NullPointerException if {@code targetClass} is {@code null} 2972 * @since 9 2973 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2974 */ 2975 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2976 if (!isClassAccessible(targetClass)) { 2977 throw makeAccessException(targetClass); 2978 } 2979 checkSecurityManager(targetClass); 2980 return targetClass; 2981 } 2982 2983 /** 2984 * Produces an early-bound method handle for a virtual method. 2985 * It will bypass checks for overriding methods on the receiver, 2986 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2987 * instruction from within the explicitly specified {@code specialCaller}. 2988 * The type of the method handle will be that of the method, 2989 * with a suitably restricted receiver type prepended. 2990 * (The receiver type will be {@code specialCaller} or a subtype.) 2991 * The method and all its argument types must be accessible 2992 * to the lookup object. 2993 * <p> 2994 * Before method resolution, 2995 * if the explicitly specified caller class is not identical with the 2996 * lookup class, or if this lookup object does not have 2997 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2998 * privileges, the access fails. 2999 * <p> 3000 * The returned method handle will have 3001 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3002 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3003 * <p style="font-size:smaller;"> 3004 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 3005 * are not visible to this API, 3006 * even though the {@code invokespecial} instruction can refer to them 3007 * in special circumstances. Use {@link #findConstructor findConstructor} 3008 * to access instance initialization methods in a safe manner.)</em> 3009 * <p><b>Example:</b> 3010 * {@snippet lang="java" : 3011 import static java.lang.invoke.MethodHandles.*; 3012 import static java.lang.invoke.MethodType.*; 3013 ... 3014 static class Listie extends ArrayList { 3015 public String toString() { return "[wee Listie]"; } 3016 static Lookup lookup() { return MethodHandles.lookup(); } 3017 } 3018 ... 3019 // no access to constructor via invokeSpecial: 3020 MethodHandle MH_newListie = Listie.lookup() 3021 .findConstructor(Listie.class, methodType(void.class)); 3022 Listie l = (Listie) MH_newListie.invokeExact(); 3023 try { assertEquals("impossible", Listie.lookup().findSpecial( 3024 Listie.class, "<init>", methodType(void.class), Listie.class)); 3025 } catch (NoSuchMethodException ex) { } // OK 3026 // access to super and self methods via invokeSpecial: 3027 MethodHandle MH_super = Listie.lookup().findSpecial( 3028 ArrayList.class, "toString" , methodType(String.class), Listie.class); 3029 MethodHandle MH_this = Listie.lookup().findSpecial( 3030 Listie.class, "toString" , methodType(String.class), Listie.class); 3031 MethodHandle MH_duper = Listie.lookup().findSpecial( 3032 Object.class, "toString" , methodType(String.class), Listie.class); 3033 assertEquals("[]", (String) MH_super.invokeExact(l)); 3034 assertEquals(""+l, (String) MH_this.invokeExact(l)); 3035 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 3036 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 3037 String.class, "toString", methodType(String.class), Listie.class)); 3038 } catch (IllegalAccessException ex) { } // OK 3039 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 3040 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 3041 * } 3042 * 3043 * @param refc the class or interface from which the method is accessed 3044 * @param name the name of the method (which must not be "<init>") 3045 * @param type the type of the method, with the receiver argument omitted 3046 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 3047 * @return the desired method handle 3048 * @throws NoSuchMethodException if the method does not exist 3049 * @throws IllegalAccessException if access checking fails, 3050 * or if the method is {@code static}, 3051 * or if the method's variable arity modifier bit 3052 * is set and {@code asVarargsCollector} fails 3053 * @throws SecurityException if a security manager is present and it 3054 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3055 * @throws NullPointerException if any argument is null 3056 */ 3057 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3058 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3059 checkSpecialCaller(specialCaller, refc); 3060 Lookup specialLookup = this.in(specialCaller); 3061 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3062 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3063 } 3064 3065 /** 3066 * Produces a method handle giving read access to a non-static field. 3067 * The type of the method handle will have a return type of the field's 3068 * value type. 3069 * The method handle's single argument will be the instance containing 3070 * the field. 3071 * Access checking is performed immediately on behalf of the lookup class. 3072 * @param refc the class or interface from which the method is accessed 3073 * @param name the field's name 3074 * @param type the field's type 3075 * @return a method handle which can load values from the field 3076 * @throws NoSuchFieldException if the field does not exist 3077 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3078 * @throws SecurityException if a security manager is present and it 3079 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3080 * @throws NullPointerException if any argument is null 3081 * @see #findVarHandle(Class, String, Class) 3082 */ 3083 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3084 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3085 return getDirectField(REF_getField, refc, field); 3086 } 3087 3088 /** 3089 * Produces a method handle giving write access to a non-static field. 3090 * The type of the method handle will have a void return type. 3091 * The method handle will take two arguments, the instance containing 3092 * the field, and the value to be stored. 3093 * The second argument will be of the field's value type. 3094 * Access checking is performed immediately on behalf of the lookup class. 3095 * @param refc the class or interface from which the method is accessed 3096 * @param name the field's name 3097 * @param type the field's type 3098 * @return a method handle which can store values into the field 3099 * @throws NoSuchFieldException if the field does not exist 3100 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3101 * or {@code final} 3102 * @throws SecurityException if a security manager is present and it 3103 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3104 * @throws NullPointerException if any argument is null 3105 * @see #findVarHandle(Class, String, Class) 3106 */ 3107 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3108 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3109 return getDirectField(REF_putField, refc, field); 3110 } 3111 3112 /** 3113 * Produces a VarHandle giving access to a non-static field {@code name} 3114 * of type {@code type} declared in a class of type {@code recv}. 3115 * The VarHandle's variable type is {@code type} and it has one 3116 * coordinate type, {@code recv}. 3117 * <p> 3118 * Access checking is performed immediately on behalf of the lookup 3119 * class. 3120 * <p> 3121 * Certain access modes of the returned VarHandle are unsupported under 3122 * the following conditions: 3123 * <ul> 3124 * <li>if the field is declared {@code final}, then the write, atomic 3125 * update, numeric atomic update, and bitwise atomic update access 3126 * modes are unsupported. 3127 * <li>if the field type is anything other than {@code byte}, 3128 * {@code short}, {@code char}, {@code int}, {@code long}, 3129 * {@code float}, or {@code double} then numeric atomic update 3130 * access modes are unsupported. 3131 * <li>if the field type is anything other than {@code boolean}, 3132 * {@code byte}, {@code short}, {@code char}, {@code int} or 3133 * {@code long} then bitwise atomic update access modes are 3134 * unsupported. 3135 * </ul> 3136 * <p> 3137 * If the field is declared {@code volatile} then the returned VarHandle 3138 * will override access to the field (effectively ignore the 3139 * {@code volatile} declaration) in accordance to its specified 3140 * access modes. 3141 * <p> 3142 * If the field type is {@code float} or {@code double} then numeric 3143 * and atomic update access modes compare values using their bitwise 3144 * representation (see {@link Float#floatToRawIntBits} and 3145 * {@link Double#doubleToRawLongBits}, respectively). 3146 * @apiNote 3147 * Bitwise comparison of {@code float} values or {@code double} values, 3148 * as performed by the numeric and atomic update access modes, differ 3149 * from the primitive {@code ==} operator and the {@link Float#equals} 3150 * and {@link Double#equals} methods, specifically with respect to 3151 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3152 * Care should be taken when performing a compare and set or a compare 3153 * and exchange operation with such values since the operation may 3154 * unexpectedly fail. 3155 * There are many possible NaN values that are considered to be 3156 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3157 * provided by Java can distinguish between them. Operation failure can 3158 * occur if the expected or witness value is a NaN value and it is 3159 * transformed (perhaps in a platform specific manner) into another NaN 3160 * value, and thus has a different bitwise representation (see 3161 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3162 * details). 3163 * The values {@code -0.0} and {@code +0.0} have different bitwise 3164 * representations but are considered equal when using the primitive 3165 * {@code ==} operator. Operation failure can occur if, for example, a 3166 * numeric algorithm computes an expected value to be say {@code -0.0} 3167 * and previously computed the witness value to be say {@code +0.0}. 3168 * @param recv the receiver class, of type {@code R}, that declares the 3169 * non-static field 3170 * @param name the field's name 3171 * @param type the field's type, of type {@code T} 3172 * @return a VarHandle giving access to non-static fields. 3173 * @throws NoSuchFieldException if the field does not exist 3174 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3175 * @throws SecurityException if a security manager is present and it 3176 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3177 * @throws NullPointerException if any argument is null 3178 * @since 9 3179 */ 3180 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3181 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3182 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3183 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3184 } 3185 3186 /** 3187 * Produces a method handle giving read access to a static field. 3188 * The type of the method handle will have a return type of the field's 3189 * value type. 3190 * The method handle will take no arguments. 3191 * Access checking is performed immediately on behalf of the lookup class. 3192 * <p> 3193 * If the returned method handle is invoked, the field's class will 3194 * be initialized, if it has not already been initialized. 3195 * @param refc the class or interface from which the method is accessed 3196 * @param name the field's name 3197 * @param type the field's type 3198 * @return a method handle which can load values from the field 3199 * @throws NoSuchFieldException if the field does not exist 3200 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3201 * @throws SecurityException if a security manager is present and it 3202 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3203 * @throws NullPointerException if any argument is null 3204 */ 3205 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3206 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3207 return getDirectField(REF_getStatic, refc, field); 3208 } 3209 3210 /** 3211 * Produces a method handle giving write access to a static field. 3212 * The type of the method handle will have a void return type. 3213 * The method handle will take a single 3214 * argument, of the field's value type, the value to be stored. 3215 * Access checking is performed immediately on behalf of the lookup class. 3216 * <p> 3217 * If the returned method handle is invoked, the field's class will 3218 * be initialized, if it has not already been initialized. 3219 * @param refc the class or interface from which the method is accessed 3220 * @param name the field's name 3221 * @param type the field's type 3222 * @return a method handle which can store values into the field 3223 * @throws NoSuchFieldException if the field does not exist 3224 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3225 * or is {@code final} 3226 * @throws SecurityException if a security manager is present and it 3227 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3228 * @throws NullPointerException if any argument is null 3229 */ 3230 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3231 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3232 return getDirectField(REF_putStatic, refc, field); 3233 } 3234 3235 /** 3236 * Produces a VarHandle giving access to a static field {@code name} of 3237 * type {@code type} declared in a class of type {@code decl}. 3238 * The VarHandle's variable type is {@code type} and it has no 3239 * coordinate types. 3240 * <p> 3241 * Access checking is performed immediately on behalf of the lookup 3242 * class. 3243 * <p> 3244 * If the returned VarHandle is operated on, the declaring class will be 3245 * initialized, if it has not already been initialized. 3246 * <p> 3247 * Certain access modes of the returned VarHandle are unsupported under 3248 * the following conditions: 3249 * <ul> 3250 * <li>if the field is declared {@code final}, then the write, atomic 3251 * update, numeric atomic update, and bitwise atomic update access 3252 * modes are unsupported. 3253 * <li>if the field type is anything other than {@code byte}, 3254 * {@code short}, {@code char}, {@code int}, {@code long}, 3255 * {@code float}, or {@code double}, then numeric atomic update 3256 * access modes are unsupported. 3257 * <li>if the field type is anything other than {@code boolean}, 3258 * {@code byte}, {@code short}, {@code char}, {@code int} or 3259 * {@code long} then bitwise atomic update access modes are 3260 * unsupported. 3261 * </ul> 3262 * <p> 3263 * If the field is declared {@code volatile} then the returned VarHandle 3264 * will override access to the field (effectively ignore the 3265 * {@code volatile} declaration) in accordance to its specified 3266 * access modes. 3267 * <p> 3268 * If the field type is {@code float} or {@code double} then numeric 3269 * and atomic update access modes compare values using their bitwise 3270 * representation (see {@link Float#floatToRawIntBits} and 3271 * {@link Double#doubleToRawLongBits}, respectively). 3272 * @apiNote 3273 * Bitwise comparison of {@code float} values or {@code double} values, 3274 * as performed by the numeric and atomic update access modes, differ 3275 * from the primitive {@code ==} operator and the {@link Float#equals} 3276 * and {@link Double#equals} methods, specifically with respect to 3277 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3278 * Care should be taken when performing a compare and set or a compare 3279 * and exchange operation with such values since the operation may 3280 * unexpectedly fail. 3281 * There are many possible NaN values that are considered to be 3282 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3283 * provided by Java can distinguish between them. Operation failure can 3284 * occur if the expected or witness value is a NaN value and it is 3285 * transformed (perhaps in a platform specific manner) into another NaN 3286 * value, and thus has a different bitwise representation (see 3287 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3288 * details). 3289 * The values {@code -0.0} and {@code +0.0} have different bitwise 3290 * representations but are considered equal when using the primitive 3291 * {@code ==} operator. Operation failure can occur if, for example, a 3292 * numeric algorithm computes an expected value to be say {@code -0.0} 3293 * and previously computed the witness value to be say {@code +0.0}. 3294 * @param decl the class that declares the static field 3295 * @param name the field's name 3296 * @param type the field's type, of type {@code T} 3297 * @return a VarHandle giving access to a static field 3298 * @throws NoSuchFieldException if the field does not exist 3299 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3300 * @throws SecurityException if a security manager is present and it 3301 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3302 * @throws NullPointerException if any argument is null 3303 * @since 9 3304 */ 3305 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3306 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3307 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3308 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3309 } 3310 3311 /** 3312 * Produces an early-bound method handle for a non-static method. 3313 * The receiver must have a supertype {@code defc} in which a method 3314 * of the given name and type is accessible to the lookup class. 3315 * The method and all its argument types must be accessible to the lookup object. 3316 * The type of the method handle will be that of the method, 3317 * without any insertion of an additional receiver parameter. 3318 * The given receiver will be bound into the method handle, 3319 * so that every call to the method handle will invoke the 3320 * requested method on the given receiver. 3321 * <p> 3322 * The returned method handle will have 3323 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3324 * the method's variable arity modifier bit ({@code 0x0080}) is set 3325 * <em>and</em> the trailing array argument is not the only argument. 3326 * (If the trailing array argument is the only argument, 3327 * the given receiver value will be bound to it.) 3328 * <p> 3329 * This is almost equivalent to the following code, with some differences noted below: 3330 * {@snippet lang="java" : 3331 import static java.lang.invoke.MethodHandles.*; 3332 import static java.lang.invoke.MethodType.*; 3333 ... 3334 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3335 MethodHandle mh1 = mh0.bindTo(receiver); 3336 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3337 return mh1; 3338 * } 3339 * where {@code defc} is either {@code receiver.getClass()} or a super 3340 * type of that class, in which the requested method is accessible 3341 * to the lookup class. 3342 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3343 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3344 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3345 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3346 * @param receiver the object from which the method is accessed 3347 * @param name the name of the method 3348 * @param type the type of the method, with the receiver argument omitted 3349 * @return the desired method handle 3350 * @throws NoSuchMethodException if the method does not exist 3351 * @throws IllegalAccessException if access checking fails 3352 * or if the method's variable arity modifier bit 3353 * is set and {@code asVarargsCollector} fails 3354 * @throws SecurityException if a security manager is present and it 3355 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3356 * @throws NullPointerException if any argument is null 3357 * @see MethodHandle#bindTo 3358 * @see #findVirtual 3359 */ 3360 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3361 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3362 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3363 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3364 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3365 throw new IllegalAccessException("The restricted defining class " + 3366 mh.type().leadingReferenceParameter().getName() + 3367 " is not assignable from receiver class " + 3368 receiver.getClass().getName()); 3369 } 3370 return mh.bindArgumentL(0, receiver).setVarargs(method); 3371 } 3372 3373 /** 3374 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3375 * to <i>m</i>, if the lookup class has permission. 3376 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3377 * If <i>m</i> is virtual, overriding is respected on every call. 3378 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3379 * The type of the method handle will be that of the method, 3380 * with the receiver type prepended (but only if it is non-static). 3381 * If the method's {@code accessible} flag is not set, 3382 * access checking is performed immediately on behalf of the lookup class. 3383 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3384 * <p> 3385 * The returned method handle will have 3386 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3387 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3388 * <p> 3389 * If <i>m</i> is static, and 3390 * if the returned method handle is invoked, the method's class will 3391 * be initialized, if it has not already been initialized. 3392 * @param m the reflected method 3393 * @return a method handle which can invoke the reflected method 3394 * @throws IllegalAccessException if access checking fails 3395 * or if the method's variable arity modifier bit 3396 * is set and {@code asVarargsCollector} fails 3397 * @throws NullPointerException if the argument is null 3398 */ 3399 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3400 if (m.getDeclaringClass() == MethodHandle.class) { 3401 MethodHandle mh = unreflectForMH(m); 3402 if (mh != null) return mh; 3403 } 3404 if (m.getDeclaringClass() == VarHandle.class) { 3405 MethodHandle mh = unreflectForVH(m); 3406 if (mh != null) return mh; 3407 } 3408 MemberName method = new MemberName(m); 3409 byte refKind = method.getReferenceKind(); 3410 if (refKind == REF_invokeSpecial) 3411 refKind = REF_invokeVirtual; 3412 assert(method.isMethod()); 3413 @SuppressWarnings("deprecation") 3414 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3415 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3416 } 3417 private MethodHandle unreflectForMH(Method m) { 3418 // these names require special lookups because they throw UnsupportedOperationException 3419 if (MemberName.isMethodHandleInvokeName(m.getName())) 3420 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3421 return null; 3422 } 3423 private MethodHandle unreflectForVH(Method m) { 3424 // these names require special lookups because they throw UnsupportedOperationException 3425 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3426 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3427 return null; 3428 } 3429 3430 /** 3431 * Produces a method handle for a reflected method. 3432 * It will bypass checks for overriding methods on the receiver, 3433 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3434 * instruction from within the explicitly specified {@code specialCaller}. 3435 * The type of the method handle will be that of the method, 3436 * with a suitably restricted receiver type prepended. 3437 * (The receiver type will be {@code specialCaller} or a subtype.) 3438 * If the method's {@code accessible} flag is not set, 3439 * access checking is performed immediately on behalf of the lookup class, 3440 * as if {@code invokespecial} instruction were being linked. 3441 * <p> 3442 * Before method resolution, 3443 * if the explicitly specified caller class is not identical with the 3444 * lookup class, or if this lookup object does not have 3445 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3446 * privileges, the access fails. 3447 * <p> 3448 * The returned method handle will have 3449 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3450 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3451 * @param m the reflected method 3452 * @param specialCaller the class nominally calling the method 3453 * @return a method handle which can invoke the reflected method 3454 * @throws IllegalAccessException if access checking fails, 3455 * or if the method is {@code static}, 3456 * or if the method's variable arity modifier bit 3457 * is set and {@code asVarargsCollector} fails 3458 * @throws NullPointerException if any argument is null 3459 */ 3460 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3461 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3462 Lookup specialLookup = this.in(specialCaller); 3463 MemberName method = new MemberName(m, true); 3464 assert(method.isMethod()); 3465 // ignore m.isAccessible: this is a new kind of access 3466 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3467 } 3468 3469 /** 3470 * Produces a method handle for a reflected constructor. 3471 * The type of the method handle will be that of the constructor, 3472 * with the return type changed to the declaring class. 3473 * The method handle will perform a {@code newInstance} operation, 3474 * creating a new instance of the constructor's class on the 3475 * arguments passed to the method handle. 3476 * <p> 3477 * If the constructor's {@code accessible} flag is not set, 3478 * access checking is performed immediately on behalf of the lookup class. 3479 * <p> 3480 * The returned method handle will have 3481 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3482 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3483 * <p> 3484 * If the returned method handle is invoked, the constructor's class will 3485 * be initialized, if it has not already been initialized. 3486 * @param c the reflected constructor 3487 * @return a method handle which can invoke the reflected constructor 3488 * @throws IllegalAccessException if access checking fails 3489 * or if the method's variable arity modifier bit 3490 * is set and {@code asVarargsCollector} fails 3491 * @throws NullPointerException if the argument is null 3492 */ 3493 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3494 MemberName ctor = new MemberName(c); 3495 assert(ctor.isConstructor()); 3496 @SuppressWarnings("deprecation") 3497 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3498 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3499 } 3500 3501 /* 3502 * Produces a method handle that is capable of creating instances of the given class 3503 * and instantiated by the given constructor. No security manager check. 3504 * 3505 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3506 */ 3507 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3508 MemberName ctor = new MemberName(c); 3509 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3510 checkAccess(REF_newInvokeSpecial, decl, ctor); 3511 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3512 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3513 } 3514 3515 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3516 if (decl == ctor.getDeclaringClass()) 3517 return true; 3518 3519 Class<?> cl = decl; 3520 while ((cl = cl.getSuperclass()) != null) { 3521 if (cl == ctor.getDeclaringClass()) { 3522 return true; 3523 } 3524 } 3525 return false; 3526 } 3527 3528 /** 3529 * Produces a method handle giving read access to a reflected field. 3530 * The type of the method handle will have a return type of the field's 3531 * value type. 3532 * If the field is {@code static}, the method handle will take no arguments. 3533 * Otherwise, its single argument will be the instance containing 3534 * the field. 3535 * If the {@code Field} object's {@code accessible} flag is not set, 3536 * access checking is performed immediately on behalf of the lookup class. 3537 * <p> 3538 * If the field is static, and 3539 * if the returned method handle is invoked, the field's class will 3540 * be initialized, if it has not already been initialized. 3541 * @param f the reflected field 3542 * @return a method handle which can load values from the reflected field 3543 * @throws IllegalAccessException if access checking fails 3544 * @throws NullPointerException if the argument is null 3545 */ 3546 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3547 return unreflectField(f, false); 3548 } 3549 3550 /** 3551 * Produces a method handle giving write access to a reflected field. 3552 * The type of the method handle will have a void return type. 3553 * If the field is {@code static}, the method handle will take a single 3554 * argument, of the field's value type, the value to be stored. 3555 * Otherwise, the two arguments will be the instance containing 3556 * the field, and the value to be stored. 3557 * If the {@code Field} object's {@code accessible} flag is not set, 3558 * access checking is performed immediately on behalf of the lookup class. 3559 * <p> 3560 * If the field is {@code final}, write access will not be 3561 * allowed and access checking will fail, except under certain 3562 * narrow circumstances documented for {@link Field#set Field.set}. 3563 * A method handle is returned only if a corresponding call to 3564 * the {@code Field} object's {@code set} method could return 3565 * normally. In particular, fields which are both {@code static} 3566 * and {@code final} may never be set. 3567 * <p> 3568 * If the field is {@code static}, and 3569 * if the returned method handle is invoked, the field's class will 3570 * be initialized, if it has not already been initialized. 3571 * @param f the reflected field 3572 * @return a method handle which can store values into the reflected field 3573 * @throws IllegalAccessException if access checking fails, 3574 * or if the field is {@code final} and write access 3575 * is not enabled on the {@code Field} object 3576 * @throws NullPointerException if the argument is null 3577 */ 3578 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3579 return unreflectField(f, true); 3580 } 3581 3582 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3583 MemberName field = new MemberName(f, isSetter); 3584 if (isSetter && field.isFinal()) { 3585 if (field.isTrustedFinalField()) { 3586 String msg = field.isStatic() ? "static final field has no write access" 3587 : "final field has no write access"; 3588 throw field.makeAccessException(msg, this); 3589 } 3590 } 3591 assert(isSetter 3592 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3593 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3594 @SuppressWarnings("deprecation") 3595 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3596 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3597 } 3598 3599 /** 3600 * Produces a VarHandle giving access to a reflected field {@code f} 3601 * of type {@code T} declared in a class of type {@code R}. 3602 * The VarHandle's variable type is {@code T}. 3603 * If the field is non-static the VarHandle has one coordinate type, 3604 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3605 * coordinate types. 3606 * <p> 3607 * Access checking is performed immediately on behalf of the lookup 3608 * class, regardless of the value of the field's {@code accessible} 3609 * flag. 3610 * <p> 3611 * If the field is static, and if the returned VarHandle is operated 3612 * on, the field's declaring class will be initialized, if it has not 3613 * already been initialized. 3614 * <p> 3615 * Certain access modes of the returned VarHandle are unsupported under 3616 * the following conditions: 3617 * <ul> 3618 * <li>if the field is declared {@code final}, then the write, atomic 3619 * update, numeric atomic update, and bitwise atomic update access 3620 * modes are unsupported. 3621 * <li>if the field type is anything other than {@code byte}, 3622 * {@code short}, {@code char}, {@code int}, {@code long}, 3623 * {@code float}, or {@code double} then numeric atomic update 3624 * access modes are unsupported. 3625 * <li>if the field type is anything other than {@code boolean}, 3626 * {@code byte}, {@code short}, {@code char}, {@code int} or 3627 * {@code long} then bitwise atomic update access modes are 3628 * unsupported. 3629 * </ul> 3630 * <p> 3631 * If the field is declared {@code volatile} then the returned VarHandle 3632 * will override access to the field (effectively ignore the 3633 * {@code volatile} declaration) in accordance to its specified 3634 * access modes. 3635 * <p> 3636 * If the field type is {@code float} or {@code double} then numeric 3637 * and atomic update access modes compare values using their bitwise 3638 * representation (see {@link Float#floatToRawIntBits} and 3639 * {@link Double#doubleToRawLongBits}, respectively). 3640 * @apiNote 3641 * Bitwise comparison of {@code float} values or {@code double} values, 3642 * as performed by the numeric and atomic update access modes, differ 3643 * from the primitive {@code ==} operator and the {@link Float#equals} 3644 * and {@link Double#equals} methods, specifically with respect to 3645 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3646 * Care should be taken when performing a compare and set or a compare 3647 * and exchange operation with such values since the operation may 3648 * unexpectedly fail. 3649 * There are many possible NaN values that are considered to be 3650 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3651 * provided by Java can distinguish between them. Operation failure can 3652 * occur if the expected or witness value is a NaN value and it is 3653 * transformed (perhaps in a platform specific manner) into another NaN 3654 * value, and thus has a different bitwise representation (see 3655 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3656 * details). 3657 * The values {@code -0.0} and {@code +0.0} have different bitwise 3658 * representations but are considered equal when using the primitive 3659 * {@code ==} operator. Operation failure can occur if, for example, a 3660 * numeric algorithm computes an expected value to be say {@code -0.0} 3661 * and previously computed the witness value to be say {@code +0.0}. 3662 * @param f the reflected field, with a field of type {@code T}, and 3663 * a declaring class of type {@code R} 3664 * @return a VarHandle giving access to non-static fields or a static 3665 * field 3666 * @throws IllegalAccessException if access checking fails 3667 * @throws NullPointerException if the argument is null 3668 * @since 9 3669 */ 3670 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3671 MemberName getField = new MemberName(f, false); 3672 MemberName putField = new MemberName(f, true); 3673 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3674 f.getDeclaringClass(), getField, putField); 3675 } 3676 3677 /** 3678 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3679 * created by this lookup object or a similar one. 3680 * Security and access checks are performed to ensure that this lookup object 3681 * is capable of reproducing the target method handle. 3682 * This means that the cracking may fail if target is a direct method handle 3683 * but was created by an unrelated lookup object. 3684 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3685 * and was created by a lookup object for a different class. 3686 * @param target a direct method handle to crack into symbolic reference components 3687 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3688 * @throws SecurityException if a security manager is present and it 3689 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3690 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3691 * @throws NullPointerException if the target is {@code null} 3692 * @see MethodHandleInfo 3693 * @since 1.8 3694 */ 3695 public MethodHandleInfo revealDirect(MethodHandle target) { 3696 if (!target.isCrackable()) { 3697 throw newIllegalArgumentException("not a direct method handle"); 3698 } 3699 MemberName member = target.internalMemberName(); 3700 Class<?> defc = member.getDeclaringClass(); 3701 byte refKind = member.getReferenceKind(); 3702 assert(MethodHandleNatives.refKindIsValid(refKind)); 3703 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3704 // Devirtualized method invocation is usually formally virtual. 3705 // To avoid creating extra MemberName objects for this common case, 3706 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3707 refKind = REF_invokeVirtual; 3708 if (refKind == REF_invokeVirtual && defc.isInterface()) 3709 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3710 refKind = REF_invokeInterface; 3711 // Check SM permissions and member access before cracking. 3712 try { 3713 checkAccess(refKind, defc, member); 3714 checkSecurityManager(defc, member); 3715 } catch (IllegalAccessException ex) { 3716 throw new IllegalArgumentException(ex); 3717 } 3718 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3719 Class<?> callerClass = target.internalCallerClass(); 3720 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3721 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3722 } 3723 // Produce the handle to the results. 3724 return new InfoFromMemberName(this, member, refKind); 3725 } 3726 3727 //--- Helper methods, all package-private. 3728 3729 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3730 checkSymbolicClass(refc); // do this before attempting to resolve 3731 Objects.requireNonNull(name); 3732 Objects.requireNonNull(type); 3733 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3734 NoSuchFieldException.class); 3735 } 3736 3737 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3738 checkSymbolicClass(refc); // do this before attempting to resolve 3739 Objects.requireNonNull(type); 3740 checkMethodName(refKind, name); // implicit null-check of name 3741 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3742 NoSuchMethodException.class); 3743 } 3744 3745 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3746 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3747 Objects.requireNonNull(member.getName()); 3748 Objects.requireNonNull(member.getType()); 3749 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3750 ReflectiveOperationException.class); 3751 } 3752 3753 MemberName resolveOrNull(byte refKind, MemberName member) { 3754 // do this before attempting to resolve 3755 if (!isClassAccessible(member.getDeclaringClass())) { 3756 return null; 3757 } 3758 Objects.requireNonNull(member.getName()); 3759 Objects.requireNonNull(member.getType()); 3760 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3761 } 3762 3763 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3764 // do this before attempting to resolve 3765 if (!isClassAccessible(refc)) { 3766 return null; 3767 } 3768 Objects.requireNonNull(type); 3769 // implicit null-check of name 3770 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3771 return null; 3772 } 3773 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3774 } 3775 3776 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3777 if (!isClassAccessible(refc)) { 3778 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3779 } 3780 } 3781 3782 boolean isClassAccessible(Class<?> refc) { 3783 Objects.requireNonNull(refc); 3784 Class<?> caller = lookupClassOrNull(); 3785 Class<?> type = refc; 3786 while (type.isArray()) { 3787 type = type.getComponentType(); 3788 } 3789 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3790 } 3791 3792 /** Check name for an illegal leading "<" character. */ 3793 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3794 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3795 throw new NoSuchMethodException("illegal method name: "+name); 3796 } 3797 3798 /** 3799 * Find my trustable caller class if m is a caller sensitive method. 3800 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3801 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3802 */ 3803 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3804 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3805 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3806 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3807 } 3808 return this; 3809 } 3810 3811 /** 3812 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3813 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3814 * 3815 * @deprecated This method was originally designed to test {@code PRIVATE} access 3816 * that implies full privilege access but {@code MODULE} access has since become 3817 * independent of {@code PRIVATE} access. It is recommended to call 3818 * {@link #hasFullPrivilegeAccess()} instead. 3819 * @since 9 3820 */ 3821 @Deprecated(since="14") 3822 public boolean hasPrivateAccess() { 3823 return hasFullPrivilegeAccess(); 3824 } 3825 3826 /** 3827 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3828 * i.e. {@code PRIVATE} and {@code MODULE} access. 3829 * A {@code Lookup} object must have full privilege access in order to 3830 * access all members that are allowed to the 3831 * {@linkplain #lookupClass() lookup class}. 3832 * 3833 * @return {@code true} if this lookup has full privilege access. 3834 * @since 14 3835 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3836 */ 3837 public boolean hasFullPrivilegeAccess() { 3838 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3839 } 3840 3841 /** 3842 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3843 * for ensureInitialized, findClass or accessClass. 3844 */ 3845 void checkSecurityManager(Class<?> refc) { 3846 if (allowedModes == TRUSTED) return; 3847 3848 @SuppressWarnings("removal") 3849 SecurityManager smgr = System.getSecurityManager(); 3850 if (smgr == null) return; 3851 3852 // Step 1: 3853 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3854 if (!fullPrivilegeLookup || 3855 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3856 ReflectUtil.checkPackageAccess(refc); 3857 } 3858 3859 // Step 2b: 3860 if (!fullPrivilegeLookup) { 3861 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3862 } 3863 } 3864 3865 /** 3866 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3867 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3868 * If this lookup object has full privilege access except original access, 3869 * then the caller class is the lookupClass. 3870 * 3871 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3872 * from the same module skips the security permission check. 3873 */ 3874 void checkSecurityManager(Class<?> refc, MemberName m) { 3875 Objects.requireNonNull(refc); 3876 Objects.requireNonNull(m); 3877 3878 if (allowedModes == TRUSTED) return; 3879 3880 @SuppressWarnings("removal") 3881 SecurityManager smgr = System.getSecurityManager(); 3882 if (smgr == null) return; 3883 3884 // Step 1: 3885 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3886 if (!fullPrivilegeLookup || 3887 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3888 ReflectUtil.checkPackageAccess(refc); 3889 } 3890 3891 // Step 2a: 3892 if (m.isPublic()) return; 3893 if (!fullPrivilegeLookup) { 3894 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3895 } 3896 3897 // Step 3: 3898 Class<?> defc = m.getDeclaringClass(); 3899 if (!fullPrivilegeLookup && defc != refc) { 3900 ReflectUtil.checkPackageAccess(defc); 3901 } 3902 } 3903 3904 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3905 boolean wantStatic = (refKind == REF_invokeStatic); 3906 String message; 3907 if (m.isConstructor()) 3908 message = "expected a method, not a constructor"; 3909 else if (!m.isMethod()) 3910 message = "expected a method"; 3911 else if (wantStatic != m.isStatic()) 3912 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3913 else 3914 { checkAccess(refKind, refc, m); return; } 3915 throw m.makeAccessException(message, this); 3916 } 3917 3918 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3919 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3920 String message; 3921 if (wantStatic != m.isStatic()) 3922 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3923 else 3924 { checkAccess(refKind, refc, m); return; } 3925 throw m.makeAccessException(message, this); 3926 } 3927 3928 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3929 return Modifier.isProtected(m.getModifiers()) && 3930 refKind == REF_invokeVirtual && 3931 m.getDeclaringClass() == Object.class && 3932 m.getName().equals("clone") && 3933 refc.isArray(); 3934 } 3935 3936 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3937 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3938 assert(m.referenceKindIsConsistentWith(refKind) && 3939 MethodHandleNatives.refKindIsValid(refKind) && 3940 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3941 int allowedModes = this.allowedModes; 3942 if (allowedModes == TRUSTED) return; 3943 int mods = m.getModifiers(); 3944 if (isArrayClone(refKind, refc, m)) { 3945 // The JVM does this hack also. 3946 // (See ClassVerifier::verify_invoke_instructions 3947 // and LinkResolver::check_method_accessability.) 3948 // Because the JVM does not allow separate methods on array types, 3949 // there is no separate method for int[].clone. 3950 // All arrays simply inherit Object.clone. 3951 // But for access checking logic, we make Object.clone 3952 // (normally protected) appear to be public. 3953 // Later on, when the DirectMethodHandle is created, 3954 // its leading argument will be restricted to the 3955 // requested array type. 3956 // N.B. The return type is not adjusted, because 3957 // that is *not* the bytecode behavior. 3958 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3959 } 3960 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3961 // cannot "new" a protected ctor in a different package 3962 mods ^= Modifier.PROTECTED; 3963 } 3964 if (Modifier.isFinal(mods) && 3965 MethodHandleNatives.refKindIsSetter(refKind)) 3966 throw m.makeAccessException("unexpected set of a final field", this); 3967 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3968 if ((requestedModes & allowedModes) != 0) { 3969 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3970 mods, lookupClass(), previousLookupClass(), allowedModes)) 3971 return; 3972 } else { 3973 // Protected members can also be checked as if they were package-private. 3974 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3975 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3976 return; 3977 } 3978 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3979 } 3980 3981 String accessFailedMessage(Class<?> refc, MemberName m) { 3982 Class<?> defc = m.getDeclaringClass(); 3983 int mods = m.getModifiers(); 3984 // check the class first: 3985 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3986 (defc == refc || 3987 Modifier.isPublic(refc.getModifiers()))); 3988 if (!classOK && (allowedModes & PACKAGE) != 0) { 3989 // ignore previous lookup class to check if default package access 3990 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3991 (defc == refc || 3992 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3993 } 3994 if (!classOK) 3995 return "class is not public"; 3996 if (Modifier.isPublic(mods)) 3997 return "access to public member failed"; // (how?, module not readable?) 3998 if (Modifier.isPrivate(mods)) 3999 return "member is private"; 4000 if (Modifier.isProtected(mods)) 4001 return "member is protected"; 4002 return "member is private to package"; 4003 } 4004 4005 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 4006 int allowedModes = this.allowedModes; 4007 if (allowedModes == TRUSTED) return; 4008 if ((lookupModes() & PRIVATE) == 0 4009 || (specialCaller != lookupClass() 4010 // ensure non-abstract methods in superinterfaces can be special-invoked 4011 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 4012 throw new MemberName(specialCaller). 4013 makeAccessException("no private access for invokespecial", this); 4014 } 4015 4016 private boolean restrictProtectedReceiver(MemberName method) { 4017 // The accessing class only has the right to use a protected member 4018 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 4019 if (!method.isProtected() || method.isStatic() 4020 || allowedModes == TRUSTED 4021 || method.getDeclaringClass() == lookupClass() 4022 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 4023 return false; 4024 return true; 4025 } 4026 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 4027 assert(!method.isStatic()); 4028 // receiver type of mh is too wide; narrow to caller 4029 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 4030 throw method.makeAccessException("caller class must be a subclass below the method", caller); 4031 } 4032 MethodType rawType = mh.type(); 4033 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 4034 MethodType narrowType = rawType.changeParameterType(0, caller); 4035 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 4036 assert(mh.viewAsTypeChecks(narrowType, true)); 4037 return mh.copyWith(narrowType, mh.form); 4038 } 4039 4040 /** Check access and get the requested method. */ 4041 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4042 final boolean doRestrict = true; 4043 final boolean checkSecurity = true; 4044 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4045 } 4046 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 4047 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4048 final boolean doRestrict = false; 4049 final boolean checkSecurity = true; 4050 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 4051 } 4052 /** Check access and get the requested method, eliding security manager checks. */ 4053 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4054 final boolean doRestrict = true; 4055 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4056 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4057 } 4058 /** Common code for all methods; do not call directly except from immediately above. */ 4059 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 4060 boolean checkSecurity, 4061 boolean doRestrict, 4062 Lookup boundCaller) throws IllegalAccessException { 4063 checkMethod(refKind, refc, method); 4064 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4065 if (checkSecurity) 4066 checkSecurityManager(refc, method); 4067 assert(!method.isMethodHandleInvoke()); 4068 4069 if (refKind == REF_invokeSpecial && 4070 refc != lookupClass() && 4071 !refc.isInterface() && !lookupClass().isInterface() && 4072 refc != lookupClass().getSuperclass() && 4073 refc.isAssignableFrom(lookupClass())) { 4074 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 4075 4076 // Per JVMS 6.5, desc. of invokespecial instruction: 4077 // If the method is in a superclass of the LC, 4078 // and if our original search was above LC.super, 4079 // repeat the search (symbolic lookup) from LC.super 4080 // and continue with the direct superclass of that class, 4081 // and so forth, until a match is found or no further superclasses exist. 4082 // FIXME: MemberName.resolve should handle this instead. 4083 Class<?> refcAsSuper = lookupClass(); 4084 MemberName m2; 4085 do { 4086 refcAsSuper = refcAsSuper.getSuperclass(); 4087 m2 = new MemberName(refcAsSuper, 4088 method.getName(), 4089 method.getMethodType(), 4090 REF_invokeSpecial); 4091 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4092 } while (m2 == null && // no method is found yet 4093 refc != refcAsSuper); // search up to refc 4094 if (m2 == null) throw new InternalError(method.toString()); 4095 method = m2; 4096 refc = refcAsSuper; 4097 // redo basic checks 4098 checkMethod(refKind, refc, method); 4099 } 4100 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4101 MethodHandle mh = dmh; 4102 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4103 if ((doRestrict && refKind == REF_invokeSpecial) || 4104 (MethodHandleNatives.refKindHasReceiver(refKind) && 4105 restrictProtectedReceiver(method) && 4106 // All arrays simply inherit the protected Object.clone method. 4107 // The leading argument is already restricted to the requested 4108 // array type (not the lookup class). 4109 !isArrayClone(refKind, refc, method))) { 4110 mh = restrictReceiver(method, dmh, lookupClass()); 4111 } 4112 mh = maybeBindCaller(method, mh, boundCaller); 4113 mh = mh.setVarargs(method); 4114 return mh; 4115 } 4116 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4117 throws IllegalAccessException { 4118 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4119 return mh; 4120 4121 // boundCaller must have full privilege access. 4122 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4123 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4124 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4125 4126 assert boundCaller.hasFullPrivilegeAccess(); 4127 4128 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4129 // Note: caller will apply varargs after this step happens. 4130 return cbmh; 4131 } 4132 4133 /** Check access and get the requested field. */ 4134 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4135 final boolean checkSecurity = true; 4136 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4137 } 4138 /** Check access and get the requested field, eliding security manager checks. */ 4139 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4140 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4141 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4142 } 4143 /** Common code for all fields; do not call directly except from immediately above. */ 4144 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4145 boolean checkSecurity) throws IllegalAccessException { 4146 checkField(refKind, refc, field); 4147 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4148 if (checkSecurity) 4149 checkSecurityManager(refc, field); 4150 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4151 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4152 restrictProtectedReceiver(field)); 4153 if (doRestrict) 4154 return restrictReceiver(field, dmh, lookupClass()); 4155 return dmh; 4156 } 4157 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4158 Class<?> refc, MemberName getField, MemberName putField) 4159 throws IllegalAccessException { 4160 final boolean checkSecurity = true; 4161 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4162 } 4163 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4164 Class<?> refc, MemberName getField, MemberName putField) 4165 throws IllegalAccessException { 4166 final boolean checkSecurity = false; 4167 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4168 } 4169 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4170 Class<?> refc, MemberName getField, MemberName putField, 4171 boolean checkSecurity) throws IllegalAccessException { 4172 assert getField.isStatic() == putField.isStatic(); 4173 assert getField.isGetter() && putField.isSetter(); 4174 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4175 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4176 4177 checkField(getRefKind, refc, getField); 4178 if (checkSecurity) 4179 checkSecurityManager(refc, getField); 4180 4181 if (!putField.isFinal()) { 4182 // A VarHandle does not support updates to final fields, any 4183 // such VarHandle to a final field will be read-only and 4184 // therefore the following write-based accessibility checks are 4185 // only required for non-final fields 4186 checkField(putRefKind, refc, putField); 4187 if (checkSecurity) 4188 checkSecurityManager(refc, putField); 4189 } 4190 4191 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4192 restrictProtectedReceiver(getField)); 4193 if (doRestrict) { 4194 assert !getField.isStatic(); 4195 // receiver type of VarHandle is too wide; narrow to caller 4196 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4197 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4198 } 4199 refc = lookupClass(); 4200 } 4201 return VarHandles.makeFieldHandle(getField, refc, 4202 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4203 } 4204 /** Check access and get the requested constructor. */ 4205 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4206 final boolean checkSecurity = true; 4207 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4208 } 4209 /** Check access and get the requested constructor, eliding security manager checks. */ 4210 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4211 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4212 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4213 } 4214 /** Common code for all constructors; do not call directly except from immediately above. */ 4215 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4216 boolean checkSecurity) throws IllegalAccessException { 4217 assert(ctor.isConstructor()); 4218 checkAccess(REF_newInvokeSpecial, refc, ctor); 4219 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4220 if (checkSecurity) 4221 checkSecurityManager(refc, ctor); 4222 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4223 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4224 } 4225 4226 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4227 */ 4228 /*non-public*/ 4229 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4230 throws ReflectiveOperationException { 4231 if (!(type instanceof Class || type instanceof MethodType)) 4232 throw new InternalError("unresolved MemberName"); 4233 MemberName member = new MemberName(refKind, defc, name, type); 4234 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4235 if (mh != null) { 4236 checkSymbolicClass(defc); 4237 return mh; 4238 } 4239 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4240 // Treat MethodHandle.invoke and invokeExact specially. 4241 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4242 if (mh != null) { 4243 return mh; 4244 } 4245 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4246 // Treat signature-polymorphic methods on VarHandle specially. 4247 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4248 if (mh != null) { 4249 return mh; 4250 } 4251 } 4252 MemberName resolved = resolveOrFail(refKind, member); 4253 mh = getDirectMethodForConstant(refKind, defc, resolved); 4254 if (mh instanceof DirectMethodHandle dmh 4255 && canBeCached(refKind, defc, resolved)) { 4256 MemberName key = mh.internalMemberName(); 4257 if (key != null) { 4258 key = key.asNormalOriginal(); 4259 } 4260 if (member.equals(key)) { // better safe than sorry 4261 LOOKASIDE_TABLE.put(key, dmh); 4262 } 4263 } 4264 return mh; 4265 } 4266 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4267 if (refKind == REF_invokeSpecial) { 4268 return false; 4269 } 4270 if (!Modifier.isPublic(defc.getModifiers()) || 4271 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4272 !member.isPublic() || 4273 member.isCallerSensitive()) { 4274 return false; 4275 } 4276 ClassLoader loader = defc.getClassLoader(); 4277 if (loader != null) { 4278 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4279 boolean found = false; 4280 while (sysl != null) { 4281 if (loader == sysl) { found = true; break; } 4282 sysl = sysl.getParent(); 4283 } 4284 if (!found) { 4285 return false; 4286 } 4287 } 4288 try { 4289 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4290 new MemberName(refKind, defc, member.getName(), member.getType())); 4291 if (resolved2 == null) { 4292 return false; 4293 } 4294 checkSecurityManager(defc, resolved2); 4295 } catch (SecurityException ex) { 4296 return false; 4297 } 4298 return true; 4299 } 4300 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4301 throws ReflectiveOperationException { 4302 if (MethodHandleNatives.refKindIsField(refKind)) { 4303 return getDirectFieldNoSecurityManager(refKind, defc, member); 4304 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4305 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4306 } else if (refKind == REF_newInvokeSpecial) { 4307 return getDirectConstructorNoSecurityManager(defc, member); 4308 } 4309 // oops 4310 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4311 } 4312 4313 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4314 } 4315 4316 /** 4317 * Produces a method handle constructing arrays of a desired type, 4318 * as if by the {@code anewarray} bytecode. 4319 * The return type of the method handle will be the array type. 4320 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4321 * 4322 * <p> If the returned method handle is invoked with a negative 4323 * array size, a {@code NegativeArraySizeException} will be thrown. 4324 * 4325 * @param arrayClass an array type 4326 * @return a method handle which can create arrays of the given type 4327 * @throws NullPointerException if the argument is {@code null} 4328 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4329 * @see java.lang.reflect.Array#newInstance(Class, int) 4330 * @jvms 6.5 {@code anewarray} Instruction 4331 * @since 9 4332 */ 4333 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4334 if (!arrayClass.isArray()) { 4335 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4336 } 4337 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4338 bindTo(arrayClass.getComponentType()); 4339 return ani.asType(ani.type().changeReturnType(arrayClass)); 4340 } 4341 4342 /** 4343 * Produces a method handle returning the length of an array, 4344 * as if by the {@code arraylength} bytecode. 4345 * The type of the method handle will have {@code int} as return type, 4346 * and its sole argument will be the array type. 4347 * 4348 * <p> If the returned method handle is invoked with a {@code null} 4349 * array reference, a {@code NullPointerException} will be thrown. 4350 * 4351 * @param arrayClass an array type 4352 * @return a method handle which can retrieve the length of an array of the given array type 4353 * @throws NullPointerException if the argument is {@code null} 4354 * @throws IllegalArgumentException if arrayClass is not an array type 4355 * @jvms 6.5 {@code arraylength} Instruction 4356 * @since 9 4357 */ 4358 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4359 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4360 } 4361 4362 /** 4363 * Produces a method handle giving read access to elements of an array, 4364 * as if by the {@code aaload} bytecode. 4365 * The type of the method handle will have a return type of the array's 4366 * element type. Its first argument will be the array type, 4367 * and the second will be {@code int}. 4368 * 4369 * <p> When the returned method handle is invoked, 4370 * the array reference and array index are checked. 4371 * A {@code NullPointerException} will be thrown if the array reference 4372 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4373 * thrown if the index is negative or if it is greater than or equal to 4374 * the length of the array. 4375 * 4376 * @param arrayClass an array type 4377 * @return a method handle which can load values from the given array type 4378 * @throws NullPointerException if the argument is null 4379 * @throws IllegalArgumentException if arrayClass is not an array type 4380 * @jvms 6.5 {@code aaload} Instruction 4381 */ 4382 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4383 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4384 } 4385 4386 /** 4387 * Produces a method handle giving write access to elements of an array, 4388 * as if by the {@code astore} bytecode. 4389 * The type of the method handle will have a void return type. 4390 * Its last argument will be the array's element type. 4391 * The first and second arguments will be the array type and int. 4392 * 4393 * <p> When the returned method handle is invoked, 4394 * the array reference and array index are checked. 4395 * A {@code NullPointerException} will be thrown if the array reference 4396 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4397 * thrown if the index is negative or if it is greater than or equal to 4398 * the length of the array. 4399 * 4400 * @param arrayClass the class of an array 4401 * @return a method handle which can store values into the array type 4402 * @throws NullPointerException if the argument is null 4403 * @throws IllegalArgumentException if arrayClass is not an array type 4404 * @jvms 6.5 {@code aastore} Instruction 4405 */ 4406 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4407 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4408 } 4409 4410 /** 4411 * Produces a VarHandle giving access to elements of an array of type 4412 * {@code arrayClass}. The VarHandle's variable type is the component type 4413 * of {@code arrayClass} and the list of coordinate types is 4414 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4415 * corresponds to an argument that is an index into an array. 4416 * <p> 4417 * Certain access modes of the returned VarHandle are unsupported under 4418 * the following conditions: 4419 * <ul> 4420 * <li>if the component type is anything other than {@code byte}, 4421 * {@code short}, {@code char}, {@code int}, {@code long}, 4422 * {@code float}, or {@code double} then numeric atomic update access 4423 * modes are unsupported. 4424 * <li>if the component type is anything other than {@code boolean}, 4425 * {@code byte}, {@code short}, {@code char}, {@code int} or 4426 * {@code long} then bitwise atomic update access modes are 4427 * unsupported. 4428 * </ul> 4429 * <p> 4430 * If the component type is {@code float} or {@code double} then numeric 4431 * and atomic update access modes compare values using their bitwise 4432 * representation (see {@link Float#floatToRawIntBits} and 4433 * {@link Double#doubleToRawLongBits}, respectively). 4434 * 4435 * <p> When the returned {@code VarHandle} is invoked, 4436 * the array reference and array index are checked. 4437 * A {@code NullPointerException} will be thrown if the array reference 4438 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4439 * thrown if the index is negative or if it is greater than or equal to 4440 * the length of the array. 4441 * 4442 * @apiNote 4443 * Bitwise comparison of {@code float} values or {@code double} values, 4444 * as performed by the numeric and atomic update access modes, differ 4445 * from the primitive {@code ==} operator and the {@link Float#equals} 4446 * and {@link Double#equals} methods, specifically with respect to 4447 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4448 * Care should be taken when performing a compare and set or a compare 4449 * and exchange operation with such values since the operation may 4450 * unexpectedly fail. 4451 * There are many possible NaN values that are considered to be 4452 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4453 * provided by Java can distinguish between them. Operation failure can 4454 * occur if the expected or witness value is a NaN value and it is 4455 * transformed (perhaps in a platform specific manner) into another NaN 4456 * value, and thus has a different bitwise representation (see 4457 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4458 * details). 4459 * The values {@code -0.0} and {@code +0.0} have different bitwise 4460 * representations but are considered equal when using the primitive 4461 * {@code ==} operator. Operation failure can occur if, for example, a 4462 * numeric algorithm computes an expected value to be say {@code -0.0} 4463 * and previously computed the witness value to be say {@code +0.0}. 4464 * @param arrayClass the class of an array, of type {@code T[]} 4465 * @return a VarHandle giving access to elements of an array 4466 * @throws NullPointerException if the arrayClass is null 4467 * @throws IllegalArgumentException if arrayClass is not an array type 4468 * @since 9 4469 */ 4470 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4471 return VarHandles.makeArrayElementHandle(arrayClass); 4472 } 4473 4474 /** 4475 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4476 * viewed as if it were a different primitive array type, such as 4477 * {@code int[]} or {@code long[]}. 4478 * The VarHandle's variable type is the component type of 4479 * {@code viewArrayClass} and the list of coordinate types is 4480 * {@code (byte[], int)}, where the {@code int} coordinate type 4481 * corresponds to an argument that is an index into a {@code byte[]} array. 4482 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4483 * array, composing bytes to or from a value of the component type of 4484 * {@code viewArrayClass} according to the given endianness. 4485 * <p> 4486 * The supported component types (variables types) are {@code short}, 4487 * {@code char}, {@code int}, {@code long}, {@code float} and 4488 * {@code double}. 4489 * <p> 4490 * Access of bytes at a given index will result in an 4491 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4492 * or greater than the {@code byte[]} array length minus the size (in bytes) 4493 * of {@code T}. 4494 * <p> 4495 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4496 * access modes are supported by the returned var handle. For all other access modes, an 4497 * {@link UnsupportedOperationException} will be thrown. 4498 * 4499 * @apiNote if access modes other than plain access are required, clients should 4500 * consider using off-heap memory through 4501 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4502 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4503 * or memory segments backed by a 4504 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4505 * for which stronger alignment guarantees can be made. 4506 * 4507 * @param viewArrayClass the view array class, with a component type of 4508 * type {@code T} 4509 * @param byteOrder the endianness of the view array elements, as 4510 * stored in the underlying {@code byte} array 4511 * @return a VarHandle giving access to elements of a {@code byte[]} array 4512 * viewed as if elements corresponding to the components type of the view 4513 * array class 4514 * @throws NullPointerException if viewArrayClass or byteOrder is null 4515 * @throws IllegalArgumentException if viewArrayClass is not an array type 4516 * @throws UnsupportedOperationException if the component type of 4517 * viewArrayClass is not supported as a variable type 4518 * @since 9 4519 */ 4520 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4521 ByteOrder byteOrder) throws IllegalArgumentException { 4522 Objects.requireNonNull(byteOrder); 4523 return VarHandles.byteArrayViewHandle(viewArrayClass, 4524 byteOrder == ByteOrder.BIG_ENDIAN); 4525 } 4526 4527 /** 4528 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4529 * viewed as if it were an array of elements of a different primitive 4530 * component type to that of {@code byte}, such as {@code int[]} or 4531 * {@code long[]}. 4532 * The VarHandle's variable type is the component type of 4533 * {@code viewArrayClass} and the list of coordinate types is 4534 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4535 * corresponds to an argument that is an index into a {@code byte[]} array. 4536 * The returned VarHandle accesses bytes at an index in a 4537 * {@code ByteBuffer}, composing bytes to or from a value of the component 4538 * type of {@code viewArrayClass} according to the given endianness. 4539 * <p> 4540 * The supported component types (variables types) are {@code short}, 4541 * {@code char}, {@code int}, {@code long}, {@code float} and 4542 * {@code double}. 4543 * <p> 4544 * Access will result in a {@code ReadOnlyBufferException} for anything 4545 * other than the read access modes if the {@code ByteBuffer} is read-only. 4546 * <p> 4547 * Access of bytes at a given index will result in an 4548 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4549 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4550 * {@code T}. 4551 * <p> 4552 * For heap byte buffers, access is always unaligned. As a result, only the plain 4553 * {@linkplain VarHandle.AccessMode#GET get} 4554 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4555 * returned var handle. For all other access modes, an {@link IllegalStateException} 4556 * will be thrown. 4557 * <p> 4558 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4559 * with respect to the underlying memory address, {@code A} say, associated 4560 * with the {@code ByteBuffer} and index. 4561 * If access is misaligned then access for anything other than the 4562 * {@code get} and {@code set} access modes will result in an 4563 * {@code IllegalStateException}. In such cases atomic access is only 4564 * guaranteed with respect to the largest power of two that divides the GCD 4565 * of {@code A} and the size (in bytes) of {@code T}. 4566 * If access is aligned then following access modes are supported and are 4567 * guaranteed to support atomic access: 4568 * <ul> 4569 * <li>read write access modes for all {@code T}, with the exception of 4570 * access modes {@code get} and {@code set} for {@code long} and 4571 * {@code double} on 32-bit platforms. 4572 * <li>atomic update access modes for {@code int}, {@code long}, 4573 * {@code float} or {@code double}. 4574 * (Future major platform releases of the JDK may support additional 4575 * types for certain currently unsupported access modes.) 4576 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4577 * (Future major platform releases of the JDK may support additional 4578 * numeric types for certain currently unsupported access modes.) 4579 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4580 * (Future major platform releases of the JDK may support additional 4581 * numeric types for certain currently unsupported access modes.) 4582 * </ul> 4583 * <p> 4584 * Misaligned access, and therefore atomicity guarantees, may be determined 4585 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4586 * {@code index}, {@code T} and its corresponding boxed type, 4587 * {@code T_BOX}, as follows: 4588 * <pre>{@code 4589 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4590 * ByteBuffer bb = ... 4591 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4592 * boolean isMisaligned = misalignedAtIndex != 0; 4593 * }</pre> 4594 * <p> 4595 * If the variable type is {@code float} or {@code double} then atomic 4596 * update access modes compare values using their bitwise representation 4597 * (see {@link Float#floatToRawIntBits} and 4598 * {@link Double#doubleToRawLongBits}, respectively). 4599 * @param viewArrayClass the view array class, with a component type of 4600 * type {@code T} 4601 * @param byteOrder the endianness of the view array elements, as 4602 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4603 * endianness of a {@code ByteBuffer}) 4604 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4605 * viewed as if elements corresponding to the components type of the view 4606 * array class 4607 * @throws NullPointerException if viewArrayClass or byteOrder is null 4608 * @throws IllegalArgumentException if viewArrayClass is not an array type 4609 * @throws UnsupportedOperationException if the component type of 4610 * viewArrayClass is not supported as a variable type 4611 * @since 9 4612 */ 4613 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4614 ByteOrder byteOrder) throws IllegalArgumentException { 4615 Objects.requireNonNull(byteOrder); 4616 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4617 byteOrder == ByteOrder.BIG_ENDIAN); 4618 } 4619 4620 4621 //--- method handle invocation (reflective style) 4622 4623 /** 4624 * Produces a method handle which will invoke any method handle of the 4625 * given {@code type}, with a given number of trailing arguments replaced by 4626 * a single trailing {@code Object[]} array. 4627 * The resulting invoker will be a method handle with the following 4628 * arguments: 4629 * <ul> 4630 * <li>a single {@code MethodHandle} target 4631 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4632 * <li>an {@code Object[]} array containing trailing arguments 4633 * </ul> 4634 * <p> 4635 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4636 * the indicated {@code type}. 4637 * That is, if the target is exactly of the given {@code type}, it will behave 4638 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4639 * is used to convert the target to the required {@code type}. 4640 * <p> 4641 * The type of the returned invoker will not be the given {@code type}, but rather 4642 * will have all parameters except the first {@code leadingArgCount} 4643 * replaced by a single array of type {@code Object[]}, which will be 4644 * the final parameter. 4645 * <p> 4646 * Before invoking its target, the invoker will spread the final array, apply 4647 * reference casts as necessary, and unbox and widen primitive arguments. 4648 * If, when the invoker is called, the supplied array argument does 4649 * not have the correct number of elements, the invoker will throw 4650 * an {@link IllegalArgumentException} instead of invoking the target. 4651 * <p> 4652 * This method is equivalent to the following code (though it may be more efficient): 4653 * {@snippet lang="java" : 4654 MethodHandle invoker = MethodHandles.invoker(type); 4655 int spreadArgCount = type.parameterCount() - leadingArgCount; 4656 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4657 return invoker; 4658 * } 4659 * This method throws no reflective or security exceptions. 4660 * @param type the desired target type 4661 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4662 * @return a method handle suitable for invoking any method handle of the given type 4663 * @throws NullPointerException if {@code type} is null 4664 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4665 * the range from 0 to {@code type.parameterCount()} inclusive, 4666 * or if the resulting method handle's type would have 4667 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4668 */ 4669 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4670 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4671 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4672 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4673 return type.invokers().spreadInvoker(leadingArgCount); 4674 } 4675 4676 /** 4677 * Produces a special <em>invoker method handle</em> which can be used to 4678 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4679 * The resulting invoker will have a type which is 4680 * exactly equal to the desired type, except that it will accept 4681 * an additional leading argument of type {@code MethodHandle}. 4682 * <p> 4683 * This method is equivalent to the following code (though it may be more efficient): 4684 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4685 * 4686 * <p style="font-size:smaller;"> 4687 * <em>Discussion:</em> 4688 * Invoker method handles can be useful when working with variable method handles 4689 * of unknown types. 4690 * For example, to emulate an {@code invokeExact} call to a variable method 4691 * handle {@code M}, extract its type {@code T}, 4692 * look up the invoker method {@code X} for {@code T}, 4693 * and call the invoker method, as {@code X.invoke(T, A...)}. 4694 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4695 * is unknown.) 4696 * If spreading, collecting, or other argument transformations are required, 4697 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4698 * method handle values, as long as they are compatible with the type of {@code X}. 4699 * <p style="font-size:smaller;"> 4700 * <em>(Note: The invoker method is not available via the Core Reflection API. 4701 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4702 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4703 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4704 * <p> 4705 * This method throws no reflective or security exceptions. 4706 * @param type the desired target type 4707 * @return a method handle suitable for invoking any method handle of the given type 4708 * @throws IllegalArgumentException if the resulting method handle's type would have 4709 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4710 */ 4711 public static MethodHandle exactInvoker(MethodType type) { 4712 return type.invokers().exactInvoker(); 4713 } 4714 4715 /** 4716 * Produces a special <em>invoker method handle</em> which can be used to 4717 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4718 * The resulting invoker will have a type which is 4719 * exactly equal to the desired type, except that it will accept 4720 * an additional leading argument of type {@code MethodHandle}. 4721 * <p> 4722 * Before invoking its target, if the target differs from the expected type, 4723 * the invoker will apply reference casts as 4724 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4725 * Similarly, the return value will be converted as necessary. 4726 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4727 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4728 * <p> 4729 * This method is equivalent to the following code (though it may be more efficient): 4730 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4731 * <p style="font-size:smaller;"> 4732 * <em>Discussion:</em> 4733 * A {@linkplain MethodType#genericMethodType general method type} is one which 4734 * mentions only {@code Object} arguments and return values. 4735 * An invoker for such a type is capable of calling any method handle 4736 * of the same arity as the general type. 4737 * <p style="font-size:smaller;"> 4738 * <em>(Note: The invoker method is not available via the Core Reflection API. 4739 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4740 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4741 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4742 * <p> 4743 * This method throws no reflective or security exceptions. 4744 * @param type the desired target type 4745 * @return a method handle suitable for invoking any method handle convertible to the given type 4746 * @throws IllegalArgumentException if the resulting method handle's type would have 4747 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4748 */ 4749 public static MethodHandle invoker(MethodType type) { 4750 return type.invokers().genericInvoker(); 4751 } 4752 4753 /** 4754 * Produces a special <em>invoker method handle</em> which can be used to 4755 * invoke a signature-polymorphic access mode method on any VarHandle whose 4756 * associated access mode type is compatible with the given type. 4757 * The resulting invoker will have a type which is exactly equal to the 4758 * desired given type, except that it will accept an additional leading 4759 * argument of type {@code VarHandle}. 4760 * 4761 * @param accessMode the VarHandle access mode 4762 * @param type the desired target type 4763 * @return a method handle suitable for invoking an access mode method of 4764 * any VarHandle whose access mode type is of the given type. 4765 * @since 9 4766 */ 4767 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4768 return type.invokers().varHandleMethodExactInvoker(accessMode); 4769 } 4770 4771 /** 4772 * Produces a special <em>invoker method handle</em> which can be used to 4773 * invoke a signature-polymorphic access mode method on any VarHandle whose 4774 * associated access mode type is compatible with the given type. 4775 * The resulting invoker will have a type which is exactly equal to the 4776 * desired given type, except that it will accept an additional leading 4777 * argument of type {@code VarHandle}. 4778 * <p> 4779 * Before invoking its target, if the access mode type differs from the 4780 * desired given type, the invoker will apply reference casts as necessary 4781 * and box, unbox, or widen primitive values, as if by 4782 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4783 * converted as necessary. 4784 * <p> 4785 * This method is equivalent to the following code (though it may be more 4786 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4787 * 4788 * @param accessMode the VarHandle access mode 4789 * @param type the desired target type 4790 * @return a method handle suitable for invoking an access mode method of 4791 * any VarHandle whose access mode type is convertible to the given 4792 * type. 4793 * @since 9 4794 */ 4795 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4796 return type.invokers().varHandleMethodInvoker(accessMode); 4797 } 4798 4799 /*non-public*/ 4800 static MethodHandle basicInvoker(MethodType type) { 4801 return type.invokers().basicInvoker(); 4802 } 4803 4804 //--- method handle modification (creation from other method handles) 4805 4806 /** 4807 * Produces a method handle which adapts the type of the 4808 * given method handle to a new type by pairwise argument and return type conversion. 4809 * The original type and new type must have the same number of arguments. 4810 * The resulting method handle is guaranteed to report a type 4811 * which is equal to the desired new type. 4812 * <p> 4813 * If the original type and new type are equal, returns target. 4814 * <p> 4815 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4816 * and some additional conversions are also applied if those conversions fail. 4817 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4818 * if possible, before or instead of any conversions done by {@code asType}: 4819 * <ul> 4820 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4821 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4822 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4823 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4824 * the boolean is converted to a byte value, 1 for true, 0 for false. 4825 * (This treatment follows the usage of the bytecode verifier.) 4826 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4827 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4828 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4829 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4830 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4831 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4832 * widening and/or narrowing.) 4833 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4834 * conversion will be applied at runtime, possibly followed 4835 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4836 * possibly followed by a conversion from byte to boolean by testing 4837 * the low-order bit. 4838 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4839 * and if the reference is null at runtime, a zero value is introduced. 4840 * </ul> 4841 * @param target the method handle to invoke after arguments are retyped 4842 * @param newType the expected type of the new method handle 4843 * @return a method handle which delegates to the target after performing 4844 * any necessary argument conversions, and arranges for any 4845 * necessary return value conversions 4846 * @throws NullPointerException if either argument is null 4847 * @throws WrongMethodTypeException if the conversion cannot be made 4848 * @see MethodHandle#asType 4849 */ 4850 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4851 explicitCastArgumentsChecks(target, newType); 4852 // use the asTypeCache when possible: 4853 MethodType oldType = target.type(); 4854 if (oldType == newType) return target; 4855 if (oldType.explicitCastEquivalentToAsType(newType)) { 4856 return target.asFixedArity().asType(newType); 4857 } 4858 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4859 } 4860 4861 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4862 if (target.type().parameterCount() != newType.parameterCount()) { 4863 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4864 } 4865 } 4866 4867 /** 4868 * Produces a method handle which adapts the calling sequence of the 4869 * given method handle to a new type, by reordering the arguments. 4870 * The resulting method handle is guaranteed to report a type 4871 * which is equal to the desired new type. 4872 * <p> 4873 * The given array controls the reordering. 4874 * Call {@code #I} the number of incoming parameters (the value 4875 * {@code newType.parameterCount()}, and call {@code #O} the number 4876 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4877 * Then the length of the reordering array must be {@code #O}, 4878 * and each element must be a non-negative number less than {@code #I}. 4879 * For every {@code N} less than {@code #O}, the {@code N}-th 4880 * outgoing argument will be taken from the {@code I}-th incoming 4881 * argument, where {@code I} is {@code reorder[N]}. 4882 * <p> 4883 * No argument or return value conversions are applied. 4884 * The type of each incoming argument, as determined by {@code newType}, 4885 * must be identical to the type of the corresponding outgoing parameter 4886 * or parameters in the target method handle. 4887 * The return type of {@code newType} must be identical to the return 4888 * type of the original target. 4889 * <p> 4890 * The reordering array need not specify an actual permutation. 4891 * An incoming argument will be duplicated if its index appears 4892 * more than once in the array, and an incoming argument will be dropped 4893 * if its index does not appear in the array. 4894 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4895 * incoming arguments which are not mentioned in the reordering array 4896 * may be of any type, as determined only by {@code newType}. 4897 * {@snippet lang="java" : 4898 import static java.lang.invoke.MethodHandles.*; 4899 import static java.lang.invoke.MethodType.*; 4900 ... 4901 MethodType intfn1 = methodType(int.class, int.class); 4902 MethodType intfn2 = methodType(int.class, int.class, int.class); 4903 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4904 assert(sub.type().equals(intfn2)); 4905 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4906 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4907 assert((int)rsub.invokeExact(1, 100) == 99); 4908 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4909 assert(add.type().equals(intfn2)); 4910 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4911 assert(twice.type().equals(intfn1)); 4912 assert((int)twice.invokeExact(21) == 42); 4913 * } 4914 * <p> 4915 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4916 * variable-arity method handle}, even if the original target method handle was. 4917 * @param target the method handle to invoke after arguments are reordered 4918 * @param newType the expected type of the new method handle 4919 * @param reorder an index array which controls the reordering 4920 * @return a method handle which delegates to the target after it 4921 * drops unused arguments and moves and/or duplicates the other arguments 4922 * @throws NullPointerException if any argument is null 4923 * @throws IllegalArgumentException if the index array length is not equal to 4924 * the arity of the target, or if any index array element 4925 * not a valid index for a parameter of {@code newType}, 4926 * or if two corresponding parameter types in 4927 * {@code target.type()} and {@code newType} are not identical, 4928 */ 4929 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4930 reorder = reorder.clone(); // get a private copy 4931 MethodType oldType = target.type(); 4932 permuteArgumentChecks(reorder, newType, oldType); 4933 // first detect dropped arguments and handle them separately 4934 int[] originalReorder = reorder; 4935 BoundMethodHandle result = target.rebind(); 4936 LambdaForm form = result.form; 4937 int newArity = newType.parameterCount(); 4938 // Normalize the reordering into a real permutation, 4939 // by removing duplicates and adding dropped elements. 4940 // This somewhat improves lambda form caching, as well 4941 // as simplifying the transform by breaking it up into steps. 4942 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4943 if (ddIdx > 0) { 4944 // We found a duplicated entry at reorder[ddIdx]. 4945 // Example: (x,y,z)->asList(x,y,z) 4946 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4947 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4948 // The starred element corresponds to the argument 4949 // deleted by the dupArgumentForm transform. 4950 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4951 boolean killFirst = false; 4952 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4953 // Set killFirst if the dup is larger than an intervening position. 4954 // This will remove at least one inversion from the permutation. 4955 if (dupVal > val) killFirst = true; 4956 } 4957 if (!killFirst) { 4958 srcPos = dstPos; 4959 dstPos = ddIdx; 4960 } 4961 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4962 assert (reorder[srcPos] == reorder[dstPos]); 4963 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4964 // contract the reordering by removing the element at dstPos 4965 int tailPos = dstPos + 1; 4966 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4967 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4968 } else { 4969 int dropVal = ~ddIdx, insPos = 0; 4970 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4971 // Find first element of reorder larger than dropVal. 4972 // This is where we will insert the dropVal. 4973 insPos += 1; 4974 } 4975 Class<?> ptype = newType.parameterType(dropVal); 4976 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4977 oldType = oldType.insertParameterTypes(insPos, ptype); 4978 // expand the reordering by inserting an element at insPos 4979 int tailPos = insPos + 1; 4980 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4981 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4982 reorder[insPos] = dropVal; 4983 } 4984 assert (permuteArgumentChecks(reorder, newType, oldType)); 4985 } 4986 assert (reorder.length == newArity); // a perfect permutation 4987 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4988 form = form.editor().permuteArgumentsForm(1, reorder); 4989 if (newType == result.type() && form == result.internalForm()) 4990 return result; 4991 return result.copyWith(newType, form); 4992 } 4993 4994 /** 4995 * Return an indication of any duplicate or omission in reorder. 4996 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4997 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4998 * Otherwise, return zero. 4999 * If an element not in [0..newArity-1] is encountered, return reorder.length. 5000 */ 5001 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 5002 final int BIT_LIMIT = 63; // max number of bits in bit mask 5003 if (newArity < BIT_LIMIT) { 5004 long mask = 0; 5005 for (int i = 0; i < reorder.length; i++) { 5006 int arg = reorder[i]; 5007 if (arg >= newArity) { 5008 return reorder.length; 5009 } 5010 long bit = 1L << arg; 5011 if ((mask & bit) != 0) { 5012 return i; // >0 indicates a dup 5013 } 5014 mask |= bit; 5015 } 5016 if (mask == (1L << newArity) - 1) { 5017 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 5018 return 0; 5019 } 5020 // find first zero 5021 long zeroBit = Long.lowestOneBit(~mask); 5022 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 5023 assert(zeroPos <= newArity); 5024 if (zeroPos == newArity) { 5025 return 0; 5026 } 5027 return ~zeroPos; 5028 } else { 5029 // same algorithm, different bit set 5030 BitSet mask = new BitSet(newArity); 5031 for (int i = 0; i < reorder.length; i++) { 5032 int arg = reorder[i]; 5033 if (arg >= newArity) { 5034 return reorder.length; 5035 } 5036 if (mask.get(arg)) { 5037 return i; // >0 indicates a dup 5038 } 5039 mask.set(arg); 5040 } 5041 int zeroPos = mask.nextClearBit(0); 5042 assert(zeroPos <= newArity); 5043 if (zeroPos == newArity) { 5044 return 0; 5045 } 5046 return ~zeroPos; 5047 } 5048 } 5049 5050 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 5051 if (newType.returnType() != oldType.returnType()) 5052 throw newIllegalArgumentException("return types do not match", 5053 oldType, newType); 5054 if (reorder.length != oldType.parameterCount()) 5055 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 5056 oldType, Arrays.toString(reorder)); 5057 5058 int limit = newType.parameterCount(); 5059 for (int j = 0; j < reorder.length; j++) { 5060 int i = reorder[j]; 5061 if (i < 0 || i >= limit) { 5062 throw newIllegalArgumentException("index is out of bounds for new type", 5063 i, newType); 5064 } 5065 Class<?> src = newType.parameterType(i); 5066 Class<?> dst = oldType.parameterType(j); 5067 if (src != dst) 5068 throw newIllegalArgumentException("parameter types do not match after reorder", 5069 oldType, newType); 5070 } 5071 return true; 5072 } 5073 5074 /** 5075 * Produces a method handle of the requested return type which returns the given 5076 * constant value every time it is invoked. 5077 * <p> 5078 * Before the method handle is returned, the passed-in value is converted to the requested type. 5079 * If the requested type is primitive, widening primitive conversions are attempted, 5080 * else reference conversions are attempted. 5081 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5082 * @param type the return type of the desired method handle 5083 * @param value the value to return 5084 * @return a method handle of the given return type and no arguments, which always returns the given value 5085 * @throws NullPointerException if the {@code type} argument is null 5086 * @throws ClassCastException if the value cannot be converted to the required return type 5087 * @throws IllegalArgumentException if the given type is {@code void.class} 5088 */ 5089 public static MethodHandle constant(Class<?> type, Object value) { 5090 if (type.isPrimitive()) { 5091 if (type == void.class) 5092 throw newIllegalArgumentException("void type"); 5093 Wrapper w = Wrapper.forPrimitiveType(type); 5094 value = w.convert(value, type); 5095 if (w.zero().equals(value)) 5096 return zero(w, type); 5097 return insertArguments(identity(type), 0, value); 5098 } else { 5099 if (value == null) 5100 return zero(Wrapper.OBJECT, type); 5101 return identity(type).bindTo(value); 5102 } 5103 } 5104 5105 /** 5106 * Produces a method handle which returns its sole argument when invoked. 5107 * @param type the type of the sole parameter and return value of the desired method handle 5108 * @return a unary method handle which accepts and returns the given type 5109 * @throws NullPointerException if the argument is null 5110 * @throws IllegalArgumentException if the given type is {@code void.class} 5111 */ 5112 public static MethodHandle identity(Class<?> type) { 5113 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5114 int pos = btw.ordinal(); 5115 MethodHandle ident = IDENTITY_MHS[pos]; 5116 if (ident == null) { 5117 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5118 } 5119 if (ident.type().returnType() == type) 5120 return ident; 5121 // something like identity(Foo.class); do not bother to intern these 5122 assert (btw == Wrapper.OBJECT); 5123 return makeIdentity(type); 5124 } 5125 5126 /** 5127 * Produces a constant method handle of the requested return type which 5128 * returns the default value for that type every time it is invoked. 5129 * The resulting constant method handle will have no side effects. 5130 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5131 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5132 * since {@code explicitCastArguments} converts {@code null} to default values. 5133 * @param type the expected return type of the desired method handle 5134 * @return a constant method handle that takes no arguments 5135 * and returns the default value of the given type (or void, if the type is void) 5136 * @throws NullPointerException if the argument is null 5137 * @see MethodHandles#constant 5138 * @see MethodHandles#empty 5139 * @see MethodHandles#explicitCastArguments 5140 * @since 9 5141 */ 5142 public static MethodHandle zero(Class<?> type) { 5143 Objects.requireNonNull(type); 5144 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5145 } 5146 5147 private static MethodHandle identityOrVoid(Class<?> type) { 5148 return type == void.class ? zero(type) : identity(type); 5149 } 5150 5151 /** 5152 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5153 * and returns a suitable default depending on the return type. 5154 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5155 * <p>The returned method handle is equivalent to 5156 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5157 * 5158 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5159 * {@code guardWithTest(pred, target, empty(target.type())}. 5160 * @param type the type of the desired method handle 5161 * @return a constant method handle of the given type, which returns a default value of the given return type 5162 * @throws NullPointerException if the argument is null 5163 * @see MethodHandles#zero 5164 * @see MethodHandles#constant 5165 * @since 9 5166 */ 5167 public static MethodHandle empty(MethodType type) { 5168 Objects.requireNonNull(type); 5169 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5170 } 5171 5172 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5173 private static MethodHandle makeIdentity(Class<?> ptype) { 5174 MethodType mtype = methodType(ptype, ptype); 5175 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5176 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5177 } 5178 5179 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5180 int pos = btw.ordinal(); 5181 MethodHandle zero = ZERO_MHS[pos]; 5182 if (zero == null) { 5183 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5184 } 5185 if (zero.type().returnType() == rtype) 5186 return zero; 5187 assert(btw == Wrapper.OBJECT); 5188 return makeZero(rtype); 5189 } 5190 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5191 private static MethodHandle makeZero(Class<?> rtype) { 5192 MethodType mtype = methodType(rtype); 5193 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5194 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5195 } 5196 5197 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5198 // Simulate a CAS, to avoid racy duplication of results. 5199 MethodHandle prev = cache[pos]; 5200 if (prev != null) return prev; 5201 return cache[pos] = value; 5202 } 5203 5204 /** 5205 * Provides a target method handle with one or more <em>bound arguments</em> 5206 * in advance of the method handle's invocation. 5207 * The formal parameters to the target corresponding to the bound 5208 * arguments are called <em>bound parameters</em>. 5209 * Returns a new method handle which saves away the bound arguments. 5210 * When it is invoked, it receives arguments for any non-bound parameters, 5211 * binds the saved arguments to their corresponding parameters, 5212 * and calls the original target. 5213 * <p> 5214 * The type of the new method handle will drop the types for the bound 5215 * parameters from the original target type, since the new method handle 5216 * will no longer require those arguments to be supplied by its callers. 5217 * <p> 5218 * Each given argument object must match the corresponding bound parameter type. 5219 * If a bound parameter type is a primitive, the argument object 5220 * must be a wrapper, and will be unboxed to produce the primitive value. 5221 * <p> 5222 * The {@code pos} argument selects which parameters are to be bound. 5223 * It may range between zero and <i>N-L</i> (inclusively), 5224 * where <i>N</i> is the arity of the target method handle 5225 * and <i>L</i> is the length of the values array. 5226 * <p> 5227 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5228 * variable-arity method handle}, even if the original target method handle was. 5229 * @param target the method handle to invoke after the argument is inserted 5230 * @param pos where to insert the argument (zero for the first) 5231 * @param values the series of arguments to insert 5232 * @return a method handle which inserts an additional argument, 5233 * before calling the original method handle 5234 * @throws NullPointerException if the target or the {@code values} array is null 5235 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 5236 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5237 * is the length of the values array. 5238 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5239 * type. 5240 * @see MethodHandle#bindTo 5241 */ 5242 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5243 int insCount = values.length; 5244 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5245 if (insCount == 0) return target; 5246 BoundMethodHandle result = target.rebind(); 5247 for (int i = 0; i < insCount; i++) { 5248 Object value = values[i]; 5249 Class<?> ptype = ptypes[pos+i]; 5250 if (ptype.isPrimitive()) { 5251 result = insertArgumentPrimitive(result, pos, ptype, value); 5252 } else { 5253 value = ptype.cast(value); // throw CCE if needed 5254 result = result.bindArgumentL(pos, value); 5255 } 5256 } 5257 return result; 5258 } 5259 5260 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5261 Class<?> ptype, Object value) { 5262 Wrapper w = Wrapper.forPrimitiveType(ptype); 5263 // perform unboxing and/or primitive conversion 5264 value = w.convert(value, ptype); 5265 return switch (w) { 5266 case INT -> result.bindArgumentI(pos, (int) value); 5267 case LONG -> result.bindArgumentJ(pos, (long) value); 5268 case FLOAT -> result.bindArgumentF(pos, (float) value); 5269 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5270 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5271 }; 5272 } 5273 5274 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5275 MethodType oldType = target.type(); 5276 int outargs = oldType.parameterCount(); 5277 int inargs = outargs - insCount; 5278 if (inargs < 0) 5279 throw newIllegalArgumentException("too many values to insert"); 5280 if (pos < 0 || pos > inargs) 5281 throw newIllegalArgumentException("no argument type to append"); 5282 return oldType.ptypes(); 5283 } 5284 5285 /** 5286 * Produces a method handle which will discard some dummy arguments 5287 * before calling some other specified <i>target</i> method handle. 5288 * The type of the new method handle will be the same as the target's type, 5289 * except it will also include the dummy argument types, 5290 * at some given position. 5291 * <p> 5292 * The {@code pos} argument may range between zero and <i>N</i>, 5293 * where <i>N</i> is the arity of the target. 5294 * If {@code pos} is zero, the dummy arguments will precede 5295 * the target's real arguments; if {@code pos} is <i>N</i> 5296 * they will come after. 5297 * <p> 5298 * <b>Example:</b> 5299 * {@snippet lang="java" : 5300 import static java.lang.invoke.MethodHandles.*; 5301 import static java.lang.invoke.MethodType.*; 5302 ... 5303 MethodHandle cat = lookup().findVirtual(String.class, 5304 "concat", methodType(String.class, String.class)); 5305 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5306 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5307 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5308 assertEquals(bigType, d0.type()); 5309 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5310 * } 5311 * <p> 5312 * This method is also equivalent to the following code: 5313 * <blockquote><pre> 5314 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5315 * </pre></blockquote> 5316 * @param target the method handle to invoke after the arguments are dropped 5317 * @param pos position of first argument to drop (zero for the leftmost) 5318 * @param valueTypes the type(s) of the argument(s) to drop 5319 * @return a method handle which drops arguments of the given types, 5320 * before calling the original method handle 5321 * @throws NullPointerException if the target is null, 5322 * or if the {@code valueTypes} list or any of its elements is null 5323 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5324 * or if {@code pos} is negative or greater than the arity of the target, 5325 * or if the new method handle's type would have too many parameters 5326 */ 5327 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5328 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5329 } 5330 5331 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5332 MethodType oldType = target.type(); // get NPE 5333 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5334 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5335 if (dropped == 0) return target; 5336 BoundMethodHandle result = target.rebind(); 5337 LambdaForm lform = result.form; 5338 int insertFormArg = 1 + pos; 5339 for (Class<?> ptype : valueTypes) { 5340 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5341 } 5342 result = result.copyWith(newType, lform); 5343 return result; 5344 } 5345 5346 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5347 int dropped = valueTypes.length; 5348 MethodType.checkSlotCount(dropped); 5349 int outargs = oldType.parameterCount(); 5350 int inargs = outargs + dropped; 5351 if (pos < 0 || pos > outargs) 5352 throw newIllegalArgumentException("no argument type to remove" 5353 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5354 ); 5355 return dropped; 5356 } 5357 5358 /** 5359 * Produces a method handle which will discard some dummy arguments 5360 * before calling some other specified <i>target</i> method handle. 5361 * The type of the new method handle will be the same as the target's type, 5362 * except it will also include the dummy argument types, 5363 * at some given position. 5364 * <p> 5365 * The {@code pos} argument may range between zero and <i>N</i>, 5366 * where <i>N</i> is the arity of the target. 5367 * If {@code pos} is zero, the dummy arguments will precede 5368 * the target's real arguments; if {@code pos} is <i>N</i> 5369 * they will come after. 5370 * @apiNote 5371 * {@snippet lang="java" : 5372 import static java.lang.invoke.MethodHandles.*; 5373 import static java.lang.invoke.MethodType.*; 5374 ... 5375 MethodHandle cat = lookup().findVirtual(String.class, 5376 "concat", methodType(String.class, String.class)); 5377 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5378 MethodHandle d0 = dropArguments(cat, 0, String.class); 5379 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5380 MethodHandle d1 = dropArguments(cat, 1, String.class); 5381 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5382 MethodHandle d2 = dropArguments(cat, 2, String.class); 5383 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5384 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5385 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5386 * } 5387 * <p> 5388 * This method is also equivalent to the following code: 5389 * <blockquote><pre> 5390 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5391 * </pre></blockquote> 5392 * @param target the method handle to invoke after the arguments are dropped 5393 * @param pos position of first argument to drop (zero for the leftmost) 5394 * @param valueTypes the type(s) of the argument(s) to drop 5395 * @return a method handle which drops arguments of the given types, 5396 * before calling the original method handle 5397 * @throws NullPointerException if the target is null, 5398 * or if the {@code valueTypes} array or any of its elements is null 5399 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5400 * or if {@code pos} is negative or greater than the arity of the target, 5401 * or if the new method handle's type would have 5402 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5403 */ 5404 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5405 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5406 } 5407 5408 /* Convenience overloads for trusting internal low-arity call-sites */ 5409 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5410 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5411 } 5412 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5413 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5414 } 5415 5416 // private version which allows caller some freedom with error handling 5417 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5418 boolean nullOnFailure) { 5419 Class<?>[] oldTypes = target.type().ptypes(); 5420 int match = oldTypes.length; 5421 if (skip != 0) { 5422 if (skip < 0 || skip > match) { 5423 throw newIllegalArgumentException("illegal skip", skip, target); 5424 } 5425 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5426 match -= skip; 5427 } 5428 Class<?>[] addTypes = newTypes; 5429 int add = addTypes.length; 5430 if (pos != 0) { 5431 if (pos < 0 || pos > add) { 5432 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5433 } 5434 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5435 add -= pos; 5436 assert(addTypes.length == add); 5437 } 5438 // Do not add types which already match the existing arguments. 5439 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5440 if (nullOnFailure) { 5441 return null; 5442 } 5443 throw newIllegalArgumentException("argument lists do not match", 5444 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5445 } 5446 addTypes = Arrays.copyOfRange(addTypes, match, add); 5447 add -= match; 5448 assert(addTypes.length == add); 5449 // newTypes: ( P*[pos], M*[match], A*[add] ) 5450 // target: ( S*[skip], M*[match] ) 5451 MethodHandle adapter = target; 5452 if (add > 0) { 5453 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5454 } 5455 // adapter: (S*[skip], M*[match], A*[add] ) 5456 if (pos > 0) { 5457 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5458 } 5459 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5460 return adapter; 5461 } 5462 5463 /** 5464 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5465 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5466 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5467 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5468 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5469 * {@link #dropArguments(MethodHandle, int, Class[])}. 5470 * <p> 5471 * The resulting handle will have the same return type as the target handle. 5472 * <p> 5473 * In more formal terms, assume these two type lists:<ul> 5474 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5475 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5476 * {@code newTypes}. 5477 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5478 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5479 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5480 * sub-list. 5481 * </ul> 5482 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5483 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5484 * {@link #dropArguments(MethodHandle, int, Class[])}. 5485 * 5486 * @apiNote 5487 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5488 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5489 * {@snippet lang="java" : 5490 import static java.lang.invoke.MethodHandles.*; 5491 import static java.lang.invoke.MethodType.*; 5492 ... 5493 ... 5494 MethodHandle h0 = constant(boolean.class, true); 5495 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5496 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5497 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5498 if (h1.type().parameterCount() < h2.type().parameterCount()) 5499 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5500 else 5501 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5502 MethodHandle h3 = guardWithTest(h0, h1, h2); 5503 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5504 * } 5505 * @param target the method handle to adapt 5506 * @param skip number of targets parameters to disregard (they will be unchanged) 5507 * @param newTypes the list of types to match {@code target}'s parameter type list to 5508 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5509 * @return a possibly adapted method handle 5510 * @throws NullPointerException if either argument is null 5511 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5512 * or if {@code skip} is negative or greater than the arity of the target, 5513 * or if {@code pos} is negative or greater than the newTypes list size, 5514 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5515 * {@code pos}. 5516 * @since 9 5517 */ 5518 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5519 Objects.requireNonNull(target); 5520 Objects.requireNonNull(newTypes); 5521 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5522 } 5523 5524 /** 5525 * Drop the return value of the target handle (if any). 5526 * The returned method handle will have a {@code void} return type. 5527 * 5528 * @param target the method handle to adapt 5529 * @return a possibly adapted method handle 5530 * @throws NullPointerException if {@code target} is null 5531 * @since 16 5532 */ 5533 public static MethodHandle dropReturn(MethodHandle target) { 5534 Objects.requireNonNull(target); 5535 MethodType oldType = target.type(); 5536 Class<?> oldReturnType = oldType.returnType(); 5537 if (oldReturnType == void.class) 5538 return target; 5539 MethodType newType = oldType.changeReturnType(void.class); 5540 BoundMethodHandle result = target.rebind(); 5541 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5542 result = result.copyWith(newType, lform); 5543 return result; 5544 } 5545 5546 /** 5547 * Adapts a target method handle by pre-processing 5548 * one or more of its arguments, each with its own unary filter function, 5549 * and then calling the target with each pre-processed argument 5550 * replaced by the result of its corresponding filter function. 5551 * <p> 5552 * The pre-processing is performed by one or more method handles, 5553 * specified in the elements of the {@code filters} array. 5554 * The first element of the filter array corresponds to the {@code pos} 5555 * argument of the target, and so on in sequence. 5556 * The filter functions are invoked in left to right order. 5557 * <p> 5558 * Null arguments in the array are treated as identity functions, 5559 * and the corresponding arguments left unchanged. 5560 * (If there are no non-null elements in the array, the original target is returned.) 5561 * Each filter is applied to the corresponding argument of the adapter. 5562 * <p> 5563 * If a filter {@code F} applies to the {@code N}th argument of 5564 * the target, then {@code F} must be a method handle which 5565 * takes exactly one argument. The type of {@code F}'s sole argument 5566 * replaces the corresponding argument type of the target 5567 * in the resulting adapted method handle. 5568 * The return type of {@code F} must be identical to the corresponding 5569 * parameter type of the target. 5570 * <p> 5571 * It is an error if there are elements of {@code filters} 5572 * (null or not) 5573 * which do not correspond to argument positions in the target. 5574 * <p><b>Example:</b> 5575 * {@snippet lang="java" : 5576 import static java.lang.invoke.MethodHandles.*; 5577 import static java.lang.invoke.MethodType.*; 5578 ... 5579 MethodHandle cat = lookup().findVirtual(String.class, 5580 "concat", methodType(String.class, String.class)); 5581 MethodHandle upcase = lookup().findVirtual(String.class, 5582 "toUpperCase", methodType(String.class)); 5583 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5584 MethodHandle f0 = filterArguments(cat, 0, upcase); 5585 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5586 MethodHandle f1 = filterArguments(cat, 1, upcase); 5587 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5588 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5589 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5590 * } 5591 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5592 * denotes the return type of both the {@code target} and resulting adapter. 5593 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5594 * of the parameters and arguments that precede and follow the filter position 5595 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5596 * values of the filtered parameters and arguments; they also represent the 5597 * return types of the {@code filter[i]} handles. The latter accept arguments 5598 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5599 * the resulting adapter. 5600 * {@snippet lang="java" : 5601 * T target(P... p, A[i]... a[i], B... b); 5602 * A[i] filter[i](V[i]); 5603 * T adapter(P... p, V[i]... v[i], B... b) { 5604 * return target(p..., filter[i](v[i])..., b...); 5605 * } 5606 * } 5607 * <p> 5608 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5609 * variable-arity method handle}, even if the original target method handle was. 5610 * 5611 * @param target the method handle to invoke after arguments are filtered 5612 * @param pos the position of the first argument to filter 5613 * @param filters method handles to call initially on filtered arguments 5614 * @return method handle which incorporates the specified argument filtering logic 5615 * @throws NullPointerException if the target is null 5616 * or if the {@code filters} array is null 5617 * @throws IllegalArgumentException if a non-null element of {@code filters} 5618 * does not match a corresponding argument type of target as described above, 5619 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5620 * or if the resulting method handle's type would have 5621 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5622 */ 5623 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5624 // In method types arguments start at index 0, while the LF 5625 // editor have the MH receiver at position 0 - adjust appropriately. 5626 final int MH_RECEIVER_OFFSET = 1; 5627 filterArgumentsCheckArity(target, pos, filters); 5628 MethodHandle adapter = target; 5629 5630 // keep track of currently matched filters, as to optimize repeated filters 5631 int index = 0; 5632 int[] positions = new int[filters.length]; 5633 MethodHandle filter = null; 5634 5635 // process filters in reverse order so that the invocation of 5636 // the resulting adapter will invoke the filters in left-to-right order 5637 for (int i = filters.length - 1; i >= 0; --i) { 5638 MethodHandle newFilter = filters[i]; 5639 if (newFilter == null) continue; // ignore null elements of filters 5640 5641 // flush changes on update 5642 if (filter != newFilter) { 5643 if (filter != null) { 5644 if (index > 1) { 5645 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5646 } else { 5647 adapter = filterArgument(adapter, positions[0] - 1, filter); 5648 } 5649 } 5650 filter = newFilter; 5651 index = 0; 5652 } 5653 5654 filterArgumentChecks(target, pos + i, newFilter); 5655 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5656 } 5657 if (index > 1) { 5658 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5659 } else if (index == 1) { 5660 adapter = filterArgument(adapter, positions[0] - 1, filter); 5661 } 5662 return adapter; 5663 } 5664 5665 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5666 MethodType targetType = adapter.type(); 5667 MethodType filterType = filter.type(); 5668 BoundMethodHandle result = adapter.rebind(); 5669 Class<?> newParamType = filterType.parameterType(0); 5670 5671 Class<?>[] ptypes = targetType.ptypes().clone(); 5672 for (int pos : positions) { 5673 ptypes[pos - 1] = newParamType; 5674 } 5675 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5676 5677 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5678 return result.copyWithExtendL(newType, lform, filter); 5679 } 5680 5681 /*non-public*/ 5682 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5683 filterArgumentChecks(target, pos, filter); 5684 MethodType targetType = target.type(); 5685 MethodType filterType = filter.type(); 5686 BoundMethodHandle result = target.rebind(); 5687 Class<?> newParamType = filterType.parameterType(0); 5688 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5689 MethodType newType = targetType.changeParameterType(pos, newParamType); 5690 result = result.copyWithExtendL(newType, lform, filter); 5691 return result; 5692 } 5693 5694 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5695 MethodType targetType = target.type(); 5696 int maxPos = targetType.parameterCount(); 5697 if (pos + filters.length > maxPos) 5698 throw newIllegalArgumentException("too many filters"); 5699 } 5700 5701 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5702 MethodType targetType = target.type(); 5703 MethodType filterType = filter.type(); 5704 if (filterType.parameterCount() != 1 5705 || filterType.returnType() != targetType.parameterType(pos)) 5706 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5707 } 5708 5709 /** 5710 * Adapts a target method handle by pre-processing 5711 * a sub-sequence of its arguments with a filter (another method handle). 5712 * The pre-processed arguments are replaced by the result (if any) of the 5713 * filter function. 5714 * The target is then called on the modified (usually shortened) argument list. 5715 * <p> 5716 * If the filter returns a value, the target must accept that value as 5717 * its argument in position {@code pos}, preceded and/or followed by 5718 * any arguments not passed to the filter. 5719 * If the filter returns void, the target must accept all arguments 5720 * not passed to the filter. 5721 * No arguments are reordered, and a result returned from the filter 5722 * replaces (in order) the whole subsequence of arguments originally 5723 * passed to the adapter. 5724 * <p> 5725 * The argument types (if any) of the filter 5726 * replace zero or one argument types of the target, at position {@code pos}, 5727 * in the resulting adapted method handle. 5728 * The return type of the filter (if any) must be identical to the 5729 * argument type of the target at position {@code pos}, and that target argument 5730 * is supplied by the return value of the filter. 5731 * <p> 5732 * In all cases, {@code pos} must be greater than or equal to zero, and 5733 * {@code pos} must also be less than or equal to the target's arity. 5734 * <p><b>Example:</b> 5735 * {@snippet lang="java" : 5736 import static java.lang.invoke.MethodHandles.*; 5737 import static java.lang.invoke.MethodType.*; 5738 ... 5739 MethodHandle deepToString = publicLookup() 5740 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5741 5742 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5743 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5744 5745 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5746 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5747 5748 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5749 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5750 assertEquals("[top, [up, down], strange]", 5751 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5752 5753 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5754 assertEquals("[top, [up, down], [strange]]", 5755 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5756 5757 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5758 assertEquals("[top, [[up, down, strange], charm], bottom]", 5759 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5760 * } 5761 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5762 * represents the return type of the {@code target} and resulting adapter. 5763 * {@code V}/{@code v} stand for the return type and value of the 5764 * {@code filter}, which are also found in the signature and arguments of 5765 * the {@code target}, respectively, unless {@code V} is {@code void}. 5766 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5767 * and values preceding and following the collection position, {@code pos}, 5768 * in the {@code target}'s signature. They also turn up in the resulting 5769 * adapter's signature and arguments, where they surround 5770 * {@code B}/{@code b}, which represent the parameter types and arguments 5771 * to the {@code filter} (if any). 5772 * {@snippet lang="java" : 5773 * T target(A...,V,C...); 5774 * V filter(B...); 5775 * T adapter(A... a,B... b,C... c) { 5776 * V v = filter(b...); 5777 * return target(a...,v,c...); 5778 * } 5779 * // and if the filter has no arguments: 5780 * T target2(A...,V,C...); 5781 * V filter2(); 5782 * T adapter2(A... a,C... c) { 5783 * V v = filter2(); 5784 * return target2(a...,v,c...); 5785 * } 5786 * // and if the filter has a void return: 5787 * T target3(A...,C...); 5788 * void filter3(B...); 5789 * T adapter3(A... a,B... b,C... c) { 5790 * filter3(b...); 5791 * return target3(a...,c...); 5792 * } 5793 * } 5794 * <p> 5795 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5796 * one which first "folds" the affected arguments, and then drops them, in separate 5797 * steps as follows: 5798 * {@snippet lang="java" : 5799 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5800 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5801 * } 5802 * If the target method handle consumes no arguments besides than the result 5803 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5804 * is equivalent to {@code filterReturnValue(coll, mh)}. 5805 * If the filter method handle {@code coll} consumes one argument and produces 5806 * a non-void result, then {@code collectArguments(mh, N, coll)} 5807 * is equivalent to {@code filterArguments(mh, N, coll)}. 5808 * Other equivalences are possible but would require argument permutation. 5809 * <p> 5810 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5811 * variable-arity method handle}, even if the original target method handle was. 5812 * 5813 * @param target the method handle to invoke after filtering the subsequence of arguments 5814 * @param pos the position of the first adapter argument to pass to the filter, 5815 * and/or the target argument which receives the result of the filter 5816 * @param filter method handle to call on the subsequence of arguments 5817 * @return method handle which incorporates the specified argument subsequence filtering logic 5818 * @throws NullPointerException if either argument is null 5819 * @throws IllegalArgumentException if the return type of {@code filter} 5820 * is non-void and is not the same as the {@code pos} argument of the target, 5821 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5822 * or if the resulting method handle's type would have 5823 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5824 * @see MethodHandles#foldArguments 5825 * @see MethodHandles#filterArguments 5826 * @see MethodHandles#filterReturnValue 5827 */ 5828 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5829 MethodType newType = collectArgumentsChecks(target, pos, filter); 5830 MethodType collectorType = filter.type(); 5831 BoundMethodHandle result = target.rebind(); 5832 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5833 return result.copyWithExtendL(newType, lform, filter); 5834 } 5835 5836 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5837 MethodType targetType = target.type(); 5838 MethodType filterType = filter.type(); 5839 Class<?> rtype = filterType.returnType(); 5840 Class<?>[] filterArgs = filterType.ptypes(); 5841 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5842 (rtype != void.class && pos >= targetType.parameterCount())) { 5843 throw newIllegalArgumentException("position is out of range for target", target, pos); 5844 } 5845 if (rtype == void.class) { 5846 return targetType.insertParameterTypes(pos, filterArgs); 5847 } 5848 if (rtype != targetType.parameterType(pos)) { 5849 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5850 } 5851 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5852 } 5853 5854 /** 5855 * Adapts a target method handle by post-processing 5856 * its return value (if any) with a filter (another method handle). 5857 * The result of the filter is returned from the adapter. 5858 * <p> 5859 * If the target returns a value, the filter must accept that value as 5860 * its only argument. 5861 * If the target returns void, the filter must accept no arguments. 5862 * <p> 5863 * The return type of the filter 5864 * replaces the return type of the target 5865 * in the resulting adapted method handle. 5866 * The argument type of the filter (if any) must be identical to the 5867 * return type of the target. 5868 * <p><b>Example:</b> 5869 * {@snippet lang="java" : 5870 import static java.lang.invoke.MethodHandles.*; 5871 import static java.lang.invoke.MethodType.*; 5872 ... 5873 MethodHandle cat = lookup().findVirtual(String.class, 5874 "concat", methodType(String.class, String.class)); 5875 MethodHandle length = lookup().findVirtual(String.class, 5876 "length", methodType(int.class)); 5877 System.out.println((String) cat.invokeExact("x", "y")); // xy 5878 MethodHandle f0 = filterReturnValue(cat, length); 5879 System.out.println((int) f0.invokeExact("x", "y")); // 2 5880 * } 5881 * <p>Here is pseudocode for the resulting adapter. In the code, 5882 * {@code T}/{@code t} represent the result type and value of the 5883 * {@code target}; {@code V}, the result type of the {@code filter}; and 5884 * {@code A}/{@code a}, the types and values of the parameters and arguments 5885 * of the {@code target} as well as the resulting adapter. 5886 * {@snippet lang="java" : 5887 * T target(A...); 5888 * V filter(T); 5889 * V adapter(A... a) { 5890 * T t = target(a...); 5891 * return filter(t); 5892 * } 5893 * // and if the target has a void return: 5894 * void target2(A...); 5895 * V filter2(); 5896 * V adapter2(A... a) { 5897 * target2(a...); 5898 * return filter2(); 5899 * } 5900 * // and if the filter has a void return: 5901 * T target3(A...); 5902 * void filter3(V); 5903 * void adapter3(A... a) { 5904 * T t = target3(a...); 5905 * filter3(t); 5906 * } 5907 * } 5908 * <p> 5909 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5910 * variable-arity method handle}, even if the original target method handle was. 5911 * @param target the method handle to invoke before filtering the return value 5912 * @param filter method handle to call on the return value 5913 * @return method handle which incorporates the specified return value filtering logic 5914 * @throws NullPointerException if either argument is null 5915 * @throws IllegalArgumentException if the argument list of {@code filter} 5916 * does not match the return type of target as described above 5917 */ 5918 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5919 MethodType targetType = target.type(); 5920 MethodType filterType = filter.type(); 5921 filterReturnValueChecks(targetType, filterType); 5922 BoundMethodHandle result = target.rebind(); 5923 BasicType rtype = BasicType.basicType(filterType.returnType()); 5924 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5925 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5926 result = result.copyWithExtendL(newType, lform, filter); 5927 return result; 5928 } 5929 5930 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5931 Class<?> rtype = targetType.returnType(); 5932 int filterValues = filterType.parameterCount(); 5933 if (filterValues == 0 5934 ? (rtype != void.class) 5935 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5936 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5937 } 5938 5939 /** 5940 * Filter the return value of a target method handle with a filter function. The filter function is 5941 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5942 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5943 * as follows: 5944 * {@snippet lang="java" : 5945 * T target(A...) 5946 * V filter(B... , T) 5947 * V adapter(A... a, B... b) { 5948 * T t = target(a...); 5949 * return filter(b..., t); 5950 * } 5951 * } 5952 * <p> 5953 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5954 * 5955 * @param target the target method handle 5956 * @param filter the filter method handle 5957 * @return the adapter method handle 5958 */ 5959 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5960 MethodType targetType = target.type(); 5961 MethodType filterType = filter.type(); 5962 BoundMethodHandle result = target.rebind(); 5963 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5964 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5965 if (filterType.parameterCount() > 1) { 5966 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5967 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5968 } 5969 } 5970 result = result.copyWithExtendL(newType, lform, filter); 5971 return result; 5972 } 5973 5974 /** 5975 * Adapts a target method handle by pre-processing 5976 * some of its arguments, and then calling the target with 5977 * the result of the pre-processing, inserted into the original 5978 * sequence of arguments. 5979 * <p> 5980 * The pre-processing is performed by {@code combiner}, a second method handle. 5981 * Of the arguments passed to the adapter, the first {@code N} arguments 5982 * are copied to the combiner, which is then called. 5983 * (Here, {@code N} is defined as the parameter count of the combiner.) 5984 * After this, control passes to the target, with any result 5985 * from the combiner inserted before the original {@code N} incoming 5986 * arguments. 5987 * <p> 5988 * If the combiner returns a value, the first parameter type of the target 5989 * must be identical with the return type of the combiner, and the next 5990 * {@code N} parameter types of the target must exactly match the parameters 5991 * of the combiner. 5992 * <p> 5993 * If the combiner has a void return, no result will be inserted, 5994 * and the first {@code N} parameter types of the target 5995 * must exactly match the parameters of the combiner. 5996 * <p> 5997 * The resulting adapter is the same type as the target, except that the 5998 * first parameter type is dropped, 5999 * if it corresponds to the result of the combiner. 6000 * <p> 6001 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 6002 * that either the combiner or the target does not wish to receive. 6003 * If some of the incoming arguments are destined only for the combiner, 6004 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 6005 * arguments will not need to be live on the stack on entry to the 6006 * target.) 6007 * <p><b>Example:</b> 6008 * {@snippet lang="java" : 6009 import static java.lang.invoke.MethodHandles.*; 6010 import static java.lang.invoke.MethodType.*; 6011 ... 6012 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6013 "println", methodType(void.class, String.class)) 6014 .bindTo(System.out); 6015 MethodHandle cat = lookup().findVirtual(String.class, 6016 "concat", methodType(String.class, String.class)); 6017 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6018 MethodHandle catTrace = foldArguments(cat, trace); 6019 // also prints "boo": 6020 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6021 * } 6022 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6023 * represents the result type of the {@code target} and resulting adapter. 6024 * {@code V}/{@code v} represent the type and value of the parameter and argument 6025 * of {@code target} that precedes the folding position; {@code V} also is 6026 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6027 * types and values of the {@code N} parameters and arguments at the folding 6028 * position. {@code B}/{@code b} represent the types and values of the 6029 * {@code target} parameters and arguments that follow the folded parameters 6030 * and arguments. 6031 * {@snippet lang="java" : 6032 * // there are N arguments in A... 6033 * T target(V, A[N]..., B...); 6034 * V combiner(A...); 6035 * T adapter(A... a, B... b) { 6036 * V v = combiner(a...); 6037 * return target(v, a..., b...); 6038 * } 6039 * // and if the combiner has a void return: 6040 * T target2(A[N]..., B...); 6041 * void combiner2(A...); 6042 * T adapter2(A... a, B... b) { 6043 * combiner2(a...); 6044 * return target2(a..., b...); 6045 * } 6046 * } 6047 * <p> 6048 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6049 * variable-arity method handle}, even if the original target method handle was. 6050 * @param target the method handle to invoke after arguments are combined 6051 * @param combiner method handle to call initially on the incoming arguments 6052 * @return method handle which incorporates the specified argument folding logic 6053 * @throws NullPointerException if either argument is null 6054 * @throws IllegalArgumentException if {@code combiner}'s return type 6055 * is non-void and not the same as the first argument type of 6056 * the target, or if the initial {@code N} argument types 6057 * of the target 6058 * (skipping one matching the {@code combiner}'s return type) 6059 * are not identical with the argument types of {@code combiner} 6060 */ 6061 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 6062 return foldArguments(target, 0, combiner); 6063 } 6064 6065 /** 6066 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6067 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6068 * before the folded arguments. 6069 * <p> 6070 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6071 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6072 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6073 * 0. 6074 * 6075 * @apiNote Example: 6076 * {@snippet lang="java" : 6077 import static java.lang.invoke.MethodHandles.*; 6078 import static java.lang.invoke.MethodType.*; 6079 ... 6080 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6081 "println", methodType(void.class, String.class)) 6082 .bindTo(System.out); 6083 MethodHandle cat = lookup().findVirtual(String.class, 6084 "concat", methodType(String.class, String.class)); 6085 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6086 MethodHandle catTrace = foldArguments(cat, 1, trace); 6087 // also prints "jum": 6088 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6089 * } 6090 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6091 * represents the result type of the {@code target} and resulting adapter. 6092 * {@code V}/{@code v} represent the type and value of the parameter and argument 6093 * of {@code target} that precedes the folding position; {@code V} also is 6094 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6095 * types and values of the {@code N} parameters and arguments at the folding 6096 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6097 * and values of the {@code target} parameters and arguments that precede and 6098 * follow the folded parameters and arguments starting at {@code pos}, 6099 * respectively. 6100 * {@snippet lang="java" : 6101 * // there are N arguments in A... 6102 * T target(Z..., V, A[N]..., B...); 6103 * V combiner(A...); 6104 * T adapter(Z... z, A... a, B... b) { 6105 * V v = combiner(a...); 6106 * return target(z..., v, a..., b...); 6107 * } 6108 * // and if the combiner has a void return: 6109 * T target2(Z..., A[N]..., B...); 6110 * void combiner2(A...); 6111 * T adapter2(Z... z, A... a, B... b) { 6112 * combiner2(a...); 6113 * return target2(z..., a..., b...); 6114 * } 6115 * } 6116 * <p> 6117 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6118 * variable-arity method handle}, even if the original target method handle was. 6119 * 6120 * @param target the method handle to invoke after arguments are combined 6121 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6122 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6123 * @param combiner method handle to call initially on the incoming arguments 6124 * @return method handle which incorporates the specified argument folding logic 6125 * @throws NullPointerException if either argument is null 6126 * @throws IllegalArgumentException if either of the following two conditions holds: 6127 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6128 * {@code pos} of the target signature; 6129 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6130 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6131 * 6132 * @see #foldArguments(MethodHandle, MethodHandle) 6133 * @since 9 6134 */ 6135 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6136 MethodType targetType = target.type(); 6137 MethodType combinerType = combiner.type(); 6138 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6139 BoundMethodHandle result = target.rebind(); 6140 boolean dropResult = rtype == void.class; 6141 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6142 MethodType newType = targetType; 6143 if (!dropResult) { 6144 newType = newType.dropParameterTypes(pos, pos + 1); 6145 } 6146 result = result.copyWithExtendL(newType, lform, combiner); 6147 return result; 6148 } 6149 6150 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6151 int foldArgs = combinerType.parameterCount(); 6152 Class<?> rtype = combinerType.returnType(); 6153 int foldVals = rtype == void.class ? 0 : 1; 6154 int afterInsertPos = foldPos + foldVals; 6155 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6156 if (ok) { 6157 for (int i = 0; i < foldArgs; i++) { 6158 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6159 ok = false; 6160 break; 6161 } 6162 } 6163 } 6164 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6165 ok = false; 6166 if (!ok) 6167 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6168 return rtype; 6169 } 6170 6171 /** 6172 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6173 * of the pre-processing replacing the argument at the given position. 6174 * 6175 * @param target the method handle to invoke after arguments are combined 6176 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6177 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6178 * @param combiner method handle to call initially on the incoming arguments 6179 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6180 * @return method handle which incorporates the specified argument folding logic 6181 * @throws NullPointerException if either argument is null 6182 * @throws IllegalArgumentException if either of the following two conditions holds: 6183 * (1) {@code combiner}'s return type is not the same as the argument type at position 6184 * {@code pos} of the target signature; 6185 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6186 * not identical with the argument types of {@code combiner}. 6187 */ 6188 /*non-public*/ 6189 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6190 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6191 } 6192 6193 /** 6194 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6195 * the pre-processing inserted into the original sequence of arguments at the given position. 6196 * 6197 * @param target the method handle to invoke after arguments are combined 6198 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6199 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6200 * @param combiner method handle to call initially on the incoming arguments 6201 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6202 * @return method handle which incorporates the specified argument folding logic 6203 * @throws NullPointerException if either argument is null 6204 * @throws IllegalArgumentException if either of the following two conditions holds: 6205 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6206 * {@code pos} of the target signature; 6207 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6208 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6209 * with the argument types of {@code combiner}. 6210 */ 6211 /*non-public*/ 6212 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6213 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6214 } 6215 6216 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6217 MethodType targetType = target.type(); 6218 MethodType combinerType = combiner.type(); 6219 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6220 BoundMethodHandle result = target.rebind(); 6221 6222 MethodType newType = targetType; 6223 LambdaForm lform; 6224 if (filter) { 6225 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6226 } else { 6227 boolean dropResult = rtype == void.class; 6228 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6229 if (!dropResult) { 6230 newType = newType.dropParameterTypes(position, position + 1); 6231 } 6232 } 6233 result = result.copyWithExtendL(newType, lform, combiner); 6234 return result; 6235 } 6236 6237 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6238 int combinerArgs = combinerType.parameterCount(); 6239 if (argPos.length != combinerArgs) { 6240 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6241 } 6242 Class<?> rtype = combinerType.returnType(); 6243 6244 for (int i = 0; i < combinerArgs; i++) { 6245 int arg = argPos[i]; 6246 if (arg < 0 || arg > targetType.parameterCount()) { 6247 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6248 } 6249 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6250 throw newIllegalArgumentException("target argument type at position " + arg 6251 + " must match combiner argument type at index " + i + ": " + targetType 6252 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6253 } 6254 } 6255 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6256 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6257 } 6258 return rtype; 6259 } 6260 6261 /** 6262 * Makes a method handle which adapts a target method handle, 6263 * by guarding it with a test, a boolean-valued method handle. 6264 * If the guard fails, a fallback handle is called instead. 6265 * All three method handles must have the same corresponding 6266 * argument and return types, except that the return type 6267 * of the test must be boolean, and the test is allowed 6268 * to have fewer arguments than the other two method handles. 6269 * <p> 6270 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6271 * represents the uniform result type of the three involved handles; 6272 * {@code A}/{@code a}, the types and values of the {@code target} 6273 * parameters and arguments that are consumed by the {@code test}; and 6274 * {@code B}/{@code b}, those types and values of the {@code target} 6275 * parameters and arguments that are not consumed by the {@code test}. 6276 * {@snippet lang="java" : 6277 * boolean test(A...); 6278 * T target(A...,B...); 6279 * T fallback(A...,B...); 6280 * T adapter(A... a,B... b) { 6281 * if (test(a...)) 6282 * return target(a..., b...); 6283 * else 6284 * return fallback(a..., b...); 6285 * } 6286 * } 6287 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6288 * be modified by execution of the test, and so are passed unchanged 6289 * from the caller to the target or fallback as appropriate. 6290 * @param test method handle used for test, must return boolean 6291 * @param target method handle to call if test passes 6292 * @param fallback method handle to call if test fails 6293 * @return method handle which incorporates the specified if/then/else logic 6294 * @throws NullPointerException if any argument is null 6295 * @throws IllegalArgumentException if {@code test} does not return boolean, 6296 * or if all three method types do not match (with the return 6297 * type of {@code test} changed to match that of the target). 6298 */ 6299 public static MethodHandle guardWithTest(MethodHandle test, 6300 MethodHandle target, 6301 MethodHandle fallback) { 6302 MethodType gtype = test.type(); 6303 MethodType ttype = target.type(); 6304 MethodType ftype = fallback.type(); 6305 if (!ttype.equals(ftype)) 6306 throw misMatchedTypes("target and fallback types", ttype, ftype); 6307 if (gtype.returnType() != boolean.class) 6308 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6309 6310 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6311 if (test == null) { 6312 throw misMatchedTypes("target and test types", ttype, gtype); 6313 } 6314 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6315 } 6316 6317 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6318 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6319 } 6320 6321 /** 6322 * Makes a method handle which adapts a target method handle, 6323 * by running it inside an exception handler. 6324 * If the target returns normally, the adapter returns that value. 6325 * If an exception matching the specified type is thrown, the fallback 6326 * handle is called instead on the exception, plus the original arguments. 6327 * <p> 6328 * The target and handler must have the same corresponding 6329 * argument and return types, except that handler may omit trailing arguments 6330 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6331 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6332 * <p> 6333 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6334 * represents the return type of the {@code target} and {@code handler}, 6335 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6336 * the types and values of arguments to the resulting handle consumed by 6337 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6338 * resulting handle discarded by {@code handler}. 6339 * {@snippet lang="java" : 6340 * T target(A..., B...); 6341 * T handler(ExType, A...); 6342 * T adapter(A... a, B... b) { 6343 * try { 6344 * return target(a..., b...); 6345 * } catch (ExType ex) { 6346 * return handler(ex, a...); 6347 * } 6348 * } 6349 * } 6350 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6351 * be modified by execution of the target, and so are passed unchanged 6352 * from the caller to the handler, if the handler is invoked. 6353 * <p> 6354 * The target and handler must return the same type, even if the handler 6355 * always throws. (This might happen, for instance, because the handler 6356 * is simulating a {@code finally} clause). 6357 * To create such a throwing handler, compose the handler creation logic 6358 * with {@link #throwException throwException}, 6359 * in order to create a method handle of the correct return type. 6360 * @param target method handle to call 6361 * @param exType the type of exception which the handler will catch 6362 * @param handler method handle to call if a matching exception is thrown 6363 * @return method handle which incorporates the specified try/catch logic 6364 * @throws NullPointerException if any argument is null 6365 * @throws IllegalArgumentException if {@code handler} does not accept 6366 * the given exception type, or if the method handle types do 6367 * not match in their return types and their 6368 * corresponding parameters 6369 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6370 */ 6371 public static MethodHandle catchException(MethodHandle target, 6372 Class<? extends Throwable> exType, 6373 MethodHandle handler) { 6374 MethodType ttype = target.type(); 6375 MethodType htype = handler.type(); 6376 if (!Throwable.class.isAssignableFrom(exType)) 6377 throw new ClassCastException(exType.getName()); 6378 if (htype.parameterCount() < 1 || 6379 !htype.parameterType(0).isAssignableFrom(exType)) 6380 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6381 if (htype.returnType() != ttype.returnType()) 6382 throw misMatchedTypes("target and handler return types", ttype, htype); 6383 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6384 if (handler == null) { 6385 throw misMatchedTypes("target and handler types", ttype, htype); 6386 } 6387 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6388 } 6389 6390 /** 6391 * Produces a method handle which will throw exceptions of the given {@code exType}. 6392 * The method handle will accept a single argument of {@code exType}, 6393 * and immediately throw it as an exception. 6394 * The method type will nominally specify a return of {@code returnType}. 6395 * The return type may be anything convenient: It doesn't matter to the 6396 * method handle's behavior, since it will never return normally. 6397 * @param returnType the return type of the desired method handle 6398 * @param exType the parameter type of the desired method handle 6399 * @return method handle which can throw the given exceptions 6400 * @throws NullPointerException if either argument is null 6401 */ 6402 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6403 if (!Throwable.class.isAssignableFrom(exType)) 6404 throw new ClassCastException(exType.getName()); 6405 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6406 } 6407 6408 /** 6409 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6410 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6411 * delivers the loop's result, which is the return value of the resulting handle. 6412 * <p> 6413 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6414 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6415 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6416 * terms of method handles, each clause will specify up to four independent actions:<ul> 6417 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6418 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6419 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6420 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6421 * </ul> 6422 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6423 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6424 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6425 * <p> 6426 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6427 * this case. See below for a detailed description. 6428 * <p> 6429 * <em>Parameters optional everywhere:</em> 6430 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6431 * As an exception, the init functions cannot take any {@code v} parameters, 6432 * because those values are not yet computed when the init functions are executed. 6433 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6434 * In fact, any clause function may take no arguments at all. 6435 * <p> 6436 * <em>Loop parameters:</em> 6437 * A clause function may take all the iteration variable values it is entitled to, in which case 6438 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6439 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6440 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6441 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6442 * init function is automatically a loop parameter {@code a}.) 6443 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6444 * These loop parameters act as loop-invariant values visible across the whole loop. 6445 * <p> 6446 * <em>Parameters visible everywhere:</em> 6447 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6448 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6449 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6450 * Most clause functions will not need all of this information, but they will be formally connected to it 6451 * as if by {@link #dropArguments}. 6452 * <a id="astar"></a> 6453 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6454 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6455 * In that notation, the general form of an init function parameter list 6456 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6457 * <p> 6458 * <em>Checking clause structure:</em> 6459 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6460 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6461 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6462 * met by the inputs to the loop combinator. 6463 * <p> 6464 * <em>Effectively identical sequences:</em> 6465 * <a id="effid"></a> 6466 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6467 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6468 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6469 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6470 * that longest list. 6471 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6472 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6473 * <p> 6474 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6475 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6476 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6477 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6478 * four. Padding takes place by appending elements to the array. 6479 * <li>Clauses with all {@code null}s are disregarded. 6480 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6481 * </ol> 6482 * <p> 6483 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6484 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6485 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6486 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6487 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6488 * iteration variable type. 6489 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6490 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6491 * </ol> 6492 * <p> 6493 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6494 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6495 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6496 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6497 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6498 * (These types will be checked in step 2, along with all the clause function types.) 6499 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6500 * <li>All of the collected parameter lists must be effectively identical. 6501 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6502 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6503 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6504 * the "internal parameter list". 6505 * </ul> 6506 * <p> 6507 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6508 * <li>Examine fini function return types, disregarding omitted fini functions. 6509 * <li>If there are no fini functions, the loop return type is {@code void}. 6510 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6511 * type. 6512 * </ol> 6513 * <p> 6514 * <em>Step 1D: Check other types.</em><ol type="a"> 6515 * <li>There must be at least one non-omitted pred function. 6516 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6517 * </ol> 6518 * <p> 6519 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6520 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6521 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6522 * (Note that their parameter lists are already effectively identical to this list.) 6523 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6524 * effectively identical to the internal parameter list {@code (V... A...)}. 6525 * </ol> 6526 * <p> 6527 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6528 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6529 * type. 6530 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6531 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6532 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6533 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6534 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6535 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6536 * loop return type. 6537 * </ol> 6538 * <p> 6539 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6540 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6541 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6542 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6543 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6544 * pad out the end of the list. 6545 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6546 * </ol> 6547 * <p> 6548 * <em>Final observations.</em><ol type="a"> 6549 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6550 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6551 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6552 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6553 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6554 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6555 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6556 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6557 * </ol> 6558 * <p> 6559 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6560 * <ul> 6561 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6562 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6563 * (Only one {@code Pn} has to be non-{@code null}.) 6564 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6565 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6566 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6567 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6568 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6569 * the resulting loop handle's parameter types {@code (A...)}. 6570 * </ul> 6571 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6572 * which is natural if most of the loop computation happens in the steps. For some loops, 6573 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6574 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6575 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6576 * where the init functions will need the extra parameters. For such reasons, the rules for 6577 * determining these parameters are as symmetric as possible, across all clause parts. 6578 * In general, the loop parameters function as common invariant values across the whole 6579 * loop, while the iteration variables function as common variant values, or (if there is 6580 * no step function) as internal loop invariant temporaries. 6581 * <p> 6582 * <em>Loop execution.</em><ol type="a"> 6583 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6584 * every clause function. These locals are loop invariant. 6585 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6586 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6587 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6588 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6589 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6590 * (in argument order). 6591 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6592 * returns {@code false}. 6593 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6594 * sequence {@code (v...)} of loop variables. 6595 * The updated value is immediately visible to all subsequent function calls. 6596 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6597 * (of type {@code R}) is returned from the loop as a whole. 6598 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6599 * except by throwing an exception. 6600 * </ol> 6601 * <p> 6602 * <em>Usage tips.</em> 6603 * <ul> 6604 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6605 * sometimes a step function only needs to observe the current value of its own variable. 6606 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6607 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6608 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6609 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6610 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6611 * <li>If some of the clause functions are virtual methods on an instance, the instance 6612 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6613 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6614 * will be the first iteration variable value, and it will be easy to use virtual 6615 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6616 * </ul> 6617 * <p> 6618 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6619 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6620 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6621 * {@snippet lang="java" : 6622 * V... init...(A...); 6623 * boolean pred...(V..., A...); 6624 * V... step...(V..., A...); 6625 * R fini...(V..., A...); 6626 * R loop(A... a) { 6627 * V... v... = init...(a...); 6628 * for (;;) { 6629 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6630 * v = s(v..., a...); 6631 * if (!p(v..., a...)) { 6632 * return f(v..., a...); 6633 * } 6634 * } 6635 * } 6636 * } 6637 * } 6638 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6639 * to their full length, even though individual clause functions may neglect to take them all. 6640 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6641 * 6642 * @apiNote Example: 6643 * {@snippet lang="java" : 6644 * // iterative implementation of the factorial function as a loop handle 6645 * static int one(int k) { return 1; } 6646 * static int inc(int i, int acc, int k) { return i + 1; } 6647 * static int mult(int i, int acc, int k) { return i * acc; } 6648 * static boolean pred(int i, int acc, int k) { return i < k; } 6649 * static int fin(int i, int acc, int k) { return acc; } 6650 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6651 * // null initializer for counter, should initialize to 0 6652 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6653 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6654 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6655 * assertEquals(120, loop.invoke(5)); 6656 * } 6657 * The same example, dropping arguments and using combinators: 6658 * {@snippet lang="java" : 6659 * // simplified implementation of the factorial function as a loop handle 6660 * static int inc(int i) { return i + 1; } // drop acc, k 6661 * static int mult(int i, int acc) { return i * acc; } //drop k 6662 * static boolean cmp(int i, int k) { return i < k; } 6663 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6664 * // null initializer for counter, should initialize to 0 6665 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6666 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6667 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6668 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6669 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6670 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6671 * assertEquals(720, loop.invoke(6)); 6672 * } 6673 * A similar example, using a helper object to hold a loop parameter: 6674 * {@snippet lang="java" : 6675 * // instance-based implementation of the factorial function as a loop handle 6676 * static class FacLoop { 6677 * final int k; 6678 * FacLoop(int k) { this.k = k; } 6679 * int inc(int i) { return i + 1; } 6680 * int mult(int i, int acc) { return i * acc; } 6681 * boolean pred(int i) { return i < k; } 6682 * int fin(int i, int acc) { return acc; } 6683 * } 6684 * // assume MH_FacLoop is a handle to the constructor 6685 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6686 * // null initializer for counter, should initialize to 0 6687 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6688 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6689 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6690 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6691 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6692 * assertEquals(5040, loop.invoke(7)); 6693 * } 6694 * 6695 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6696 * 6697 * @return a method handle embodying the looping behavior as defined by the arguments. 6698 * 6699 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6700 * 6701 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6702 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6703 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6704 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6705 * @since 9 6706 */ 6707 public static MethodHandle loop(MethodHandle[]... clauses) { 6708 // Step 0: determine clause structure. 6709 loopChecks0(clauses); 6710 6711 List<MethodHandle> init = new ArrayList<>(); 6712 List<MethodHandle> step = new ArrayList<>(); 6713 List<MethodHandle> pred = new ArrayList<>(); 6714 List<MethodHandle> fini = new ArrayList<>(); 6715 6716 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6717 init.add(clause[0]); // all clauses have at least length 1 6718 step.add(clause.length <= 1 ? null : clause[1]); 6719 pred.add(clause.length <= 2 ? null : clause[2]); 6720 fini.add(clause.length <= 3 ? null : clause[3]); 6721 }); 6722 6723 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6724 final int nclauses = init.size(); 6725 6726 // Step 1A: determine iteration variables (V...). 6727 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6728 for (int i = 0; i < nclauses; ++i) { 6729 MethodHandle in = init.get(i); 6730 MethodHandle st = step.get(i); 6731 if (in == null && st == null) { 6732 iterationVariableTypes.add(void.class); 6733 } else if (in != null && st != null) { 6734 loopChecks1a(i, in, st); 6735 iterationVariableTypes.add(in.type().returnType()); 6736 } else { 6737 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6738 } 6739 } 6740 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6741 6742 // Step 1B: determine loop parameters (A...). 6743 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6744 loopChecks1b(init, commonSuffix); 6745 6746 // Step 1C: determine loop return type. 6747 // Step 1D: check other types. 6748 // local variable required here; see JDK-8223553 6749 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6750 .map(MethodType::returnType); 6751 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6752 loopChecks1cd(pred, fini, loopReturnType); 6753 6754 // Step 2: determine parameter lists. 6755 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6756 commonParameterSequence.addAll(commonSuffix); 6757 loopChecks2(step, pred, fini, commonParameterSequence); 6758 // Step 3: fill in omitted functions. 6759 for (int i = 0; i < nclauses; ++i) { 6760 Class<?> t = iterationVariableTypes.get(i); 6761 if (init.get(i) == null) { 6762 init.set(i, empty(methodType(t, commonSuffix))); 6763 } 6764 if (step.get(i) == null) { 6765 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6766 } 6767 if (pred.get(i) == null) { 6768 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6769 } 6770 if (fini.get(i) == null) { 6771 fini.set(i, empty(methodType(t, commonParameterSequence))); 6772 } 6773 } 6774 6775 // Step 4: fill in missing parameter types. 6776 // Also convert all handles to fixed-arity handles. 6777 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6778 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6779 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6780 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6781 6782 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6783 allMatch(pl -> pl.equals(commonSuffix)); 6784 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6785 allMatch(pl -> pl.equals(commonParameterSequence)); 6786 6787 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6788 } 6789 6790 private static void loopChecks0(MethodHandle[][] clauses) { 6791 if (clauses == null || clauses.length == 0) { 6792 throw newIllegalArgumentException("null or no clauses passed"); 6793 } 6794 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6795 throw newIllegalArgumentException("null clauses are not allowed"); 6796 } 6797 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6798 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6799 } 6800 } 6801 6802 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6803 if (in.type().returnType() != st.type().returnType()) { 6804 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6805 st.type().returnType()); 6806 } 6807 } 6808 6809 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6810 return mhs.filter(Objects::nonNull) 6811 // take only those that can contribute to a common suffix because they are longer than the prefix 6812 .map(MethodHandle::type) 6813 .filter(t -> t.parameterCount() > skipSize) 6814 .max(Comparator.comparingInt(MethodType::parameterCount)) 6815 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6816 .orElse(List.of()); 6817 } 6818 6819 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6820 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6821 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6822 return longest1.size() >= longest2.size() ? longest1 : longest2; 6823 } 6824 6825 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6826 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6827 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6828 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6829 " (common suffix: " + commonSuffix + ")"); 6830 } 6831 } 6832 6833 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6834 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6835 anyMatch(t -> t != loopReturnType)) { 6836 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6837 loopReturnType + ")"); 6838 } 6839 6840 if (pred.stream().noneMatch(Objects::nonNull)) { 6841 throw newIllegalArgumentException("no predicate found", pred); 6842 } 6843 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6844 anyMatch(t -> t != boolean.class)) { 6845 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6846 } 6847 } 6848 6849 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6850 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6851 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6852 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6853 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6854 } 6855 } 6856 6857 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6858 return hs.stream().map(h -> { 6859 int pc = h.type().parameterCount(); 6860 int tpsize = targetParams.size(); 6861 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6862 }).toList(); 6863 } 6864 6865 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6866 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6867 } 6868 6869 /** 6870 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6871 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6872 * <p> 6873 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6874 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6875 * evaluates to {@code true}). 6876 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6877 * <p> 6878 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6879 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6880 * and updated with the value returned from its invocation. The result of loop execution will be 6881 * the final value of the additional loop-local variable (if present). 6882 * <p> 6883 * The following rules hold for these argument handles:<ul> 6884 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6885 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6886 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6887 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6888 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6889 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6890 * It will constrain the parameter lists of the other loop parts. 6891 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6892 * list {@code (A...)} is called the <em>external parameter list</em>. 6893 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6894 * additional state variable of the loop. 6895 * The body must both accept and return a value of this type {@code V}. 6896 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6897 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6898 * <a href="MethodHandles.html#effid">effectively identical</a> 6899 * to the external parameter list {@code (A...)}. 6900 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6901 * {@linkplain #empty default value}. 6902 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6903 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6904 * effectively identical to the internal parameter list. 6905 * </ul> 6906 * <p> 6907 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6908 * <li>The loop handle's result type is the result type {@code V} of the body. 6909 * <li>The loop handle's parameter types are the types {@code (A...)}, 6910 * from the external parameter list. 6911 * </ul> 6912 * <p> 6913 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6914 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6915 * passed to the loop. 6916 * {@snippet lang="java" : 6917 * V init(A...); 6918 * boolean pred(V, A...); 6919 * V body(V, A...); 6920 * V whileLoop(A... a...) { 6921 * V v = init(a...); 6922 * while (pred(v, a...)) { 6923 * v = body(v, a...); 6924 * } 6925 * return v; 6926 * } 6927 * } 6928 * 6929 * @apiNote Example: 6930 * {@snippet lang="java" : 6931 * // implement the zip function for lists as a loop handle 6932 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6933 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6934 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6935 * zip.add(a.next()); 6936 * zip.add(b.next()); 6937 * return zip; 6938 * } 6939 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6940 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6941 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6942 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6943 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6944 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6945 * } 6946 * 6947 * 6948 * @apiNote The implementation of this method can be expressed as follows: 6949 * {@snippet lang="java" : 6950 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6951 * MethodHandle fini = (body.type().returnType() == void.class 6952 * ? null : identity(body.type().returnType())); 6953 * MethodHandle[] 6954 * checkExit = { null, null, pred, fini }, 6955 * varBody = { init, body }; 6956 * return loop(checkExit, varBody); 6957 * } 6958 * } 6959 * 6960 * @param init optional initializer, providing the initial value of the loop variable. 6961 * May be {@code null}, implying a default initial value. See above for other constraints. 6962 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6963 * above for other constraints. 6964 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6965 * See above for other constraints. 6966 * 6967 * @return a method handle implementing the {@code while} loop as described by the arguments. 6968 * @throws IllegalArgumentException if the rules for the arguments are violated. 6969 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6970 * 6971 * @see #loop(MethodHandle[][]) 6972 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6973 * @since 9 6974 */ 6975 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6976 whileLoopChecks(init, pred, body); 6977 MethodHandle fini = identityOrVoid(body.type().returnType()); 6978 MethodHandle[] checkExit = { null, null, pred, fini }; 6979 MethodHandle[] varBody = { init, body }; 6980 return loop(checkExit, varBody); 6981 } 6982 6983 /** 6984 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6985 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6986 * <p> 6987 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6988 * method will, in each iteration, first execute its body and then evaluate the predicate. 6989 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6990 * <p> 6991 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6992 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6993 * and updated with the value returned from its invocation. The result of loop execution will be 6994 * the final value of the additional loop-local variable (if present). 6995 * <p> 6996 * The following rules hold for these argument handles:<ul> 6997 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6998 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6999 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7000 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 7001 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 7002 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 7003 * It will constrain the parameter lists of the other loop parts. 7004 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 7005 * list {@code (A...)} is called the <em>external parameter list</em>. 7006 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7007 * additional state variable of the loop. 7008 * The body must both accept and return a value of this type {@code V}. 7009 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7010 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7011 * <a href="MethodHandles.html#effid">effectively identical</a> 7012 * to the external parameter list {@code (A...)}. 7013 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7014 * {@linkplain #empty default value}. 7015 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 7016 * Its parameter list (either empty or of the form {@code (V A*)}) must be 7017 * effectively identical to the internal parameter list. 7018 * </ul> 7019 * <p> 7020 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7021 * <li>The loop handle's result type is the result type {@code V} of the body. 7022 * <li>The loop handle's parameter types are the types {@code (A...)}, 7023 * from the external parameter list. 7024 * </ul> 7025 * <p> 7026 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7027 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 7028 * passed to the loop. 7029 * {@snippet lang="java" : 7030 * V init(A...); 7031 * boolean pred(V, A...); 7032 * V body(V, A...); 7033 * V doWhileLoop(A... a...) { 7034 * V v = init(a...); 7035 * do { 7036 * v = body(v, a...); 7037 * } while (pred(v, a...)); 7038 * return v; 7039 * } 7040 * } 7041 * 7042 * @apiNote Example: 7043 * {@snippet lang="java" : 7044 * // int i = 0; while (i < limit) { ++i; } return i; => limit 7045 * static int zero(int limit) { return 0; } 7046 * static int step(int i, int limit) { return i + 1; } 7047 * static boolean pred(int i, int limit) { return i < limit; } 7048 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 7049 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 7050 * assertEquals(23, loop.invoke(23)); 7051 * } 7052 * 7053 * 7054 * @apiNote The implementation of this method can be expressed as follows: 7055 * {@snippet lang="java" : 7056 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7057 * MethodHandle fini = (body.type().returnType() == void.class 7058 * ? null : identity(body.type().returnType())); 7059 * MethodHandle[] clause = { init, body, pred, fini }; 7060 * return loop(clause); 7061 * } 7062 * } 7063 * 7064 * @param init optional initializer, providing the initial value of the loop variable. 7065 * May be {@code null}, implying a default initial value. See above for other constraints. 7066 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7067 * See above for other constraints. 7068 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7069 * above for other constraints. 7070 * 7071 * @return a method handle implementing the {@code while} loop as described by the arguments. 7072 * @throws IllegalArgumentException if the rules for the arguments are violated. 7073 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7074 * 7075 * @see #loop(MethodHandle[][]) 7076 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7077 * @since 9 7078 */ 7079 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7080 whileLoopChecks(init, pred, body); 7081 MethodHandle fini = identityOrVoid(body.type().returnType()); 7082 MethodHandle[] clause = {init, body, pred, fini }; 7083 return loop(clause); 7084 } 7085 7086 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7087 Objects.requireNonNull(pred); 7088 Objects.requireNonNull(body); 7089 MethodType bodyType = body.type(); 7090 Class<?> returnType = bodyType.returnType(); 7091 List<Class<?>> innerList = bodyType.parameterList(); 7092 List<Class<?>> outerList = innerList; 7093 if (returnType == void.class) { 7094 // OK 7095 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7096 // leading V argument missing => error 7097 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7098 throw misMatchedTypes("body function", bodyType, expected); 7099 } else { 7100 outerList = innerList.subList(1, innerList.size()); 7101 } 7102 MethodType predType = pred.type(); 7103 if (predType.returnType() != boolean.class || 7104 !predType.effectivelyIdenticalParameters(0, innerList)) { 7105 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7106 } 7107 if (init != null) { 7108 MethodType initType = init.type(); 7109 if (initType.returnType() != returnType || 7110 !initType.effectivelyIdenticalParameters(0, outerList)) { 7111 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7112 } 7113 } 7114 } 7115 7116 /** 7117 * Constructs a loop that runs a given number of iterations. 7118 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7119 * <p> 7120 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7121 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7122 * It will be initialized to 0 and incremented by 1 in each iteration. 7123 * <p> 7124 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7125 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7126 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7127 * <p> 7128 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7129 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7130 * iteration variable. 7131 * The result of the loop handle execution will be the final {@code V} value of that variable 7132 * (or {@code void} if there is no {@code V} variable). 7133 * <p> 7134 * The following rules hold for the argument handles:<ul> 7135 * <li>The {@code iterations} handle must not be {@code null}, and must return 7136 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7137 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7138 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7139 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7140 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7141 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7142 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7143 * of types called the <em>internal parameter list</em>. 7144 * It will constrain the parameter lists of the other loop parts. 7145 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7146 * with no additional {@code A} types, then the internal parameter list is extended by 7147 * the argument types {@code A...} of the {@code iterations} handle. 7148 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7149 * list {@code (A...)} is called the <em>external parameter list</em>. 7150 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7151 * additional state variable of the loop. 7152 * The body must both accept a leading parameter and return a value of this type {@code V}. 7153 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7154 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7155 * <a href="MethodHandles.html#effid">effectively identical</a> 7156 * to the external parameter list {@code (A...)}. 7157 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7158 * {@linkplain #empty default value}. 7159 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7160 * effectively identical to the external parameter list {@code (A...)}. 7161 * </ul> 7162 * <p> 7163 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7164 * <li>The loop handle's result type is the result type {@code V} of the body. 7165 * <li>The loop handle's parameter types are the types {@code (A...)}, 7166 * from the external parameter list. 7167 * </ul> 7168 * <p> 7169 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7170 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7171 * arguments passed to the loop. 7172 * {@snippet lang="java" : 7173 * int iterations(A...); 7174 * V init(A...); 7175 * V body(V, int, A...); 7176 * V countedLoop(A... a...) { 7177 * int end = iterations(a...); 7178 * V v = init(a...); 7179 * for (int i = 0; i < end; ++i) { 7180 * v = body(v, i, a...); 7181 * } 7182 * return v; 7183 * } 7184 * } 7185 * 7186 * @apiNote Example with a fully conformant body method: 7187 * {@snippet lang="java" : 7188 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7189 * // => a variation on a well known theme 7190 * static String step(String v, int counter, String init) { return "na " + v; } 7191 * // assume MH_step is a handle to the method above 7192 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7193 * MethodHandle start = MethodHandles.identity(String.class); 7194 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7195 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7196 * } 7197 * 7198 * @apiNote Example with the simplest possible body method type, 7199 * and passing the number of iterations to the loop invocation: 7200 * {@snippet lang="java" : 7201 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7202 * // => a variation on a well known theme 7203 * static String step(String v, int counter ) { return "na " + v; } 7204 * // assume MH_step is a handle to the method above 7205 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7206 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7207 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7208 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7209 * } 7210 * 7211 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7212 * as loop parameters: 7213 * {@snippet lang="java" : 7214 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7215 * // => a variation on a well known theme 7216 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 7217 * // assume MH_step is a handle to the method above 7218 * MethodHandle count = MethodHandles.identity(int.class); 7219 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7220 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7221 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7222 * } 7223 * 7224 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7225 * to enforce a loop type: 7226 * {@snippet lang="java" : 7227 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7228 * // => a variation on a well known theme 7229 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7230 * // assume MH_step is a handle to the method above 7231 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7232 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7233 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7234 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7235 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7236 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7237 * } 7238 * 7239 * @apiNote The implementation of this method can be expressed as follows: 7240 * {@snippet lang="java" : 7241 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7242 * return countedLoop(empty(iterations.type()), iterations, init, body); 7243 * } 7244 * } 7245 * 7246 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7247 * result type must be {@code int}. See above for other constraints. 7248 * @param init optional initializer, providing the initial value of the loop variable. 7249 * May be {@code null}, implying a default initial value. See above for other constraints. 7250 * @param body body of the loop, which may not be {@code null}. 7251 * It controls the loop parameters and result type in the standard case (see above for details). 7252 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7253 * and may accept any number of additional types. 7254 * See above for other constraints. 7255 * 7256 * @return a method handle representing the loop. 7257 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7258 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7259 * 7260 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7261 * @since 9 7262 */ 7263 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7264 return countedLoop(empty(iterations.type()), iterations, init, body); 7265 } 7266 7267 /** 7268 * Constructs a loop that counts over a range of numbers. 7269 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7270 * <p> 7271 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7272 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7273 * values of the loop counter. 7274 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7275 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7276 * <p> 7277 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7278 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7279 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7280 * <p> 7281 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7282 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7283 * iteration variable. 7284 * The result of the loop handle execution will be the final {@code V} value of that variable 7285 * (or {@code void} if there is no {@code V} variable). 7286 * <p> 7287 * The following rules hold for the argument handles:<ul> 7288 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7289 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7290 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7291 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7292 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7293 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7294 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7295 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7296 * of types called the <em>internal parameter list</em>. 7297 * It will constrain the parameter lists of the other loop parts. 7298 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7299 * with no additional {@code A} types, then the internal parameter list is extended by 7300 * the argument types {@code A...} of the {@code end} handle. 7301 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7302 * list {@code (A...)} is called the <em>external parameter list</em>. 7303 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7304 * additional state variable of the loop. 7305 * The body must both accept a leading parameter and return a value of this type {@code V}. 7306 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7307 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7308 * <a href="MethodHandles.html#effid">effectively identical</a> 7309 * to the external parameter list {@code (A...)}. 7310 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7311 * {@linkplain #empty default value}. 7312 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7313 * effectively identical to the external parameter list {@code (A...)}. 7314 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7315 * to the external parameter list. 7316 * </ul> 7317 * <p> 7318 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7319 * <li>The loop handle's result type is the result type {@code V} of the body. 7320 * <li>The loop handle's parameter types are the types {@code (A...)}, 7321 * from the external parameter list. 7322 * </ul> 7323 * <p> 7324 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7325 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7326 * arguments passed to the loop. 7327 * {@snippet lang="java" : 7328 * int start(A...); 7329 * int end(A...); 7330 * V init(A...); 7331 * V body(V, int, A...); 7332 * V countedLoop(A... a...) { 7333 * int e = end(a...); 7334 * int s = start(a...); 7335 * V v = init(a...); 7336 * for (int i = s; i < e; ++i) { 7337 * v = body(v, i, a...); 7338 * } 7339 * return v; 7340 * } 7341 * } 7342 * 7343 * @apiNote The implementation of this method can be expressed as follows: 7344 * {@snippet lang="java" : 7345 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7346 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7347 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7348 * // the following semantics: 7349 * // MH_increment: (int limit, int counter) -> counter + 1 7350 * // MH_predicate: (int limit, int counter) -> counter < limit 7351 * Class<?> counterType = start.type().returnType(); // int 7352 * Class<?> returnType = body.type().returnType(); 7353 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7354 * if (returnType != void.class) { // ignore the V variable 7355 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7356 * pred = dropArguments(pred, 1, returnType); // ditto 7357 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7358 * } 7359 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7360 * MethodHandle[] 7361 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7362 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7363 * indexVar = { start, incr }; // i = start(); i = i + 1 7364 * return loop(loopLimit, bodyClause, indexVar); 7365 * } 7366 * } 7367 * 7368 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7369 * See above for other constraints. 7370 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7371 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7372 * @param init optional initializer, providing the initial value of the loop variable. 7373 * May be {@code null}, implying a default initial value. See above for other constraints. 7374 * @param body body of the loop, which may not be {@code null}. 7375 * It controls the loop parameters and result type in the standard case (see above for details). 7376 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7377 * and may accept any number of additional types. 7378 * See above for other constraints. 7379 * 7380 * @return a method handle representing the loop. 7381 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7382 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7383 * 7384 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7385 * @since 9 7386 */ 7387 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7388 countedLoopChecks(start, end, init, body); 7389 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7390 Class<?> limitType = end.type().returnType(); // yes, int again 7391 Class<?> returnType = body.type().returnType(); 7392 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7393 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7394 MethodHandle retv = null; 7395 if (returnType != void.class) { 7396 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7397 pred = dropArguments(pred, 1, returnType); // ditto 7398 retv = dropArguments(identity(returnType), 0, counterType); 7399 } 7400 body = dropArguments(body, 0, counterType); // ignore the limit variable 7401 MethodHandle[] 7402 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7403 bodyClause = { init, body }, // v = init(); v = body(v, i) 7404 indexVar = { start, incr }; // i = start(); i = i + 1 7405 return loop(loopLimit, bodyClause, indexVar); 7406 } 7407 7408 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7409 Objects.requireNonNull(start); 7410 Objects.requireNonNull(end); 7411 Objects.requireNonNull(body); 7412 Class<?> counterType = start.type().returnType(); 7413 if (counterType != int.class) { 7414 MethodType expected = start.type().changeReturnType(int.class); 7415 throw misMatchedTypes("start function", start.type(), expected); 7416 } else if (end.type().returnType() != counterType) { 7417 MethodType expected = end.type().changeReturnType(counterType); 7418 throw misMatchedTypes("end function", end.type(), expected); 7419 } 7420 MethodType bodyType = body.type(); 7421 Class<?> returnType = bodyType.returnType(); 7422 List<Class<?>> innerList = bodyType.parameterList(); 7423 // strip leading V value if present 7424 int vsize = (returnType == void.class ? 0 : 1); 7425 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7426 // argument list has no "V" => error 7427 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7428 throw misMatchedTypes("body function", bodyType, expected); 7429 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7430 // missing I type => error 7431 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7432 throw misMatchedTypes("body function", bodyType, expected); 7433 } 7434 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7435 if (outerList.isEmpty()) { 7436 // special case; take lists from end handle 7437 outerList = end.type().parameterList(); 7438 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7439 } 7440 MethodType expected = methodType(counterType, outerList); 7441 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7442 throw misMatchedTypes("start parameter types", start.type(), expected); 7443 } 7444 if (end.type() != start.type() && 7445 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7446 throw misMatchedTypes("end parameter types", end.type(), expected); 7447 } 7448 if (init != null) { 7449 MethodType initType = init.type(); 7450 if (initType.returnType() != returnType || 7451 !initType.effectivelyIdenticalParameters(0, outerList)) { 7452 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7453 } 7454 } 7455 } 7456 7457 /** 7458 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7459 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7460 * <p> 7461 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7462 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7463 * <p> 7464 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7465 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7466 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7467 * <p> 7468 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7469 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7470 * iteration variable. 7471 * The result of the loop handle execution will be the final {@code V} value of that variable 7472 * (or {@code void} if there is no {@code V} variable). 7473 * <p> 7474 * The following rules hold for the argument handles:<ul> 7475 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7476 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7477 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7478 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7479 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7480 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7481 * of types called the <em>internal parameter list</em>. 7482 * It will constrain the parameter lists of the other loop parts. 7483 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7484 * with no additional {@code A} types, then the internal parameter list is extended by 7485 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7486 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7487 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7488 * list {@code (A...)} is called the <em>external parameter list</em>. 7489 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7490 * additional state variable of the loop. 7491 * The body must both accept a leading parameter and return a value of this type {@code V}. 7492 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7493 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7494 * <a href="MethodHandles.html#effid">effectively identical</a> 7495 * to the external parameter list {@code (A...)}. 7496 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7497 * {@linkplain #empty default value}. 7498 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7499 * type {@code java.util.Iterator} or a subtype thereof. 7500 * The iterator it produces when the loop is executed will be assumed 7501 * to yield values which can be converted to type {@code T}. 7502 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7503 * effectively identical to the external parameter list {@code (A...)}. 7504 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7505 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7506 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7507 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7508 * the {@link MethodHandle#asType asType} conversion method. 7509 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7510 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7511 * </ul> 7512 * <p> 7513 * The type {@code T} may be either a primitive or reference. 7514 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7515 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7516 * as if by the {@link MethodHandle#asType asType} conversion method. 7517 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7518 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7519 * <p> 7520 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7521 * <li>The loop handle's result type is the result type {@code V} of the body. 7522 * <li>The loop handle's parameter types are the types {@code (A...)}, 7523 * from the external parameter list. 7524 * </ul> 7525 * <p> 7526 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7527 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7528 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7529 * {@snippet lang="java" : 7530 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7531 * V init(A...); 7532 * V body(V,T,A...); 7533 * V iteratedLoop(A... a...) { 7534 * Iterator<T> it = iterator(a...); 7535 * V v = init(a...); 7536 * while (it.hasNext()) { 7537 * T t = it.next(); 7538 * v = body(v, t, a...); 7539 * } 7540 * return v; 7541 * } 7542 * } 7543 * 7544 * @apiNote Example: 7545 * {@snippet lang="java" : 7546 * // get an iterator from a list 7547 * static List<String> reverseStep(List<String> r, String e) { 7548 * r.add(0, e); 7549 * return r; 7550 * } 7551 * static List<String> newArrayList() { return new ArrayList<>(); } 7552 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7553 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7554 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7555 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7556 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7557 * } 7558 * 7559 * @apiNote The implementation of this method can be expressed approximately as follows: 7560 * {@snippet lang="java" : 7561 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7562 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7563 * Class<?> returnType = body.type().returnType(); 7564 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7565 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7566 * MethodHandle retv = null, step = body, startIter = iterator; 7567 * if (returnType != void.class) { 7568 * // the simple thing first: in (I V A...), drop the I to get V 7569 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7570 * // body type signature (V T A...), internal loop types (I V A...) 7571 * step = swapArguments(body, 0, 1); // swap V <-> T 7572 * } 7573 * if (startIter == null) startIter = MH_getIter; 7574 * MethodHandle[] 7575 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7576 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7577 * return loop(iterVar, bodyClause); 7578 * } 7579 * } 7580 * 7581 * @param iterator an optional handle to return the iterator to start the loop. 7582 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7583 * See above for other constraints. 7584 * @param init optional initializer, providing the initial value of the loop variable. 7585 * May be {@code null}, implying a default initial value. See above for other constraints. 7586 * @param body body of the loop, which may not be {@code null}. 7587 * It controls the loop parameters and result type in the standard case (see above for details). 7588 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7589 * and may accept any number of additional types. 7590 * See above for other constraints. 7591 * 7592 * @return a method handle embodying the iteration loop functionality. 7593 * @throws NullPointerException if the {@code body} handle is {@code null}. 7594 * @throws IllegalArgumentException if any argument violates the above requirements. 7595 * 7596 * @since 9 7597 */ 7598 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7599 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7600 Class<?> returnType = body.type().returnType(); 7601 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7602 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7603 MethodHandle startIter; 7604 MethodHandle nextVal; 7605 { 7606 MethodType iteratorType; 7607 if (iterator == null) { 7608 // derive argument type from body, if available, else use Iterable 7609 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7610 iteratorType = startIter.type().changeParameterType(0, iterableType); 7611 } else { 7612 // force return type to the internal iterator class 7613 iteratorType = iterator.type().changeReturnType(Iterator.class); 7614 startIter = iterator; 7615 } 7616 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7617 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7618 7619 // perform the asType transforms under an exception transformer, as per spec.: 7620 try { 7621 startIter = startIter.asType(iteratorType); 7622 nextVal = nextRaw.asType(nextValType); 7623 } catch (WrongMethodTypeException ex) { 7624 throw new IllegalArgumentException(ex); 7625 } 7626 } 7627 7628 MethodHandle retv = null, step = body; 7629 if (returnType != void.class) { 7630 // the simple thing first: in (I V A...), drop the I to get V 7631 retv = dropArguments(identity(returnType), 0, Iterator.class); 7632 // body type signature (V T A...), internal loop types (I V A...) 7633 step = swapArguments(body, 0, 1); // swap V <-> T 7634 } 7635 7636 MethodHandle[] 7637 iterVar = { startIter, null, hasNext, retv }, 7638 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7639 return loop(iterVar, bodyClause); 7640 } 7641 7642 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7643 Objects.requireNonNull(body); 7644 MethodType bodyType = body.type(); 7645 Class<?> returnType = bodyType.returnType(); 7646 List<Class<?>> internalParamList = bodyType.parameterList(); 7647 // strip leading V value if present 7648 int vsize = (returnType == void.class ? 0 : 1); 7649 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7650 // argument list has no "V" => error 7651 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7652 throw misMatchedTypes("body function", bodyType, expected); 7653 } else if (internalParamList.size() <= vsize) { 7654 // missing T type => error 7655 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7656 throw misMatchedTypes("body function", bodyType, expected); 7657 } 7658 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7659 Class<?> iterableType = null; 7660 if (iterator != null) { 7661 // special case; if the body handle only declares V and T then 7662 // the external parameter list is obtained from iterator handle 7663 if (externalParamList.isEmpty()) { 7664 externalParamList = iterator.type().parameterList(); 7665 } 7666 MethodType itype = iterator.type(); 7667 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7668 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7669 } 7670 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7671 MethodType expected = methodType(itype.returnType(), externalParamList); 7672 throw misMatchedTypes("iterator parameters", itype, expected); 7673 } 7674 } else { 7675 if (externalParamList.isEmpty()) { 7676 // special case; if the iterator handle is null and the body handle 7677 // only declares V and T then the external parameter list consists 7678 // of Iterable 7679 externalParamList = List.of(Iterable.class); 7680 iterableType = Iterable.class; 7681 } else { 7682 // special case; if the iterator handle is null and the external 7683 // parameter list is not empty then the first parameter must be 7684 // assignable to Iterable 7685 iterableType = externalParamList.get(0); 7686 if (!Iterable.class.isAssignableFrom(iterableType)) { 7687 throw newIllegalArgumentException( 7688 "inferred first loop argument must inherit from Iterable: " + iterableType); 7689 } 7690 } 7691 } 7692 if (init != null) { 7693 MethodType initType = init.type(); 7694 if (initType.returnType() != returnType || 7695 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7696 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7697 } 7698 } 7699 return iterableType; // help the caller a bit 7700 } 7701 7702 /*non-public*/ 7703 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7704 // there should be a better way to uncross my wires 7705 int arity = mh.type().parameterCount(); 7706 int[] order = new int[arity]; 7707 for (int k = 0; k < arity; k++) order[k] = k; 7708 order[i] = j; order[j] = i; 7709 Class<?>[] types = mh.type().parameterArray(); 7710 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7711 MethodType swapType = methodType(mh.type().returnType(), types); 7712 return permuteArguments(mh, swapType, order); 7713 } 7714 7715 /** 7716 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7717 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7718 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7719 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7720 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7721 * {@code try-finally} handle. 7722 * <p> 7723 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7724 * The first is the exception thrown during the 7725 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7726 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7727 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7728 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7729 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7730 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7731 * <p> 7732 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7733 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7734 * two extra leading parameters:<ul> 7735 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7736 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7737 * the result from the execution of the {@code target} handle. 7738 * This parameter is not present if the {@code target} returns {@code void}. 7739 * </ul> 7740 * <p> 7741 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7742 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7743 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7744 * the cleanup. 7745 * {@snippet lang="java" : 7746 * V target(A..., B...); 7747 * V cleanup(Throwable, V, A...); 7748 * V adapter(A... a, B... b) { 7749 * V result = (zero value for V); 7750 * Throwable throwable = null; 7751 * try { 7752 * result = target(a..., b...); 7753 * } catch (Throwable t) { 7754 * throwable = t; 7755 * throw t; 7756 * } finally { 7757 * result = cleanup(throwable, result, a...); 7758 * } 7759 * return result; 7760 * } 7761 * } 7762 * <p> 7763 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7764 * be modified by execution of the target, and so are passed unchanged 7765 * from the caller to the cleanup, if it is invoked. 7766 * <p> 7767 * The target and cleanup must return the same type, even if the cleanup 7768 * always throws. 7769 * To create such a throwing cleanup, compose the cleanup logic 7770 * with {@link #throwException throwException}, 7771 * in order to create a method handle of the correct return type. 7772 * <p> 7773 * Note that {@code tryFinally} never converts exceptions into normal returns. 7774 * In rare cases where exceptions must be converted in that way, first wrap 7775 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7776 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7777 * <p> 7778 * It is recommended that the first parameter type of {@code cleanup} be 7779 * declared {@code Throwable} rather than a narrower subtype. This ensures 7780 * {@code cleanup} will always be invoked with whatever exception that 7781 * {@code target} throws. Declaring a narrower type may result in a 7782 * {@code ClassCastException} being thrown by the {@code try-finally} 7783 * handle if the type of the exception thrown by {@code target} is not 7784 * assignable to the first parameter type of {@code cleanup}. Note that 7785 * various exception types of {@code VirtualMachineError}, 7786 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7787 * thrown by almost any kind of Java code, and a finally clause that 7788 * catches (say) only {@code IOException} would mask any of the others 7789 * behind a {@code ClassCastException}. 7790 * 7791 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7792 * @param cleanup the handle that is invoked in the finally block. 7793 * 7794 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7795 * @throws NullPointerException if any argument is null 7796 * @throws IllegalArgumentException if {@code cleanup} does not accept 7797 * the required leading arguments, or if the method handle types do 7798 * not match in their return types and their 7799 * corresponding trailing parameters 7800 * 7801 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7802 * @since 9 7803 */ 7804 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7805 Class<?>[] targetParamTypes = target.type().ptypes(); 7806 Class<?> rtype = target.type().returnType(); 7807 7808 tryFinallyChecks(target, cleanup); 7809 7810 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7811 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7812 // target parameter list. 7813 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7814 7815 // Ensure that the intrinsic type checks the instance thrown by the 7816 // target against the first parameter of cleanup 7817 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7818 7819 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7820 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7821 } 7822 7823 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7824 Class<?> rtype = target.type().returnType(); 7825 if (rtype != cleanup.type().returnType()) { 7826 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7827 } 7828 MethodType cleanupType = cleanup.type(); 7829 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7830 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7831 } 7832 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7833 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7834 } 7835 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7836 // target parameter list. 7837 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7838 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7839 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7840 cleanup.type(), target.type()); 7841 } 7842 } 7843 7844 /** 7845 * Creates a table switch method handle, which can be used to switch over a set of target 7846 * method handles, based on a given target index, called selector. 7847 * <p> 7848 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7849 * and where {@code N} is the number of target method handles, the table switch method 7850 * handle will invoke the n-th target method handle from the list of target method handles. 7851 * <p> 7852 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7853 * method handle will invoke the given fallback method handle. 7854 * <p> 7855 * All method handles passed to this method must have the same type, with the additional 7856 * requirement that the leading parameter be of type {@code int}. The leading parameter 7857 * represents the selector. 7858 * <p> 7859 * Any trailing parameters present in the type will appear on the returned table switch 7860 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7861 * together with the selector value, to the selected method handle when invoking it. 7862 * 7863 * @apiNote Example: 7864 * The cases each drop the {@code selector} value they are given, and take an additional 7865 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7866 * to a specific constant label string for each case: 7867 * {@snippet lang="java" : 7868 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7869 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7870 * MethodType.methodType(String.class, String.class)); 7871 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7872 * 7873 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7874 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7875 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7876 * 7877 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7878 * caseDefault, 7879 * case0, 7880 * case1 7881 * ); 7882 * 7883 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7884 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7885 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7886 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7887 * } 7888 * 7889 * @param fallback the fallback method handle that is called when the selector is not 7890 * within the range {@code [0, N)}. 7891 * @param targets array of target method handles. 7892 * @return the table switch method handle. 7893 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7894 * any of the elements of the {@code targets} array are 7895 * {@code null}. 7896 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7897 * parameter of the fallback handle or any of the target 7898 * handles is not {@code int}, or if the types of 7899 * the fallback handle and all of target handles are 7900 * not the same. 7901 * 7902 * @since 17 7903 */ 7904 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7905 Objects.requireNonNull(fallback); 7906 Objects.requireNonNull(targets); 7907 targets = targets.clone(); 7908 MethodType type = tableSwitchChecks(fallback, targets); 7909 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7910 } 7911 7912 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7913 if (caseActions.length == 0) 7914 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7915 7916 MethodType expectedType = defaultCase.type(); 7917 7918 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7919 throw new IllegalArgumentException( 7920 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7921 7922 for (MethodHandle mh : caseActions) { 7923 Objects.requireNonNull(mh); 7924 if (mh.type() != expectedType) 7925 throw new IllegalArgumentException( 7926 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7927 } 7928 7929 return expectedType; 7930 } 7931 7932 /** 7933 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7934 * <p> 7935 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7936 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7937 * to the target var handle. 7938 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7939 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7940 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7941 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7942 * <p> 7943 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7944 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7945 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7946 * will be appended to the coordinates of the target var handle). 7947 * <p> 7948 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7949 * throw an {@link IllegalStateException}. 7950 * <p> 7951 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7952 * atomic access guarantees as those featured by the target var handle. 7953 * 7954 * @param target the target var handle 7955 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7956 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7957 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7958 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7959 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7960 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7961 * @throws NullPointerException if any of the arguments is {@code null}. 7962 * @since 22 7963 */ 7964 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7965 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7966 } 7967 7968 /** 7969 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7970 * <p> 7971 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7972 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7973 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7974 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7975 * by the adaptation) to the target var handle. 7976 * <p> 7977 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7978 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7979 * <p> 7980 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7981 * throw an {@link IllegalStateException}. 7982 * <p> 7983 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7984 * atomic access guarantees as those featured by the target var handle. 7985 * 7986 * @param target the target var handle 7987 * @param pos the position of the first coordinate to be transformed 7988 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7989 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7990 * to the new coordinate values. 7991 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7992 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7993 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7994 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7995 * or if it's determined that any of the filters throws any checked exceptions. 7996 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 7997 * @since 22 7998 */ 7999 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8000 return VarHandles.filterCoordinates(target, pos, filters); 8001 } 8002 8003 /** 8004 * Provides a target var handle with one or more <em>bound coordinates</em> 8005 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8006 * coordinate types than the target var handle. 8007 * <p> 8008 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8009 * are joined with bound coordinate values, and then passed to the target var handle. 8010 * <p> 8011 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8012 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8013 * <p> 8014 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8015 * atomic access guarantees as those featured by the target var handle. 8016 * 8017 * @param target the var handle to invoke after the bound coordinates are inserted 8018 * @param pos the position of the first coordinate to be inserted 8019 * @param values the series of bound coordinates to insert 8020 * @return an adapter var handle which inserts additional coordinates, 8021 * before calling the target var handle 8022 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8023 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8024 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8025 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8026 * of the target var handle. 8027 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8028 * @since 22 8029 */ 8030 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8031 return VarHandles.insertCoordinates(target, pos, values); 8032 } 8033 8034 /** 8035 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8036 * so that the new coordinates match the provided ones. 8037 * <p> 8038 * The given array controls the reordering. 8039 * Call {@code #I} the number of incoming coordinates (the value 8040 * {@code newCoordinates.size()}), and call {@code #O} the number 8041 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8042 * Then the length of the reordering array must be {@code #O}, 8043 * and each element must be a non-negative number less than {@code #I}. 8044 * For every {@code N} less than {@code #O}, the {@code N}-th 8045 * outgoing coordinate will be taken from the {@code I}-th incoming 8046 * coordinate, where {@code I} is {@code reorder[N]}. 8047 * <p> 8048 * No coordinate value conversions are applied. 8049 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8050 * must be identical to the type of the corresponding outgoing coordinate 8051 * in the target var handle. 8052 * <p> 8053 * The reordering array need not specify an actual permutation. 8054 * An incoming coordinate will be duplicated if its index appears 8055 * more than once in the array, and an incoming coordinate will be dropped 8056 * if its index does not appear in the array. 8057 * <p> 8058 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8059 * atomic access guarantees as those featured by the target var handle. 8060 * @param target the var handle to invoke after the coordinates have been reordered 8061 * @param newCoordinates the new coordinate types 8062 * @param reorder an index array which controls the reordering 8063 * @return an adapter var handle which re-arranges the incoming coordinate values, 8064 * before calling the target var handle 8065 * @throws IllegalArgumentException if the index array length is not equal to 8066 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8067 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8068 * the target var handle and in {@code newCoordinates} are not identical. 8069 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8070 * @since 22 8071 */ 8072 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8073 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8074 } 8075 8076 /** 8077 * Adapts a target var handle by pre-processing 8078 * a sub-sequence of its coordinate values with a filter (a method handle). 8079 * The pre-processed coordinates are replaced by the result (if any) of the 8080 * filter function and the target var handle is then called on the modified (usually shortened) 8081 * coordinate list. 8082 * <p> 8083 * If {@code R} is the return type of the filter, then: 8084 * <ul> 8085 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 8086 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 8087 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 8088 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 8089 * target var handle.</li> 8090 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 8091 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 8092 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 8093 * downstream invocation of the target var handle.</li> 8094 * </ul> 8095 * <p> 8096 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8097 * throw an {@link IllegalStateException}. 8098 * <p> 8099 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8100 * atomic access guarantees as those featured by the target var handle. 8101 * 8102 * @param target the var handle to invoke after the coordinates have been filtered 8103 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 8104 * @param filter the filter method handle 8105 * @return an adapter var handle which filters the incoming coordinate values, 8106 * before calling the target var handle 8107 * @throws IllegalArgumentException if the return type of {@code filter} 8108 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 8109 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8110 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8111 * or if it's determined that {@code filter} throws any checked exceptions. 8112 * @throws NullPointerException if any of the arguments is {@code null}. 8113 * @since 22 8114 */ 8115 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8116 return VarHandles.collectCoordinates(target, pos, filter); 8117 } 8118 8119 /** 8120 * Returns a var handle which will discard some dummy coordinates before delegating to the 8121 * target var handle. As a consequence, the resulting var handle will feature more 8122 * coordinate types than the target var handle. 8123 * <p> 8124 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8125 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8126 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8127 * <p> 8128 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8129 * atomic access guarantees as those featured by the target var handle. 8130 * 8131 * @param target the var handle to invoke after the dummy coordinates are dropped 8132 * @param pos position of the first coordinate to drop (zero for the leftmost) 8133 * @param valueTypes the type(s) of the coordinate(s) to drop 8134 * @return an adapter var handle which drops some dummy coordinates, 8135 * before calling the target var handle 8136 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8137 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8138 * @since 22 8139 */ 8140 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8141 return VarHandles.dropCoordinates(target, pos, valueTypes); 8142 } 8143 }