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.ClassModel; 43 import java.lang.constant.ConstantDescs; 44 import java.lang.invoke.LambdaForm.BasicType; 45 import java.lang.invoke.MethodHandleImpl.Intrinsic; 46 import java.lang.reflect.Constructor; 47 import java.lang.reflect.Field; 48 import java.lang.reflect.Member; 49 import java.lang.reflect.Method; 50 import java.lang.reflect.Modifier; 51 import java.nio.ByteOrder; 52 import java.security.ProtectionDomain; 53 import java.util.ArrayList; 54 import java.util.Arrays; 55 import java.util.BitSet; 56 import java.util.Comparator; 57 import java.util.Iterator; 58 import java.util.List; 59 import java.util.Objects; 60 import java.util.Set; 61 import java.util.concurrent.ConcurrentHashMap; 62 import java.util.stream.Stream; 63 64 import static java.lang.classfile.ClassFile.*; 65 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 66 import static java.lang.invoke.MethodHandleNatives.Constants.*; 67 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 68 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 69 import static java.lang.invoke.MethodHandleStatics.newInternalError; 70 import static java.lang.invoke.MethodType.methodType; 71 72 /** 73 * This class consists exclusively of static methods that operate on or return 74 * method handles. They fall into several categories: 75 * <ul> 76 * <li>Lookup methods which help create method handles for methods and fields. 77 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 78 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 79 * </ul> 80 * A lookup, combinator, or factory method will fail and throw an 81 * {@code IllegalArgumentException} if the created method handle's type 82 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 83 * 84 * @author John Rose, JSR 292 EG 85 * @since 1.7 86 */ 87 public class MethodHandles { 88 89 private MethodHandles() { } // do not instantiate 90 91 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 92 93 // See IMPL_LOOKUP below. 94 95 //--- Method handle creation from ordinary methods. 96 97 /** 98 * Returns a {@link Lookup lookup object} with 99 * full capabilities to emulate all supported bytecode behaviors of the caller. 100 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 101 * Factory methods on the lookup object can create 102 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 103 * for any member that the caller has access to via bytecodes, 104 * including protected and private fields and methods. 105 * This lookup object is created by the original lookup class 106 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 107 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 108 * Do not store it in place where untrusted code can access it. 109 * <p> 110 * This method is caller sensitive, which means that it may return different 111 * values to different callers. 112 * In cases where {@code MethodHandles.lookup} is called from a context where 113 * there is no caller frame on the stack (e.g. when called directly 114 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 115 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 116 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 117 * to obtain a low-privileged lookup instead. 118 * @return a lookup object for the caller of this method, with 119 * {@linkplain Lookup#ORIGINAL original} and 120 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 121 * @throws IllegalCallerException if there is no caller frame on the stack. 122 */ 123 @CallerSensitive 124 @ForceInline // to ensure Reflection.getCallerClass optimization 125 public static Lookup lookup() { 126 final Class<?> c = Reflection.getCallerClass(); 127 if (c == null) { 128 throw new IllegalCallerException("no caller frame"); 129 } 130 return new Lookup(c); 131 } 132 133 /** 134 * This lookup method is the alternate implementation of 135 * the lookup method with a leading caller class argument which is 136 * non-caller-sensitive. This method is only invoked by reflection 137 * and method handle. 138 */ 139 @CallerSensitiveAdapter 140 private static Lookup lookup(Class<?> caller) { 141 if (caller.getClassLoader() == null) { 142 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 143 } 144 return new Lookup(caller); 145 } 146 147 /** 148 * Returns a {@link Lookup lookup object} which is trusted minimally. 149 * The lookup has the {@code UNCONDITIONAL} mode. 150 * It can only be used to create method handles to public members of 151 * public classes in packages that are exported unconditionally. 152 * <p> 153 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 154 * of this lookup object will be {@link java.lang.Object}. 155 * 156 * @apiNote The use of Object is conventional, and because the lookup modes are 157 * limited, there is no special access provided to the internals of Object, its package 158 * or its module. This public lookup object or other lookup object with 159 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 160 * is not used to determine the lookup context. 161 * 162 * <p style="font-size:smaller;"> 163 * <em>Discussion:</em> 164 * The lookup class can be changed to any other class {@code C} using an expression of the form 165 * {@link Lookup#in publicLookup().in(C.class)}. 166 * A public lookup object is always subject to 167 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 168 * Also, it cannot access 169 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 170 * @return a lookup object which is trusted minimally 171 */ 172 public static Lookup publicLookup() { 173 return Lookup.PUBLIC_LOOKUP; 174 } 175 176 /** 177 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 178 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 179 * The returned lookup object can provide access to classes in modules and packages, 180 * and members of those classes, outside the normal rules of Java access control, 181 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 182 * <p> 183 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 184 * allowed to do deep reflection on module {@code M2} and package of the target class 185 * if and only if all of the following conditions are {@code true}: 186 * <ul> 187 * <li>If there is a security manager, its {@code checkPermission} method is 188 * called to check {@code ReflectPermission("suppressAccessChecks")} and 189 * that must return normally. 190 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 191 * full privilege access}. Specifically: 192 * <ul> 193 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 194 * (This is because otherwise there would be no way to ensure the original lookup 195 * creator was a member of any particular module, and so any subsequent checks 196 * for readability and qualified exports would become ineffective.) 197 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 198 * (This is because an application intending to share intra-module access 199 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 200 * deep reflection to its own module.) 201 * </ul> 202 * <li>The target class must be a proper class, not a primitive or array class. 203 * (Thus, {@code M2} is well-defined.) 204 * <li>If the caller module {@code M1} differs from 205 * the target module {@code M2} then both of the following must be true: 206 * <ul> 207 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 208 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 209 * containing the target class to at least {@code M1}.</li> 210 * </ul> 211 * </ul> 212 * <p> 213 * If any of the above checks is violated, this method fails with an 214 * exception. 215 * <p> 216 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 217 * returns a {@code Lookup} on {@code targetClass} with 218 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 219 * with {@code null} previous lookup class. 220 * <p> 221 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 222 * returns a {@code Lookup} on {@code targetClass} that records 223 * the lookup class of the caller as the new previous lookup class with 224 * {@code PRIVATE} access but no {@code MODULE} access. 225 * <p> 226 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 227 * 228 * @apiNote The {@code Lookup} object returned by this method is allowed to 229 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 230 * of {@code targetClass}. Extreme caution should be taken when opening a package 231 * to another module as such defined classes have the same full privilege 232 * access as other members in {@code targetClass}'s module. 233 * 234 * @param targetClass the target class 235 * @param caller the caller lookup object 236 * @return a lookup object for the target class, with private access 237 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 238 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 239 * @throws SecurityException if denied by the security manager 240 * @throws IllegalAccessException if any of the other access checks specified above fails 241 * @since 9 242 * @see Lookup#dropLookupMode 243 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 244 */ 245 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 246 if (caller.allowedModes == Lookup.TRUSTED) { 247 return new Lookup(targetClass); 248 } 249 250 @SuppressWarnings("removal") 251 SecurityManager sm = System.getSecurityManager(); 252 if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION); 253 if (targetClass.isPrimitive()) 254 throw new IllegalArgumentException(targetClass + " is a primitive class"); 255 if (targetClass.isArray()) 256 throw new IllegalArgumentException(targetClass + " is an array class"); 257 // Ensure that we can reason accurately about private and module access. 258 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 259 if ((caller.lookupModes() & requireAccess) != requireAccess) 260 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 261 262 // previous lookup class is never set if it has MODULE access 263 assert caller.previousLookupClass() == null; 264 265 Class<?> callerClass = caller.lookupClass(); 266 Module callerModule = callerClass.getModule(); // M1 267 Module targetModule = targetClass.getModule(); // M2 268 Class<?> newPreviousClass = null; 269 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 270 271 if (targetModule != callerModule) { 272 if (!callerModule.canRead(targetModule)) 273 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 274 if (targetModule.isNamed()) { 275 String pn = targetClass.getPackageName(); 276 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 277 if (!targetModule.isOpen(pn, callerModule)) 278 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 279 } 280 281 // M2 != M1, set previous lookup class to M1 and drop MODULE access 282 newPreviousClass = callerClass; 283 newModes &= ~Lookup.MODULE; 284 } 285 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 286 } 287 288 /** 289 * Returns the <em>class data</em> associated with the lookup class 290 * of the given {@code caller} lookup object, or {@code null}. 291 * 292 * <p> A hidden class with class data can be created by calling 293 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 294 * Lookup::defineHiddenClassWithClassData}. 295 * This method will cause the static class initializer of the lookup 296 * class of the given {@code caller} lookup object be executed if 297 * it has not been initialized. 298 * 299 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 300 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 301 * {@code null} is returned if this method is called on the lookup object 302 * on these classes. 303 * 304 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 305 * must have {@linkplain Lookup#ORIGINAL original access} 306 * in order to retrieve the class data. 307 * 308 * @apiNote 309 * This method can be called as a bootstrap method for a dynamically computed 310 * constant. A framework can create a hidden class with class data, for 311 * example that can be {@code Class} or {@code MethodHandle} object. 312 * The class data is accessible only to the lookup object 313 * created by the original caller but inaccessible to other members 314 * in the same nest. If a framework passes security sensitive objects 315 * to a hidden class via class data, it is recommended to load the value 316 * of class data as a dynamically computed constant instead of storing 317 * the class data in private static field(s) which are accessible to 318 * other nestmates. 319 * 320 * @param <T> the type to cast the class data object to 321 * @param caller the lookup context describing the class performing the 322 * operation (normally stacked by the JVM) 323 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 324 * ({@code "_"}) 325 * @param type the type of the class data 326 * @return the value of the class data if present in the lookup class; 327 * otherwise {@code null} 328 * @throws IllegalArgumentException if name is not {@code "_"} 329 * @throws IllegalAccessException if the lookup context does not have 330 * {@linkplain Lookup#ORIGINAL original} access 331 * @throws ClassCastException if the class data cannot be converted to 332 * the given {@code type} 333 * @throws NullPointerException if {@code caller} or {@code type} argument 334 * is {@code null} 335 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 336 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 337 * @since 16 338 * @jvms 5.5 Initialization 339 */ 340 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 341 Objects.requireNonNull(caller); 342 Objects.requireNonNull(type); 343 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 344 throw new IllegalArgumentException("name must be \"_\": " + name); 345 } 346 347 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 348 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 349 } 350 351 Object classdata = classData(caller.lookupClass()); 352 if (classdata == null) return null; 353 354 try { 355 return BootstrapMethodInvoker.widenAndCast(classdata, type); 356 } catch (RuntimeException|Error e) { 357 throw e; // let CCE and other runtime exceptions through 358 } catch (Throwable e) { 359 throw new InternalError(e); 360 } 361 } 362 363 /* 364 * Returns the class data set by the VM in the Class::classData field. 365 * 366 * This is also invoked by LambdaForms as it cannot use condy via 367 * MethodHandles::classData due to bootstrapping issue. 368 */ 369 static Object classData(Class<?> c) { 370 UNSAFE.ensureClassInitialized(c); 371 return SharedSecrets.getJavaLangAccess().classData(c); 372 } 373 374 /** 375 * Returns the element at the specified index in the 376 * {@linkplain #classData(Lookup, String, Class) class data}, 377 * if the class data associated with the lookup class 378 * of the given {@code caller} lookup object is a {@code List}. 379 * If the class data is not present in this lookup class, this method 380 * returns {@code null}. 381 * 382 * <p> A hidden class with class data can be created by calling 383 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 384 * Lookup::defineHiddenClassWithClassData}. 385 * This method will cause the static class initializer of the lookup 386 * class of the given {@code caller} lookup object be executed if 387 * it has not been initialized. 388 * 389 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 390 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 391 * {@code null} is returned if this method is called on the lookup object 392 * on these classes. 393 * 394 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 395 * must have {@linkplain Lookup#ORIGINAL original access} 396 * in order to retrieve the class data. 397 * 398 * @apiNote 399 * This method can be called as a bootstrap method for a dynamically computed 400 * constant. A framework can create a hidden class with class data, for 401 * example that can be {@code List.of(o1, o2, o3....)} containing more than 402 * one object and use this method to load one element at a specific index. 403 * The class data is accessible only to the lookup object 404 * created by the original caller but inaccessible to other members 405 * in the same nest. If a framework passes security sensitive objects 406 * to a hidden class via class data, it is recommended to load the value 407 * of class data as a dynamically computed constant instead of storing 408 * the class data in private static field(s) which are accessible to other 409 * nestmates. 410 * 411 * @param <T> the type to cast the result object to 412 * @param caller the lookup context describing the class performing the 413 * operation (normally stacked by the JVM) 414 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 415 * ({@code "_"}) 416 * @param type the type of the element at the given index in the class data 417 * @param index index of the element in the class data 418 * @return the element at the given index in the class data 419 * if the class data is present; otherwise {@code null} 420 * @throws IllegalArgumentException if name is not {@code "_"} 421 * @throws IllegalAccessException if the lookup context does not have 422 * {@linkplain Lookup#ORIGINAL original} access 423 * @throws ClassCastException if the class data cannot be converted to {@code List} 424 * or the element at the specified index cannot be converted to the given type 425 * @throws IndexOutOfBoundsException if the index is out of range 426 * @throws NullPointerException if {@code caller} or {@code type} argument is 427 * {@code null}; or if unboxing operation fails because 428 * the element at the given index is {@code null} 429 * 430 * @since 16 431 * @see #classData(Lookup, String, Class) 432 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 433 */ 434 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 435 throws IllegalAccessException 436 { 437 @SuppressWarnings("unchecked") 438 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 439 if (classdata == null) return null; 440 441 try { 442 Object element = classdata.get(index); 443 return BootstrapMethodInvoker.widenAndCast(element, type); 444 } catch (RuntimeException|Error e) { 445 throw e; // let specified exceptions and other runtime exceptions/errors through 446 } catch (Throwable e) { 447 throw new InternalError(e); 448 } 449 } 450 451 /** 452 * Performs an unchecked "crack" of a 453 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 454 * The result is as if the user had obtained a lookup object capable enough 455 * to crack the target method handle, called 456 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 457 * on the target to obtain its symbolic reference, and then called 458 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 459 * to resolve the symbolic reference to a member. 460 * <p> 461 * If there is a security manager, its {@code checkPermission} method 462 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 463 * @param <T> the desired type of the result, either {@link Member} or a subtype 464 * @param target a direct method handle to crack into symbolic reference components 465 * @param expected a class object representing the desired result type {@code T} 466 * @return a reference to the method, constructor, or field object 467 * @throws SecurityException if the caller is not privileged to call {@code setAccessible} 468 * @throws NullPointerException if either argument is {@code null} 469 * @throws IllegalArgumentException if the target is not a direct method handle 470 * @throws ClassCastException if the member is not of the expected type 471 * @since 1.8 472 */ 473 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 474 @SuppressWarnings("removal") 475 SecurityManager smgr = System.getSecurityManager(); 476 if (smgr != null) smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION); 477 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 478 return lookup.revealDirect(target).reflectAs(expected, lookup); 479 } 480 481 /** 482 * A <em>lookup object</em> is a factory for creating method handles, 483 * when the creation requires access checking. 484 * Method handles do not perform 485 * access checks when they are called, but rather when they are created. 486 * Therefore, method handle access 487 * restrictions must be enforced when a method handle is created. 488 * The caller class against which those restrictions are enforced 489 * is known as the {@linkplain #lookupClass() lookup class}. 490 * <p> 491 * A lookup class which needs to create method handles will call 492 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 493 * When the {@code Lookup} factory object is created, the identity of the lookup class is 494 * determined, and securely stored in the {@code Lookup} object. 495 * The lookup class (or its delegates) may then use factory methods 496 * on the {@code Lookup} object to create method handles for access-checked members. 497 * This includes all methods, constructors, and fields which are allowed to the lookup class, 498 * even private ones. 499 * 500 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 501 * The factory methods on a {@code Lookup} object correspond to all major 502 * use cases for methods, constructors, and fields. 503 * Each method handle created by a factory method is the functional 504 * equivalent of a particular <em>bytecode behavior</em>. 505 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 506 * the Java Virtual Machine Specification.) 507 * Here is a summary of the correspondence between these factory methods and 508 * the behavior of the resulting method handles: 509 * <table class="striped"> 510 * <caption style="display:none">lookup method behaviors</caption> 511 * <thead> 512 * <tr> 513 * <th scope="col"><a id="equiv"></a>lookup expression</th> 514 * <th scope="col">member</th> 515 * <th scope="col">bytecode behavior</th> 516 * </tr> 517 * </thead> 518 * <tbody> 519 * <tr> 520 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 521 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 522 * </tr> 523 * <tr> 524 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 525 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 526 * </tr> 527 * <tr> 528 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 529 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 530 * </tr> 531 * <tr> 532 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 533 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 534 * </tr> 535 * <tr> 536 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 537 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 538 * </tr> 539 * <tr> 540 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 541 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 542 * </tr> 543 * <tr> 544 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 545 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 546 * </tr> 547 * <tr> 548 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 549 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 550 * </tr> 551 * <tr> 552 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 553 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 554 * </tr> 555 * <tr> 556 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 557 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 558 * </tr> 559 * <tr> 560 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 561 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 562 * </tr> 563 * <tr> 564 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 565 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 566 * </tr> 567 * <tr> 568 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 569 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 570 * </tr> 571 * <tr> 572 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 573 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 574 * </tr> 575 * </tbody> 576 * </table> 577 * 578 * Here, the type {@code C} is the class or interface being searched for a member, 579 * documented as a parameter named {@code refc} in the lookup methods. 580 * The method type {@code MT} is composed from the return type {@code T} 581 * and the sequence of argument types {@code A*}. 582 * The constructor also has a sequence of argument types {@code A*} and 583 * is deemed to return the newly-created object of type {@code C}. 584 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 585 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 586 * if it is present, it is always the leading argument to the method handle invocation. 587 * (In the case of some {@code protected} members, {@code this} may be 588 * restricted in type to the lookup class; see below.) 589 * The name {@code arg} stands for all the other method handle arguments. 590 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 591 * stands for a null reference if the accessed method or field is static, 592 * and {@code this} otherwise. 593 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 594 * for reflective objects corresponding to the given members declared in type {@code C}. 595 * <p> 596 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 597 * as if by {@code ldc CONSTANT_Class}. 598 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 599 * <p> 600 * In cases where the given member is of variable arity (i.e., a method or constructor) 601 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 602 * In all other cases, the returned method handle will be of fixed arity. 603 * <p style="font-size:smaller;"> 604 * <em>Discussion:</em> 605 * The equivalence between looked-up method handles and underlying 606 * class members and bytecode behaviors 607 * can break down in a few ways: 608 * <ul style="font-size:smaller;"> 609 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 610 * the lookup can still succeed, even when there is no equivalent 611 * Java expression or bytecoded constant. 612 * <li>Likewise, if {@code T} or {@code MT} 613 * is not symbolically accessible from the lookup class's loader, 614 * the lookup can still succeed. 615 * For example, lookups for {@code MethodHandle.invokeExact} and 616 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 617 * <li>If there is a security manager installed, it can forbid the lookup 618 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 619 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 620 * constant is not subject to security manager checks. 621 * <li>If the looked-up method has a 622 * <a href="MethodHandle.html#maxarity">very large arity</a>, 623 * the method handle creation may fail with an 624 * {@code IllegalArgumentException}, due to the method handle type having 625 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 626 * </ul> 627 * 628 * <h2><a id="access"></a>Access checking</h2> 629 * Access checks are applied in the factory methods of {@code Lookup}, 630 * when a method handle is created. 631 * This is a key difference from the Core Reflection API, since 632 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 633 * performs access checking against every caller, on every call. 634 * <p> 635 * All access checks start from a {@code Lookup} object, which 636 * compares its recorded lookup class against all requests to 637 * create method handles. 638 * A single {@code Lookup} object can be used to create any number 639 * of access-checked method handles, all checked against a single 640 * lookup class. 641 * <p> 642 * A {@code Lookup} object can be shared with other trusted code, 643 * such as a metaobject protocol. 644 * A shared {@code Lookup} object delegates the capability 645 * to create method handles on private members of the lookup class. 646 * Even if privileged code uses the {@code Lookup} object, 647 * the access checking is confined to the privileges of the 648 * original lookup class. 649 * <p> 650 * A lookup can fail, because 651 * the containing class is not accessible to the lookup class, or 652 * because the desired class member is missing, or because the 653 * desired class member is not accessible to the lookup class, or 654 * because the lookup object is not trusted enough to access the member. 655 * In the case of a field setter function on a {@code final} field, 656 * finality enforcement is treated as a kind of access control, 657 * and the lookup will fail, except in special cases of 658 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 659 * In any of these cases, a {@code ReflectiveOperationException} will be 660 * thrown from the attempted lookup. The exact class will be one of 661 * the following: 662 * <ul> 663 * <li>NoSuchMethodException — if a method is requested but does not exist 664 * <li>NoSuchFieldException — if a field is requested but does not exist 665 * <li>IllegalAccessException — if the member exists but an access check fails 666 * </ul> 667 * <p> 668 * In general, the conditions under which a method handle may be 669 * looked up for a method {@code M} are no more restrictive than the conditions 670 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 671 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 672 * a method handle lookup will generally raise a corresponding 673 * checked exception, such as {@code NoSuchMethodException}. 674 * And the effect of invoking the method handle resulting from the lookup 675 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 676 * to executing the compiled, verified, and resolved call to {@code M}. 677 * The same point is true of fields and constructors. 678 * <p style="font-size:smaller;"> 679 * <em>Discussion:</em> 680 * Access checks only apply to named and reflected methods, 681 * constructors, and fields. 682 * Other method handle creation methods, such as 683 * {@link MethodHandle#asType MethodHandle.asType}, 684 * do not require any access checks, and are used 685 * independently of any {@code Lookup} object. 686 * <p> 687 * If the desired member is {@code protected}, the usual JVM rules apply, 688 * including the requirement that the lookup class must either be in the 689 * same package as the desired member, or must inherit that member. 690 * (See the Java Virtual Machine Specification, sections {@jvms 691 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 692 * In addition, if the desired member is a non-static field or method 693 * in a different package, the resulting method handle may only be applied 694 * to objects of the lookup class or one of its subclasses. 695 * This requirement is enforced by narrowing the type of the leading 696 * {@code this} parameter from {@code C} 697 * (which will necessarily be a superclass of the lookup class) 698 * to the lookup class itself. 699 * <p> 700 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 701 * that the receiver argument must match both the resolved method <em>and</em> 702 * the current class. Again, this requirement is enforced by narrowing the 703 * type of the leading parameter to the resulting method handle. 704 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 705 * <p> 706 * The JVM represents constructors and static initializer blocks as internal methods 707 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 708 * ConstantDescs#CLASS_INIT_NAME}). 709 * The internal syntax of invocation instructions allows them to refer to such internal 710 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 711 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 712 * <p> 713 * If the relationship between nested types is expressed directly through the 714 * {@code NestHost} and {@code NestMembers} attributes 715 * (see the Java Virtual Machine Specification, sections {@jvms 716 * 4.7.28} and {@jvms 4.7.29}), 717 * then the associated {@code Lookup} object provides direct access to 718 * the lookup class and all of its nestmates 719 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 720 * Otherwise, access between nested classes is obtained by the Java compiler creating 721 * a wrapper method to access a private method of another class in the same nest. 722 * For example, a nested class {@code C.D} 723 * can access private members within other related classes such as 724 * {@code C}, {@code C.D.E}, or {@code C.B}, 725 * but the Java compiler may need to generate wrapper methods in 726 * those related classes. In such cases, a {@code Lookup} object on 727 * {@code C.E} would be unable to access those private members. 728 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 729 * which can transform a lookup on {@code C.E} into one on any of those other 730 * classes, without special elevation of privilege. 731 * <p> 732 * The accesses permitted to a given lookup object may be limited, 733 * according to its set of {@link #lookupModes lookupModes}, 734 * to a subset of members normally accessible to the lookup class. 735 * For example, the {@link MethodHandles#publicLookup publicLookup} 736 * method produces a lookup object which is only allowed to access 737 * public members in public classes of exported packages. 738 * The caller sensitive method {@link MethodHandles#lookup lookup} 739 * produces a lookup object with full capabilities relative to 740 * its caller class, to emulate all supported bytecode behaviors. 741 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 742 * with fewer access modes than the original lookup object. 743 * 744 * <p style="font-size:smaller;"> 745 * <a id="privacc"></a> 746 * <em>Discussion of private and module access:</em> 747 * We say that a lookup has <em>private access</em> 748 * if its {@linkplain #lookupModes lookup modes} 749 * include the possibility of accessing {@code private} members 750 * (which includes the private members of nestmates). 751 * As documented in the relevant methods elsewhere, 752 * only lookups with private access possess the following capabilities: 753 * <ul style="font-size:smaller;"> 754 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 755 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 756 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 757 * for classes accessible to the lookup class 758 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 759 * within the same package member 760 * </ul> 761 * <p style="font-size:smaller;"> 762 * Similarly, a lookup with module access ensures that the original lookup creator was 763 * a member in the same module as the lookup class. 764 * <p style="font-size:smaller;"> 765 * Private and module access are independently determined modes; a lookup may have 766 * either or both or neither. A lookup which possesses both access modes is said to 767 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 768 * <p style="font-size:smaller;"> 769 * A lookup with <em>original access</em> ensures that this lookup is created by 770 * the original lookup class and the bootstrap method invoked by the VM. 771 * Such a lookup with original access also has private and module access 772 * which has the following additional capability: 773 * <ul style="font-size:smaller;"> 774 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 775 * such as {@code Class.forName} 776 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 777 * class data} associated with the lookup class</li> 778 * </ul> 779 * <p style="font-size:smaller;"> 780 * Each of these permissions is a consequence of the fact that a lookup object 781 * with private access can be securely traced back to an originating class, 782 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 783 * can be reliably determined and emulated by method handles. 784 * 785 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 786 * When a lookup class in one module {@code M1} accesses a class in another module 787 * {@code M2}, extra access checking is performed beyond the access mode bits. 788 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 789 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 790 * and when the type is in a package of {@code M2} that is exported to 791 * at least {@code M1}. 792 * <p> 793 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 794 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 795 * MethodHandles.privateLookupIn} methods. 796 * Teleporting across modules will always record the original lookup class as 797 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 798 * and drops {@link Lookup#MODULE MODULE} access. 799 * If the target class is in the same module as the lookup class {@code C}, 800 * then the target class becomes the new lookup class 801 * and there is no change to the previous lookup class. 802 * If the target class is in a different module from {@code M1} ({@code C}'s module), 803 * {@code C} becomes the new previous lookup class 804 * and the target class becomes the new lookup class. 805 * In that case, if there was already a previous lookup class in {@code M0}, 806 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 807 * drops all privileges. 808 * For example, 809 * {@snippet lang="java" : 810 * Lookup lookup = MethodHandles.lookup(); // in class C 811 * Lookup lookup2 = lookup.in(D.class); 812 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 813 * } 814 * <p> 815 * The {@link #lookup()} factory method produces a {@code Lookup} object 816 * with {@code null} previous lookup class. 817 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 818 * to class {@code D} without elevation of privileges. 819 * If {@code C} and {@code D} are in the same module, 820 * {@code lookup2} records {@code D} as the new lookup class and keeps the 821 * same previous lookup class as the original {@code lookup}, or 822 * {@code null} if not present. 823 * <p> 824 * When a {@code Lookup} teleports from a class 825 * in one nest to another nest, {@code PRIVATE} access is dropped. 826 * When a {@code Lookup} teleports from a class in one package to 827 * another package, {@code PACKAGE} access is dropped. 828 * When a {@code Lookup} teleports from a class in one module to another module, 829 * {@code MODULE} access is dropped. 830 * Teleporting across modules drops the ability to access non-exported classes 831 * in both the module of the new lookup class and the module of the old lookup class 832 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 833 * A {@code Lookup} can teleport back and forth to a class in the module of 834 * the lookup class and the module of the previous class lookup. 835 * Teleporting across modules can only decrease access but cannot increase it. 836 * Teleporting to some third module drops all accesses. 837 * <p> 838 * In the above example, if {@code C} and {@code D} are in different modules, 839 * {@code lookup2} records {@code D} as its lookup class and 840 * {@code C} as its previous lookup class and {@code lookup2} has only 841 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 842 * {@code C}'s module and {@code D}'s module. 843 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 844 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 845 * class {@code D} is recorded as its previous lookup class. 846 * <p> 847 * Teleporting across modules restricts access to the public types that 848 * both the lookup class and the previous lookup class can equally access 849 * (see below). 850 * <p> 851 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 852 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 853 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 854 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 855 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 856 * to call {@code privateLookupIn}. 857 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 858 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 859 * produces a new {@code Lookup} on {@code T} with full capabilities. 860 * A {@code lookup} on {@code C} is also allowed 861 * to do deep reflection on {@code T} in another module {@code M2} if 862 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 863 * the package containing {@code T} to at least {@code M1}. 864 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 865 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 866 * The resulting {@code Lookup} can be used to do member lookup or teleport 867 * to another lookup class by calling {@link #in Lookup::in}. But 868 * it cannot be used to obtain another private {@code Lookup} by calling 869 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 870 * because it has no {@code MODULE} access. 871 * <p> 872 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 873 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 874 * of {@code T}. Extreme caution should be taken when opening a package 875 * to another module as such defined classes have the same full privilege 876 * access as other members in {@code M2}. 877 * 878 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 879 * 880 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 881 * allows cross-module access. The access checking is performed with respect 882 * to both the lookup class and the previous lookup class if present. 883 * <p> 884 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 885 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 886 * exported unconditionally}. 887 * <p> 888 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 889 * the lookup with {@link #PUBLIC} mode can access all public types in modules 890 * that are readable to {@code M1} and the type is in a package that is exported 891 * at least to {@code M1}. 892 * <p> 893 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 894 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 895 * the intersection of all public types that are accessible to {@code M1} 896 * with all public types that are accessible to {@code M0}. {@code M0} 897 * reads {@code M1} and hence the set of accessible types includes: 898 * 899 * <ul> 900 * <li>unconditional-exported packages from {@code M1}</li> 901 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 902 * <li> 903 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 904 * and {@code M1} read {@code M2} 905 * </li> 906 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 907 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 908 * <li> 909 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 910 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 911 * </li> 912 * </ul> 913 * 914 * <h2><a id="access-modes"></a>Access modes</h2> 915 * 916 * The table below shows the access modes of a {@code Lookup} produced by 917 * any of the following factory or transformation methods: 918 * <ul> 919 * <li>{@link #lookup() MethodHandles::lookup}</li> 920 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 921 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 922 * <li>{@link Lookup#in Lookup::in}</li> 923 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 924 * </ul> 925 * 926 * <table class="striped"> 927 * <caption style="display:none"> 928 * Access mode summary 929 * </caption> 930 * <thead> 931 * <tr> 932 * <th scope="col">Lookup object</th> 933 * <th style="text-align:center">original</th> 934 * <th style="text-align:center">protected</th> 935 * <th style="text-align:center">private</th> 936 * <th style="text-align:center">package</th> 937 * <th style="text-align:center">module</th> 938 * <th style="text-align:center">public</th> 939 * </tr> 940 * </thead> 941 * <tbody> 942 * <tr> 943 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 944 * <td style="text-align:center">ORI</td> 945 * <td style="text-align:center">PRO</td> 946 * <td style="text-align:center">PRI</td> 947 * <td style="text-align:center">PAC</td> 948 * <td style="text-align:center">MOD</td> 949 * <td style="text-align:center">1R</td> 950 * </tr> 951 * <tr> 952 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 953 * <td></td> 954 * <td></td> 955 * <td></td> 956 * <td style="text-align:center">PAC</td> 957 * <td style="text-align:center">MOD</td> 958 * <td style="text-align:center">1R</td> 959 * </tr> 960 * <tr> 961 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 962 * <td></td> 963 * <td></td> 964 * <td></td> 965 * <td></td> 966 * <td style="text-align:center">MOD</td> 967 * <td style="text-align:center">1R</td> 968 * </tr> 969 * <tr> 970 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 971 * <td></td> 972 * <td></td> 973 * <td></td> 974 * <td></td> 975 * <td></td> 976 * <td style="text-align:center">2R</td> 977 * </tr> 978 * <tr> 979 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 980 * <td></td> 981 * <td></td> 982 * <td></td> 983 * <td></td> 984 * <td></td> 985 * <td style="text-align:center">2R</td> 986 * </tr> 987 * <tr> 988 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 989 * <td></td> 990 * <td style="text-align:center">PRO</td> 991 * <td style="text-align:center">PRI</td> 992 * <td style="text-align:center">PAC</td> 993 * <td style="text-align:center">MOD</td> 994 * <td style="text-align:center">1R</td> 995 * </tr> 996 * <tr> 997 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 998 * <td></td> 999 * <td style="text-align:center">PRO</td> 1000 * <td style="text-align:center">PRI</td> 1001 * <td style="text-align:center">PAC</td> 1002 * <td style="text-align:center">MOD</td> 1003 * <td style="text-align:center">1R</td> 1004 * </tr> 1005 * <tr> 1006 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1007 * <td></td> 1008 * <td></td> 1009 * <td></td> 1010 * <td style="text-align:center">PAC</td> 1011 * <td style="text-align:center">MOD</td> 1012 * <td style="text-align:center">1R</td> 1013 * </tr> 1014 * <tr> 1015 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1016 * <td></td> 1017 * <td></td> 1018 * <td></td> 1019 * <td></td> 1020 * <td style="text-align:center">MOD</td> 1021 * <td style="text-align:center">1R</td> 1022 * </tr> 1023 * <tr> 1024 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1025 * <td></td> 1026 * <td></td> 1027 * <td></td> 1028 * <td></td> 1029 * <td></td> 1030 * <td style="text-align:center">2R</td> 1031 * </tr> 1032 * <tr> 1033 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1034 * <td></td> 1035 * <td></td> 1036 * <td style="text-align:center">PRI</td> 1037 * <td style="text-align:center">PAC</td> 1038 * <td style="text-align:center">MOD</td> 1039 * <td style="text-align:center">1R</td> 1040 * </tr> 1041 * <tr> 1042 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1043 * <td></td> 1044 * <td></td> 1045 * <td></td> 1046 * <td style="text-align:center">PAC</td> 1047 * <td style="text-align:center">MOD</td> 1048 * <td style="text-align:center">1R</td> 1049 * </tr> 1050 * <tr> 1051 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1052 * <td></td> 1053 * <td></td> 1054 * <td></td> 1055 * <td></td> 1056 * <td style="text-align:center">MOD</td> 1057 * <td style="text-align:center">1R</td> 1058 * </tr> 1059 * <tr> 1060 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1061 * <td></td> 1062 * <td></td> 1063 * <td></td> 1064 * <td></td> 1065 * <td></td> 1066 * <td style="text-align:center">1R</td> 1067 * </tr> 1068 * <tr> 1069 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1070 * <td></td> 1071 * <td></td> 1072 * <td></td> 1073 * <td></td> 1074 * <td></td> 1075 * <td style="text-align:center">none</td> 1076 * <tr> 1077 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1078 * <td></td> 1079 * <td style="text-align:center">PRO</td> 1080 * <td style="text-align:center">PRI</td> 1081 * <td style="text-align:center">PAC</td> 1082 * <td></td> 1083 * <td style="text-align:center">2R</td> 1084 * </tr> 1085 * <tr> 1086 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1087 * <td></td> 1088 * <td style="text-align:center">PRO</td> 1089 * <td style="text-align:center">PRI</td> 1090 * <td style="text-align:center">PAC</td> 1091 * <td></td> 1092 * <td style="text-align:center">2R</td> 1093 * </tr> 1094 * <tr> 1095 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1096 * <td></td> 1097 * <td></td> 1098 * <td></td> 1099 * <td></td> 1100 * <td></td> 1101 * <td style="text-align:center">IAE</td> 1102 * </tr> 1103 * <tr> 1104 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1105 * <td></td> 1106 * <td></td> 1107 * <td></td> 1108 * <td style="text-align:center">PAC</td> 1109 * <td></td> 1110 * <td style="text-align:center">2R</td> 1111 * </tr> 1112 * <tr> 1113 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1114 * <td></td> 1115 * <td></td> 1116 * <td></td> 1117 * <td></td> 1118 * <td></td> 1119 * <td style="text-align:center">2R</td> 1120 * </tr> 1121 * <tr> 1122 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1123 * <td></td> 1124 * <td></td> 1125 * <td></td> 1126 * <td></td> 1127 * <td></td> 1128 * <td style="text-align:center">2R</td> 1129 * </tr> 1130 * <tr> 1131 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1132 * <td></td> 1133 * <td></td> 1134 * <td></td> 1135 * <td></td> 1136 * <td></td> 1137 * <td style="text-align:center">none</td> 1138 * </tr> 1139 * <tr> 1140 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1141 * <td></td> 1142 * <td></td> 1143 * <td style="text-align:center">PRI</td> 1144 * <td style="text-align:center">PAC</td> 1145 * <td></td> 1146 * <td style="text-align:center">2R</td> 1147 * </tr> 1148 * <tr> 1149 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1150 * <td></td> 1151 * <td></td> 1152 * <td></td> 1153 * <td style="text-align:center">PAC</td> 1154 * <td></td> 1155 * <td style="text-align:center">2R</td> 1156 * </tr> 1157 * <tr> 1158 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1159 * <td></td> 1160 * <td></td> 1161 * <td></td> 1162 * <td></td> 1163 * <td></td> 1164 * <td style="text-align:center">2R</td> 1165 * </tr> 1166 * <tr> 1167 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1168 * <td></td> 1169 * <td></td> 1170 * <td></td> 1171 * <td></td> 1172 * <td></td> 1173 * <td style="text-align:center">2R</td> 1174 * </tr> 1175 * <tr> 1176 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1177 * <td></td> 1178 * <td></td> 1179 * <td></td> 1180 * <td></td> 1181 * <td></td> 1182 * <td style="text-align:center">none</td> 1183 * </tr> 1184 * <tr> 1185 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1186 * <td></td> 1187 * <td></td> 1188 * <td style="text-align:center">PRI</td> 1189 * <td style="text-align:center">PAC</td> 1190 * <td style="text-align:center">MOD</td> 1191 * <td style="text-align:center">1R</td> 1192 * </tr> 1193 * <tr> 1194 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1195 * <td></td> 1196 * <td></td> 1197 * <td></td> 1198 * <td style="text-align:center">PAC</td> 1199 * <td style="text-align:center">MOD</td> 1200 * <td style="text-align:center">1R</td> 1201 * </tr> 1202 * <tr> 1203 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1204 * <td></td> 1205 * <td></td> 1206 * <td></td> 1207 * <td></td> 1208 * <td style="text-align:center">MOD</td> 1209 * <td style="text-align:center">1R</td> 1210 * </tr> 1211 * <tr> 1212 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1213 * <td></td> 1214 * <td></td> 1215 * <td></td> 1216 * <td></td> 1217 * <td></td> 1218 * <td style="text-align:center">1R</td> 1219 * </tr> 1220 * <tr> 1221 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1222 * <td></td> 1223 * <td></td> 1224 * <td></td> 1225 * <td></td> 1226 * <td></td> 1227 * <td style="text-align:center">none</td> 1228 * </tr> 1229 * <tr> 1230 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1231 * <td></td> 1232 * <td></td> 1233 * <td></td> 1234 * <td></td> 1235 * <td></td> 1236 * <td style="text-align:center">U</td> 1237 * </tr> 1238 * <tr> 1239 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1240 * <td></td> 1241 * <td></td> 1242 * <td></td> 1243 * <td></td> 1244 * <td></td> 1245 * <td style="text-align:center">U</td> 1246 * </tr> 1247 * <tr> 1248 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1249 * <td></td> 1250 * <td></td> 1251 * <td></td> 1252 * <td></td> 1253 * <td></td> 1254 * <td style="text-align:center">U</td> 1255 * </tr> 1256 * <tr> 1257 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1258 * <td></td> 1259 * <td></td> 1260 * <td></td> 1261 * <td></td> 1262 * <td></td> 1263 * <td style="text-align:center">none</td> 1264 * </tr> 1265 * <tr> 1266 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1267 * <td></td> 1268 * <td></td> 1269 * <td></td> 1270 * <td></td> 1271 * <td></td> 1272 * <td style="text-align:center">IAE</td> 1273 * </tr> 1274 * <tr> 1275 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1276 * <td></td> 1277 * <td></td> 1278 * <td></td> 1279 * <td></td> 1280 * <td></td> 1281 * <td style="text-align:center">none</td> 1282 * </tr> 1283 * </tbody> 1284 * </table> 1285 * 1286 * <p> 1287 * Notes: 1288 * <ul> 1289 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1290 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1291 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1292 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1293 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1294 * {@code PRO} indicates {@link #PROTECTED} bit set, 1295 * {@code PRI} indicates {@link #PRIVATE} bit set, 1296 * {@code PAC} indicates {@link #PACKAGE} bit set, 1297 * {@code MOD} indicates {@link #MODULE} bit set, 1298 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1299 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1300 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1301 * <li>Public access comes in three kinds: 1302 * <ul> 1303 * <li>unconditional ({@code U}): the lookup assumes readability. 1304 * The lookup has {@code null} previous lookup class. 1305 * <li>one-module-reads ({@code 1R}): the module access checking is 1306 * performed with respect to the lookup class. The lookup has {@code null} 1307 * previous lookup class. 1308 * <li>two-module-reads ({@code 2R}): the module access checking is 1309 * performed with respect to the lookup class and the previous lookup class. 1310 * The lookup has a non-null previous lookup class which is in a 1311 * different module from the current lookup class. 1312 * </ul> 1313 * <li>Any attempt to reach a third module loses all access.</li> 1314 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1315 * all access modes are dropped.</li> 1316 * </ul> 1317 * 1318 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1319 * Although bytecode instructions can only refer to classes in 1320 * a related class loader, this API can search for methods in any 1321 * class, as long as a reference to its {@code Class} object is 1322 * available. Such cross-loader references are also possible with the 1323 * Core Reflection API, and are impossible to bytecode instructions 1324 * such as {@code invokestatic} or {@code getfield}. 1325 * There is a {@linkplain java.lang.SecurityManager security manager API} 1326 * to allow applications to check such cross-loader references. 1327 * These checks apply to both the {@code MethodHandles.Lookup} API 1328 * and the Core Reflection API 1329 * (as found on {@link java.lang.Class Class}). 1330 * <p> 1331 * If a security manager is present, member and class lookups are subject to 1332 * additional checks. 1333 * From one to three calls are made to the security manager. 1334 * Any of these calls can refuse access by throwing a 1335 * {@link java.lang.SecurityException SecurityException}. 1336 * Define {@code smgr} as the security manager, 1337 * {@code lookc} as the lookup class of the current lookup object, 1338 * {@code refc} as the containing class in which the member 1339 * is being sought, and {@code defc} as the class in which the 1340 * member is actually defined. 1341 * (If a class or other type is being accessed, 1342 * the {@code refc} and {@code defc} values are the class itself.) 1343 * The value {@code lookc} is defined as <em>not present</em> 1344 * if the current lookup object does not have 1345 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1346 * The calls are made according to the following rules: 1347 * <ul> 1348 * <li><b>Step 1:</b> 1349 * If {@code lookc} is not present, or if its class loader is not 1350 * the same as or an ancestor of the class loader of {@code refc}, 1351 * then {@link SecurityManager#checkPackageAccess 1352 * smgr.checkPackageAccess(refcPkg)} is called, 1353 * where {@code refcPkg} is the package of {@code refc}. 1354 * <li><b>Step 2a:</b> 1355 * If the retrieved member is not public and 1356 * {@code lookc} is not present, then 1357 * {@link SecurityManager#checkPermission smgr.checkPermission} 1358 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1359 * <li><b>Step 2b:</b> 1360 * If the retrieved class has a {@code null} class loader, 1361 * and {@code lookc} is not present, then 1362 * {@link SecurityManager#checkPermission smgr.checkPermission} 1363 * with {@code RuntimePermission("getClassLoader")} is called. 1364 * <li><b>Step 3:</b> 1365 * If the retrieved member is not public, 1366 * and if {@code lookc} is not present, 1367 * and if {@code defc} and {@code refc} are different, 1368 * then {@link SecurityManager#checkPackageAccess 1369 * smgr.checkPackageAccess(defcPkg)} is called, 1370 * where {@code defcPkg} is the package of {@code defc}. 1371 * </ul> 1372 * Security checks are performed after other access checks have passed. 1373 * Therefore, the above rules presuppose a member or class that is public, 1374 * or else that is being accessed from a lookup class that has 1375 * rights to access the member or class. 1376 * <p> 1377 * If a security manager is present and the current lookup object does not have 1378 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1379 * {@link #defineClass(byte[]) defineClass}, 1380 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1381 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1382 * defineHiddenClassWithClassData} 1383 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1384 * with {@code RuntimePermission("defineClass")}. 1385 * 1386 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1387 * A small number of Java methods have a special property called caller sensitivity. 1388 * A <em>caller-sensitive</em> method can behave differently depending on the 1389 * identity of its immediate caller. 1390 * <p> 1391 * If a method handle for a caller-sensitive method is requested, 1392 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1393 * but they take account of the lookup class in a special way. 1394 * The resulting method handle behaves as if it were called 1395 * from an instruction contained in the lookup class, 1396 * so that the caller-sensitive method detects the lookup class. 1397 * (By contrast, the invoker of the method handle is disregarded.) 1398 * Thus, in the case of caller-sensitive methods, 1399 * different lookup classes may give rise to 1400 * differently behaving method handles. 1401 * <p> 1402 * In cases where the lookup object is 1403 * {@link MethodHandles#publicLookup() publicLookup()}, 1404 * or some other lookup object without the 1405 * {@linkplain #ORIGINAL original access}, 1406 * the lookup class is disregarded. 1407 * In such cases, no caller-sensitive method handle can be created, 1408 * access is forbidden, and the lookup fails with an 1409 * {@code IllegalAccessException}. 1410 * <p style="font-size:smaller;"> 1411 * <em>Discussion:</em> 1412 * For example, the caller-sensitive method 1413 * {@link java.lang.Class#forName(String) Class.forName(x)} 1414 * can return varying classes or throw varying exceptions, 1415 * depending on the class loader of the class that calls it. 1416 * A public lookup of {@code Class.forName} will fail, because 1417 * there is no reasonable way to determine its bytecode behavior. 1418 * <p style="font-size:smaller;"> 1419 * If an application caches method handles for broad sharing, 1420 * it should use {@code publicLookup()} to create them. 1421 * If there is a lookup of {@code Class.forName}, it will fail, 1422 * and the application must take appropriate action in that case. 1423 * It may be that a later lookup, perhaps during the invocation of a 1424 * bootstrap method, can incorporate the specific identity 1425 * of the caller, making the method accessible. 1426 * <p style="font-size:smaller;"> 1427 * The function {@code MethodHandles.lookup} is caller sensitive 1428 * so that there can be a secure foundation for lookups. 1429 * Nearly all other methods in the JSR 292 API rely on lookup 1430 * objects to check access requests. 1431 */ 1432 public static final 1433 class Lookup { 1434 /** The class on behalf of whom the lookup is being performed. */ 1435 private final Class<?> lookupClass; 1436 1437 /** previous lookup class */ 1438 private final Class<?> prevLookupClass; 1439 1440 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1441 private final int allowedModes; 1442 1443 static { 1444 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1445 } 1446 1447 /** A single-bit mask representing {@code public} access, 1448 * which may contribute to the result of {@link #lookupModes lookupModes}. 1449 * The value, {@code 0x01}, happens to be the same as the value of the 1450 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1451 * <p> 1452 * A {@code Lookup} with this lookup mode performs cross-module access check 1453 * with respect to the {@linkplain #lookupClass() lookup class} and 1454 * {@linkplain #previousLookupClass() previous lookup class} if present. 1455 */ 1456 public static final int PUBLIC = Modifier.PUBLIC; 1457 1458 /** A single-bit mask representing {@code private} access, 1459 * which may contribute to the result of {@link #lookupModes lookupModes}. 1460 * The value, {@code 0x02}, happens to be the same as the value of the 1461 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1462 */ 1463 public static final int PRIVATE = Modifier.PRIVATE; 1464 1465 /** A single-bit mask representing {@code protected} access, 1466 * which may contribute to the result of {@link #lookupModes lookupModes}. 1467 * The value, {@code 0x04}, happens to be the same as the value of the 1468 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1469 */ 1470 public static final int PROTECTED = Modifier.PROTECTED; 1471 1472 /** A single-bit mask representing {@code package} access (default access), 1473 * which may contribute to the result of {@link #lookupModes lookupModes}. 1474 * The value is {@code 0x08}, which does not correspond meaningfully to 1475 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1476 */ 1477 public static final int PACKAGE = Modifier.STATIC; 1478 1479 /** A single-bit mask representing {@code module} access, 1480 * which may contribute to the result of {@link #lookupModes lookupModes}. 1481 * The value is {@code 0x10}, which does not correspond meaningfully to 1482 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1483 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1484 * with this lookup mode can access all public types in the module of the 1485 * lookup class and public types in packages exported by other modules 1486 * to the module of the lookup class. 1487 * <p> 1488 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1489 * previous lookup class} is always {@code null}. 1490 * 1491 * @since 9 1492 */ 1493 public static final int MODULE = PACKAGE << 1; 1494 1495 /** A single-bit mask representing {@code unconditional} access 1496 * which may contribute to the result of {@link #lookupModes lookupModes}. 1497 * The value is {@code 0x20}, which does not correspond meaningfully to 1498 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1499 * A {@code Lookup} with this lookup mode assumes {@linkplain 1500 * java.lang.Module#canRead(java.lang.Module) readability}. 1501 * This lookup mode can access all public members of public types 1502 * of all modules when the type is in a package that is {@link 1503 * java.lang.Module#isExported(String) exported unconditionally}. 1504 * 1505 * <p> 1506 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1507 * previous lookup class} is always {@code null}. 1508 * 1509 * @since 9 1510 * @see #publicLookup() 1511 */ 1512 public static final int UNCONDITIONAL = PACKAGE << 2; 1513 1514 /** A single-bit mask representing {@code original} access 1515 * which may contribute to the result of {@link #lookupModes lookupModes}. 1516 * The value is {@code 0x40}, which does not correspond meaningfully to 1517 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1518 * 1519 * <p> 1520 * If this lookup mode is set, the {@code Lookup} object must be 1521 * created by the original lookup class by calling 1522 * {@link MethodHandles#lookup()} method or by a bootstrap method 1523 * invoked by the VM. The {@code Lookup} object with this lookup 1524 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1525 * 1526 * @since 16 1527 */ 1528 public static final int ORIGINAL = PACKAGE << 3; 1529 1530 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1531 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1532 private static final int TRUSTED = -1; 1533 1534 /* 1535 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1536 * Adjust 0 => PACKAGE 1537 */ 1538 private static int fixmods(int mods) { 1539 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1540 if (Modifier.isPublic(mods)) 1541 mods |= UNCONDITIONAL; 1542 return (mods != 0) ? mods : PACKAGE; 1543 } 1544 1545 /** Tells which class is performing the lookup. It is this class against 1546 * which checks are performed for visibility and access permissions. 1547 * <p> 1548 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1549 * access checks are performed against both the lookup class and the previous lookup class. 1550 * <p> 1551 * The class implies a maximum level of access permission, 1552 * but the permissions may be additionally limited by the bitmask 1553 * {@link #lookupModes lookupModes}, which controls whether non-public members 1554 * can be accessed. 1555 * @return the lookup class, on behalf of which this lookup object finds members 1556 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1557 */ 1558 public Class<?> lookupClass() { 1559 return lookupClass; 1560 } 1561 1562 /** Reports a lookup class in another module that this lookup object 1563 * was previously teleported from, or {@code null}. 1564 * <p> 1565 * A {@code Lookup} object produced by the factory methods, such as the 1566 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1567 * has {@code null} previous lookup class. 1568 * A {@code Lookup} object has a non-null previous lookup class 1569 * when this lookup was teleported from an old lookup class 1570 * in one module to a new lookup class in another module. 1571 * 1572 * @return the lookup class in another module that this lookup object was 1573 * previously teleported from, or {@code null} 1574 * @since 14 1575 * @see #in(Class) 1576 * @see MethodHandles#privateLookupIn(Class, Lookup) 1577 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1578 */ 1579 public Class<?> previousLookupClass() { 1580 return prevLookupClass; 1581 } 1582 1583 // This is just for calling out to MethodHandleImpl. 1584 private Class<?> lookupClassOrNull() { 1585 return (allowedModes == TRUSTED) ? null : lookupClass; 1586 } 1587 1588 /** Tells which access-protection classes of members this lookup object can produce. 1589 * The result is a bit-mask of the bits 1590 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1591 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1592 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1593 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1594 * {@linkplain #MODULE MODULE (0x10)}, 1595 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1596 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1597 * <p> 1598 * A freshly-created lookup object 1599 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1600 * all possible bits set, except {@code UNCONDITIONAL}. 1601 * A lookup object on a new lookup class 1602 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1603 * may have some mode bits set to zero. 1604 * Mode bits can also be 1605 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1606 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1607 * The purpose of this is to restrict access via the new lookup object, 1608 * so that it can access only names which can be reached by the original 1609 * lookup object, and also by the new lookup class. 1610 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1611 * @see #in 1612 * @see #dropLookupMode 1613 */ 1614 public int lookupModes() { 1615 return allowedModes & ALL_MODES; 1616 } 1617 1618 /** Embody the current class (the lookupClass) as a lookup class 1619 * for method handle creation. 1620 * Must be called by from a method in this package, 1621 * which in turn is called by a method not in this package. 1622 */ 1623 Lookup(Class<?> lookupClass) { 1624 this(lookupClass, null, FULL_POWER_MODES); 1625 } 1626 1627 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1628 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1629 && prevLookupClass.getModule() != lookupClass.getModule()); 1630 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1631 this.lookupClass = lookupClass; 1632 this.prevLookupClass = prevLookupClass; 1633 this.allowedModes = allowedModes; 1634 } 1635 1636 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1637 // make sure we haven't accidentally picked up a privileged class: 1638 checkUnprivilegedlookupClass(lookupClass); 1639 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1640 } 1641 1642 /** 1643 * Creates a lookup on the specified new lookup class. 1644 * The resulting object will report the specified 1645 * class as its own {@link #lookupClass() lookupClass}. 1646 * 1647 * <p> 1648 * However, the resulting {@code Lookup} object is guaranteed 1649 * to have no more access capabilities than the original. 1650 * In particular, access capabilities can be lost as follows:<ul> 1651 * <li>If the new lookup class is different from the old lookup class, 1652 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1653 * <li>If the new lookup class is in a different module from the old one, 1654 * i.e. {@link #MODULE MODULE} access is lost. 1655 * <li>If the new lookup class is in a different package 1656 * than the old one, protected and default (package) members will not be accessible, 1657 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1658 * <li>If the new lookup class is not within the same package member 1659 * as the old one, private members will not be accessible, and protected members 1660 * will not be accessible by virtue of inheritance, 1661 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1662 * (Protected members may continue to be accessible because of package sharing.) 1663 * <li>If the new lookup class is not 1664 * {@linkplain #accessClass(Class) accessible} to this lookup, 1665 * then no members, not even public members, will be accessible 1666 * i.e. all access modes are lost. 1667 * <li>If the new lookup class, the old lookup class and the previous lookup class 1668 * are all in different modules i.e. teleporting to a third module, 1669 * all access modes are lost. 1670 * </ul> 1671 * <p> 1672 * The new previous lookup class is chosen as follows: 1673 * <ul> 1674 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1675 * the new previous lookup class is {@code null}. 1676 * <li>If the new lookup class is in the same module as the old lookup class, 1677 * the new previous lookup class is the old previous lookup class. 1678 * <li>If the new lookup class is in a different module from the old lookup class, 1679 * the new previous lookup class is the old lookup class. 1680 *</ul> 1681 * <p> 1682 * The resulting lookup's capabilities for loading classes 1683 * (used during {@link #findClass} invocations) 1684 * are determined by the lookup class' loader, 1685 * which may change due to this operation. 1686 * 1687 * @param requestedLookupClass the desired lookup class for the new lookup object 1688 * @return a lookup object which reports the desired lookup class, or the same object 1689 * if there is no change 1690 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1691 * @throws NullPointerException if the argument is null 1692 * 1693 * @see #accessClass(Class) 1694 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1695 */ 1696 public Lookup in(Class<?> requestedLookupClass) { 1697 Objects.requireNonNull(requestedLookupClass); 1698 if (requestedLookupClass.isPrimitive()) 1699 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1700 if (requestedLookupClass.isArray()) 1701 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1702 1703 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1704 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1705 if (requestedLookupClass == this.lookupClass) 1706 return this; // keep same capabilities 1707 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1708 Module fromModule = this.lookupClass.getModule(); 1709 Module targetModule = requestedLookupClass.getModule(); 1710 Class<?> plc = this.previousLookupClass(); 1711 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1712 assert plc == null; 1713 newModes = UNCONDITIONAL; 1714 } else if (fromModule != targetModule) { 1715 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1716 // allow hopping back and forth between fromModule and plc's module 1717 // but not the third module 1718 newModes = 0; 1719 } 1720 // drop MODULE access 1721 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1722 // teleport from this lookup class 1723 plc = this.lookupClass; 1724 } 1725 if ((newModes & PACKAGE) != 0 1726 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1727 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1728 } 1729 // Allow nestmate lookups to be created without special privilege: 1730 if ((newModes & PRIVATE) != 0 1731 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1732 newModes &= ~(PRIVATE|PROTECTED); 1733 } 1734 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1735 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1736 // The requested class it not accessible from the lookup class. 1737 // No permissions. 1738 newModes = 0; 1739 } 1740 return newLookup(requestedLookupClass, plc, newModes); 1741 } 1742 1743 /** 1744 * Creates a lookup on the same lookup class which this lookup object 1745 * finds members, but with a lookup mode that has lost the given lookup mode. 1746 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1747 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1748 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1749 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1750 * 1751 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1752 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1753 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1754 * lookup has no access. 1755 * 1756 * <p> If this lookup is not a public lookup, then the following applies 1757 * regardless of its {@linkplain #lookupModes() lookup modes}. 1758 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1759 * dropped and so the resulting lookup mode will never have these access 1760 * capabilities. When dropping {@code PACKAGE} 1761 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1762 * access. When dropping {@code MODULE} then the resulting lookup will not 1763 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1764 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1765 * 1766 * @apiNote 1767 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1768 * delegate non-public access within the package of the lookup class without 1769 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1770 * A lookup with {@code MODULE} but not 1771 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1772 * the module of the lookup class without conferring package access. 1773 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1774 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1775 * to public classes accessible to both the module of the lookup class 1776 * and the module of the previous lookup class. 1777 * 1778 * @param modeToDrop the lookup mode to drop 1779 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1780 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1781 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1782 * or {@code UNCONDITIONAL} 1783 * @see MethodHandles#privateLookupIn 1784 * @since 9 1785 */ 1786 public Lookup dropLookupMode(int modeToDrop) { 1787 int oldModes = lookupModes(); 1788 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1789 switch (modeToDrop) { 1790 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1791 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1792 case PACKAGE: newModes &= ~(PRIVATE); break; 1793 case PROTECTED: 1794 case PRIVATE: 1795 case ORIGINAL: 1796 case UNCONDITIONAL: break; 1797 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1798 } 1799 if (newModes == oldModes) return this; // return self if no change 1800 return newLookup(lookupClass(), previousLookupClass(), newModes); 1801 } 1802 1803 /** 1804 * Creates and links a class or interface from {@code bytes} 1805 * with the same class loader and in the same runtime package and 1806 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1807 * {@linkplain #lookupClass() lookup class} as if calling 1808 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1809 * ClassLoader::defineClass}. 1810 * 1811 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1812 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1813 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1814 * that the lookup object was created by a caller in the runtime package (or derived 1815 * from a lookup originally created by suitably privileged code to a target class in 1816 * the runtime package). </p> 1817 * 1818 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1819 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1820 * same package as the lookup class. </p> 1821 * 1822 * <p> This method does not run the class initializer. The class initializer may 1823 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1824 * Specification</em>. </p> 1825 * 1826 * <p> If there is a security manager and this lookup does not have {@linkplain 1827 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1828 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1829 * 1830 * @param bytes the class bytes 1831 * @return the {@code Class} object for the class 1832 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1833 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1834 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1835 * than the lookup class or {@code bytes} is not a class or interface 1836 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1837 * @throws VerifyError if the newly created class cannot be verified 1838 * @throws LinkageError if the newly created class cannot be linked for any other reason 1839 * @throws SecurityException if a security manager is present and it 1840 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1841 * @throws NullPointerException if {@code bytes} is {@code null} 1842 * @since 9 1843 * @see MethodHandles#privateLookupIn 1844 * @see Lookup#dropLookupMode 1845 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1846 */ 1847 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1848 ensureDefineClassPermission(); 1849 if ((lookupModes() & PACKAGE) == 0) 1850 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1851 return makeClassDefiner(bytes.clone()).defineClass(false); 1852 } 1853 1854 private void ensureDefineClassPermission() { 1855 if (allowedModes == TRUSTED) return; 1856 1857 if (!hasFullPrivilegeAccess()) { 1858 @SuppressWarnings("removal") 1859 SecurityManager sm = System.getSecurityManager(); 1860 if (sm != null) 1861 sm.checkPermission(new RuntimePermission("defineClass")); 1862 } 1863 } 1864 1865 /** 1866 * The set of class options that specify whether a hidden class created by 1867 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1868 * Lookup::defineHiddenClass} method is dynamically added as a new member 1869 * to the nest of a lookup class and/or whether a hidden class has 1870 * a strong relationship with the class loader marked as its defining loader. 1871 * 1872 * @since 15 1873 */ 1874 public enum ClassOption { 1875 /** 1876 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1877 * of a lookup class as a nestmate. 1878 * 1879 * <p> A hidden nestmate class has access to the private members of all 1880 * classes and interfaces in the same nest. 1881 * 1882 * @see Class#getNestHost() 1883 */ 1884 NESTMATE(NESTMATE_CLASS), 1885 1886 /** 1887 * Specifies that a hidden class has a <em>strong</em> 1888 * relationship with the class loader marked as its defining loader, 1889 * as a normal class or interface has with its own defining loader. 1890 * This means that the hidden class may be unloaded if and only if 1891 * its defining loader is not reachable and thus may be reclaimed 1892 * by a garbage collector (JLS {@jls 12.7}). 1893 * 1894 * <p> By default, a hidden class or interface may be unloaded 1895 * even if the class loader that is marked as its defining loader is 1896 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1897 1898 * 1899 * @jls 12.7 Unloading of Classes and Interfaces 1900 */ 1901 STRONG(STRONG_LOADER_LINK); 1902 1903 /* the flag value is used by VM at define class time */ 1904 private final int flag; 1905 ClassOption(int flag) { 1906 this.flag = flag; 1907 } 1908 1909 static int optionsToFlag(Set<ClassOption> options) { 1910 int flags = 0; 1911 for (ClassOption cp : options) { 1912 flags |= cp.flag; 1913 } 1914 return flags; 1915 } 1916 } 1917 1918 /** 1919 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1920 * returning a {@code Lookup} on the newly created class or interface. 1921 * 1922 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1923 * which either defines {@code C} directly or delegates to another class loader. 1924 * A class loader defines {@code C} directly by invoking 1925 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1926 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1927 * to derive {@code C} from a purported representation in {@code class} file format. 1928 * In situations where use of a class loader is undesirable, a class or interface 1929 * {@code C} can be created by this method instead. This method is capable of 1930 * defining {@code C}, and thereby creating it, without invoking 1931 * {@code ClassLoader::defineClass}. 1932 * Instead, this method defines {@code C} as if by arranging for 1933 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1934 * from a purported representation in {@code class} file format 1935 * using the following rules: 1936 * 1937 * <ol> 1938 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1939 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1940 * This level of access is needed to create {@code C} in the module 1941 * of the lookup class of this {@code Lookup}.</li> 1942 * 1943 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1944 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1945 * The major and minor version may differ from the {@code class} file version 1946 * of the lookup class of this {@code Lookup}.</li> 1947 * 1948 * <li> The value of {@code this_class} must be a valid index in the 1949 * {@code constant_pool} table, and the entry at that index must be a valid 1950 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1951 * encoded in internal form that is specified by this structure. {@code N} must 1952 * denote a class or interface in the same package as the lookup class.</li> 1953 * 1954 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1955 * where {@code <suffix>} is an unqualified name. 1956 * 1957 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1958 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1959 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1960 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1961 * refers to the new {@code CONSTANT_Utf8_info} structure. 1962 * 1963 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1964 * 1965 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1966 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1967 * with the following adjustments: 1968 * <ul> 1969 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1970 * that includes a single {@code "."} character, even though this is not a valid 1971 * binary class or interface name in internal form.</li> 1972 * 1973 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1974 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1975 * 1976 * <li> {@code C} is considered to have the same runtime 1977 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1978 * and {@linkplain java.security.ProtectionDomain protection domain} 1979 * as the lookup class of this {@code Lookup}. 1980 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1981 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1982 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1983 * <ul> 1984 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1985 * even though this is not a valid binary class or interface name.</li> 1986 * <li> {@link Class#descriptorString()} returns the string 1987 * {@code "L" + N + "." + <suffix> + ";"}, 1988 * even though this is not a valid type descriptor name.</li> 1989 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1990 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1991 * </ul> 1992 * </ul> 1993 * </li> 1994 * </ol> 1995 * 1996 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1997 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1998 * <ul> 1999 * <li> During verification, whenever it is necessary to load the class named 2000 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2001 * made of any class loader.</li> 2002 * 2003 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2004 * by {@code this_class}, the symbolic reference is considered to be resolved to 2005 * {@code C} and resolution always succeeds immediately.</li> 2006 * </ul> 2007 * 2008 * <p> If the {@code initialize} parameter is {@code true}, 2009 * then {@code C} is initialized by the Java Virtual Machine. 2010 * 2011 * <p> The newly created class or interface {@code C} serves as the 2012 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2013 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2014 * no other class or interface can refer to {@code C} via a constant pool entry. 2015 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2016 * a method parameter type, or a method return type by any other class. 2017 * This is because a hidden class or interface does not have a binary name, so 2018 * there is no internal form available to record in any class's constant pool. 2019 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2020 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2021 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2022 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2023 * JVM Tool Interface</a>. 2024 * 2025 * <p> A class or interface created by 2026 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2027 * a class loader} has a strong relationship with that class loader. 2028 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2029 * that {@linkplain Class#getClassLoader() defined it}. 2030 * This means that a class created by a class loader may be unloaded if and 2031 * only if its defining loader is not reachable and thus may be reclaimed 2032 * by a garbage collector (JLS {@jls 12.7}). 2033 * 2034 * By default, however, a hidden class or interface may be unloaded even if 2035 * the class loader that is marked as its defining loader is 2036 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2037 * This behavior is useful when a hidden class or interface serves multiple 2038 * classes defined by arbitrary class loaders. In other cases, a hidden 2039 * class or interface may be linked to a single class (or a small number of classes) 2040 * with the same defining loader as the hidden class or interface. 2041 * In such cases, where the hidden class or interface must be coterminous 2042 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2043 * option may be passed in {@code options}. 2044 * This arranges for a hidden class to have the same strong relationship 2045 * with the class loader marked as its defining loader, 2046 * as a normal class or interface has with its own defining loader. 2047 * 2048 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2049 * may still prevent a hidden class or interface from being 2050 * unloaded by ensuring that the {@code Class} object is reachable. 2051 * 2052 * <p> The unloading characteristics are set for each hidden class when it is 2053 * defined, and cannot be changed later. An advantage of allowing hidden classes 2054 * to be unloaded independently of the class loader marked as their defining loader 2055 * is that a very large number of hidden classes may be created by an application. 2056 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2057 * just as if normal classes were created by class loaders. 2058 * 2059 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2060 * their private members. The nest relationship is determined by 2061 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2062 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2063 * By default, a hidden class belongs to a nest consisting only of itself 2064 * because a hidden class has no binary name. 2065 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2066 * to create a hidden class or interface {@code C} as a member of a nest. 2067 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2068 * in the {@code ClassFile} structure from which {@code C} was derived. 2069 * Instead, the following rules determine the nest host of {@code C}: 2070 * <ul> 2071 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2072 * been determined, then let {@code H} be the nest host of the lookup class. 2073 * Otherwise, the nest host of the lookup class is determined using the 2074 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2075 * <li>The nest host of {@code C} is determined to be {@code H}, 2076 * the nest host of the lookup class.</li> 2077 * </ul> 2078 * 2079 * <p> A hidden class or interface may be serializable, but this requires a custom 2080 * serialization mechanism in order to ensure that instances are properly serialized 2081 * and deserialized. The default serialization mechanism supports only classes and 2082 * interfaces that are discoverable by their class name. 2083 * 2084 * @param bytes the bytes that make up the class data, 2085 * in the format of a valid {@code class} file as defined by 2086 * <cite>The Java Virtual Machine Specification</cite>. 2087 * @param initialize if {@code true} the class will be initialized. 2088 * @param options {@linkplain ClassOption class options} 2089 * @return the {@code Lookup} object on the hidden class, 2090 * with {@linkplain #ORIGINAL original} and 2091 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2092 * 2093 * @throws IllegalAccessException if this {@code Lookup} does not have 2094 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2095 * @throws SecurityException if a security manager is present and it 2096 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2097 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2098 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2099 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2100 * than the lookup class or {@code bytes} is not a class or interface 2101 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2102 * @throws IncompatibleClassChangeError if the class or interface named as 2103 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2104 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2105 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2106 * {@code C} is {@code C} itself 2107 * @throws VerifyError if the newly created class cannot be verified 2108 * @throws LinkageError if the newly created class cannot be linked for any other reason 2109 * @throws NullPointerException if any parameter is {@code null} 2110 * 2111 * @since 15 2112 * @see Class#isHidden() 2113 * @jvms 4.2.1 Binary Class and Interface Names 2114 * @jvms 4.2.2 Unqualified Names 2115 * @jvms 4.7.28 The {@code NestHost} Attribute 2116 * @jvms 4.7.29 The {@code NestMembers} Attribute 2117 * @jvms 5.4.3.1 Class and Interface Resolution 2118 * @jvms 5.4.4 Access Control 2119 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2120 * @jvms 5.4 Linking 2121 * @jvms 5.5 Initialization 2122 * @jls 12.7 Unloading of Classes and Interfaces 2123 */ 2124 @SuppressWarnings("doclint:reference") // cross-module links 2125 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2126 throws IllegalAccessException 2127 { 2128 Objects.requireNonNull(bytes); 2129 Objects.requireNonNull(options); 2130 2131 ensureDefineClassPermission(); 2132 if (!hasFullPrivilegeAccess()) { 2133 throw new IllegalAccessException(this + " does not have full privilege access"); 2134 } 2135 2136 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize); 2137 } 2138 2139 /** 2140 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2141 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2142 * returning a {@code Lookup} on the newly created class or interface. 2143 * 2144 * <p> This method is equivalent to calling 2145 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2146 * as if the hidden class is injected with a private static final <i>unnamed</i> 2147 * field which is initialized with the given {@code classData} at 2148 * the first instruction of the class initializer. 2149 * The newly created class is linked by the Java Virtual Machine. 2150 * 2151 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2152 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2153 * methods can be used to retrieve the {@code classData}. 2154 * 2155 * @apiNote 2156 * A framework can create a hidden class with class data with one or more 2157 * objects and load the class data as dynamically-computed constant(s) 2158 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2159 * Class data} is accessible only to the lookup object created by the newly 2160 * defined hidden class but inaccessible to other members in the same nest 2161 * (unlike private static fields that are accessible to nestmates). 2162 * Care should be taken w.r.t. mutability for example when passing 2163 * an array or other mutable structure through the class data. 2164 * Changing any value stored in the class data at runtime may lead to 2165 * unpredictable behavior. 2166 * If the class data is a {@code List}, it is good practice to make it 2167 * unmodifiable for example via {@link List#of List::of}. 2168 * 2169 * @param bytes the class bytes 2170 * @param classData pre-initialized class data 2171 * @param initialize if {@code true} the class will be initialized. 2172 * @param options {@linkplain ClassOption class options} 2173 * @return the {@code Lookup} object on the hidden class, 2174 * with {@linkplain #ORIGINAL original} and 2175 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2176 * 2177 * @throws IllegalAccessException if this {@code Lookup} does not have 2178 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2179 * @throws SecurityException if a security manager is present and it 2180 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2181 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2182 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2183 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2184 * than the lookup class or {@code bytes} is not a class or interface 2185 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2186 * @throws IncompatibleClassChangeError if the class or interface named as 2187 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2188 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2189 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2190 * {@code C} is {@code C} itself 2191 * @throws VerifyError if the newly created class cannot be verified 2192 * @throws LinkageError if the newly created class cannot be linked for any other reason 2193 * @throws NullPointerException if any parameter is {@code null} 2194 * 2195 * @since 16 2196 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2197 * @see Class#isHidden() 2198 * @see MethodHandles#classData(Lookup, String, Class) 2199 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2200 * @jvms 4.2.1 Binary Class and Interface Names 2201 * @jvms 4.2.2 Unqualified Names 2202 * @jvms 4.7.28 The {@code NestHost} Attribute 2203 * @jvms 4.7.29 The {@code NestMembers} Attribute 2204 * @jvms 5.4.3.1 Class and Interface Resolution 2205 * @jvms 5.4.4 Access Control 2206 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2207 * @jvms 5.4 Linking 2208 * @jvms 5.5 Initialization 2209 * @jls 12.7 Unloading of Classes and Interface 2210 */ 2211 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2212 throws IllegalAccessException 2213 { 2214 Objects.requireNonNull(bytes); 2215 Objects.requireNonNull(classData); 2216 Objects.requireNonNull(options); 2217 2218 ensureDefineClassPermission(); 2219 if (!hasFullPrivilegeAccess()) { 2220 throw new IllegalAccessException(this + " does not have full privilege access"); 2221 } 2222 2223 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false) 2224 .defineClassAsLookup(initialize, classData); 2225 } 2226 2227 // A default dumper for writing class files passed to Lookup::defineClass 2228 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2229 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2230 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2231 // 2232 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2233 // and LambdaForms and method handle internals. They are dumped via 2234 // different ClassFileDumpers. 2235 private static ClassFileDumper defaultDumper() { 2236 return DEFAULT_DUMPER; 2237 } 2238 2239 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2240 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2241 2242 static class ClassFile { 2243 final String name; // internal name 2244 final int accessFlags; 2245 final byte[] bytes; 2246 ClassFile(String name, int accessFlags, byte[] bytes) { 2247 this.name = name; 2248 this.accessFlags = accessFlags; 2249 this.bytes = bytes; 2250 } 2251 2252 static ClassFile newInstanceNoCheck(String name, byte[] bytes) { 2253 return new ClassFile(name, 0, bytes); 2254 } 2255 2256 /** 2257 * This method checks the class file version and the structure of `this_class`. 2258 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2259 * that is in the named package. 2260 * 2261 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2262 * or the class is not in the given package name. 2263 */ 2264 static ClassFile newInstance(byte[] bytes, String pkgName) { 2265 var cf = readClassFile(bytes); 2266 2267 // check if it's in the named package 2268 int index = cf.name.lastIndexOf('/'); 2269 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.'); 2270 if (!pn.equals(pkgName)) { 2271 throw newIllegalArgumentException(cf.name + " not in same package as lookup class"); 2272 } 2273 return cf; 2274 } 2275 2276 private static ClassFile readClassFile(byte[] bytes) { 2277 int magic = readInt(bytes, 0); 2278 if (magic != 0xCAFEBABE) { 2279 throw new ClassFormatError("Incompatible magic value: " + magic); 2280 } 2281 int minor = readUnsignedShort(bytes, 4); 2282 int major = readUnsignedShort(bytes, 6); 2283 if (!VM.isSupportedClassFileVersion(major, minor)) { 2284 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2285 } 2286 2287 String name; 2288 int accessFlags; 2289 try { 2290 ClassModel cm = java.lang.classfile.ClassFile.of().parse(bytes); 2291 name = cm.thisClass().asInternalName(); 2292 accessFlags = cm.flags().flagsMask(); 2293 } catch (IllegalArgumentException e) { 2294 ClassFormatError cfe = new ClassFormatError(); 2295 cfe.initCause(e); 2296 throw cfe; 2297 } 2298 // must be a class or interface 2299 if ((accessFlags & ACC_MODULE) != 0) { 2300 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2301 } 2302 return new ClassFile(name, accessFlags, bytes); 2303 } 2304 2305 private static int readInt(byte[] bytes, int offset) { 2306 if ((offset+4) > bytes.length) { 2307 throw new ClassFormatError("Invalid ClassFile structure"); 2308 } 2309 return ((bytes[offset] & 0xFF) << 24) 2310 | ((bytes[offset + 1] & 0xFF) << 16) 2311 | ((bytes[offset + 2] & 0xFF) << 8) 2312 | (bytes[offset + 3] & 0xFF); 2313 } 2314 2315 private static int readUnsignedShort(byte[] bytes, int offset) { 2316 if ((offset+2) > bytes.length) { 2317 throw new ClassFormatError("Invalid ClassFile structure"); 2318 } 2319 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2320 } 2321 } 2322 2323 /* 2324 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2325 * from the given bytes. 2326 * 2327 * Caller should make a defensive copy of the arguments if needed 2328 * before calling this factory method. 2329 * 2330 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2331 * {@code bytes} denotes a class in a different package than the lookup class 2332 */ 2333 private ClassDefiner makeClassDefiner(byte[] bytes) { 2334 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2335 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper()); 2336 } 2337 2338 /** 2339 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2340 * from the given bytes. No package name check on the given bytes. 2341 * 2342 * @param name internal name 2343 * @param bytes class bytes 2344 * @param dumper dumper to write the given bytes to the dumper's output directory 2345 * @return ClassDefiner that defines a normal class of the given bytes. 2346 */ 2347 ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) { 2348 // skip package name validation 2349 ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes); 2350 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper); 2351 } 2352 2353 /** 2354 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2355 * from the given bytes. The name must be in the same package as the lookup class. 2356 * 2357 * Caller should make a defensive copy of the arguments if needed 2358 * before calling this factory method. 2359 * 2360 * @param bytes class bytes 2361 * @param dumper dumper to write the given bytes to the dumper's output directory 2362 * @return ClassDefiner that defines a hidden class of the given bytes. 2363 * 2364 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2365 * {@code bytes} denotes a class in a different package than the lookup class 2366 */ 2367 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2368 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2369 return makeHiddenClassDefiner(cf, Set.of(), false, dumper); 2370 } 2371 2372 /** 2373 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2374 * from the given bytes and options. 2375 * The name must be in the same package as the lookup class. 2376 * 2377 * Caller should make a defensive copy of the arguments if needed 2378 * before calling this factory method. 2379 * 2380 * @param bytes class bytes 2381 * @param options class options 2382 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2383 * @return ClassDefiner that defines a hidden class of the given bytes and options 2384 * 2385 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2386 * {@code bytes} denotes a class in a different package than the lookup class 2387 */ 2388 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2389 Set<ClassOption> options, 2390 boolean accessVmAnnotations) { 2391 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2392 return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper()); 2393 } 2394 2395 /** 2396 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2397 * from the given bytes and the given options. No package name check on the given bytes. 2398 * 2399 * @param name internal name that specifies the prefix of the hidden class 2400 * @param bytes class bytes 2401 * @param options class options 2402 * @param dumper dumper to write the given bytes to the dumper's output directory 2403 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2404 */ 2405 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) { 2406 Objects.requireNonNull(dumper); 2407 // skip name and access flags validation 2408 return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper); 2409 } 2410 2411 /** 2412 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2413 * from the given class file and options. 2414 * 2415 * @param cf ClassFile 2416 * @param options class options 2417 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2418 * @param dumper dumper to write the given bytes to the dumper's output directory 2419 */ 2420 private ClassDefiner makeHiddenClassDefiner(ClassFile cf, 2421 Set<ClassOption> options, 2422 boolean accessVmAnnotations, 2423 ClassFileDumper dumper) { 2424 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options); 2425 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2426 // jdk.internal.vm.annotations are permitted for classes 2427 // defined to boot loader and platform loader 2428 flags |= ACCESS_VM_ANNOTATIONS; 2429 } 2430 2431 return new ClassDefiner(this, cf, flags, dumper); 2432 } 2433 2434 static class ClassDefiner { 2435 private final Lookup lookup; 2436 private final String name; // internal name 2437 private final byte[] bytes; 2438 private final int classFlags; 2439 private final ClassFileDumper dumper; 2440 2441 private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) { 2442 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2443 this.lookup = lookup; 2444 this.bytes = cf.bytes; 2445 this.name = cf.name; 2446 this.classFlags = flags; 2447 this.dumper = dumper; 2448 } 2449 2450 String internalName() { 2451 return name; 2452 } 2453 2454 Class<?> defineClass(boolean initialize) { 2455 return defineClass(initialize, null); 2456 } 2457 2458 Lookup defineClassAsLookup(boolean initialize) { 2459 Class<?> c = defineClass(initialize, null); 2460 return new Lookup(c, null, FULL_POWER_MODES); 2461 } 2462 2463 /** 2464 * Defines the class of the given bytes and the given classData. 2465 * If {@code initialize} parameter is true, then the class will be initialized. 2466 * 2467 * @param initialize true if the class to be initialized 2468 * @param classData classData or null 2469 * @return the class 2470 * 2471 * @throws LinkageError linkage error 2472 */ 2473 Class<?> defineClass(boolean initialize, Object classData) { 2474 Class<?> lookupClass = lookup.lookupClass(); 2475 ClassLoader loader = lookupClass.getClassLoader(); 2476 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2477 Class<?> c = null; 2478 try { 2479 c = SharedSecrets.getJavaLangAccess() 2480 .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData); 2481 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2482 return c; 2483 } finally { 2484 // dump the classfile for debugging 2485 if (dumper.isEnabled()) { 2486 String name = internalName(); 2487 if (c != null) { 2488 dumper.dumpClass(name, c, bytes); 2489 } else { 2490 dumper.dumpFailedClass(name, bytes); 2491 } 2492 } 2493 } 2494 } 2495 2496 /** 2497 * Defines the class of the given bytes and the given classData. 2498 * If {@code initialize} parameter is true, then the class will be initialized. 2499 * 2500 * @param initialize true if the class to be initialized 2501 * @param classData classData or null 2502 * @return a Lookup for the defined class 2503 * 2504 * @throws LinkageError linkage error 2505 */ 2506 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2507 Class<?> c = defineClass(initialize, classData); 2508 return new Lookup(c, null, FULL_POWER_MODES); 2509 } 2510 2511 private boolean isNestmate() { 2512 return (classFlags & NESTMATE_CLASS) != 0; 2513 } 2514 } 2515 2516 private ProtectionDomain lookupClassProtectionDomain() { 2517 ProtectionDomain pd = cachedProtectionDomain; 2518 if (pd == null) { 2519 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2520 } 2521 return pd; 2522 } 2523 2524 // cached protection domain 2525 private volatile ProtectionDomain cachedProtectionDomain; 2526 2527 // Make sure outer class is initialized first. 2528 static { IMPL_NAMES.getClass(); } 2529 2530 /** Package-private version of lookup which is trusted. */ 2531 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2532 2533 /** Version of lookup which is trusted minimally. 2534 * It can only be used to create method handles to publicly accessible 2535 * members in packages that are exported unconditionally. 2536 */ 2537 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2538 2539 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2540 String name = lookupClass.getName(); 2541 if (name.startsWith("java.lang.invoke.")) 2542 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2543 } 2544 2545 /** 2546 * Displays the name of the class from which lookups are to be made, 2547 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2548 * previous lookup class} if present. 2549 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2550 * If there are restrictions on the access permitted to this lookup, 2551 * this is indicated by adding a suffix to the class name, consisting 2552 * of a slash and a keyword. The keyword represents the strongest 2553 * allowed access, and is chosen as follows: 2554 * <ul> 2555 * <li>If no access is allowed, the suffix is "/noaccess". 2556 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2557 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2558 * <li>If only public and module access are allowed, the suffix is "/module". 2559 * <li>If public and package access are allowed, the suffix is "/package". 2560 * <li>If public, package, and private access are allowed, the suffix is "/private". 2561 * </ul> 2562 * If none of the above cases apply, it is the case that 2563 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2564 * (public, module, package, private, and protected) is allowed. 2565 * In this case, no suffix is added. 2566 * This is true only of an object obtained originally from 2567 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2568 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2569 * always have restricted access, and will display a suffix. 2570 * <p> 2571 * (It may seem strange that protected access should be 2572 * stronger than private access. Viewed independently from 2573 * package access, protected access is the first to be lost, 2574 * because it requires a direct subclass relationship between 2575 * caller and callee.) 2576 * @see #in 2577 */ 2578 @Override 2579 public String toString() { 2580 String cname = lookupClass.getName(); 2581 if (prevLookupClass != null) 2582 cname += "/" + prevLookupClass.getName(); 2583 switch (allowedModes) { 2584 case 0: // no privileges 2585 return cname + "/noaccess"; 2586 case UNCONDITIONAL: 2587 return cname + "/publicLookup"; 2588 case PUBLIC: 2589 return cname + "/public"; 2590 case PUBLIC|MODULE: 2591 return cname + "/module"; 2592 case PUBLIC|PACKAGE: 2593 case PUBLIC|MODULE|PACKAGE: 2594 return cname + "/package"; 2595 case PUBLIC|PACKAGE|PRIVATE: 2596 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2597 return cname + "/private"; 2598 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2599 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2600 case FULL_POWER_MODES: 2601 return cname; 2602 case TRUSTED: 2603 return "/trusted"; // internal only; not exported 2604 default: // Should not happen, but it's a bitfield... 2605 cname = cname + "/" + Integer.toHexString(allowedModes); 2606 assert(false) : cname; 2607 return cname; 2608 } 2609 } 2610 2611 /** 2612 * Produces a method handle for a static method. 2613 * The type of the method handle will be that of the method. 2614 * (Since static methods do not take receivers, there is no 2615 * additional receiver argument inserted into the method handle type, 2616 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2617 * The method and all its argument types must be accessible to the lookup object. 2618 * <p> 2619 * The returned method handle will have 2620 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2621 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2622 * <p> 2623 * If the returned method handle is invoked, the method's class will 2624 * be initialized, if it has not already been initialized. 2625 * <p><b>Example:</b> 2626 * {@snippet lang="java" : 2627 import static java.lang.invoke.MethodHandles.*; 2628 import static java.lang.invoke.MethodType.*; 2629 ... 2630 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2631 "asList", methodType(List.class, Object[].class)); 2632 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2633 * } 2634 * @param refc the class from which the method is accessed 2635 * @param name the name of the method 2636 * @param type the type of the method 2637 * @return the desired method handle 2638 * @throws NoSuchMethodException if the method does not exist 2639 * @throws IllegalAccessException if access checking fails, 2640 * or if the method is not {@code static}, 2641 * or if the method's variable arity modifier bit 2642 * is set and {@code asVarargsCollector} fails 2643 * @throws SecurityException if a security manager is present and it 2644 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2645 * @throws NullPointerException if any argument is null 2646 */ 2647 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2648 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2649 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2650 } 2651 2652 /** 2653 * Produces a method handle for a virtual method. 2654 * The type of the method handle will be that of the method, 2655 * with the receiver type (usually {@code refc}) prepended. 2656 * The method and all its argument types must be accessible to the lookup object. 2657 * <p> 2658 * When called, the handle will treat the first argument as a receiver 2659 * and, for non-private methods, dispatch on the receiver's type to determine which method 2660 * implementation to enter. 2661 * For private methods the named method in {@code refc} will be invoked on the receiver. 2662 * (The dispatching action is identical with that performed by an 2663 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2664 * <p> 2665 * The first argument will be of type {@code refc} if the lookup 2666 * class has full privileges to access the member. Otherwise 2667 * the member must be {@code protected} and the first argument 2668 * will be restricted in type to the lookup class. 2669 * <p> 2670 * The returned method handle will have 2671 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2672 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2673 * <p> 2674 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2675 * instructions and method handles produced by {@code findVirtual}, 2676 * if the class is {@code MethodHandle} and the name string is 2677 * {@code invokeExact} or {@code invoke}, the resulting 2678 * method handle is equivalent to one produced by 2679 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2680 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2681 * with the same {@code type} argument. 2682 * <p> 2683 * If the class is {@code VarHandle} and the name string corresponds to 2684 * the name of a signature-polymorphic access mode method, the resulting 2685 * method handle is equivalent to one produced by 2686 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2687 * the access mode corresponding to the name string and with the same 2688 * {@code type} arguments. 2689 * <p> 2690 * <b>Example:</b> 2691 * {@snippet lang="java" : 2692 import static java.lang.invoke.MethodHandles.*; 2693 import static java.lang.invoke.MethodType.*; 2694 ... 2695 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2696 "concat", methodType(String.class, String.class)); 2697 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2698 "hashCode", methodType(int.class)); 2699 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2700 "hashCode", methodType(int.class)); 2701 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2702 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2703 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2704 // interface method: 2705 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2706 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2707 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2708 // constructor "internal method" must be accessed differently: 2709 MethodType MT_newString = methodType(void.class); //()V for new String() 2710 try { assertEquals("impossible", lookup() 2711 .findVirtual(String.class, "<init>", MT_newString)); 2712 } catch (NoSuchMethodException ex) { } // OK 2713 MethodHandle MH_newString = publicLookup() 2714 .findConstructor(String.class, MT_newString); 2715 assertEquals("", (String) MH_newString.invokeExact()); 2716 * } 2717 * 2718 * @param refc the class or interface from which the method is accessed 2719 * @param name the name of the method 2720 * @param type the type of the method, with the receiver argument omitted 2721 * @return the desired method handle 2722 * @throws NoSuchMethodException if the method does not exist 2723 * @throws IllegalAccessException if access checking fails, 2724 * or if the method is {@code static}, 2725 * or if the method's variable arity modifier bit 2726 * is set and {@code asVarargsCollector} fails 2727 * @throws SecurityException if a security manager is present and it 2728 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2729 * @throws NullPointerException if any argument is null 2730 */ 2731 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2732 if (refc == MethodHandle.class) { 2733 MethodHandle mh = findVirtualForMH(name, type); 2734 if (mh != null) return mh; 2735 } else if (refc == VarHandle.class) { 2736 MethodHandle mh = findVirtualForVH(name, type); 2737 if (mh != null) return mh; 2738 } 2739 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2740 MemberName method = resolveOrFail(refKind, refc, name, type); 2741 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2742 } 2743 private MethodHandle findVirtualForMH(String name, MethodType type) { 2744 // these names require special lookups because of the implicit MethodType argument 2745 if ("invoke".equals(name)) 2746 return invoker(type); 2747 if ("invokeExact".equals(name)) 2748 return exactInvoker(type); 2749 assert(!MemberName.isMethodHandleInvokeName(name)); 2750 return null; 2751 } 2752 private MethodHandle findVirtualForVH(String name, MethodType type) { 2753 try { 2754 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2755 } catch (IllegalArgumentException e) { 2756 return null; 2757 } 2758 } 2759 2760 /** 2761 * Produces a method handle which creates an object and initializes it, using 2762 * the constructor of the specified type. 2763 * The parameter types of the method handle will be those of the constructor, 2764 * while the return type will be a reference to the constructor's class. 2765 * The constructor and all its argument types must be accessible to the lookup object. 2766 * <p> 2767 * The requested type must have a return type of {@code void}. 2768 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2769 * <p> 2770 * The returned method handle will have 2771 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2772 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2773 * <p> 2774 * If the returned method handle is invoked, the constructor's class will 2775 * be initialized, if it has not already been initialized. 2776 * <p><b>Example:</b> 2777 * {@snippet lang="java" : 2778 import static java.lang.invoke.MethodHandles.*; 2779 import static java.lang.invoke.MethodType.*; 2780 ... 2781 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2782 ArrayList.class, methodType(void.class, Collection.class)); 2783 Collection orig = Arrays.asList("x", "y"); 2784 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2785 assert(orig != copy); 2786 assertEquals(orig, copy); 2787 // a variable-arity constructor: 2788 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2789 ProcessBuilder.class, methodType(void.class, String[].class)); 2790 ProcessBuilder pb = (ProcessBuilder) 2791 MH_newProcessBuilder.invoke("x", "y", "z"); 2792 assertEquals("[x, y, z]", pb.command().toString()); 2793 * } 2794 * 2795 * 2796 * @param refc the class or interface from which the method is accessed 2797 * @param type the type of the method, with the receiver argument omitted, and a void return type 2798 * @return the desired method handle 2799 * @throws NoSuchMethodException if the constructor does not exist 2800 * @throws IllegalAccessException if access checking fails 2801 * or if the method's variable arity modifier bit 2802 * is set and {@code asVarargsCollector} fails 2803 * @throws SecurityException if a security manager is present and it 2804 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2805 * @throws NullPointerException if any argument is null 2806 */ 2807 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2808 if (refc.isArray()) { 2809 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2810 } 2811 if (type.returnType() != void.class) { 2812 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName()); 2813 } 2814 String name = ConstantDescs.INIT_NAME; 2815 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2816 return getDirectConstructor(refc, ctor); 2817 } 2818 2819 /** 2820 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2821 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2822 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2823 * and then determines whether the class is accessible to this lookup object. 2824 * <p> 2825 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2826 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2827 * of {@code '['} and followed by the element type as encoded in the 2828 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2829 * <p> 2830 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2831 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2832 * 2833 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2834 * or the string representing an array class 2835 * @return the requested class. 2836 * @throws SecurityException if a security manager is present and it 2837 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2838 * @throws LinkageError if the linkage fails 2839 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2840 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2841 * modes. 2842 * @throws NullPointerException if {@code targetName} is null 2843 * @since 9 2844 * @jvms 5.4.3.1 Class and Interface Resolution 2845 */ 2846 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2847 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2848 return accessClass(targetClass); 2849 } 2850 2851 /** 2852 * Ensures that {@code targetClass} has been initialized. The class 2853 * to be initialized must be {@linkplain #accessClass accessible} 2854 * to this {@code Lookup} object. This method causes {@code targetClass} 2855 * to be initialized if it has not been already initialized, 2856 * as specified in JVMS {@jvms 5.5}. 2857 * 2858 * <p> 2859 * This method returns when {@code targetClass} is fully initialized, or 2860 * when {@code targetClass} is being initialized by the current thread. 2861 * 2862 * @param <T> the type of the class to be initialized 2863 * @param targetClass the class to be initialized 2864 * @return {@code targetClass} that has been initialized, or that is being 2865 * initialized by the current thread. 2866 * 2867 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2868 * or array class 2869 * @throws IllegalAccessException if {@code targetClass} is not 2870 * {@linkplain #accessClass accessible} to this lookup 2871 * @throws ExceptionInInitializerError if the class initialization provoked 2872 * by this method fails 2873 * @throws SecurityException if a security manager is present and it 2874 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2875 * @since 15 2876 * @jvms 5.5 Initialization 2877 */ 2878 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2879 if (targetClass.isPrimitive()) 2880 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2881 if (targetClass.isArray()) 2882 throw new IllegalArgumentException(targetClass + " is an array class"); 2883 2884 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2885 throw makeAccessException(targetClass); 2886 } 2887 checkSecurityManager(targetClass); 2888 2889 // ensure class initialization 2890 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2891 return targetClass; 2892 } 2893 2894 /* 2895 * Returns IllegalAccessException due to access violation to the given targetClass. 2896 * 2897 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2898 * which verifies access to a class rather a member. 2899 */ 2900 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2901 String message = "access violation: "+ targetClass; 2902 if (this == MethodHandles.publicLookup()) { 2903 message += ", from public Lookup"; 2904 } else { 2905 Module m = lookupClass().getModule(); 2906 message += ", from " + lookupClass() + " (" + m + ")"; 2907 if (prevLookupClass != null) { 2908 message += ", previous lookup " + 2909 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2910 } 2911 } 2912 return new IllegalAccessException(message); 2913 } 2914 2915 /** 2916 * Determines if a class can be accessed from the lookup context defined by 2917 * this {@code Lookup} object. The static initializer of the class is not run. 2918 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2919 * if the element type of the array class is accessible. Otherwise, 2920 * {@code targetClass} is determined as accessible as follows. 2921 * 2922 * <p> 2923 * If {@code targetClass} is in the same module as the lookup class, 2924 * the lookup class is {@code LC} in module {@code M1} and 2925 * the previous lookup class is in module {@code M0} or 2926 * {@code null} if not present, 2927 * {@code targetClass} is accessible if and only if one of the following is true: 2928 * <ul> 2929 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2930 * {@code LC} or other class in the same nest of {@code LC}.</li> 2931 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2932 * in the same runtime package of {@code LC}.</li> 2933 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2934 * a public type in {@code M1}.</li> 2935 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2936 * a public type in a package exported by {@code M1} to at least {@code M0} 2937 * if the previous lookup class is present; otherwise, {@code targetClass} 2938 * is a public type in a package exported by {@code M1} unconditionally.</li> 2939 * </ul> 2940 * 2941 * <p> 2942 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2943 * can access public types in all modules when the type is in a package 2944 * that is exported unconditionally. 2945 * <p> 2946 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2947 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2948 * is inaccessible. 2949 * <p> 2950 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2951 * {@code M1} is the module containing {@code lookupClass} and 2952 * {@code M2} is the module containing {@code targetClass}, 2953 * then {@code targetClass} is accessible if and only if 2954 * <ul> 2955 * <li>{@code M1} reads {@code M2}, and 2956 * <li>{@code targetClass} is public and in a package exported by 2957 * {@code M2} at least to {@code M1}. 2958 * </ul> 2959 * <p> 2960 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2961 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2962 * containing the previous lookup class, then {@code targetClass} is accessible 2963 * if and only if one of the following is true: 2964 * <ul> 2965 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2966 * {@linkplain Module#reads reads} {@code M0} and the type is 2967 * in a package that is exported to at least {@code M1}. 2968 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2969 * {@linkplain Module#reads reads} {@code M1} and the type is 2970 * in a package that is exported to at least {@code M0}. 2971 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2972 * and {@code M1} reads {@code M2} and the type is in a package 2973 * that is exported to at least both {@code M0} and {@code M2}. 2974 * </ul> 2975 * <p> 2976 * Otherwise, {@code targetClass} is not accessible. 2977 * 2978 * @param <T> the type of the class to be access-checked 2979 * @param targetClass the class to be access-checked 2980 * @return {@code targetClass} that has been access-checked 2981 * @throws IllegalAccessException if the class is not accessible from the lookup class 2982 * and previous lookup class, if present, using the allowed access modes. 2983 * @throws SecurityException if a security manager is present and it 2984 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2985 * @throws NullPointerException if {@code targetClass} is {@code null} 2986 * @since 9 2987 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2988 */ 2989 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2990 if (!isClassAccessible(targetClass)) { 2991 throw makeAccessException(targetClass); 2992 } 2993 checkSecurityManager(targetClass); 2994 return targetClass; 2995 } 2996 2997 /** 2998 * Produces an early-bound method handle for a virtual method. 2999 * It will bypass checks for overriding methods on the receiver, 3000 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3001 * instruction from within the explicitly specified {@code specialCaller}. 3002 * The type of the method handle will be that of the method, 3003 * with a suitably restricted receiver type prepended. 3004 * (The receiver type will be {@code specialCaller} or a subtype.) 3005 * The method and all its argument types must be accessible 3006 * to the lookup object. 3007 * <p> 3008 * Before method resolution, 3009 * if the explicitly specified caller class is not identical with the 3010 * lookup class, or if this lookup object does not have 3011 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3012 * privileges, the access fails. 3013 * <p> 3014 * The returned method handle will have 3015 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3016 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3017 * <p style="font-size:smaller;"> 3018 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 3019 * are not visible to this API, 3020 * even though the {@code invokespecial} instruction can refer to them 3021 * in special circumstances. Use {@link #findConstructor findConstructor} 3022 * to access instance initialization methods in a safe manner.)</em> 3023 * <p><b>Example:</b> 3024 * {@snippet lang="java" : 3025 import static java.lang.invoke.MethodHandles.*; 3026 import static java.lang.invoke.MethodType.*; 3027 ... 3028 static class Listie extends ArrayList { 3029 public String toString() { return "[wee Listie]"; } 3030 static Lookup lookup() { return MethodHandles.lookup(); } 3031 } 3032 ... 3033 // no access to constructor via invokeSpecial: 3034 MethodHandle MH_newListie = Listie.lookup() 3035 .findConstructor(Listie.class, methodType(void.class)); 3036 Listie l = (Listie) MH_newListie.invokeExact(); 3037 try { assertEquals("impossible", Listie.lookup().findSpecial( 3038 Listie.class, "<init>", methodType(void.class), Listie.class)); 3039 } catch (NoSuchMethodException ex) { } // OK 3040 // access to super and self methods via invokeSpecial: 3041 MethodHandle MH_super = Listie.lookup().findSpecial( 3042 ArrayList.class, "toString" , methodType(String.class), Listie.class); 3043 MethodHandle MH_this = Listie.lookup().findSpecial( 3044 Listie.class, "toString" , methodType(String.class), Listie.class); 3045 MethodHandle MH_duper = Listie.lookup().findSpecial( 3046 Object.class, "toString" , methodType(String.class), Listie.class); 3047 assertEquals("[]", (String) MH_super.invokeExact(l)); 3048 assertEquals(""+l, (String) MH_this.invokeExact(l)); 3049 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 3050 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 3051 String.class, "toString", methodType(String.class), Listie.class)); 3052 } catch (IllegalAccessException ex) { } // OK 3053 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 3054 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 3055 * } 3056 * 3057 * @param refc the class or interface from which the method is accessed 3058 * @param name the name of the method (which must not be "<init>") 3059 * @param type the type of the method, with the receiver argument omitted 3060 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 3061 * @return the desired method handle 3062 * @throws NoSuchMethodException if the method does not exist 3063 * @throws IllegalAccessException if access checking fails, 3064 * or if the method is {@code static}, 3065 * or if the method's variable arity modifier bit 3066 * is set and {@code asVarargsCollector} fails 3067 * @throws SecurityException if a security manager is present and it 3068 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3069 * @throws NullPointerException if any argument is null 3070 */ 3071 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3072 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3073 checkSpecialCaller(specialCaller, refc); 3074 Lookup specialLookup = this.in(specialCaller); 3075 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3076 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3077 } 3078 3079 /** 3080 * Produces a method handle giving read access to a non-static field. 3081 * The type of the method handle will have a return type of the field's 3082 * value type. 3083 * The method handle's single argument will be the instance containing 3084 * the field. 3085 * Access checking is performed immediately on behalf of the lookup class. 3086 * @param refc the class or interface from which the method is accessed 3087 * @param name the field's name 3088 * @param type the field's type 3089 * @return a method handle which can load values from the field 3090 * @throws NoSuchFieldException if the field does not exist 3091 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3092 * @throws SecurityException if a security manager is present and it 3093 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3094 * @throws NullPointerException if any argument is null 3095 * @see #findVarHandle(Class, String, Class) 3096 */ 3097 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3098 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3099 return getDirectField(REF_getField, refc, field); 3100 } 3101 3102 /** 3103 * Produces a method handle giving write access to a non-static field. 3104 * The type of the method handle will have a void return type. 3105 * The method handle will take two arguments, the instance containing 3106 * the field, and the value to be stored. 3107 * The second argument will be of the field's value type. 3108 * Access checking is performed immediately on behalf of the lookup class. 3109 * @param refc the class or interface from which the method is accessed 3110 * @param name the field's name 3111 * @param type the field's type 3112 * @return a method handle which can store values into the field 3113 * @throws NoSuchFieldException if the field does not exist 3114 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3115 * or {@code final} 3116 * @throws SecurityException if a security manager is present and it 3117 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3118 * @throws NullPointerException if any argument is null 3119 * @see #findVarHandle(Class, String, Class) 3120 */ 3121 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3122 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3123 return getDirectField(REF_putField, refc, field); 3124 } 3125 3126 /** 3127 * Produces a VarHandle giving access to a non-static field {@code name} 3128 * of type {@code type} declared in a class of type {@code recv}. 3129 * The VarHandle's variable type is {@code type} and it has one 3130 * coordinate type, {@code recv}. 3131 * <p> 3132 * Access checking is performed immediately on behalf of the lookup 3133 * class. 3134 * <p> 3135 * Certain access modes of the returned VarHandle are unsupported under 3136 * the following conditions: 3137 * <ul> 3138 * <li>if the field is declared {@code final}, then the write, atomic 3139 * update, numeric atomic update, and bitwise atomic update access 3140 * modes are unsupported. 3141 * <li>if the field type is anything other than {@code byte}, 3142 * {@code short}, {@code char}, {@code int}, {@code long}, 3143 * {@code float}, or {@code double} then numeric atomic update 3144 * access modes are unsupported. 3145 * <li>if the field type is anything other than {@code boolean}, 3146 * {@code byte}, {@code short}, {@code char}, {@code int} or 3147 * {@code long} then bitwise atomic update access modes are 3148 * unsupported. 3149 * </ul> 3150 * <p> 3151 * If the field is declared {@code volatile} then the returned VarHandle 3152 * will override access to the field (effectively ignore the 3153 * {@code volatile} declaration) in accordance to its specified 3154 * access modes. 3155 * <p> 3156 * If the field type is {@code float} or {@code double} then numeric 3157 * and atomic update access modes compare values using their bitwise 3158 * representation (see {@link Float#floatToRawIntBits} and 3159 * {@link Double#doubleToRawLongBits}, respectively). 3160 * @apiNote 3161 * Bitwise comparison of {@code float} values or {@code double} values, 3162 * as performed by the numeric and atomic update access modes, differ 3163 * from the primitive {@code ==} operator and the {@link Float#equals} 3164 * and {@link Double#equals} methods, specifically with respect to 3165 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3166 * Care should be taken when performing a compare and set or a compare 3167 * and exchange operation with such values since the operation may 3168 * unexpectedly fail. 3169 * There are many possible NaN values that are considered to be 3170 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3171 * provided by Java can distinguish between them. Operation failure can 3172 * occur if the expected or witness value is a NaN value and it is 3173 * transformed (perhaps in a platform specific manner) into another NaN 3174 * value, and thus has a different bitwise representation (see 3175 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3176 * details). 3177 * The values {@code -0.0} and {@code +0.0} have different bitwise 3178 * representations but are considered equal when using the primitive 3179 * {@code ==} operator. Operation failure can occur if, for example, a 3180 * numeric algorithm computes an expected value to be say {@code -0.0} 3181 * and previously computed the witness value to be say {@code +0.0}. 3182 * @param recv the receiver class, of type {@code R}, that declares the 3183 * non-static field 3184 * @param name the field's name 3185 * @param type the field's type, of type {@code T} 3186 * @return a VarHandle giving access to non-static fields. 3187 * @throws NoSuchFieldException if the field does not exist 3188 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3189 * @throws SecurityException if a security manager is present and it 3190 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3191 * @throws NullPointerException if any argument is null 3192 * @since 9 3193 */ 3194 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3195 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3196 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3197 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3198 } 3199 3200 /** 3201 * Produces a method handle giving read access to a static field. 3202 * The type of the method handle will have a return type of the field's 3203 * value type. 3204 * The method handle will take no arguments. 3205 * Access checking is performed immediately on behalf of the lookup class. 3206 * <p> 3207 * If the returned method handle is invoked, the field's class will 3208 * be initialized, if it has not already been initialized. 3209 * @param refc the class or interface from which the method is accessed 3210 * @param name the field's name 3211 * @param type the field's type 3212 * @return a method handle which can load values from the field 3213 * @throws NoSuchFieldException if the field does not exist 3214 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3215 * @throws SecurityException if a security manager is present and it 3216 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3217 * @throws NullPointerException if any argument is null 3218 */ 3219 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3220 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3221 return getDirectField(REF_getStatic, refc, field); 3222 } 3223 3224 /** 3225 * Produces a method handle giving write access to a static field. 3226 * The type of the method handle will have a void return type. 3227 * The method handle will take a single 3228 * argument, of the field's value type, the value to be stored. 3229 * Access checking is performed immediately on behalf of the lookup class. 3230 * <p> 3231 * If the returned method handle is invoked, the field's class will 3232 * be initialized, if it has not already been initialized. 3233 * @param refc the class or interface from which the method is accessed 3234 * @param name the field's name 3235 * @param type the field's type 3236 * @return a method handle which can store values into the field 3237 * @throws NoSuchFieldException if the field does not exist 3238 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3239 * or is {@code final} 3240 * @throws SecurityException if a security manager is present and it 3241 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3242 * @throws NullPointerException if any argument is null 3243 */ 3244 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3245 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3246 return getDirectField(REF_putStatic, refc, field); 3247 } 3248 3249 /** 3250 * Produces a VarHandle giving access to a static field {@code name} of 3251 * type {@code type} declared in a class of type {@code decl}. 3252 * The VarHandle's variable type is {@code type} and it has no 3253 * coordinate types. 3254 * <p> 3255 * Access checking is performed immediately on behalf of the lookup 3256 * class. 3257 * <p> 3258 * If the returned VarHandle is operated on, the declaring class will be 3259 * initialized, if it has not already been initialized. 3260 * <p> 3261 * Certain access modes of the returned VarHandle are unsupported under 3262 * the following conditions: 3263 * <ul> 3264 * <li>if the field is declared {@code final}, then the write, atomic 3265 * update, numeric atomic update, and bitwise atomic update access 3266 * modes are unsupported. 3267 * <li>if the field type is anything other than {@code byte}, 3268 * {@code short}, {@code char}, {@code int}, {@code long}, 3269 * {@code float}, or {@code double}, then numeric atomic update 3270 * access modes are unsupported. 3271 * <li>if the field type is anything other than {@code boolean}, 3272 * {@code byte}, {@code short}, {@code char}, {@code int} or 3273 * {@code long} then bitwise atomic update access modes are 3274 * unsupported. 3275 * </ul> 3276 * <p> 3277 * If the field is declared {@code volatile} then the returned VarHandle 3278 * will override access to the field (effectively ignore the 3279 * {@code volatile} declaration) in accordance to its specified 3280 * access modes. 3281 * <p> 3282 * If the field type is {@code float} or {@code double} then numeric 3283 * and atomic update access modes compare values using their bitwise 3284 * representation (see {@link Float#floatToRawIntBits} and 3285 * {@link Double#doubleToRawLongBits}, respectively). 3286 * @apiNote 3287 * Bitwise comparison of {@code float} values or {@code double} values, 3288 * as performed by the numeric and atomic update access modes, differ 3289 * from the primitive {@code ==} operator and the {@link Float#equals} 3290 * and {@link Double#equals} methods, specifically with respect to 3291 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3292 * Care should be taken when performing a compare and set or a compare 3293 * and exchange operation with such values since the operation may 3294 * unexpectedly fail. 3295 * There are many possible NaN values that are considered to be 3296 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3297 * provided by Java can distinguish between them. Operation failure can 3298 * occur if the expected or witness value is a NaN value and it is 3299 * transformed (perhaps in a platform specific manner) into another NaN 3300 * value, and thus has a different bitwise representation (see 3301 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3302 * details). 3303 * The values {@code -0.0} and {@code +0.0} have different bitwise 3304 * representations but are considered equal when using the primitive 3305 * {@code ==} operator. Operation failure can occur if, for example, a 3306 * numeric algorithm computes an expected value to be say {@code -0.0} 3307 * and previously computed the witness value to be say {@code +0.0}. 3308 * @param decl the class that declares the static field 3309 * @param name the field's name 3310 * @param type the field's type, of type {@code T} 3311 * @return a VarHandle giving access to a static field 3312 * @throws NoSuchFieldException if the field does not exist 3313 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3314 * @throws SecurityException if a security manager is present and it 3315 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3316 * @throws NullPointerException if any argument is null 3317 * @since 9 3318 */ 3319 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3320 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3321 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3322 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3323 } 3324 3325 /** 3326 * Produces an early-bound method handle for a non-static method. 3327 * The receiver must have a supertype {@code defc} in which a method 3328 * of the given name and type is accessible to the lookup class. 3329 * The method and all its argument types must be accessible to the lookup object. 3330 * The type of the method handle will be that of the method, 3331 * without any insertion of an additional receiver parameter. 3332 * The given receiver will be bound into the method handle, 3333 * so that every call to the method handle will invoke the 3334 * requested method on the given receiver. 3335 * <p> 3336 * The returned method handle will have 3337 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3338 * the method's variable arity modifier bit ({@code 0x0080}) is set 3339 * <em>and</em> the trailing array argument is not the only argument. 3340 * (If the trailing array argument is the only argument, 3341 * the given receiver value will be bound to it.) 3342 * <p> 3343 * This is almost equivalent to the following code, with some differences noted below: 3344 * {@snippet lang="java" : 3345 import static java.lang.invoke.MethodHandles.*; 3346 import static java.lang.invoke.MethodType.*; 3347 ... 3348 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3349 MethodHandle mh1 = mh0.bindTo(receiver); 3350 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3351 return mh1; 3352 * } 3353 * where {@code defc} is either {@code receiver.getClass()} or a super 3354 * type of that class, in which the requested method is accessible 3355 * to the lookup class. 3356 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3357 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3358 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3359 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3360 * @param receiver the object from which the method is accessed 3361 * @param name the name of the method 3362 * @param type the type of the method, with the receiver argument omitted 3363 * @return the desired method handle 3364 * @throws NoSuchMethodException if the method does not exist 3365 * @throws IllegalAccessException if access checking fails 3366 * or if the method's variable arity modifier bit 3367 * is set and {@code asVarargsCollector} fails 3368 * @throws SecurityException if a security manager is present and it 3369 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3370 * @throws NullPointerException if any argument is null 3371 * @see MethodHandle#bindTo 3372 * @see #findVirtual 3373 */ 3374 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3375 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3376 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3377 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3378 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3379 throw new IllegalAccessException("The restricted defining class " + 3380 mh.type().leadingReferenceParameter().getName() + 3381 " is not assignable from receiver class " + 3382 receiver.getClass().getName()); 3383 } 3384 return mh.bindArgumentL(0, receiver).setVarargs(method); 3385 } 3386 3387 /** 3388 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3389 * to <i>m</i>, if the lookup class has permission. 3390 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3391 * If <i>m</i> is virtual, overriding is respected on every call. 3392 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3393 * The type of the method handle will be that of the method, 3394 * with the receiver type prepended (but only if it is non-static). 3395 * If the method's {@code accessible} flag is not set, 3396 * access checking is performed immediately on behalf of the lookup class. 3397 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3398 * <p> 3399 * The returned method handle will have 3400 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3401 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3402 * <p> 3403 * If <i>m</i> is static, and 3404 * if the returned method handle is invoked, the method's class will 3405 * be initialized, if it has not already been initialized. 3406 * @param m the reflected method 3407 * @return a method handle which can invoke the reflected method 3408 * @throws IllegalAccessException if access checking fails 3409 * or if the method's variable arity modifier bit 3410 * is set and {@code asVarargsCollector} fails 3411 * @throws NullPointerException if the argument is null 3412 */ 3413 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3414 if (m.getDeclaringClass() == MethodHandle.class) { 3415 MethodHandle mh = unreflectForMH(m); 3416 if (mh != null) return mh; 3417 } 3418 if (m.getDeclaringClass() == VarHandle.class) { 3419 MethodHandle mh = unreflectForVH(m); 3420 if (mh != null) return mh; 3421 } 3422 MemberName method = new MemberName(m); 3423 byte refKind = method.getReferenceKind(); 3424 if (refKind == REF_invokeSpecial) 3425 refKind = REF_invokeVirtual; 3426 assert(method.isMethod()); 3427 @SuppressWarnings("deprecation") 3428 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3429 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3430 } 3431 private MethodHandle unreflectForMH(Method m) { 3432 // these names require special lookups because they throw UnsupportedOperationException 3433 if (MemberName.isMethodHandleInvokeName(m.getName())) 3434 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3435 return null; 3436 } 3437 private MethodHandle unreflectForVH(Method m) { 3438 // these names require special lookups because they throw UnsupportedOperationException 3439 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3440 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3441 return null; 3442 } 3443 3444 /** 3445 * Produces a method handle for a reflected method. 3446 * It will bypass checks for overriding methods on the receiver, 3447 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3448 * instruction from within the explicitly specified {@code specialCaller}. 3449 * The type of the method handle will be that of the method, 3450 * with a suitably restricted receiver type prepended. 3451 * (The receiver type will be {@code specialCaller} or a subtype.) 3452 * If the method's {@code accessible} flag is not set, 3453 * access checking is performed immediately on behalf of the lookup class, 3454 * as if {@code invokespecial} instruction were being linked. 3455 * <p> 3456 * Before method resolution, 3457 * if the explicitly specified caller class is not identical with the 3458 * lookup class, or if this lookup object does not have 3459 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3460 * privileges, the access fails. 3461 * <p> 3462 * The returned method handle will have 3463 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3464 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3465 * @param m the reflected method 3466 * @param specialCaller the class nominally calling the method 3467 * @return a method handle which can invoke the reflected method 3468 * @throws IllegalAccessException if access checking fails, 3469 * or if the method is {@code static}, 3470 * or if the method's variable arity modifier bit 3471 * is set and {@code asVarargsCollector} fails 3472 * @throws NullPointerException if any argument is null 3473 */ 3474 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3475 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3476 Lookup specialLookup = this.in(specialCaller); 3477 MemberName method = new MemberName(m, true); 3478 assert(method.isMethod()); 3479 // ignore m.isAccessible: this is a new kind of access 3480 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3481 } 3482 3483 /** 3484 * Produces a method handle for a reflected constructor. 3485 * The type of the method handle will be that of the constructor, 3486 * with the return type changed to the declaring class. 3487 * The method handle will perform a {@code newInstance} operation, 3488 * creating a new instance of the constructor's class on the 3489 * arguments passed to the method handle. 3490 * <p> 3491 * If the constructor's {@code accessible} flag is not set, 3492 * access checking is performed immediately on behalf of the lookup class. 3493 * <p> 3494 * The returned method handle will have 3495 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3496 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3497 * <p> 3498 * If the returned method handle is invoked, the constructor's class will 3499 * be initialized, if it has not already been initialized. 3500 * @param c the reflected constructor 3501 * @return a method handle which can invoke the reflected constructor 3502 * @throws IllegalAccessException if access checking fails 3503 * or if the method's variable arity modifier bit 3504 * is set and {@code asVarargsCollector} fails 3505 * @throws NullPointerException if the argument is null 3506 */ 3507 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3508 MemberName ctor = new MemberName(c); 3509 assert(ctor.isConstructor()); 3510 @SuppressWarnings("deprecation") 3511 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3512 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3513 } 3514 3515 /* 3516 * Produces a method handle that is capable of creating instances of the given class 3517 * and instantiated by the given constructor. No security manager check. 3518 * 3519 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3520 */ 3521 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3522 MemberName ctor = new MemberName(c); 3523 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3524 checkAccess(REF_newInvokeSpecial, decl, ctor); 3525 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3526 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3527 } 3528 3529 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3530 if (decl == ctor.getDeclaringClass()) 3531 return true; 3532 3533 Class<?> cl = decl; 3534 while ((cl = cl.getSuperclass()) != null) { 3535 if (cl == ctor.getDeclaringClass()) { 3536 return true; 3537 } 3538 } 3539 return false; 3540 } 3541 3542 /** 3543 * Produces a method handle giving read access to a reflected field. 3544 * The type of the method handle will have a return type of the field's 3545 * value type. 3546 * If the field is {@code static}, the method handle will take no arguments. 3547 * Otherwise, its single argument will be the instance containing 3548 * the field. 3549 * If the {@code Field} object's {@code accessible} flag is not set, 3550 * access checking is performed immediately on behalf of the lookup class. 3551 * <p> 3552 * If the field is static, and 3553 * if the returned method handle is invoked, the field's class will 3554 * be initialized, if it has not already been initialized. 3555 * @param f the reflected field 3556 * @return a method handle which can load values from the reflected field 3557 * @throws IllegalAccessException if access checking fails 3558 * @throws NullPointerException if the argument is null 3559 */ 3560 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3561 return unreflectField(f, false); 3562 } 3563 3564 /** 3565 * Produces a method handle giving write access to a reflected field. 3566 * The type of the method handle will have a void return type. 3567 * If the field is {@code static}, the method handle will take a single 3568 * argument, of the field's value type, the value to be stored. 3569 * Otherwise, the two arguments will be the instance containing 3570 * the field, and the value to be stored. 3571 * If the {@code Field} object's {@code accessible} flag is not set, 3572 * access checking is performed immediately on behalf of the lookup class. 3573 * <p> 3574 * If the field is {@code final}, write access will not be 3575 * allowed and access checking will fail, except under certain 3576 * narrow circumstances documented for {@link Field#set Field.set}. 3577 * A method handle is returned only if a corresponding call to 3578 * the {@code Field} object's {@code set} method could return 3579 * normally. In particular, fields which are both {@code static} 3580 * and {@code final} may never be set. 3581 * <p> 3582 * If the field is {@code static}, and 3583 * if the returned method handle is invoked, the field's class will 3584 * be initialized, if it has not already been initialized. 3585 * @param f the reflected field 3586 * @return a method handle which can store values into the reflected field 3587 * @throws IllegalAccessException if access checking fails, 3588 * or if the field is {@code final} and write access 3589 * is not enabled on the {@code Field} object 3590 * @throws NullPointerException if the argument is null 3591 */ 3592 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3593 return unreflectField(f, true); 3594 } 3595 3596 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3597 MemberName field = new MemberName(f, isSetter); 3598 if (isSetter && field.isFinal()) { 3599 if (field.isTrustedFinalField()) { 3600 String msg = field.isStatic() ? "static final field has no write access" 3601 : "final field has no write access"; 3602 throw field.makeAccessException(msg, this); 3603 } 3604 } 3605 assert(isSetter 3606 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3607 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3608 @SuppressWarnings("deprecation") 3609 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3610 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3611 } 3612 3613 /** 3614 * Produces a VarHandle giving access to a reflected field {@code f} 3615 * of type {@code T} declared in a class of type {@code R}. 3616 * The VarHandle's variable type is {@code T}. 3617 * If the field is non-static the VarHandle has one coordinate type, 3618 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3619 * coordinate types. 3620 * <p> 3621 * Access checking is performed immediately on behalf of the lookup 3622 * class, regardless of the value of the field's {@code accessible} 3623 * flag. 3624 * <p> 3625 * If the field is static, and if the returned VarHandle is operated 3626 * on, the field's declaring class will be initialized, if it has not 3627 * already been initialized. 3628 * <p> 3629 * Certain access modes of the returned VarHandle are unsupported under 3630 * the following conditions: 3631 * <ul> 3632 * <li>if the field is declared {@code final}, then the write, atomic 3633 * update, numeric atomic update, and bitwise atomic update access 3634 * modes are unsupported. 3635 * <li>if the field type is anything other than {@code byte}, 3636 * {@code short}, {@code char}, {@code int}, {@code long}, 3637 * {@code float}, or {@code double} then numeric atomic update 3638 * access modes are unsupported. 3639 * <li>if the field type is anything other than {@code boolean}, 3640 * {@code byte}, {@code short}, {@code char}, {@code int} or 3641 * {@code long} then bitwise atomic update access modes are 3642 * unsupported. 3643 * </ul> 3644 * <p> 3645 * If the field is declared {@code volatile} then the returned VarHandle 3646 * will override access to the field (effectively ignore the 3647 * {@code volatile} declaration) in accordance to its specified 3648 * access modes. 3649 * <p> 3650 * If the field type is {@code float} or {@code double} then numeric 3651 * and atomic update access modes compare values using their bitwise 3652 * representation (see {@link Float#floatToRawIntBits} and 3653 * {@link Double#doubleToRawLongBits}, respectively). 3654 * @apiNote 3655 * Bitwise comparison of {@code float} values or {@code double} values, 3656 * as performed by the numeric and atomic update access modes, differ 3657 * from the primitive {@code ==} operator and the {@link Float#equals} 3658 * and {@link Double#equals} methods, specifically with respect to 3659 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3660 * Care should be taken when performing a compare and set or a compare 3661 * and exchange operation with such values since the operation may 3662 * unexpectedly fail. 3663 * There are many possible NaN values that are considered to be 3664 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3665 * provided by Java can distinguish between them. Operation failure can 3666 * occur if the expected or witness value is a NaN value and it is 3667 * transformed (perhaps in a platform specific manner) into another NaN 3668 * value, and thus has a different bitwise representation (see 3669 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3670 * details). 3671 * The values {@code -0.0} and {@code +0.0} have different bitwise 3672 * representations but are considered equal when using the primitive 3673 * {@code ==} operator. Operation failure can occur if, for example, a 3674 * numeric algorithm computes an expected value to be say {@code -0.0} 3675 * and previously computed the witness value to be say {@code +0.0}. 3676 * @param f the reflected field, with a field of type {@code T}, and 3677 * a declaring class of type {@code R} 3678 * @return a VarHandle giving access to non-static fields or a static 3679 * field 3680 * @throws IllegalAccessException if access checking fails 3681 * @throws NullPointerException if the argument is null 3682 * @since 9 3683 */ 3684 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3685 MemberName getField = new MemberName(f, false); 3686 MemberName putField = new MemberName(f, true); 3687 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3688 f.getDeclaringClass(), getField, putField); 3689 } 3690 3691 /** 3692 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3693 * created by this lookup object or a similar one. 3694 * Security and access checks are performed to ensure that this lookup object 3695 * is capable of reproducing the target method handle. 3696 * This means that the cracking may fail if target is a direct method handle 3697 * but was created by an unrelated lookup object. 3698 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3699 * and was created by a lookup object for a different class. 3700 * @param target a direct method handle to crack into symbolic reference components 3701 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3702 * @throws SecurityException if a security manager is present and it 3703 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3704 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3705 * @throws NullPointerException if the target is {@code null} 3706 * @see MethodHandleInfo 3707 * @since 1.8 3708 */ 3709 public MethodHandleInfo revealDirect(MethodHandle target) { 3710 if (!target.isCrackable()) { 3711 throw newIllegalArgumentException("not a direct method handle"); 3712 } 3713 MemberName member = target.internalMemberName(); 3714 Class<?> defc = member.getDeclaringClass(); 3715 byte refKind = member.getReferenceKind(); 3716 assert(MethodHandleNatives.refKindIsValid(refKind)); 3717 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3718 // Devirtualized method invocation is usually formally virtual. 3719 // To avoid creating extra MemberName objects for this common case, 3720 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3721 refKind = REF_invokeVirtual; 3722 if (refKind == REF_invokeVirtual && defc.isInterface()) 3723 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3724 refKind = REF_invokeInterface; 3725 // Check SM permissions and member access before cracking. 3726 try { 3727 checkAccess(refKind, defc, member); 3728 checkSecurityManager(defc, member); 3729 } catch (IllegalAccessException ex) { 3730 throw new IllegalArgumentException(ex); 3731 } 3732 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3733 Class<?> callerClass = target.internalCallerClass(); 3734 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3735 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3736 } 3737 // Produce the handle to the results. 3738 return new InfoFromMemberName(this, member, refKind); 3739 } 3740 3741 //--- Helper methods, all package-private. 3742 3743 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3744 checkSymbolicClass(refc); // do this before attempting to resolve 3745 Objects.requireNonNull(name); 3746 Objects.requireNonNull(type); 3747 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3748 NoSuchFieldException.class); 3749 } 3750 3751 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3752 checkSymbolicClass(refc); // do this before attempting to resolve 3753 Objects.requireNonNull(type); 3754 checkMethodName(refKind, name); // implicit null-check of name 3755 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3756 NoSuchMethodException.class); 3757 } 3758 3759 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3760 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3761 Objects.requireNonNull(member.getName()); 3762 Objects.requireNonNull(member.getType()); 3763 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3764 ReflectiveOperationException.class); 3765 } 3766 3767 MemberName resolveOrNull(byte refKind, MemberName member) { 3768 // do this before attempting to resolve 3769 if (!isClassAccessible(member.getDeclaringClass())) { 3770 return null; 3771 } 3772 Objects.requireNonNull(member.getName()); 3773 Objects.requireNonNull(member.getType()); 3774 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3775 } 3776 3777 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3778 // do this before attempting to resolve 3779 if (!isClassAccessible(refc)) { 3780 return null; 3781 } 3782 Objects.requireNonNull(type); 3783 // implicit null-check of name 3784 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3785 return null; 3786 } 3787 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3788 } 3789 3790 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3791 if (!isClassAccessible(refc)) { 3792 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3793 } 3794 } 3795 3796 boolean isClassAccessible(Class<?> refc) { 3797 Objects.requireNonNull(refc); 3798 Class<?> caller = lookupClassOrNull(); 3799 Class<?> type = refc; 3800 while (type.isArray()) { 3801 type = type.getComponentType(); 3802 } 3803 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3804 } 3805 3806 /** Check name for an illegal leading "<" character. */ 3807 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3808 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3809 throw new NoSuchMethodException("illegal method name: "+name); 3810 } 3811 3812 /** 3813 * Find my trustable caller class if m is a caller sensitive method. 3814 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3815 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3816 */ 3817 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3818 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3819 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3820 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3821 } 3822 return this; 3823 } 3824 3825 /** 3826 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3827 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3828 * 3829 * @deprecated This method was originally designed to test {@code PRIVATE} access 3830 * that implies full privilege access but {@code MODULE} access has since become 3831 * independent of {@code PRIVATE} access. It is recommended to call 3832 * {@link #hasFullPrivilegeAccess()} instead. 3833 * @since 9 3834 */ 3835 @Deprecated(since="14") 3836 public boolean hasPrivateAccess() { 3837 return hasFullPrivilegeAccess(); 3838 } 3839 3840 /** 3841 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3842 * i.e. {@code PRIVATE} and {@code MODULE} access. 3843 * A {@code Lookup} object must have full privilege access in order to 3844 * access all members that are allowed to the 3845 * {@linkplain #lookupClass() lookup class}. 3846 * 3847 * @return {@code true} if this lookup has full privilege access. 3848 * @since 14 3849 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3850 */ 3851 public boolean hasFullPrivilegeAccess() { 3852 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3853 } 3854 3855 /** 3856 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3857 * for ensureInitialized, findClass or accessClass. 3858 */ 3859 void checkSecurityManager(Class<?> refc) { 3860 if (allowedModes == TRUSTED) return; 3861 3862 @SuppressWarnings("removal") 3863 SecurityManager smgr = System.getSecurityManager(); 3864 if (smgr == null) return; 3865 3866 // Step 1: 3867 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3868 if (!fullPrivilegeLookup || 3869 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3870 ReflectUtil.checkPackageAccess(refc); 3871 } 3872 3873 // Step 2b: 3874 if (!fullPrivilegeLookup) { 3875 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3876 } 3877 } 3878 3879 /** 3880 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3881 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3882 * If this lookup object has full privilege access except original access, 3883 * then the caller class is the lookupClass. 3884 * 3885 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3886 * from the same module skips the security permission check. 3887 */ 3888 void checkSecurityManager(Class<?> refc, MemberName m) { 3889 Objects.requireNonNull(refc); 3890 Objects.requireNonNull(m); 3891 3892 if (allowedModes == TRUSTED) return; 3893 3894 @SuppressWarnings("removal") 3895 SecurityManager smgr = System.getSecurityManager(); 3896 if (smgr == null) return; 3897 3898 // Step 1: 3899 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3900 if (!fullPrivilegeLookup || 3901 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3902 ReflectUtil.checkPackageAccess(refc); 3903 } 3904 3905 // Step 2a: 3906 if (m.isPublic()) return; 3907 if (!fullPrivilegeLookup) { 3908 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3909 } 3910 3911 // Step 3: 3912 Class<?> defc = m.getDeclaringClass(); 3913 if (!fullPrivilegeLookup && defc != refc) { 3914 ReflectUtil.checkPackageAccess(defc); 3915 } 3916 } 3917 3918 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3919 boolean wantStatic = (refKind == REF_invokeStatic); 3920 String message; 3921 if (m.isConstructor()) 3922 message = "expected a method, not a constructor"; 3923 else if (!m.isMethod()) 3924 message = "expected a method"; 3925 else if (wantStatic != m.isStatic()) 3926 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3927 else 3928 { checkAccess(refKind, refc, m); return; } 3929 throw m.makeAccessException(message, this); 3930 } 3931 3932 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3933 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3934 String message; 3935 if (wantStatic != m.isStatic()) 3936 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3937 else 3938 { checkAccess(refKind, refc, m); return; } 3939 throw m.makeAccessException(message, this); 3940 } 3941 3942 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3943 return Modifier.isProtected(m.getModifiers()) && 3944 refKind == REF_invokeVirtual && 3945 m.getDeclaringClass() == Object.class && 3946 m.getName().equals("clone") && 3947 refc.isArray(); 3948 } 3949 3950 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3951 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3952 assert(m.referenceKindIsConsistentWith(refKind) && 3953 MethodHandleNatives.refKindIsValid(refKind) && 3954 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3955 int allowedModes = this.allowedModes; 3956 if (allowedModes == TRUSTED) return; 3957 int mods = m.getModifiers(); 3958 if (isArrayClone(refKind, refc, m)) { 3959 // The JVM does this hack also. 3960 // (See ClassVerifier::verify_invoke_instructions 3961 // and LinkResolver::check_method_accessability.) 3962 // Because the JVM does not allow separate methods on array types, 3963 // there is no separate method for int[].clone. 3964 // All arrays simply inherit Object.clone. 3965 // But for access checking logic, we make Object.clone 3966 // (normally protected) appear to be public. 3967 // Later on, when the DirectMethodHandle is created, 3968 // its leading argument will be restricted to the 3969 // requested array type. 3970 // N.B. The return type is not adjusted, because 3971 // that is *not* the bytecode behavior. 3972 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3973 } 3974 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3975 // cannot "new" a protected ctor in a different package 3976 mods ^= Modifier.PROTECTED; 3977 } 3978 if (Modifier.isFinal(mods) && 3979 MethodHandleNatives.refKindIsSetter(refKind)) 3980 throw m.makeAccessException("unexpected set of a final field", this); 3981 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3982 if ((requestedModes & allowedModes) != 0) { 3983 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3984 mods, lookupClass(), previousLookupClass(), allowedModes)) 3985 return; 3986 } else { 3987 // Protected members can also be checked as if they were package-private. 3988 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3989 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3990 return; 3991 } 3992 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3993 } 3994 3995 String accessFailedMessage(Class<?> refc, MemberName m) { 3996 Class<?> defc = m.getDeclaringClass(); 3997 int mods = m.getModifiers(); 3998 // check the class first: 3999 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 4000 (defc == refc || 4001 Modifier.isPublic(refc.getModifiers()))); 4002 if (!classOK && (allowedModes & PACKAGE) != 0) { 4003 // ignore previous lookup class to check if default package access 4004 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 4005 (defc == refc || 4006 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 4007 } 4008 if (!classOK) 4009 return "class is not public"; 4010 if (Modifier.isPublic(mods)) 4011 return "access to public member failed"; // (how?, module not readable?) 4012 if (Modifier.isPrivate(mods)) 4013 return "member is private"; 4014 if (Modifier.isProtected(mods)) 4015 return "member is protected"; 4016 return "member is private to package"; 4017 } 4018 4019 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 4020 int allowedModes = this.allowedModes; 4021 if (allowedModes == TRUSTED) return; 4022 if ((lookupModes() & PRIVATE) == 0 4023 || (specialCaller != lookupClass() 4024 // ensure non-abstract methods in superinterfaces can be special-invoked 4025 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 4026 throw new MemberName(specialCaller). 4027 makeAccessException("no private access for invokespecial", this); 4028 } 4029 4030 private boolean restrictProtectedReceiver(MemberName method) { 4031 // The accessing class only has the right to use a protected member 4032 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 4033 if (!method.isProtected() || method.isStatic() 4034 || allowedModes == TRUSTED 4035 || method.getDeclaringClass() == lookupClass() 4036 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 4037 return false; 4038 return true; 4039 } 4040 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 4041 assert(!method.isStatic()); 4042 // receiver type of mh is too wide; narrow to caller 4043 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 4044 throw method.makeAccessException("caller class must be a subclass below the method", caller); 4045 } 4046 MethodType rawType = mh.type(); 4047 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 4048 MethodType narrowType = rawType.changeParameterType(0, caller); 4049 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 4050 assert(mh.viewAsTypeChecks(narrowType, true)); 4051 return mh.copyWith(narrowType, mh.form); 4052 } 4053 4054 /** Check access and get the requested method. */ 4055 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4056 final boolean doRestrict = true; 4057 final boolean checkSecurity = true; 4058 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4059 } 4060 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 4061 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4062 final boolean doRestrict = false; 4063 final boolean checkSecurity = true; 4064 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 4065 } 4066 /** Check access and get the requested method, eliding security manager checks. */ 4067 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4068 final boolean doRestrict = true; 4069 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4070 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4071 } 4072 /** Common code for all methods; do not call directly except from immediately above. */ 4073 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 4074 boolean checkSecurity, 4075 boolean doRestrict, 4076 Lookup boundCaller) throws IllegalAccessException { 4077 checkMethod(refKind, refc, method); 4078 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4079 if (checkSecurity) 4080 checkSecurityManager(refc, method); 4081 assert(!method.isMethodHandleInvoke()); 4082 if (refKind == REF_invokeSpecial && 4083 refc != lookupClass() && 4084 !refc.isInterface() && !lookupClass().isInterface() && 4085 refc != lookupClass().getSuperclass() && 4086 refc.isAssignableFrom(lookupClass())) { 4087 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 4088 4089 // Per JVMS 6.5, desc. of invokespecial instruction: 4090 // If the method is in a superclass of the LC, 4091 // and if our original search was above LC.super, 4092 // repeat the search (symbolic lookup) from LC.super 4093 // and continue with the direct superclass of that class, 4094 // and so forth, until a match is found or no further superclasses exist. 4095 // FIXME: MemberName.resolve should handle this instead. 4096 Class<?> refcAsSuper = lookupClass(); 4097 MemberName m2; 4098 do { 4099 refcAsSuper = refcAsSuper.getSuperclass(); 4100 m2 = new MemberName(refcAsSuper, 4101 method.getName(), 4102 method.getMethodType(), 4103 REF_invokeSpecial); 4104 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4105 } while (m2 == null && // no method is found yet 4106 refc != refcAsSuper); // search up to refc 4107 if (m2 == null) throw new InternalError(method.toString()); 4108 method = m2; 4109 refc = refcAsSuper; 4110 // redo basic checks 4111 checkMethod(refKind, refc, method); 4112 } 4113 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4114 MethodHandle mh = dmh; 4115 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4116 if ((doRestrict && refKind == REF_invokeSpecial) || 4117 (MethodHandleNatives.refKindHasReceiver(refKind) && 4118 restrictProtectedReceiver(method) && 4119 // All arrays simply inherit the protected Object.clone method. 4120 // The leading argument is already restricted to the requested 4121 // array type (not the lookup class). 4122 !isArrayClone(refKind, refc, method))) { 4123 mh = restrictReceiver(method, dmh, lookupClass()); 4124 } 4125 mh = maybeBindCaller(method, mh, boundCaller); 4126 mh = mh.setVarargs(method); 4127 return mh; 4128 } 4129 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4130 throws IllegalAccessException { 4131 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4132 return mh; 4133 4134 // boundCaller must have full privilege access. 4135 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4136 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4137 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4138 4139 assert boundCaller.hasFullPrivilegeAccess(); 4140 4141 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4142 // Note: caller will apply varargs after this step happens. 4143 return cbmh; 4144 } 4145 4146 /** Check access and get the requested field. */ 4147 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4148 final boolean checkSecurity = true; 4149 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4150 } 4151 /** Check access and get the requested field, eliding security manager checks. */ 4152 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4153 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4154 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4155 } 4156 /** Common code for all fields; do not call directly except from immediately above. */ 4157 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4158 boolean checkSecurity) throws IllegalAccessException { 4159 checkField(refKind, refc, field); 4160 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4161 if (checkSecurity) 4162 checkSecurityManager(refc, field); 4163 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4164 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4165 restrictProtectedReceiver(field)); 4166 if (doRestrict) 4167 return restrictReceiver(field, dmh, lookupClass()); 4168 return dmh; 4169 } 4170 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4171 Class<?> refc, MemberName getField, MemberName putField) 4172 throws IllegalAccessException { 4173 final boolean checkSecurity = true; 4174 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4175 } 4176 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4177 Class<?> refc, MemberName getField, MemberName putField) 4178 throws IllegalAccessException { 4179 final boolean checkSecurity = false; 4180 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4181 } 4182 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4183 Class<?> refc, MemberName getField, MemberName putField, 4184 boolean checkSecurity) throws IllegalAccessException { 4185 assert getField.isStatic() == putField.isStatic(); 4186 assert getField.isGetter() && putField.isSetter(); 4187 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4188 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4189 4190 checkField(getRefKind, refc, getField); 4191 if (checkSecurity) 4192 checkSecurityManager(refc, getField); 4193 4194 if (!putField.isFinal()) { 4195 // A VarHandle does not support updates to final fields, any 4196 // such VarHandle to a final field will be read-only and 4197 // therefore the following write-based accessibility checks are 4198 // only required for non-final fields 4199 checkField(putRefKind, refc, putField); 4200 if (checkSecurity) 4201 checkSecurityManager(refc, putField); 4202 } 4203 4204 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4205 restrictProtectedReceiver(getField)); 4206 if (doRestrict) { 4207 assert !getField.isStatic(); 4208 // receiver type of VarHandle is too wide; narrow to caller 4209 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4210 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4211 } 4212 refc = lookupClass(); 4213 } 4214 return VarHandles.makeFieldHandle(getField, refc, 4215 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4216 } 4217 /** Check access and get the requested constructor. */ 4218 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4219 final boolean checkSecurity = true; 4220 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4221 } 4222 /** Check access and get the requested constructor, eliding security manager checks. */ 4223 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4224 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4225 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4226 } 4227 /** Common code for all constructors; do not call directly except from immediately above. */ 4228 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4229 boolean checkSecurity) throws IllegalAccessException { 4230 assert(ctor.isConstructor()); 4231 checkAccess(REF_newInvokeSpecial, refc, ctor); 4232 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4233 if (checkSecurity) 4234 checkSecurityManager(refc, ctor); 4235 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4236 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4237 } 4238 4239 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4240 */ 4241 /*non-public*/ 4242 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4243 throws ReflectiveOperationException { 4244 if (!(type instanceof Class || type instanceof MethodType)) 4245 throw new InternalError("unresolved MemberName"); 4246 MemberName member = new MemberName(refKind, defc, name, type); 4247 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4248 if (mh != null) { 4249 checkSymbolicClass(defc); 4250 return mh; 4251 } 4252 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4253 // Treat MethodHandle.invoke and invokeExact specially. 4254 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4255 if (mh != null) { 4256 return mh; 4257 } 4258 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4259 // Treat signature-polymorphic methods on VarHandle specially. 4260 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4261 if (mh != null) { 4262 return mh; 4263 } 4264 } 4265 MemberName resolved = resolveOrFail(refKind, member); 4266 mh = getDirectMethodForConstant(refKind, defc, resolved); 4267 if (mh instanceof DirectMethodHandle dmh 4268 && canBeCached(refKind, defc, resolved)) { 4269 MemberName key = mh.internalMemberName(); 4270 if (key != null) { 4271 key = key.asNormalOriginal(); 4272 } 4273 if (member.equals(key)) { // better safe than sorry 4274 LOOKASIDE_TABLE.put(key, dmh); 4275 } 4276 } 4277 return mh; 4278 } 4279 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4280 if (refKind == REF_invokeSpecial) { 4281 return false; 4282 } 4283 if (!Modifier.isPublic(defc.getModifiers()) || 4284 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4285 !member.isPublic() || 4286 member.isCallerSensitive()) { 4287 return false; 4288 } 4289 ClassLoader loader = defc.getClassLoader(); 4290 if (loader != null) { 4291 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4292 boolean found = false; 4293 while (sysl != null) { 4294 if (loader == sysl) { found = true; break; } 4295 sysl = sysl.getParent(); 4296 } 4297 if (!found) { 4298 return false; 4299 } 4300 } 4301 try { 4302 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4303 new MemberName(refKind, defc, member.getName(), member.getType())); 4304 if (resolved2 == null) { 4305 return false; 4306 } 4307 checkSecurityManager(defc, resolved2); 4308 } catch (SecurityException ex) { 4309 return false; 4310 } 4311 return true; 4312 } 4313 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4314 throws ReflectiveOperationException { 4315 if (MethodHandleNatives.refKindIsField(refKind)) { 4316 return getDirectFieldNoSecurityManager(refKind, defc, member); 4317 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4318 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4319 } else if (refKind == REF_newInvokeSpecial) { 4320 return getDirectConstructorNoSecurityManager(defc, member); 4321 } 4322 // oops 4323 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4324 } 4325 4326 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4327 } 4328 4329 /** 4330 * Produces a method handle constructing arrays of a desired type, 4331 * as if by the {@code anewarray} bytecode. 4332 * The return type of the method handle will be the array type. 4333 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4334 * 4335 * <p> If the returned method handle is invoked with a negative 4336 * array size, a {@code NegativeArraySizeException} will be thrown. 4337 * 4338 * @param arrayClass an array type 4339 * @return a method handle which can create arrays of the given type 4340 * @throws NullPointerException if the argument is {@code null} 4341 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4342 * @see java.lang.reflect.Array#newInstance(Class, int) 4343 * @jvms 6.5 {@code anewarray} Instruction 4344 * @since 9 4345 */ 4346 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4347 if (!arrayClass.isArray()) { 4348 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4349 } 4350 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4351 bindTo(arrayClass.getComponentType()); 4352 return ani.asType(ani.type().changeReturnType(arrayClass)); 4353 } 4354 4355 /** 4356 * Produces a method handle returning the length of an array, 4357 * as if by the {@code arraylength} bytecode. 4358 * The type of the method handle will have {@code int} as return type, 4359 * and its sole argument will be the array type. 4360 * 4361 * <p> If the returned method handle is invoked with a {@code null} 4362 * array reference, a {@code NullPointerException} will be thrown. 4363 * 4364 * @param arrayClass an array type 4365 * @return a method handle which can retrieve the length of an array of the given array type 4366 * @throws NullPointerException if the argument is {@code null} 4367 * @throws IllegalArgumentException if arrayClass is not an array type 4368 * @jvms 6.5 {@code arraylength} Instruction 4369 * @since 9 4370 */ 4371 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4372 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4373 } 4374 4375 /** 4376 * Produces a method handle giving read access to elements of an array, 4377 * as if by the {@code aaload} bytecode. 4378 * The type of the method handle will have a return type of the array's 4379 * element type. Its first argument will be the array type, 4380 * and the second will be {@code int}. 4381 * 4382 * <p> When the returned method handle is invoked, 4383 * the array reference and array index are checked. 4384 * A {@code NullPointerException} will be thrown if the array reference 4385 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4386 * thrown if the index is negative or if it is greater than or equal to 4387 * the length of the array. 4388 * 4389 * @param arrayClass an array type 4390 * @return a method handle which can load values from the given array type 4391 * @throws NullPointerException if the argument is null 4392 * @throws IllegalArgumentException if arrayClass is not an array type 4393 * @jvms 6.5 {@code aaload} Instruction 4394 */ 4395 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4396 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4397 } 4398 4399 /** 4400 * Produces a method handle giving write access to elements of an array, 4401 * as if by the {@code astore} bytecode. 4402 * The type of the method handle will have a void return type. 4403 * Its last argument will be the array's element type. 4404 * The first and second arguments will be the array type and int. 4405 * 4406 * <p> When the returned method handle is invoked, 4407 * the array reference and array index are checked. 4408 * A {@code NullPointerException} will be thrown if the array reference 4409 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4410 * thrown if the index is negative or if it is greater than or equal to 4411 * the length of the array. 4412 * 4413 * @param arrayClass the class of an array 4414 * @return a method handle which can store values into the array type 4415 * @throws NullPointerException if the argument is null 4416 * @throws IllegalArgumentException if arrayClass is not an array type 4417 * @jvms 6.5 {@code aastore} Instruction 4418 */ 4419 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4420 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4421 } 4422 4423 /** 4424 * Produces a VarHandle giving access to elements of an array of type 4425 * {@code arrayClass}. The VarHandle's variable type is the component type 4426 * of {@code arrayClass} and the list of coordinate types is 4427 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4428 * corresponds to an argument that is an index into an array. 4429 * <p> 4430 * Certain access modes of the returned VarHandle are unsupported under 4431 * the following conditions: 4432 * <ul> 4433 * <li>if the component type is anything other than {@code byte}, 4434 * {@code short}, {@code char}, {@code int}, {@code long}, 4435 * {@code float}, or {@code double} then numeric atomic update access 4436 * modes are unsupported. 4437 * <li>if the component type is anything other than {@code boolean}, 4438 * {@code byte}, {@code short}, {@code char}, {@code int} or 4439 * {@code long} then bitwise atomic update access modes are 4440 * unsupported. 4441 * </ul> 4442 * <p> 4443 * If the component type is {@code float} or {@code double} then numeric 4444 * and atomic update access modes compare values using their bitwise 4445 * representation (see {@link Float#floatToRawIntBits} and 4446 * {@link Double#doubleToRawLongBits}, respectively). 4447 * 4448 * <p> When the returned {@code VarHandle} is invoked, 4449 * the array reference and array index are checked. 4450 * A {@code NullPointerException} will be thrown if the array reference 4451 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4452 * thrown if the index is negative or if it is greater than or equal to 4453 * the length of the array. 4454 * 4455 * @apiNote 4456 * Bitwise comparison of {@code float} values or {@code double} values, 4457 * as performed by the numeric and atomic update access modes, differ 4458 * from the primitive {@code ==} operator and the {@link Float#equals} 4459 * and {@link Double#equals} methods, specifically with respect to 4460 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4461 * Care should be taken when performing a compare and set or a compare 4462 * and exchange operation with such values since the operation may 4463 * unexpectedly fail. 4464 * There are many possible NaN values that are considered to be 4465 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4466 * provided by Java can distinguish between them. Operation failure can 4467 * occur if the expected or witness value is a NaN value and it is 4468 * transformed (perhaps in a platform specific manner) into another NaN 4469 * value, and thus has a different bitwise representation (see 4470 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4471 * details). 4472 * The values {@code -0.0} and {@code +0.0} have different bitwise 4473 * representations but are considered equal when using the primitive 4474 * {@code ==} operator. Operation failure can occur if, for example, a 4475 * numeric algorithm computes an expected value to be say {@code -0.0} 4476 * and previously computed the witness value to be say {@code +0.0}. 4477 * @param arrayClass the class of an array, of type {@code T[]} 4478 * @return a VarHandle giving access to elements of an array 4479 * @throws NullPointerException if the arrayClass is null 4480 * @throws IllegalArgumentException if arrayClass is not an array type 4481 * @since 9 4482 */ 4483 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4484 return VarHandles.makeArrayElementHandle(arrayClass); 4485 } 4486 4487 /** 4488 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4489 * viewed as if it were a different primitive array type, such as 4490 * {@code int[]} or {@code long[]}. 4491 * The VarHandle's variable type is the component type of 4492 * {@code viewArrayClass} and the list of coordinate types is 4493 * {@code (byte[], int)}, where the {@code int} coordinate type 4494 * corresponds to an argument that is an index into a {@code byte[]} array. 4495 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4496 * array, composing bytes to or from a value of the component type of 4497 * {@code viewArrayClass} according to the given endianness. 4498 * <p> 4499 * The supported component types (variables types) are {@code short}, 4500 * {@code char}, {@code int}, {@code long}, {@code float} and 4501 * {@code double}. 4502 * <p> 4503 * Access of bytes at a given index will result in an 4504 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4505 * or greater than the {@code byte[]} array length minus the size (in bytes) 4506 * of {@code T}. 4507 * <p> 4508 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4509 * access modes are supported by the returned var handle. For all other access modes, an 4510 * {@link UnsupportedOperationException} will be thrown. 4511 * 4512 * @apiNote if access modes other than plain access are required, clients should 4513 * consider using off-heap memory through 4514 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4515 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4516 * or memory segments backed by a 4517 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4518 * for which stronger alignment guarantees can be made. 4519 * 4520 * @param viewArrayClass the view array class, with a component type of 4521 * type {@code T} 4522 * @param byteOrder the endianness of the view array elements, as 4523 * stored in the underlying {@code byte} array 4524 * @return a VarHandle giving access to elements of a {@code byte[]} array 4525 * viewed as if elements corresponding to the components type of the view 4526 * array class 4527 * @throws NullPointerException if viewArrayClass or byteOrder is null 4528 * @throws IllegalArgumentException if viewArrayClass is not an array type 4529 * @throws UnsupportedOperationException if the component type of 4530 * viewArrayClass is not supported as a variable type 4531 * @since 9 4532 */ 4533 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4534 ByteOrder byteOrder) throws IllegalArgumentException { 4535 Objects.requireNonNull(byteOrder); 4536 return VarHandles.byteArrayViewHandle(viewArrayClass, 4537 byteOrder == ByteOrder.BIG_ENDIAN); 4538 } 4539 4540 /** 4541 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4542 * viewed as if it were an array of elements of a different primitive 4543 * component type to that of {@code byte}, such as {@code int[]} or 4544 * {@code long[]}. 4545 * The VarHandle's variable type is the component type of 4546 * {@code viewArrayClass} and the list of coordinate types is 4547 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4548 * corresponds to an argument that is an index into a {@code byte[]} array. 4549 * The returned VarHandle accesses bytes at an index in a 4550 * {@code ByteBuffer}, composing bytes to or from a value of the component 4551 * type of {@code viewArrayClass} according to the given endianness. 4552 * <p> 4553 * The supported component types (variables types) are {@code short}, 4554 * {@code char}, {@code int}, {@code long}, {@code float} and 4555 * {@code double}. 4556 * <p> 4557 * Access will result in a {@code ReadOnlyBufferException} for anything 4558 * other than the read access modes if the {@code ByteBuffer} is read-only. 4559 * <p> 4560 * Access of bytes at a given index will result in an 4561 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4562 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4563 * {@code T}. 4564 * <p> 4565 * For heap byte buffers, access is always unaligned. As a result, only the plain 4566 * {@linkplain VarHandle.AccessMode#GET get} 4567 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4568 * returned var handle. For all other access modes, an {@link IllegalStateException} 4569 * will be thrown. 4570 * <p> 4571 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4572 * with respect to the underlying memory address, {@code A} say, associated 4573 * with the {@code ByteBuffer} and index. 4574 * If access is misaligned then access for anything other than the 4575 * {@code get} and {@code set} access modes will result in an 4576 * {@code IllegalStateException}. In such cases atomic access is only 4577 * guaranteed with respect to the largest power of two that divides the GCD 4578 * of {@code A} and the size (in bytes) of {@code T}. 4579 * If access is aligned then following access modes are supported and are 4580 * guaranteed to support atomic access: 4581 * <ul> 4582 * <li>read write access modes for all {@code T}, with the exception of 4583 * access modes {@code get} and {@code set} for {@code long} and 4584 * {@code double} on 32-bit platforms. 4585 * <li>atomic update access modes for {@code int}, {@code long}, 4586 * {@code float} or {@code double}. 4587 * (Future major platform releases of the JDK may support additional 4588 * types for certain currently unsupported access modes.) 4589 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4590 * (Future major platform releases of the JDK may support additional 4591 * numeric types for certain currently unsupported access modes.) 4592 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4593 * (Future major platform releases of the JDK may support additional 4594 * numeric types for certain currently unsupported access modes.) 4595 * </ul> 4596 * <p> 4597 * Misaligned access, and therefore atomicity guarantees, may be determined 4598 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4599 * {@code index}, {@code T} and its corresponding boxed type, 4600 * {@code T_BOX}, as follows: 4601 * <pre>{@code 4602 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4603 * ByteBuffer bb = ... 4604 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4605 * boolean isMisaligned = misalignedAtIndex != 0; 4606 * }</pre> 4607 * <p> 4608 * If the variable type is {@code float} or {@code double} then atomic 4609 * update access modes compare values using their bitwise representation 4610 * (see {@link Float#floatToRawIntBits} and 4611 * {@link Double#doubleToRawLongBits}, respectively). 4612 * @param viewArrayClass the view array class, with a component type of 4613 * type {@code T} 4614 * @param byteOrder the endianness of the view array elements, as 4615 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4616 * endianness of a {@code ByteBuffer}) 4617 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4618 * viewed as if elements corresponding to the components type of the view 4619 * array class 4620 * @throws NullPointerException if viewArrayClass or byteOrder is null 4621 * @throws IllegalArgumentException if viewArrayClass is not an array type 4622 * @throws UnsupportedOperationException if the component type of 4623 * viewArrayClass is not supported as a variable type 4624 * @since 9 4625 */ 4626 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4627 ByteOrder byteOrder) throws IllegalArgumentException { 4628 Objects.requireNonNull(byteOrder); 4629 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4630 byteOrder == ByteOrder.BIG_ENDIAN); 4631 } 4632 4633 4634 //--- method handle invocation (reflective style) 4635 4636 /** 4637 * Produces a method handle which will invoke any method handle of the 4638 * given {@code type}, with a given number of trailing arguments replaced by 4639 * a single trailing {@code Object[]} array. 4640 * The resulting invoker will be a method handle with the following 4641 * arguments: 4642 * <ul> 4643 * <li>a single {@code MethodHandle} target 4644 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4645 * <li>an {@code Object[]} array containing trailing arguments 4646 * </ul> 4647 * <p> 4648 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4649 * the indicated {@code type}. 4650 * That is, if the target is exactly of the given {@code type}, it will behave 4651 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4652 * is used to convert the target to the required {@code type}. 4653 * <p> 4654 * The type of the returned invoker will not be the given {@code type}, but rather 4655 * will have all parameters except the first {@code leadingArgCount} 4656 * replaced by a single array of type {@code Object[]}, which will be 4657 * the final parameter. 4658 * <p> 4659 * Before invoking its target, the invoker will spread the final array, apply 4660 * reference casts as necessary, and unbox and widen primitive arguments. 4661 * If, when the invoker is called, the supplied array argument does 4662 * not have the correct number of elements, the invoker will throw 4663 * an {@link IllegalArgumentException} instead of invoking the target. 4664 * <p> 4665 * This method is equivalent to the following code (though it may be more efficient): 4666 * {@snippet lang="java" : 4667 MethodHandle invoker = MethodHandles.invoker(type); 4668 int spreadArgCount = type.parameterCount() - leadingArgCount; 4669 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4670 return invoker; 4671 * } 4672 * This method throws no reflective or security exceptions. 4673 * @param type the desired target type 4674 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4675 * @return a method handle suitable for invoking any method handle of the given type 4676 * @throws NullPointerException if {@code type} is null 4677 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4678 * the range from 0 to {@code type.parameterCount()} inclusive, 4679 * or if the resulting method handle's type would have 4680 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4681 */ 4682 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4683 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4684 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4685 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4686 return type.invokers().spreadInvoker(leadingArgCount); 4687 } 4688 4689 /** 4690 * Produces a special <em>invoker method handle</em> which can be used to 4691 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4692 * The resulting invoker will have a type which is 4693 * exactly equal to the desired type, except that it will accept 4694 * an additional leading argument of type {@code MethodHandle}. 4695 * <p> 4696 * This method is equivalent to the following code (though it may be more efficient): 4697 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4698 * 4699 * <p style="font-size:smaller;"> 4700 * <em>Discussion:</em> 4701 * Invoker method handles can be useful when working with variable method handles 4702 * of unknown types. 4703 * For example, to emulate an {@code invokeExact} call to a variable method 4704 * handle {@code M}, extract its type {@code T}, 4705 * look up the invoker method {@code X} for {@code T}, 4706 * and call the invoker method, as {@code X.invoke(T, A...)}. 4707 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4708 * is unknown.) 4709 * If spreading, collecting, or other argument transformations are required, 4710 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4711 * method handle values, as long as they are compatible with the type of {@code X}. 4712 * <p style="font-size:smaller;"> 4713 * <em>(Note: The invoker method is not available via the Core Reflection API. 4714 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4715 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4716 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4717 * <p> 4718 * This method throws no reflective or security exceptions. 4719 * @param type the desired target type 4720 * @return a method handle suitable for invoking any method handle of the given type 4721 * @throws IllegalArgumentException if the resulting method handle's type would have 4722 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4723 */ 4724 public static MethodHandle exactInvoker(MethodType type) { 4725 return type.invokers().exactInvoker(); 4726 } 4727 4728 /** 4729 * Produces a special <em>invoker method handle</em> which can be used to 4730 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4731 * The resulting invoker will have a type which is 4732 * exactly equal to the desired type, except that it will accept 4733 * an additional leading argument of type {@code MethodHandle}. 4734 * <p> 4735 * Before invoking its target, if the target differs from the expected type, 4736 * the invoker will apply reference casts as 4737 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4738 * Similarly, the return value will be converted as necessary. 4739 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4740 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4741 * <p> 4742 * This method is equivalent to the following code (though it may be more efficient): 4743 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4744 * <p style="font-size:smaller;"> 4745 * <em>Discussion:</em> 4746 * A {@linkplain MethodType#genericMethodType general method type} is one which 4747 * mentions only {@code Object} arguments and return values. 4748 * An invoker for such a type is capable of calling any method handle 4749 * of the same arity as the general type. 4750 * <p style="font-size:smaller;"> 4751 * <em>(Note: The invoker method is not available via the Core Reflection API. 4752 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4753 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4754 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4755 * <p> 4756 * This method throws no reflective or security exceptions. 4757 * @param type the desired target type 4758 * @return a method handle suitable for invoking any method handle convertible to the given type 4759 * @throws IllegalArgumentException if the resulting method handle's type would have 4760 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4761 */ 4762 public static MethodHandle invoker(MethodType type) { 4763 return type.invokers().genericInvoker(); 4764 } 4765 4766 /** 4767 * Produces a special <em>invoker method handle</em> which can be used to 4768 * invoke a signature-polymorphic access mode method on any VarHandle whose 4769 * associated access mode type is compatible with the given type. 4770 * The resulting invoker will have a type which is exactly equal to the 4771 * desired given type, except that it will accept an additional leading 4772 * argument of type {@code VarHandle}. 4773 * 4774 * @param accessMode the VarHandle access mode 4775 * @param type the desired target type 4776 * @return a method handle suitable for invoking an access mode method of 4777 * any VarHandle whose access mode type is of the given type. 4778 * @since 9 4779 */ 4780 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4781 return type.invokers().varHandleMethodExactInvoker(accessMode); 4782 } 4783 4784 /** 4785 * Produces a special <em>invoker method handle</em> which can be used to 4786 * invoke a signature-polymorphic access mode method on any VarHandle whose 4787 * associated access mode type is compatible with the given type. 4788 * The resulting invoker will have a type which is exactly equal to the 4789 * desired given type, except that it will accept an additional leading 4790 * argument of type {@code VarHandle}. 4791 * <p> 4792 * Before invoking its target, if the access mode type differs from the 4793 * desired given type, the invoker will apply reference casts as necessary 4794 * and box, unbox, or widen primitive values, as if by 4795 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4796 * converted as necessary. 4797 * <p> 4798 * This method is equivalent to the following code (though it may be more 4799 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4800 * 4801 * @param accessMode the VarHandle access mode 4802 * @param type the desired target type 4803 * @return a method handle suitable for invoking an access mode method of 4804 * any VarHandle whose access mode type is convertible to the given 4805 * type. 4806 * @since 9 4807 */ 4808 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4809 return type.invokers().varHandleMethodInvoker(accessMode); 4810 } 4811 4812 /*non-public*/ 4813 static MethodHandle basicInvoker(MethodType type) { 4814 return type.invokers().basicInvoker(); 4815 } 4816 4817 //--- method handle modification (creation from other method handles) 4818 4819 /** 4820 * Produces a method handle which adapts the type of the 4821 * given method handle to a new type by pairwise argument and return type conversion. 4822 * The original type and new type must have the same number of arguments. 4823 * The resulting method handle is guaranteed to report a type 4824 * which is equal to the desired new type. 4825 * <p> 4826 * If the original type and new type are equal, returns target. 4827 * <p> 4828 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4829 * and some additional conversions are also applied if those conversions fail. 4830 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4831 * if possible, before or instead of any conversions done by {@code asType}: 4832 * <ul> 4833 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4834 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4835 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4836 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4837 * the boolean is converted to a byte value, 1 for true, 0 for false. 4838 * (This treatment follows the usage of the bytecode verifier.) 4839 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4840 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4841 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4842 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4843 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4844 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4845 * widening and/or narrowing.) 4846 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4847 * conversion will be applied at runtime, possibly followed 4848 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4849 * possibly followed by a conversion from byte to boolean by testing 4850 * the low-order bit. 4851 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4852 * and if the reference is null at runtime, a zero value is introduced. 4853 * </ul> 4854 * @param target the method handle to invoke after arguments are retyped 4855 * @param newType the expected type of the new method handle 4856 * @return a method handle which delegates to the target after performing 4857 * any necessary argument conversions, and arranges for any 4858 * necessary return value conversions 4859 * @throws NullPointerException if either argument is null 4860 * @throws WrongMethodTypeException if the conversion cannot be made 4861 * @see MethodHandle#asType 4862 */ 4863 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4864 explicitCastArgumentsChecks(target, newType); 4865 // use the asTypeCache when possible: 4866 MethodType oldType = target.type(); 4867 if (oldType == newType) return target; 4868 if (oldType.explicitCastEquivalentToAsType(newType)) { 4869 return target.asFixedArity().asType(newType); 4870 } 4871 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4872 } 4873 4874 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4875 if (target.type().parameterCount() != newType.parameterCount()) { 4876 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4877 } 4878 } 4879 4880 /** 4881 * Produces a method handle which adapts the calling sequence of the 4882 * given method handle to a new type, by reordering the arguments. 4883 * The resulting method handle is guaranteed to report a type 4884 * which is equal to the desired new type. 4885 * <p> 4886 * The given array controls the reordering. 4887 * Call {@code #I} the number of incoming parameters (the value 4888 * {@code newType.parameterCount()}, and call {@code #O} the number 4889 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4890 * Then the length of the reordering array must be {@code #O}, 4891 * and each element must be a non-negative number less than {@code #I}. 4892 * For every {@code N} less than {@code #O}, the {@code N}-th 4893 * outgoing argument will be taken from the {@code I}-th incoming 4894 * argument, where {@code I} is {@code reorder[N]}. 4895 * <p> 4896 * No argument or return value conversions are applied. 4897 * The type of each incoming argument, as determined by {@code newType}, 4898 * must be identical to the type of the corresponding outgoing parameter 4899 * or parameters in the target method handle. 4900 * The return type of {@code newType} must be identical to the return 4901 * type of the original target. 4902 * <p> 4903 * The reordering array need not specify an actual permutation. 4904 * An incoming argument will be duplicated if its index appears 4905 * more than once in the array, and an incoming argument will be dropped 4906 * if its index does not appear in the array. 4907 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4908 * incoming arguments which are not mentioned in the reordering array 4909 * may be of any type, as determined only by {@code newType}. 4910 * {@snippet lang="java" : 4911 import static java.lang.invoke.MethodHandles.*; 4912 import static java.lang.invoke.MethodType.*; 4913 ... 4914 MethodType intfn1 = methodType(int.class, int.class); 4915 MethodType intfn2 = methodType(int.class, int.class, int.class); 4916 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4917 assert(sub.type().equals(intfn2)); 4918 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4919 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4920 assert((int)rsub.invokeExact(1, 100) == 99); 4921 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4922 assert(add.type().equals(intfn2)); 4923 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4924 assert(twice.type().equals(intfn1)); 4925 assert((int)twice.invokeExact(21) == 42); 4926 * } 4927 * <p> 4928 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4929 * variable-arity method handle}, even if the original target method handle was. 4930 * @param target the method handle to invoke after arguments are reordered 4931 * @param newType the expected type of the new method handle 4932 * @param reorder an index array which controls the reordering 4933 * @return a method handle which delegates to the target after it 4934 * drops unused arguments and moves and/or duplicates the other arguments 4935 * @throws NullPointerException if any argument is null 4936 * @throws IllegalArgumentException if the index array length is not equal to 4937 * the arity of the target, or if any index array element 4938 * not a valid index for a parameter of {@code newType}, 4939 * or if two corresponding parameter types in 4940 * {@code target.type()} and {@code newType} are not identical, 4941 */ 4942 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4943 reorder = reorder.clone(); // get a private copy 4944 MethodType oldType = target.type(); 4945 permuteArgumentChecks(reorder, newType, oldType); 4946 // first detect dropped arguments and handle them separately 4947 int[] originalReorder = reorder; 4948 BoundMethodHandle result = target.rebind(); 4949 LambdaForm form = result.form; 4950 int newArity = newType.parameterCount(); 4951 // Normalize the reordering into a real permutation, 4952 // by removing duplicates and adding dropped elements. 4953 // This somewhat improves lambda form caching, as well 4954 // as simplifying the transform by breaking it up into steps. 4955 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4956 if (ddIdx > 0) { 4957 // We found a duplicated entry at reorder[ddIdx]. 4958 // Example: (x,y,z)->asList(x,y,z) 4959 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4960 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4961 // The starred element corresponds to the argument 4962 // deleted by the dupArgumentForm transform. 4963 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4964 boolean killFirst = false; 4965 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4966 // Set killFirst if the dup is larger than an intervening position. 4967 // This will remove at least one inversion from the permutation. 4968 if (dupVal > val) killFirst = true; 4969 } 4970 if (!killFirst) { 4971 srcPos = dstPos; 4972 dstPos = ddIdx; 4973 } 4974 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4975 assert (reorder[srcPos] == reorder[dstPos]); 4976 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4977 // contract the reordering by removing the element at dstPos 4978 int tailPos = dstPos + 1; 4979 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4980 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4981 } else { 4982 int dropVal = ~ddIdx, insPos = 0; 4983 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4984 // Find first element of reorder larger than dropVal. 4985 // This is where we will insert the dropVal. 4986 insPos += 1; 4987 } 4988 Class<?> ptype = newType.parameterType(dropVal); 4989 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4990 oldType = oldType.insertParameterTypes(insPos, ptype); 4991 // expand the reordering by inserting an element at insPos 4992 int tailPos = insPos + 1; 4993 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4994 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4995 reorder[insPos] = dropVal; 4996 } 4997 assert (permuteArgumentChecks(reorder, newType, oldType)); 4998 } 4999 assert (reorder.length == newArity); // a perfect permutation 5000 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 5001 form = form.editor().permuteArgumentsForm(1, reorder); 5002 if (newType == result.type() && form == result.internalForm()) 5003 return result; 5004 return result.copyWith(newType, form); 5005 } 5006 5007 /** 5008 * Return an indication of any duplicate or omission in reorder. 5009 * If the reorder contains a duplicate entry, return the index of the second occurrence. 5010 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 5011 * Otherwise, return zero. 5012 * If an element not in [0..newArity-1] is encountered, return reorder.length. 5013 */ 5014 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 5015 final int BIT_LIMIT = 63; // max number of bits in bit mask 5016 if (newArity < BIT_LIMIT) { 5017 long mask = 0; 5018 for (int i = 0; i < reorder.length; i++) { 5019 int arg = reorder[i]; 5020 if (arg >= newArity) { 5021 return reorder.length; 5022 } 5023 long bit = 1L << arg; 5024 if ((mask & bit) != 0) { 5025 return i; // >0 indicates a dup 5026 } 5027 mask |= bit; 5028 } 5029 if (mask == (1L << newArity) - 1) { 5030 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 5031 return 0; 5032 } 5033 // find first zero 5034 long zeroBit = Long.lowestOneBit(~mask); 5035 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 5036 assert(zeroPos <= newArity); 5037 if (zeroPos == newArity) { 5038 return 0; 5039 } 5040 return ~zeroPos; 5041 } else { 5042 // same algorithm, different bit set 5043 BitSet mask = new BitSet(newArity); 5044 for (int i = 0; i < reorder.length; i++) { 5045 int arg = reorder[i]; 5046 if (arg >= newArity) { 5047 return reorder.length; 5048 } 5049 if (mask.get(arg)) { 5050 return i; // >0 indicates a dup 5051 } 5052 mask.set(arg); 5053 } 5054 int zeroPos = mask.nextClearBit(0); 5055 assert(zeroPos <= newArity); 5056 if (zeroPos == newArity) { 5057 return 0; 5058 } 5059 return ~zeroPos; 5060 } 5061 } 5062 5063 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 5064 if (newType.returnType() != oldType.returnType()) 5065 throw newIllegalArgumentException("return types do not match", 5066 oldType, newType); 5067 if (reorder.length != oldType.parameterCount()) 5068 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 5069 oldType, Arrays.toString(reorder)); 5070 5071 int limit = newType.parameterCount(); 5072 for (int j = 0; j < reorder.length; j++) { 5073 int i = reorder[j]; 5074 if (i < 0 || i >= limit) { 5075 throw newIllegalArgumentException("index is out of bounds for new type", 5076 i, newType); 5077 } 5078 Class<?> src = newType.parameterType(i); 5079 Class<?> dst = oldType.parameterType(j); 5080 if (src != dst) 5081 throw newIllegalArgumentException("parameter types do not match after reorder", 5082 oldType, newType); 5083 } 5084 return true; 5085 } 5086 5087 /** 5088 * Produces a method handle of the requested return type which returns the given 5089 * constant value every time it is invoked. 5090 * <p> 5091 * Before the method handle is returned, the passed-in value is converted to the requested type. 5092 * If the requested type is primitive, widening primitive conversions are attempted, 5093 * else reference conversions are attempted. 5094 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5095 * @param type the return type of the desired method handle 5096 * @param value the value to return 5097 * @return a method handle of the given return type and no arguments, which always returns the given value 5098 * @throws NullPointerException if the {@code type} argument is null 5099 * @throws ClassCastException if the value cannot be converted to the required return type 5100 * @throws IllegalArgumentException if the given type is {@code void.class} 5101 */ 5102 public static MethodHandle constant(Class<?> type, Object value) { 5103 if (type.isPrimitive()) { 5104 if (type == void.class) 5105 throw newIllegalArgumentException("void type"); 5106 Wrapper w = Wrapper.forPrimitiveType(type); 5107 value = w.convert(value, type); 5108 if (w.zero().equals(value)) 5109 return zero(w, type); 5110 return insertArguments(identity(type), 0, value); 5111 } else { 5112 if (value == null) 5113 return zero(Wrapper.OBJECT, type); 5114 return identity(type).bindTo(value); 5115 } 5116 } 5117 5118 /** 5119 * Produces a method handle which returns its sole argument when invoked. 5120 * @param type the type of the sole parameter and return value of the desired method handle 5121 * @return a unary method handle which accepts and returns the given type 5122 * @throws NullPointerException if the argument is null 5123 * @throws IllegalArgumentException if the given type is {@code void.class} 5124 */ 5125 public static MethodHandle identity(Class<?> type) { 5126 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5127 int pos = btw.ordinal(); 5128 MethodHandle ident = IDENTITY_MHS[pos]; 5129 if (ident == null) { 5130 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5131 } 5132 if (ident.type().returnType() == type) 5133 return ident; 5134 // something like identity(Foo.class); do not bother to intern these 5135 assert (btw == Wrapper.OBJECT); 5136 return makeIdentity(type); 5137 } 5138 5139 /** 5140 * Produces a constant method handle of the requested return type which 5141 * returns the default value for that type every time it is invoked. 5142 * The resulting constant method handle will have no side effects. 5143 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5144 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5145 * since {@code explicitCastArguments} converts {@code null} to default values. 5146 * @param type the expected return type of the desired method handle 5147 * @return a constant method handle that takes no arguments 5148 * and returns the default value of the given type (or void, if the type is void) 5149 * @throws NullPointerException if the argument is null 5150 * @see MethodHandles#constant 5151 * @see MethodHandles#empty 5152 * @see MethodHandles#explicitCastArguments 5153 * @since 9 5154 */ 5155 public static MethodHandle zero(Class<?> type) { 5156 Objects.requireNonNull(type); 5157 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5158 } 5159 5160 private static MethodHandle identityOrVoid(Class<?> type) { 5161 return type == void.class ? zero(type) : identity(type); 5162 } 5163 5164 /** 5165 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5166 * and returns a suitable default depending on the return type. 5167 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5168 * <p>The returned method handle is equivalent to 5169 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5170 * 5171 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5172 * {@code guardWithTest(pred, target, empty(target.type())}. 5173 * @param type the type of the desired method handle 5174 * @return a constant method handle of the given type, which returns a default value of the given return type 5175 * @throws NullPointerException if the argument is null 5176 * @see MethodHandles#zero 5177 * @see MethodHandles#constant 5178 * @since 9 5179 */ 5180 public static MethodHandle empty(MethodType type) { 5181 Objects.requireNonNull(type); 5182 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5183 } 5184 5185 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5186 private static MethodHandle makeIdentity(Class<?> ptype) { 5187 MethodType mtype = methodType(ptype, ptype); 5188 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5189 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5190 } 5191 5192 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5193 int pos = btw.ordinal(); 5194 MethodHandle zero = ZERO_MHS[pos]; 5195 if (zero == null) { 5196 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5197 } 5198 if (zero.type().returnType() == rtype) 5199 return zero; 5200 assert(btw == Wrapper.OBJECT); 5201 return makeZero(rtype); 5202 } 5203 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5204 private static MethodHandle makeZero(Class<?> rtype) { 5205 MethodType mtype = methodType(rtype); 5206 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5207 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5208 } 5209 5210 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5211 // Simulate a CAS, to avoid racy duplication of results. 5212 MethodHandle prev = cache[pos]; 5213 if (prev != null) return prev; 5214 return cache[pos] = value; 5215 } 5216 5217 /** 5218 * Provides a target method handle with one or more <em>bound arguments</em> 5219 * in advance of the method handle's invocation. 5220 * The formal parameters to the target corresponding to the bound 5221 * arguments are called <em>bound parameters</em>. 5222 * Returns a new method handle which saves away the bound arguments. 5223 * When it is invoked, it receives arguments for any non-bound parameters, 5224 * binds the saved arguments to their corresponding parameters, 5225 * and calls the original target. 5226 * <p> 5227 * The type of the new method handle will drop the types for the bound 5228 * parameters from the original target type, since the new method handle 5229 * will no longer require those arguments to be supplied by its callers. 5230 * <p> 5231 * Each given argument object must match the corresponding bound parameter type. 5232 * If a bound parameter type is a primitive, the argument object 5233 * must be a wrapper, and will be unboxed to produce the primitive value. 5234 * <p> 5235 * The {@code pos} argument selects which parameters are to be bound. 5236 * It may range between zero and <i>N-L</i> (inclusively), 5237 * where <i>N</i> is the arity of the target method handle 5238 * and <i>L</i> is the length of the values array. 5239 * <p> 5240 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5241 * variable-arity method handle}, even if the original target method handle was. 5242 * @param target the method handle to invoke after the argument is inserted 5243 * @param pos where to insert the argument (zero for the first) 5244 * @param values the series of arguments to insert 5245 * @return a method handle which inserts an additional argument, 5246 * before calling the original method handle 5247 * @throws NullPointerException if the target or the {@code values} array is null 5248 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 5249 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5250 * is the length of the values array. 5251 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5252 * type. 5253 * @see MethodHandle#bindTo 5254 */ 5255 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5256 int insCount = values.length; 5257 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5258 if (insCount == 0) return target; 5259 BoundMethodHandle result = target.rebind(); 5260 for (int i = 0; i < insCount; i++) { 5261 Object value = values[i]; 5262 Class<?> ptype = ptypes[pos+i]; 5263 if (ptype.isPrimitive()) { 5264 result = insertArgumentPrimitive(result, pos, ptype, value); 5265 } else { 5266 value = ptype.cast(value); // throw CCE if needed 5267 result = result.bindArgumentL(pos, value); 5268 } 5269 } 5270 return result; 5271 } 5272 5273 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5274 Class<?> ptype, Object value) { 5275 Wrapper w = Wrapper.forPrimitiveType(ptype); 5276 // perform unboxing and/or primitive conversion 5277 value = w.convert(value, ptype); 5278 return switch (w) { 5279 case INT -> result.bindArgumentI(pos, (int) value); 5280 case LONG -> result.bindArgumentJ(pos, (long) value); 5281 case FLOAT -> result.bindArgumentF(pos, (float) value); 5282 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5283 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5284 }; 5285 } 5286 5287 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5288 MethodType oldType = target.type(); 5289 int outargs = oldType.parameterCount(); 5290 int inargs = outargs - insCount; 5291 if (inargs < 0) 5292 throw newIllegalArgumentException("too many values to insert"); 5293 if (pos < 0 || pos > inargs) 5294 throw newIllegalArgumentException("no argument type to append"); 5295 return oldType.ptypes(); 5296 } 5297 5298 /** 5299 * Produces a method handle which will discard some dummy arguments 5300 * before calling some other specified <i>target</i> method handle. 5301 * The type of the new method handle will be the same as the target's type, 5302 * except it will also include the dummy argument types, 5303 * at some given position. 5304 * <p> 5305 * The {@code pos} argument may range between zero and <i>N</i>, 5306 * where <i>N</i> is the arity of the target. 5307 * If {@code pos} is zero, the dummy arguments will precede 5308 * the target's real arguments; if {@code pos} is <i>N</i> 5309 * they will come after. 5310 * <p> 5311 * <b>Example:</b> 5312 * {@snippet lang="java" : 5313 import static java.lang.invoke.MethodHandles.*; 5314 import static java.lang.invoke.MethodType.*; 5315 ... 5316 MethodHandle cat = lookup().findVirtual(String.class, 5317 "concat", methodType(String.class, String.class)); 5318 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5319 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5320 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5321 assertEquals(bigType, d0.type()); 5322 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5323 * } 5324 * <p> 5325 * This method is also equivalent to the following code: 5326 * <blockquote><pre> 5327 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5328 * </pre></blockquote> 5329 * @param target the method handle to invoke after the arguments are dropped 5330 * @param pos position of first argument to drop (zero for the leftmost) 5331 * @param valueTypes the type(s) of the argument(s) to drop 5332 * @return a method handle which drops arguments of the given types, 5333 * before calling the original method handle 5334 * @throws NullPointerException if the target is null, 5335 * or if the {@code valueTypes} list or any of its elements is null 5336 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5337 * or if {@code pos} is negative or greater than the arity of the target, 5338 * or if the new method handle's type would have too many parameters 5339 */ 5340 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5341 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5342 } 5343 5344 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5345 MethodType oldType = target.type(); // get NPE 5346 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5347 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5348 if (dropped == 0) return target; 5349 BoundMethodHandle result = target.rebind(); 5350 LambdaForm lform = result.form; 5351 int insertFormArg = 1 + pos; 5352 for (Class<?> ptype : valueTypes) { 5353 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5354 } 5355 result = result.copyWith(newType, lform); 5356 return result; 5357 } 5358 5359 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5360 int dropped = valueTypes.length; 5361 MethodType.checkSlotCount(dropped); 5362 int outargs = oldType.parameterCount(); 5363 int inargs = outargs + dropped; 5364 if (pos < 0 || pos > outargs) 5365 throw newIllegalArgumentException("no argument type to remove" 5366 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5367 ); 5368 return dropped; 5369 } 5370 5371 /** 5372 * Produces a method handle which will discard some dummy arguments 5373 * before calling some other specified <i>target</i> method handle. 5374 * The type of the new method handle will be the same as the target's type, 5375 * except it will also include the dummy argument types, 5376 * at some given position. 5377 * <p> 5378 * The {@code pos} argument may range between zero and <i>N</i>, 5379 * where <i>N</i> is the arity of the target. 5380 * If {@code pos} is zero, the dummy arguments will precede 5381 * the target's real arguments; if {@code pos} is <i>N</i> 5382 * they will come after. 5383 * @apiNote 5384 * {@snippet lang="java" : 5385 import static java.lang.invoke.MethodHandles.*; 5386 import static java.lang.invoke.MethodType.*; 5387 ... 5388 MethodHandle cat = lookup().findVirtual(String.class, 5389 "concat", methodType(String.class, String.class)); 5390 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5391 MethodHandle d0 = dropArguments(cat, 0, String.class); 5392 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5393 MethodHandle d1 = dropArguments(cat, 1, String.class); 5394 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5395 MethodHandle d2 = dropArguments(cat, 2, String.class); 5396 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5397 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5398 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5399 * } 5400 * <p> 5401 * This method is also equivalent to the following code: 5402 * <blockquote><pre> 5403 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5404 * </pre></blockquote> 5405 * @param target the method handle to invoke after the arguments are dropped 5406 * @param pos position of first argument to drop (zero for the leftmost) 5407 * @param valueTypes the type(s) of the argument(s) to drop 5408 * @return a method handle which drops arguments of the given types, 5409 * before calling the original method handle 5410 * @throws NullPointerException if the target is null, 5411 * or if the {@code valueTypes} array or any of its elements is null 5412 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5413 * or if {@code pos} is negative or greater than the arity of the target, 5414 * or if the new method handle's type would have 5415 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5416 */ 5417 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5418 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5419 } 5420 5421 /* Convenience overloads for trusting internal low-arity call-sites */ 5422 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5423 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5424 } 5425 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5426 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5427 } 5428 5429 // private version which allows caller some freedom with error handling 5430 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5431 boolean nullOnFailure) { 5432 Class<?>[] oldTypes = target.type().ptypes(); 5433 int match = oldTypes.length; 5434 if (skip != 0) { 5435 if (skip < 0 || skip > match) { 5436 throw newIllegalArgumentException("illegal skip", skip, target); 5437 } 5438 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5439 match -= skip; 5440 } 5441 Class<?>[] addTypes = newTypes; 5442 int add = addTypes.length; 5443 if (pos != 0) { 5444 if (pos < 0 || pos > add) { 5445 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5446 } 5447 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5448 add -= pos; 5449 assert(addTypes.length == add); 5450 } 5451 // Do not add types which already match the existing arguments. 5452 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5453 if (nullOnFailure) { 5454 return null; 5455 } 5456 throw newIllegalArgumentException("argument lists do not match", 5457 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5458 } 5459 addTypes = Arrays.copyOfRange(addTypes, match, add); 5460 add -= match; 5461 assert(addTypes.length == add); 5462 // newTypes: ( P*[pos], M*[match], A*[add] ) 5463 // target: ( S*[skip], M*[match] ) 5464 MethodHandle adapter = target; 5465 if (add > 0) { 5466 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5467 } 5468 // adapter: (S*[skip], M*[match], A*[add] ) 5469 if (pos > 0) { 5470 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5471 } 5472 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5473 return adapter; 5474 } 5475 5476 /** 5477 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5478 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5479 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5480 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5481 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5482 * {@link #dropArguments(MethodHandle, int, Class[])}. 5483 * <p> 5484 * The resulting handle will have the same return type as the target handle. 5485 * <p> 5486 * In more formal terms, assume these two type lists:<ul> 5487 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5488 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5489 * {@code newTypes}. 5490 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5491 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5492 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5493 * sub-list. 5494 * </ul> 5495 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5496 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5497 * {@link #dropArguments(MethodHandle, int, Class[])}. 5498 * 5499 * @apiNote 5500 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5501 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5502 * {@snippet lang="java" : 5503 import static java.lang.invoke.MethodHandles.*; 5504 import static java.lang.invoke.MethodType.*; 5505 ... 5506 ... 5507 MethodHandle h0 = constant(boolean.class, true); 5508 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5509 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5510 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5511 if (h1.type().parameterCount() < h2.type().parameterCount()) 5512 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5513 else 5514 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5515 MethodHandle h3 = guardWithTest(h0, h1, h2); 5516 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5517 * } 5518 * @param target the method handle to adapt 5519 * @param skip number of targets parameters to disregard (they will be unchanged) 5520 * @param newTypes the list of types to match {@code target}'s parameter type list to 5521 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5522 * @return a possibly adapted method handle 5523 * @throws NullPointerException if either argument is null 5524 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5525 * or if {@code skip} is negative or greater than the arity of the target, 5526 * or if {@code pos} is negative or greater than the newTypes list size, 5527 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5528 * {@code pos}. 5529 * @since 9 5530 */ 5531 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5532 Objects.requireNonNull(target); 5533 Objects.requireNonNull(newTypes); 5534 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5535 } 5536 5537 /** 5538 * Drop the return value of the target handle (if any). 5539 * The returned method handle will have a {@code void} return type. 5540 * 5541 * @param target the method handle to adapt 5542 * @return a possibly adapted method handle 5543 * @throws NullPointerException if {@code target} is null 5544 * @since 16 5545 */ 5546 public static MethodHandle dropReturn(MethodHandle target) { 5547 Objects.requireNonNull(target); 5548 MethodType oldType = target.type(); 5549 Class<?> oldReturnType = oldType.returnType(); 5550 if (oldReturnType == void.class) 5551 return target; 5552 MethodType newType = oldType.changeReturnType(void.class); 5553 BoundMethodHandle result = target.rebind(); 5554 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5555 result = result.copyWith(newType, lform); 5556 return result; 5557 } 5558 5559 /** 5560 * Adapts a target method handle by pre-processing 5561 * one or more of its arguments, each with its own unary filter function, 5562 * and then calling the target with each pre-processed argument 5563 * replaced by the result of its corresponding filter function. 5564 * <p> 5565 * The pre-processing is performed by one or more method handles, 5566 * specified in the elements of the {@code filters} array. 5567 * The first element of the filter array corresponds to the {@code pos} 5568 * argument of the target, and so on in sequence. 5569 * The filter functions are invoked in left to right order. 5570 * <p> 5571 * Null arguments in the array are treated as identity functions, 5572 * and the corresponding arguments left unchanged. 5573 * (If there are no non-null elements in the array, the original target is returned.) 5574 * Each filter is applied to the corresponding argument of the adapter. 5575 * <p> 5576 * If a filter {@code F} applies to the {@code N}th argument of 5577 * the target, then {@code F} must be a method handle which 5578 * takes exactly one argument. The type of {@code F}'s sole argument 5579 * replaces the corresponding argument type of the target 5580 * in the resulting adapted method handle. 5581 * The return type of {@code F} must be identical to the corresponding 5582 * parameter type of the target. 5583 * <p> 5584 * It is an error if there are elements of {@code filters} 5585 * (null or not) 5586 * which do not correspond to argument positions in the target. 5587 * <p><b>Example:</b> 5588 * {@snippet lang="java" : 5589 import static java.lang.invoke.MethodHandles.*; 5590 import static java.lang.invoke.MethodType.*; 5591 ... 5592 MethodHandle cat = lookup().findVirtual(String.class, 5593 "concat", methodType(String.class, String.class)); 5594 MethodHandle upcase = lookup().findVirtual(String.class, 5595 "toUpperCase", methodType(String.class)); 5596 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5597 MethodHandle f0 = filterArguments(cat, 0, upcase); 5598 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5599 MethodHandle f1 = filterArguments(cat, 1, upcase); 5600 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5601 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5602 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5603 * } 5604 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5605 * denotes the return type of both the {@code target} and resulting adapter. 5606 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5607 * of the parameters and arguments that precede and follow the filter position 5608 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5609 * values of the filtered parameters and arguments; they also represent the 5610 * return types of the {@code filter[i]} handles. The latter accept arguments 5611 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5612 * the resulting adapter. 5613 * {@snippet lang="java" : 5614 * T target(P... p, A[i]... a[i], B... b); 5615 * A[i] filter[i](V[i]); 5616 * T adapter(P... p, V[i]... v[i], B... b) { 5617 * return target(p..., filter[i](v[i])..., b...); 5618 * } 5619 * } 5620 * <p> 5621 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5622 * variable-arity method handle}, even if the original target method handle was. 5623 * 5624 * @param target the method handle to invoke after arguments are filtered 5625 * @param pos the position of the first argument to filter 5626 * @param filters method handles to call initially on filtered arguments 5627 * @return method handle which incorporates the specified argument filtering logic 5628 * @throws NullPointerException if the target is null 5629 * or if the {@code filters} array is null 5630 * @throws IllegalArgumentException if a non-null element of {@code filters} 5631 * does not match a corresponding argument type of target as described above, 5632 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5633 * or if the resulting method handle's type would have 5634 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5635 */ 5636 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5637 // In method types arguments start at index 0, while the LF 5638 // editor have the MH receiver at position 0 - adjust appropriately. 5639 final int MH_RECEIVER_OFFSET = 1; 5640 filterArgumentsCheckArity(target, pos, filters); 5641 MethodHandle adapter = target; 5642 5643 // keep track of currently matched filters, as to optimize repeated filters 5644 int index = 0; 5645 int[] positions = new int[filters.length]; 5646 MethodHandle filter = null; 5647 5648 // process filters in reverse order so that the invocation of 5649 // the resulting adapter will invoke the filters in left-to-right order 5650 for (int i = filters.length - 1; i >= 0; --i) { 5651 MethodHandle newFilter = filters[i]; 5652 if (newFilter == null) continue; // ignore null elements of filters 5653 5654 // flush changes on update 5655 if (filter != newFilter) { 5656 if (filter != null) { 5657 if (index > 1) { 5658 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5659 } else { 5660 adapter = filterArgument(adapter, positions[0] - 1, filter); 5661 } 5662 } 5663 filter = newFilter; 5664 index = 0; 5665 } 5666 5667 filterArgumentChecks(target, pos + i, newFilter); 5668 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5669 } 5670 if (index > 1) { 5671 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5672 } else if (index == 1) { 5673 adapter = filterArgument(adapter, positions[0] - 1, filter); 5674 } 5675 return adapter; 5676 } 5677 5678 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5679 MethodType targetType = adapter.type(); 5680 MethodType filterType = filter.type(); 5681 BoundMethodHandle result = adapter.rebind(); 5682 Class<?> newParamType = filterType.parameterType(0); 5683 5684 Class<?>[] ptypes = targetType.ptypes().clone(); 5685 for (int pos : positions) { 5686 ptypes[pos - 1] = newParamType; 5687 } 5688 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5689 5690 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5691 return result.copyWithExtendL(newType, lform, filter); 5692 } 5693 5694 /*non-public*/ 5695 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5696 filterArgumentChecks(target, pos, filter); 5697 MethodType targetType = target.type(); 5698 MethodType filterType = filter.type(); 5699 BoundMethodHandle result = target.rebind(); 5700 Class<?> newParamType = filterType.parameterType(0); 5701 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5702 MethodType newType = targetType.changeParameterType(pos, newParamType); 5703 result = result.copyWithExtendL(newType, lform, filter); 5704 return result; 5705 } 5706 5707 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5708 MethodType targetType = target.type(); 5709 int maxPos = targetType.parameterCount(); 5710 if (pos + filters.length > maxPos) 5711 throw newIllegalArgumentException("too many filters"); 5712 } 5713 5714 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5715 MethodType targetType = target.type(); 5716 MethodType filterType = filter.type(); 5717 if (filterType.parameterCount() != 1 5718 || filterType.returnType() != targetType.parameterType(pos)) 5719 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5720 } 5721 5722 /** 5723 * Adapts a target method handle by pre-processing 5724 * a sub-sequence of its arguments with a filter (another method handle). 5725 * The pre-processed arguments are replaced by the result (if any) of the 5726 * filter function. 5727 * The target is then called on the modified (usually shortened) argument list. 5728 * <p> 5729 * If the filter returns a value, the target must accept that value as 5730 * its argument in position {@code pos}, preceded and/or followed by 5731 * any arguments not passed to the filter. 5732 * If the filter returns void, the target must accept all arguments 5733 * not passed to the filter. 5734 * No arguments are reordered, and a result returned from the filter 5735 * replaces (in order) the whole subsequence of arguments originally 5736 * passed to the adapter. 5737 * <p> 5738 * The argument types (if any) of the filter 5739 * replace zero or one argument types of the target, at position {@code pos}, 5740 * in the resulting adapted method handle. 5741 * The return type of the filter (if any) must be identical to the 5742 * argument type of the target at position {@code pos}, and that target argument 5743 * is supplied by the return value of the filter. 5744 * <p> 5745 * In all cases, {@code pos} must be greater than or equal to zero, and 5746 * {@code pos} must also be less than or equal to the target's arity. 5747 * <p><b>Example:</b> 5748 * {@snippet lang="java" : 5749 import static java.lang.invoke.MethodHandles.*; 5750 import static java.lang.invoke.MethodType.*; 5751 ... 5752 MethodHandle deepToString = publicLookup() 5753 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5754 5755 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5756 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5757 5758 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5759 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5760 5761 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5762 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5763 assertEquals("[top, [up, down], strange]", 5764 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5765 5766 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5767 assertEquals("[top, [up, down], [strange]]", 5768 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5769 5770 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5771 assertEquals("[top, [[up, down, strange], charm], bottom]", 5772 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5773 * } 5774 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5775 * represents the return type of the {@code target} and resulting adapter. 5776 * {@code V}/{@code v} stand for the return type and value of the 5777 * {@code filter}, which are also found in the signature and arguments of 5778 * the {@code target}, respectively, unless {@code V} is {@code void}. 5779 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5780 * and values preceding and following the collection position, {@code pos}, 5781 * in the {@code target}'s signature. They also turn up in the resulting 5782 * adapter's signature and arguments, where they surround 5783 * {@code B}/{@code b}, which represent the parameter types and arguments 5784 * to the {@code filter} (if any). 5785 * {@snippet lang="java" : 5786 * T target(A...,V,C...); 5787 * V filter(B...); 5788 * T adapter(A... a,B... b,C... c) { 5789 * V v = filter(b...); 5790 * return target(a...,v,c...); 5791 * } 5792 * // and if the filter has no arguments: 5793 * T target2(A...,V,C...); 5794 * V filter2(); 5795 * T adapter2(A... a,C... c) { 5796 * V v = filter2(); 5797 * return target2(a...,v,c...); 5798 * } 5799 * // and if the filter has a void return: 5800 * T target3(A...,C...); 5801 * void filter3(B...); 5802 * T adapter3(A... a,B... b,C... c) { 5803 * filter3(b...); 5804 * return target3(a...,c...); 5805 * } 5806 * } 5807 * <p> 5808 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5809 * one which first "folds" the affected arguments, and then drops them, in separate 5810 * steps as follows: 5811 * {@snippet lang="java" : 5812 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5813 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5814 * } 5815 * If the target method handle consumes no arguments besides than the result 5816 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5817 * is equivalent to {@code filterReturnValue(coll, mh)}. 5818 * If the filter method handle {@code coll} consumes one argument and produces 5819 * a non-void result, then {@code collectArguments(mh, N, coll)} 5820 * is equivalent to {@code filterArguments(mh, N, coll)}. 5821 * Other equivalences are possible but would require argument permutation. 5822 * <p> 5823 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5824 * variable-arity method handle}, even if the original target method handle was. 5825 * 5826 * @param target the method handle to invoke after filtering the subsequence of arguments 5827 * @param pos the position of the first adapter argument to pass to the filter, 5828 * and/or the target argument which receives the result of the filter 5829 * @param filter method handle to call on the subsequence of arguments 5830 * @return method handle which incorporates the specified argument subsequence filtering logic 5831 * @throws NullPointerException if either argument is null 5832 * @throws IllegalArgumentException if the return type of {@code filter} 5833 * is non-void and is not the same as the {@code pos} argument of the target, 5834 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5835 * or if the resulting method handle's type would have 5836 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5837 * @see MethodHandles#foldArguments 5838 * @see MethodHandles#filterArguments 5839 * @see MethodHandles#filterReturnValue 5840 */ 5841 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5842 MethodType newType = collectArgumentsChecks(target, pos, filter); 5843 MethodType collectorType = filter.type(); 5844 BoundMethodHandle result = target.rebind(); 5845 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5846 return result.copyWithExtendL(newType, lform, filter); 5847 } 5848 5849 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5850 MethodType targetType = target.type(); 5851 MethodType filterType = filter.type(); 5852 Class<?> rtype = filterType.returnType(); 5853 Class<?>[] filterArgs = filterType.ptypes(); 5854 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5855 (rtype != void.class && pos >= targetType.parameterCount())) { 5856 throw newIllegalArgumentException("position is out of range for target", target, pos); 5857 } 5858 if (rtype == void.class) { 5859 return targetType.insertParameterTypes(pos, filterArgs); 5860 } 5861 if (rtype != targetType.parameterType(pos)) { 5862 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5863 } 5864 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5865 } 5866 5867 /** 5868 * Adapts a target method handle by post-processing 5869 * its return value (if any) with a filter (another method handle). 5870 * The result of the filter is returned from the adapter. 5871 * <p> 5872 * If the target returns a value, the filter must accept that value as 5873 * its only argument. 5874 * If the target returns void, the filter must accept no arguments. 5875 * <p> 5876 * The return type of the filter 5877 * replaces the return type of the target 5878 * in the resulting adapted method handle. 5879 * The argument type of the filter (if any) must be identical to the 5880 * return type of the target. 5881 * <p><b>Example:</b> 5882 * {@snippet lang="java" : 5883 import static java.lang.invoke.MethodHandles.*; 5884 import static java.lang.invoke.MethodType.*; 5885 ... 5886 MethodHandle cat = lookup().findVirtual(String.class, 5887 "concat", methodType(String.class, String.class)); 5888 MethodHandle length = lookup().findVirtual(String.class, 5889 "length", methodType(int.class)); 5890 System.out.println((String) cat.invokeExact("x", "y")); // xy 5891 MethodHandle f0 = filterReturnValue(cat, length); 5892 System.out.println((int) f0.invokeExact("x", "y")); // 2 5893 * } 5894 * <p>Here is pseudocode for the resulting adapter. In the code, 5895 * {@code T}/{@code t} represent the result type and value of the 5896 * {@code target}; {@code V}, the result type of the {@code filter}; and 5897 * {@code A}/{@code a}, the types and values of the parameters and arguments 5898 * of the {@code target} as well as the resulting adapter. 5899 * {@snippet lang="java" : 5900 * T target(A...); 5901 * V filter(T); 5902 * V adapter(A... a) { 5903 * T t = target(a...); 5904 * return filter(t); 5905 * } 5906 * // and if the target has a void return: 5907 * void target2(A...); 5908 * V filter2(); 5909 * V adapter2(A... a) { 5910 * target2(a...); 5911 * return filter2(); 5912 * } 5913 * // and if the filter has a void return: 5914 * T target3(A...); 5915 * void filter3(V); 5916 * void adapter3(A... a) { 5917 * T t = target3(a...); 5918 * filter3(t); 5919 * } 5920 * } 5921 * <p> 5922 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5923 * variable-arity method handle}, even if the original target method handle was. 5924 * @param target the method handle to invoke before filtering the return value 5925 * @param filter method handle to call on the return value 5926 * @return method handle which incorporates the specified return value filtering logic 5927 * @throws NullPointerException if either argument is null 5928 * @throws IllegalArgumentException if the argument list of {@code filter} 5929 * does not match the return type of target as described above 5930 */ 5931 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5932 MethodType targetType = target.type(); 5933 MethodType filterType = filter.type(); 5934 filterReturnValueChecks(targetType, filterType); 5935 BoundMethodHandle result = target.rebind(); 5936 BasicType rtype = BasicType.basicType(filterType.returnType()); 5937 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5938 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5939 result = result.copyWithExtendL(newType, lform, filter); 5940 return result; 5941 } 5942 5943 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5944 Class<?> rtype = targetType.returnType(); 5945 int filterValues = filterType.parameterCount(); 5946 if (filterValues == 0 5947 ? (rtype != void.class) 5948 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5949 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5950 } 5951 5952 /** 5953 * Filter the return value of a target method handle with a filter function. The filter function is 5954 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5955 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5956 * as follows: 5957 * {@snippet lang="java" : 5958 * T target(A...) 5959 * V filter(B... , T) 5960 * V adapter(A... a, B... b) { 5961 * T t = target(a...); 5962 * return filter(b..., t); 5963 * } 5964 * } 5965 * <p> 5966 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5967 * 5968 * @param target the target method handle 5969 * @param filter the filter method handle 5970 * @return the adapter method handle 5971 */ 5972 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5973 MethodType targetType = target.type(); 5974 MethodType filterType = filter.type(); 5975 BoundMethodHandle result = target.rebind(); 5976 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5977 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5978 if (filterType.parameterCount() > 1) { 5979 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5980 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5981 } 5982 } 5983 result = result.copyWithExtendL(newType, lform, filter); 5984 return result; 5985 } 5986 5987 /** 5988 * Adapts a target method handle by pre-processing 5989 * some of its arguments, and then calling the target with 5990 * the result of the pre-processing, inserted into the original 5991 * sequence of arguments. 5992 * <p> 5993 * The pre-processing is performed by {@code combiner}, a second method handle. 5994 * Of the arguments passed to the adapter, the first {@code N} arguments 5995 * are copied to the combiner, which is then called. 5996 * (Here, {@code N} is defined as the parameter count of the combiner.) 5997 * After this, control passes to the target, with any result 5998 * from the combiner inserted before the original {@code N} incoming 5999 * arguments. 6000 * <p> 6001 * If the combiner returns a value, the first parameter type of the target 6002 * must be identical with the return type of the combiner, and the next 6003 * {@code N} parameter types of the target must exactly match the parameters 6004 * of the combiner. 6005 * <p> 6006 * If the combiner has a void return, no result will be inserted, 6007 * and the first {@code N} parameter types of the target 6008 * must exactly match the parameters of the combiner. 6009 * <p> 6010 * The resulting adapter is the same type as the target, except that the 6011 * first parameter type is dropped, 6012 * if it corresponds to the result of the combiner. 6013 * <p> 6014 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 6015 * that either the combiner or the target does not wish to receive. 6016 * If some of the incoming arguments are destined only for the combiner, 6017 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 6018 * arguments will not need to be live on the stack on entry to the 6019 * target.) 6020 * <p><b>Example:</b> 6021 * {@snippet lang="java" : 6022 import static java.lang.invoke.MethodHandles.*; 6023 import static java.lang.invoke.MethodType.*; 6024 ... 6025 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6026 "println", methodType(void.class, String.class)) 6027 .bindTo(System.out); 6028 MethodHandle cat = lookup().findVirtual(String.class, 6029 "concat", methodType(String.class, String.class)); 6030 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6031 MethodHandle catTrace = foldArguments(cat, trace); 6032 // also prints "boo": 6033 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6034 * } 6035 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6036 * represents the result type of the {@code target} and resulting adapter. 6037 * {@code V}/{@code v} represent the type and value of the parameter and argument 6038 * of {@code target} that precedes the folding position; {@code V} also is 6039 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6040 * types and values of the {@code N} parameters and arguments at the folding 6041 * position. {@code B}/{@code b} represent the types and values of the 6042 * {@code target} parameters and arguments that follow the folded parameters 6043 * and arguments. 6044 * {@snippet lang="java" : 6045 * // there are N arguments in A... 6046 * T target(V, A[N]..., B...); 6047 * V combiner(A...); 6048 * T adapter(A... a, B... b) { 6049 * V v = combiner(a...); 6050 * return target(v, a..., b...); 6051 * } 6052 * // and if the combiner has a void return: 6053 * T target2(A[N]..., B...); 6054 * void combiner2(A...); 6055 * T adapter2(A... a, B... b) { 6056 * combiner2(a...); 6057 * return target2(a..., b...); 6058 * } 6059 * } 6060 * <p> 6061 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6062 * variable-arity method handle}, even if the original target method handle was. 6063 * @param target the method handle to invoke after arguments are combined 6064 * @param combiner method handle to call initially on the incoming arguments 6065 * @return method handle which incorporates the specified argument folding logic 6066 * @throws NullPointerException if either argument is null 6067 * @throws IllegalArgumentException if {@code combiner}'s return type 6068 * is non-void and not the same as the first argument type of 6069 * the target, or if the initial {@code N} argument types 6070 * of the target 6071 * (skipping one matching the {@code combiner}'s return type) 6072 * are not identical with the argument types of {@code combiner} 6073 */ 6074 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 6075 return foldArguments(target, 0, combiner); 6076 } 6077 6078 /** 6079 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6080 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6081 * before the folded arguments. 6082 * <p> 6083 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6084 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6085 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6086 * 0. 6087 * 6088 * @apiNote Example: 6089 * {@snippet lang="java" : 6090 import static java.lang.invoke.MethodHandles.*; 6091 import static java.lang.invoke.MethodType.*; 6092 ... 6093 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6094 "println", methodType(void.class, String.class)) 6095 .bindTo(System.out); 6096 MethodHandle cat = lookup().findVirtual(String.class, 6097 "concat", methodType(String.class, String.class)); 6098 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6099 MethodHandle catTrace = foldArguments(cat, 1, trace); 6100 // also prints "jum": 6101 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6102 * } 6103 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6104 * represents the result type of the {@code target} and resulting adapter. 6105 * {@code V}/{@code v} represent the type and value of the parameter and argument 6106 * of {@code target} that precedes the folding position; {@code V} also is 6107 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6108 * types and values of the {@code N} parameters and arguments at the folding 6109 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6110 * and values of the {@code target} parameters and arguments that precede and 6111 * follow the folded parameters and arguments starting at {@code pos}, 6112 * respectively. 6113 * {@snippet lang="java" : 6114 * // there are N arguments in A... 6115 * T target(Z..., V, A[N]..., B...); 6116 * V combiner(A...); 6117 * T adapter(Z... z, A... a, B... b) { 6118 * V v = combiner(a...); 6119 * return target(z..., v, a..., b...); 6120 * } 6121 * // and if the combiner has a void return: 6122 * T target2(Z..., A[N]..., B...); 6123 * void combiner2(A...); 6124 * T adapter2(Z... z, A... a, B... b) { 6125 * combiner2(a...); 6126 * return target2(z..., a..., b...); 6127 * } 6128 * } 6129 * <p> 6130 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6131 * variable-arity method handle}, even if the original target method handle was. 6132 * 6133 * @param target the method handle to invoke after arguments are combined 6134 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6135 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6136 * @param combiner method handle to call initially on the incoming arguments 6137 * @return method handle which incorporates the specified argument folding logic 6138 * @throws NullPointerException if either argument is null 6139 * @throws IllegalArgumentException if either of the following two conditions holds: 6140 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6141 * {@code pos} of the target signature; 6142 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6143 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6144 * 6145 * @see #foldArguments(MethodHandle, MethodHandle) 6146 * @since 9 6147 */ 6148 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6149 MethodType targetType = target.type(); 6150 MethodType combinerType = combiner.type(); 6151 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6152 BoundMethodHandle result = target.rebind(); 6153 boolean dropResult = rtype == void.class; 6154 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6155 MethodType newType = targetType; 6156 if (!dropResult) { 6157 newType = newType.dropParameterTypes(pos, pos + 1); 6158 } 6159 result = result.copyWithExtendL(newType, lform, combiner); 6160 return result; 6161 } 6162 6163 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6164 int foldArgs = combinerType.parameterCount(); 6165 Class<?> rtype = combinerType.returnType(); 6166 int foldVals = rtype == void.class ? 0 : 1; 6167 int afterInsertPos = foldPos + foldVals; 6168 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6169 if (ok) { 6170 for (int i = 0; i < foldArgs; i++) { 6171 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6172 ok = false; 6173 break; 6174 } 6175 } 6176 } 6177 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6178 ok = false; 6179 if (!ok) 6180 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6181 return rtype; 6182 } 6183 6184 /** 6185 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6186 * of the pre-processing replacing the argument at the given position. 6187 * 6188 * @param target the method handle to invoke after arguments are combined 6189 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6190 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6191 * @param combiner method handle to call initially on the incoming arguments 6192 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6193 * @return method handle which incorporates the specified argument folding logic 6194 * @throws NullPointerException if either argument is null 6195 * @throws IllegalArgumentException if either of the following two conditions holds: 6196 * (1) {@code combiner}'s return type is not the same as the argument type at position 6197 * {@code pos} of the target signature; 6198 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6199 * not identical with the argument types of {@code combiner}. 6200 */ 6201 /*non-public*/ 6202 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6203 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6204 } 6205 6206 /** 6207 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6208 * the pre-processing inserted into the original sequence of arguments at the given position. 6209 * 6210 * @param target the method handle to invoke after arguments are combined 6211 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6212 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6213 * @param combiner method handle to call initially on the incoming arguments 6214 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6215 * @return method handle which incorporates the specified argument folding logic 6216 * @throws NullPointerException if either argument is null 6217 * @throws IllegalArgumentException if either of the following two conditions holds: 6218 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6219 * {@code pos} of the target signature; 6220 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6221 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6222 * with the argument types of {@code combiner}. 6223 */ 6224 /*non-public*/ 6225 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6226 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6227 } 6228 6229 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6230 MethodType targetType = target.type(); 6231 MethodType combinerType = combiner.type(); 6232 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6233 BoundMethodHandle result = target.rebind(); 6234 6235 MethodType newType = targetType; 6236 LambdaForm lform; 6237 if (filter) { 6238 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6239 } else { 6240 boolean dropResult = rtype == void.class; 6241 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6242 if (!dropResult) { 6243 newType = newType.dropParameterTypes(position, position + 1); 6244 } 6245 } 6246 result = result.copyWithExtendL(newType, lform, combiner); 6247 return result; 6248 } 6249 6250 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6251 int combinerArgs = combinerType.parameterCount(); 6252 if (argPos.length != combinerArgs) { 6253 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6254 } 6255 Class<?> rtype = combinerType.returnType(); 6256 6257 for (int i = 0; i < combinerArgs; i++) { 6258 int arg = argPos[i]; 6259 if (arg < 0 || arg > targetType.parameterCount()) { 6260 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6261 } 6262 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6263 throw newIllegalArgumentException("target argument type at position " + arg 6264 + " must match combiner argument type at index " + i + ": " + targetType 6265 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6266 } 6267 } 6268 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6269 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6270 } 6271 return rtype; 6272 } 6273 6274 /** 6275 * Makes a method handle which adapts a target method handle, 6276 * by guarding it with a test, a boolean-valued method handle. 6277 * If the guard fails, a fallback handle is called instead. 6278 * All three method handles must have the same corresponding 6279 * argument and return types, except that the return type 6280 * of the test must be boolean, and the test is allowed 6281 * to have fewer arguments than the other two method handles. 6282 * <p> 6283 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6284 * represents the uniform result type of the three involved handles; 6285 * {@code A}/{@code a}, the types and values of the {@code target} 6286 * parameters and arguments that are consumed by the {@code test}; and 6287 * {@code B}/{@code b}, those types and values of the {@code target} 6288 * parameters and arguments that are not consumed by the {@code test}. 6289 * {@snippet lang="java" : 6290 * boolean test(A...); 6291 * T target(A...,B...); 6292 * T fallback(A...,B...); 6293 * T adapter(A... a,B... b) { 6294 * if (test(a...)) 6295 * return target(a..., b...); 6296 * else 6297 * return fallback(a..., b...); 6298 * } 6299 * } 6300 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6301 * be modified by execution of the test, and so are passed unchanged 6302 * from the caller to the target or fallback as appropriate. 6303 * @param test method handle used for test, must return boolean 6304 * @param target method handle to call if test passes 6305 * @param fallback method handle to call if test fails 6306 * @return method handle which incorporates the specified if/then/else logic 6307 * @throws NullPointerException if any argument is null 6308 * @throws IllegalArgumentException if {@code test} does not return boolean, 6309 * or if all three method types do not match (with the return 6310 * type of {@code test} changed to match that of the target). 6311 */ 6312 public static MethodHandle guardWithTest(MethodHandle test, 6313 MethodHandle target, 6314 MethodHandle fallback) { 6315 MethodType gtype = test.type(); 6316 MethodType ttype = target.type(); 6317 MethodType ftype = fallback.type(); 6318 if (!ttype.equals(ftype)) 6319 throw misMatchedTypes("target and fallback types", ttype, ftype); 6320 if (gtype.returnType() != boolean.class) 6321 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6322 6323 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6324 if (test == null) { 6325 throw misMatchedTypes("target and test types", ttype, gtype); 6326 } 6327 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6328 } 6329 6330 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6331 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6332 } 6333 6334 /** 6335 * Makes a method handle which adapts a target method handle, 6336 * by running it inside an exception handler. 6337 * If the target returns normally, the adapter returns that value. 6338 * If an exception matching the specified type is thrown, the fallback 6339 * handle is called instead on the exception, plus the original arguments. 6340 * <p> 6341 * The target and handler must have the same corresponding 6342 * argument and return types, except that handler may omit trailing arguments 6343 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6344 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6345 * <p> 6346 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6347 * represents the return type of the {@code target} and {@code handler}, 6348 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6349 * the types and values of arguments to the resulting handle consumed by 6350 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6351 * resulting handle discarded by {@code handler}. 6352 * {@snippet lang="java" : 6353 * T target(A..., B...); 6354 * T handler(ExType, A...); 6355 * T adapter(A... a, B... b) { 6356 * try { 6357 * return target(a..., b...); 6358 * } catch (ExType ex) { 6359 * return handler(ex, a...); 6360 * } 6361 * } 6362 * } 6363 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6364 * be modified by execution of the target, and so are passed unchanged 6365 * from the caller to the handler, if the handler is invoked. 6366 * <p> 6367 * The target and handler must return the same type, even if the handler 6368 * always throws. (This might happen, for instance, because the handler 6369 * is simulating a {@code finally} clause). 6370 * To create such a throwing handler, compose the handler creation logic 6371 * with {@link #throwException throwException}, 6372 * in order to create a method handle of the correct return type. 6373 * @param target method handle to call 6374 * @param exType the type of exception which the handler will catch 6375 * @param handler method handle to call if a matching exception is thrown 6376 * @return method handle which incorporates the specified try/catch logic 6377 * @throws NullPointerException if any argument is null 6378 * @throws IllegalArgumentException if {@code handler} does not accept 6379 * the given exception type, or if the method handle types do 6380 * not match in their return types and their 6381 * corresponding parameters 6382 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6383 */ 6384 public static MethodHandle catchException(MethodHandle target, 6385 Class<? extends Throwable> exType, 6386 MethodHandle handler) { 6387 MethodType ttype = target.type(); 6388 MethodType htype = handler.type(); 6389 if (!Throwable.class.isAssignableFrom(exType)) 6390 throw new ClassCastException(exType.getName()); 6391 if (htype.parameterCount() < 1 || 6392 !htype.parameterType(0).isAssignableFrom(exType)) 6393 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6394 if (htype.returnType() != ttype.returnType()) 6395 throw misMatchedTypes("target and handler return types", ttype, htype); 6396 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6397 if (handler == null) { 6398 throw misMatchedTypes("target and handler types", ttype, htype); 6399 } 6400 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6401 } 6402 6403 /** 6404 * Produces a method handle which will throw exceptions of the given {@code exType}. 6405 * The method handle will accept a single argument of {@code exType}, 6406 * and immediately throw it as an exception. 6407 * The method type will nominally specify a return of {@code returnType}. 6408 * The return type may be anything convenient: It doesn't matter to the 6409 * method handle's behavior, since it will never return normally. 6410 * @param returnType the return type of the desired method handle 6411 * @param exType the parameter type of the desired method handle 6412 * @return method handle which can throw the given exceptions 6413 * @throws NullPointerException if either argument is null 6414 */ 6415 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6416 if (!Throwable.class.isAssignableFrom(exType)) 6417 throw new ClassCastException(exType.getName()); 6418 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6419 } 6420 6421 /** 6422 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6423 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6424 * delivers the loop's result, which is the return value of the resulting handle. 6425 * <p> 6426 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6427 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6428 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6429 * terms of method handles, each clause will specify up to four independent actions:<ul> 6430 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6431 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6432 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6433 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6434 * </ul> 6435 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6436 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6437 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6438 * <p> 6439 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6440 * this case. See below for a detailed description. 6441 * <p> 6442 * <em>Parameters optional everywhere:</em> 6443 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6444 * As an exception, the init functions cannot take any {@code v} parameters, 6445 * because those values are not yet computed when the init functions are executed. 6446 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6447 * In fact, any clause function may take no arguments at all. 6448 * <p> 6449 * <em>Loop parameters:</em> 6450 * A clause function may take all the iteration variable values it is entitled to, in which case 6451 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6452 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6453 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6454 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6455 * init function is automatically a loop parameter {@code a}.) 6456 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6457 * These loop parameters act as loop-invariant values visible across the whole loop. 6458 * <p> 6459 * <em>Parameters visible everywhere:</em> 6460 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6461 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6462 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6463 * Most clause functions will not need all of this information, but they will be formally connected to it 6464 * as if by {@link #dropArguments}. 6465 * <a id="astar"></a> 6466 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6467 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6468 * In that notation, the general form of an init function parameter list 6469 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6470 * <p> 6471 * <em>Checking clause structure:</em> 6472 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6473 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6474 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6475 * met by the inputs to the loop combinator. 6476 * <p> 6477 * <em>Effectively identical sequences:</em> 6478 * <a id="effid"></a> 6479 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6480 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6481 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6482 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6483 * that longest list. 6484 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6485 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6486 * <p> 6487 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6488 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6489 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6490 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6491 * four. Padding takes place by appending elements to the array. 6492 * <li>Clauses with all {@code null}s are disregarded. 6493 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6494 * </ol> 6495 * <p> 6496 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6497 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6498 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6499 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6500 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6501 * iteration variable type. 6502 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6503 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6504 * </ol> 6505 * <p> 6506 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6507 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6508 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6509 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6510 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6511 * (These types will be checked in step 2, along with all the clause function types.) 6512 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6513 * <li>All of the collected parameter lists must be effectively identical. 6514 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6515 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6516 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6517 * the "internal parameter list". 6518 * </ul> 6519 * <p> 6520 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6521 * <li>Examine fini function return types, disregarding omitted fini functions. 6522 * <li>If there are no fini functions, the loop return type is {@code void}. 6523 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6524 * type. 6525 * </ol> 6526 * <p> 6527 * <em>Step 1D: Check other types.</em><ol type="a"> 6528 * <li>There must be at least one non-omitted pred function. 6529 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6530 * </ol> 6531 * <p> 6532 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6533 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6534 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6535 * (Note that their parameter lists are already effectively identical to this list.) 6536 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6537 * effectively identical to the internal parameter list {@code (V... A...)}. 6538 * </ol> 6539 * <p> 6540 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6541 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6542 * type. 6543 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6544 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6545 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6546 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6547 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6548 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6549 * loop return type. 6550 * </ol> 6551 * <p> 6552 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6553 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6554 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6555 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6556 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6557 * pad out the end of the list. 6558 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6559 * </ol> 6560 * <p> 6561 * <em>Final observations.</em><ol type="a"> 6562 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6563 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6564 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6565 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6566 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6567 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6568 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6569 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6570 * </ol> 6571 * <p> 6572 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6573 * <ul> 6574 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6575 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6576 * (Only one {@code Pn} has to be non-{@code null}.) 6577 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6578 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6579 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6580 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6581 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6582 * the resulting loop handle's parameter types {@code (A...)}. 6583 * </ul> 6584 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6585 * which is natural if most of the loop computation happens in the steps. For some loops, 6586 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6587 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6588 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6589 * where the init functions will need the extra parameters. For such reasons, the rules for 6590 * determining these parameters are as symmetric as possible, across all clause parts. 6591 * In general, the loop parameters function as common invariant values across the whole 6592 * loop, while the iteration variables function as common variant values, or (if there is 6593 * no step function) as internal loop invariant temporaries. 6594 * <p> 6595 * <em>Loop execution.</em><ol type="a"> 6596 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6597 * every clause function. These locals are loop invariant. 6598 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6599 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6600 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6601 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6602 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6603 * (in argument order). 6604 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6605 * returns {@code false}. 6606 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6607 * sequence {@code (v...)} of loop variables. 6608 * The updated value is immediately visible to all subsequent function calls. 6609 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6610 * (of type {@code R}) is returned from the loop as a whole. 6611 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6612 * except by throwing an exception. 6613 * </ol> 6614 * <p> 6615 * <em>Usage tips.</em> 6616 * <ul> 6617 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6618 * sometimes a step function only needs to observe the current value of its own variable. 6619 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6620 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6621 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6622 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6623 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6624 * <li>If some of the clause functions are virtual methods on an instance, the instance 6625 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6626 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6627 * will be the first iteration variable value, and it will be easy to use virtual 6628 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6629 * </ul> 6630 * <p> 6631 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6632 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6633 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6634 * {@snippet lang="java" : 6635 * V... init...(A...); 6636 * boolean pred...(V..., A...); 6637 * V... step...(V..., A...); 6638 * R fini...(V..., A...); 6639 * R loop(A... a) { 6640 * V... v... = init...(a...); 6641 * for (;;) { 6642 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6643 * v = s(v..., a...); 6644 * if (!p(v..., a...)) { 6645 * return f(v..., a...); 6646 * } 6647 * } 6648 * } 6649 * } 6650 * } 6651 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6652 * to their full length, even though individual clause functions may neglect to take them all. 6653 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6654 * 6655 * @apiNote Example: 6656 * {@snippet lang="java" : 6657 * // iterative implementation of the factorial function as a loop handle 6658 * static int one(int k) { return 1; } 6659 * static int inc(int i, int acc, int k) { return i + 1; } 6660 * static int mult(int i, int acc, int k) { return i * acc; } 6661 * static boolean pred(int i, int acc, int k) { return i < k; } 6662 * static int fin(int i, int acc, int k) { return acc; } 6663 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6664 * // null initializer for counter, should initialize to 0 6665 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6666 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6667 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6668 * assertEquals(120, loop.invoke(5)); 6669 * } 6670 * The same example, dropping arguments and using combinators: 6671 * {@snippet lang="java" : 6672 * // simplified implementation of the factorial function as a loop handle 6673 * static int inc(int i) { return i + 1; } // drop acc, k 6674 * static int mult(int i, int acc) { return i * acc; } //drop k 6675 * static boolean cmp(int i, int k) { return i < k; } 6676 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6677 * // null initializer for counter, should initialize to 0 6678 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6679 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6680 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6681 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6682 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6683 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6684 * assertEquals(720, loop.invoke(6)); 6685 * } 6686 * A similar example, using a helper object to hold a loop parameter: 6687 * {@snippet lang="java" : 6688 * // instance-based implementation of the factorial function as a loop handle 6689 * static class FacLoop { 6690 * final int k; 6691 * FacLoop(int k) { this.k = k; } 6692 * int inc(int i) { return i + 1; } 6693 * int mult(int i, int acc) { return i * acc; } 6694 * boolean pred(int i) { return i < k; } 6695 * int fin(int i, int acc) { return acc; } 6696 * } 6697 * // assume MH_FacLoop is a handle to the constructor 6698 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6699 * // null initializer for counter, should initialize to 0 6700 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6701 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6702 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6703 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6704 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6705 * assertEquals(5040, loop.invoke(7)); 6706 * } 6707 * 6708 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6709 * 6710 * @return a method handle embodying the looping behavior as defined by the arguments. 6711 * 6712 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6713 * 6714 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6715 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6716 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6717 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6718 * @since 9 6719 */ 6720 public static MethodHandle loop(MethodHandle[]... clauses) { 6721 // Step 0: determine clause structure. 6722 loopChecks0(clauses); 6723 6724 List<MethodHandle> init = new ArrayList<>(); 6725 List<MethodHandle> step = new ArrayList<>(); 6726 List<MethodHandle> pred = new ArrayList<>(); 6727 List<MethodHandle> fini = new ArrayList<>(); 6728 6729 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6730 init.add(clause[0]); // all clauses have at least length 1 6731 step.add(clause.length <= 1 ? null : clause[1]); 6732 pred.add(clause.length <= 2 ? null : clause[2]); 6733 fini.add(clause.length <= 3 ? null : clause[3]); 6734 }); 6735 6736 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6737 final int nclauses = init.size(); 6738 6739 // Step 1A: determine iteration variables (V...). 6740 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6741 for (int i = 0; i < nclauses; ++i) { 6742 MethodHandle in = init.get(i); 6743 MethodHandle st = step.get(i); 6744 if (in == null && st == null) { 6745 iterationVariableTypes.add(void.class); 6746 } else if (in != null && st != null) { 6747 loopChecks1a(i, in, st); 6748 iterationVariableTypes.add(in.type().returnType()); 6749 } else { 6750 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6751 } 6752 } 6753 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6754 6755 // Step 1B: determine loop parameters (A...). 6756 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6757 loopChecks1b(init, commonSuffix); 6758 6759 // Step 1C: determine loop return type. 6760 // Step 1D: check other types. 6761 // local variable required here; see JDK-8223553 6762 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6763 .map(MethodType::returnType); 6764 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6765 loopChecks1cd(pred, fini, loopReturnType); 6766 6767 // Step 2: determine parameter lists. 6768 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6769 commonParameterSequence.addAll(commonSuffix); 6770 loopChecks2(step, pred, fini, commonParameterSequence); 6771 // Step 3: fill in omitted functions. 6772 for (int i = 0; i < nclauses; ++i) { 6773 Class<?> t = iterationVariableTypes.get(i); 6774 if (init.get(i) == null) { 6775 init.set(i, empty(methodType(t, commonSuffix))); 6776 } 6777 if (step.get(i) == null) { 6778 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6779 } 6780 if (pred.get(i) == null) { 6781 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6782 } 6783 if (fini.get(i) == null) { 6784 fini.set(i, empty(methodType(t, commonParameterSequence))); 6785 } 6786 } 6787 6788 // Step 4: fill in missing parameter types. 6789 // Also convert all handles to fixed-arity handles. 6790 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6791 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6792 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6793 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6794 6795 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6796 allMatch(pl -> pl.equals(commonSuffix)); 6797 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6798 allMatch(pl -> pl.equals(commonParameterSequence)); 6799 6800 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6801 } 6802 6803 private static void loopChecks0(MethodHandle[][] clauses) { 6804 if (clauses == null || clauses.length == 0) { 6805 throw newIllegalArgumentException("null or no clauses passed"); 6806 } 6807 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6808 throw newIllegalArgumentException("null clauses are not allowed"); 6809 } 6810 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6811 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6812 } 6813 } 6814 6815 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6816 if (in.type().returnType() != st.type().returnType()) { 6817 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6818 st.type().returnType()); 6819 } 6820 } 6821 6822 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6823 return mhs.filter(Objects::nonNull) 6824 // take only those that can contribute to a common suffix because they are longer than the prefix 6825 .map(MethodHandle::type) 6826 .filter(t -> t.parameterCount() > skipSize) 6827 .max(Comparator.comparingInt(MethodType::parameterCount)) 6828 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6829 .orElse(List.of()); 6830 } 6831 6832 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6833 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6834 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6835 return longest1.size() >= longest2.size() ? longest1 : longest2; 6836 } 6837 6838 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6839 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6840 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6841 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6842 " (common suffix: " + commonSuffix + ")"); 6843 } 6844 } 6845 6846 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6847 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6848 anyMatch(t -> t != loopReturnType)) { 6849 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6850 loopReturnType + ")"); 6851 } 6852 6853 if (pred.stream().noneMatch(Objects::nonNull)) { 6854 throw newIllegalArgumentException("no predicate found", pred); 6855 } 6856 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6857 anyMatch(t -> t != boolean.class)) { 6858 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6859 } 6860 } 6861 6862 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6863 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6864 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6865 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6866 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6867 } 6868 } 6869 6870 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6871 return hs.stream().map(h -> { 6872 int pc = h.type().parameterCount(); 6873 int tpsize = targetParams.size(); 6874 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6875 }).toList(); 6876 } 6877 6878 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6879 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6880 } 6881 6882 /** 6883 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6884 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6885 * <p> 6886 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6887 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6888 * evaluates to {@code true}). 6889 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6890 * <p> 6891 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6892 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6893 * and updated with the value returned from its invocation. The result of loop execution will be 6894 * the final value of the additional loop-local variable (if present). 6895 * <p> 6896 * The following rules hold for these argument handles:<ul> 6897 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6898 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6899 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6900 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6901 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6902 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6903 * It will constrain the parameter lists of the other loop parts. 6904 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6905 * list {@code (A...)} is called the <em>external parameter list</em>. 6906 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6907 * additional state variable of the loop. 6908 * The body must both accept and return a value of this type {@code V}. 6909 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6910 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6911 * <a href="MethodHandles.html#effid">effectively identical</a> 6912 * to the external parameter list {@code (A...)}. 6913 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6914 * {@linkplain #empty default value}. 6915 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6916 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6917 * effectively identical to the internal parameter list. 6918 * </ul> 6919 * <p> 6920 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6921 * <li>The loop handle's result type is the result type {@code V} of the body. 6922 * <li>The loop handle's parameter types are the types {@code (A...)}, 6923 * from the external parameter list. 6924 * </ul> 6925 * <p> 6926 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6927 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6928 * passed to the loop. 6929 * {@snippet lang="java" : 6930 * V init(A...); 6931 * boolean pred(V, A...); 6932 * V body(V, A...); 6933 * V whileLoop(A... a...) { 6934 * V v = init(a...); 6935 * while (pred(v, a...)) { 6936 * v = body(v, a...); 6937 * } 6938 * return v; 6939 * } 6940 * } 6941 * 6942 * @apiNote Example: 6943 * {@snippet lang="java" : 6944 * // implement the zip function for lists as a loop handle 6945 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6946 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6947 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6948 * zip.add(a.next()); 6949 * zip.add(b.next()); 6950 * return zip; 6951 * } 6952 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6953 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6954 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6955 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6956 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6957 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6958 * } 6959 * 6960 * 6961 * @apiNote The implementation of this method can be expressed as follows: 6962 * {@snippet lang="java" : 6963 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6964 * MethodHandle fini = (body.type().returnType() == void.class 6965 * ? null : identity(body.type().returnType())); 6966 * MethodHandle[] 6967 * checkExit = { null, null, pred, fini }, 6968 * varBody = { init, body }; 6969 * return loop(checkExit, varBody); 6970 * } 6971 * } 6972 * 6973 * @param init optional initializer, providing the initial value of the loop variable. 6974 * May be {@code null}, implying a default initial value. See above for other constraints. 6975 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6976 * above for other constraints. 6977 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6978 * See above for other constraints. 6979 * 6980 * @return a method handle implementing the {@code while} loop as described by the arguments. 6981 * @throws IllegalArgumentException if the rules for the arguments are violated. 6982 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6983 * 6984 * @see #loop(MethodHandle[][]) 6985 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6986 * @since 9 6987 */ 6988 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6989 whileLoopChecks(init, pred, body); 6990 MethodHandle fini = identityOrVoid(body.type().returnType()); 6991 MethodHandle[] checkExit = { null, null, pred, fini }; 6992 MethodHandle[] varBody = { init, body }; 6993 return loop(checkExit, varBody); 6994 } 6995 6996 /** 6997 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6998 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6999 * <p> 7000 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 7001 * method will, in each iteration, first execute its body and then evaluate the predicate. 7002 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 7003 * <p> 7004 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 7005 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 7006 * and updated with the value returned from its invocation. The result of loop execution will be 7007 * the final value of the additional loop-local variable (if present). 7008 * <p> 7009 * The following rules hold for these argument handles:<ul> 7010 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7011 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 7012 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7013 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 7014 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 7015 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 7016 * It will constrain the parameter lists of the other loop parts. 7017 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 7018 * list {@code (A...)} is called the <em>external parameter list</em>. 7019 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7020 * additional state variable of the loop. 7021 * The body must both accept and return a value of this type {@code V}. 7022 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7023 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7024 * <a href="MethodHandles.html#effid">effectively identical</a> 7025 * to the external parameter list {@code (A...)}. 7026 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7027 * {@linkplain #empty default value}. 7028 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 7029 * Its parameter list (either empty or of the form {@code (V A*)}) must be 7030 * effectively identical to the internal parameter list. 7031 * </ul> 7032 * <p> 7033 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7034 * <li>The loop handle's result type is the result type {@code V} of the body. 7035 * <li>The loop handle's parameter types are the types {@code (A...)}, 7036 * from the external parameter list. 7037 * </ul> 7038 * <p> 7039 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7040 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 7041 * passed to the loop. 7042 * {@snippet lang="java" : 7043 * V init(A...); 7044 * boolean pred(V, A...); 7045 * V body(V, A...); 7046 * V doWhileLoop(A... a...) { 7047 * V v = init(a...); 7048 * do { 7049 * v = body(v, a...); 7050 * } while (pred(v, a...)); 7051 * return v; 7052 * } 7053 * } 7054 * 7055 * @apiNote Example: 7056 * {@snippet lang="java" : 7057 * // int i = 0; while (i < limit) { ++i; } return i; => limit 7058 * static int zero(int limit) { return 0; } 7059 * static int step(int i, int limit) { return i + 1; } 7060 * static boolean pred(int i, int limit) { return i < limit; } 7061 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 7062 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 7063 * assertEquals(23, loop.invoke(23)); 7064 * } 7065 * 7066 * 7067 * @apiNote The implementation of this method can be expressed as follows: 7068 * {@snippet lang="java" : 7069 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7070 * MethodHandle fini = (body.type().returnType() == void.class 7071 * ? null : identity(body.type().returnType())); 7072 * MethodHandle[] clause = { init, body, pred, fini }; 7073 * return loop(clause); 7074 * } 7075 * } 7076 * 7077 * @param init optional initializer, providing the initial value of the loop variable. 7078 * May be {@code null}, implying a default initial value. See above for other constraints. 7079 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7080 * See above for other constraints. 7081 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7082 * above for other constraints. 7083 * 7084 * @return a method handle implementing the {@code while} loop as described by the arguments. 7085 * @throws IllegalArgumentException if the rules for the arguments are violated. 7086 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7087 * 7088 * @see #loop(MethodHandle[][]) 7089 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7090 * @since 9 7091 */ 7092 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7093 whileLoopChecks(init, pred, body); 7094 MethodHandle fini = identityOrVoid(body.type().returnType()); 7095 MethodHandle[] clause = {init, body, pred, fini }; 7096 return loop(clause); 7097 } 7098 7099 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7100 Objects.requireNonNull(pred); 7101 Objects.requireNonNull(body); 7102 MethodType bodyType = body.type(); 7103 Class<?> returnType = bodyType.returnType(); 7104 List<Class<?>> innerList = bodyType.parameterList(); 7105 List<Class<?>> outerList = innerList; 7106 if (returnType == void.class) { 7107 // OK 7108 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7109 // leading V argument missing => error 7110 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7111 throw misMatchedTypes("body function", bodyType, expected); 7112 } else { 7113 outerList = innerList.subList(1, innerList.size()); 7114 } 7115 MethodType predType = pred.type(); 7116 if (predType.returnType() != boolean.class || 7117 !predType.effectivelyIdenticalParameters(0, innerList)) { 7118 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7119 } 7120 if (init != null) { 7121 MethodType initType = init.type(); 7122 if (initType.returnType() != returnType || 7123 !initType.effectivelyIdenticalParameters(0, outerList)) { 7124 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7125 } 7126 } 7127 } 7128 7129 /** 7130 * Constructs a loop that runs a given number of iterations. 7131 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7132 * <p> 7133 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7134 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7135 * It will be initialized to 0 and incremented by 1 in each iteration. 7136 * <p> 7137 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7138 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7139 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7140 * <p> 7141 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7142 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7143 * iteration variable. 7144 * The result of the loop handle execution will be the final {@code V} value of that variable 7145 * (or {@code void} if there is no {@code V} variable). 7146 * <p> 7147 * The following rules hold for the argument handles:<ul> 7148 * <li>The {@code iterations} handle must not be {@code null}, and must return 7149 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7150 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7151 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7152 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7153 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7154 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7155 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7156 * of types called the <em>internal parameter list</em>. 7157 * It will constrain the parameter lists of the other loop parts. 7158 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7159 * with no additional {@code A} types, then the internal parameter list is extended by 7160 * the argument types {@code A...} of the {@code iterations} handle. 7161 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7162 * list {@code (A...)} is called the <em>external parameter list</em>. 7163 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7164 * additional state variable of the loop. 7165 * The body must both accept a leading parameter and return a value of this type {@code V}. 7166 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7167 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7168 * <a href="MethodHandles.html#effid">effectively identical</a> 7169 * to the external parameter list {@code (A...)}. 7170 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7171 * {@linkplain #empty default value}. 7172 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7173 * effectively identical to the external parameter list {@code (A...)}. 7174 * </ul> 7175 * <p> 7176 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7177 * <li>The loop handle's result type is the result type {@code V} of the body. 7178 * <li>The loop handle's parameter types are the types {@code (A...)}, 7179 * from the external parameter list. 7180 * </ul> 7181 * <p> 7182 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7183 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7184 * arguments passed to the loop. 7185 * {@snippet lang="java" : 7186 * int iterations(A...); 7187 * V init(A...); 7188 * V body(V, int, A...); 7189 * V countedLoop(A... a...) { 7190 * int end = iterations(a...); 7191 * V v = init(a...); 7192 * for (int i = 0; i < end; ++i) { 7193 * v = body(v, i, a...); 7194 * } 7195 * return v; 7196 * } 7197 * } 7198 * 7199 * @apiNote Example with a fully conformant body method: 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, String init) { return "na " + v; } 7204 * // assume MH_step is a handle to the method above 7205 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7206 * MethodHandle start = MethodHandles.identity(String.class); 7207 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7208 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7209 * } 7210 * 7211 * @apiNote Example with the simplest possible body method type, 7212 * and passing the number of iterations to the loop invocation: 7213 * {@snippet lang="java" : 7214 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7215 * // => a variation on a well known theme 7216 * static String step(String v, int counter ) { return "na " + v; } 7217 * // assume MH_step is a handle to the method above 7218 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7219 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7220 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7221 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7222 * } 7223 * 7224 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7225 * as loop parameters: 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, int iterations_, String pre, String start_) { return pre + " " + v; } 7230 * // assume MH_step is a handle to the method above 7231 * MethodHandle count = MethodHandles.identity(int.class); 7232 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7233 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7234 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7235 * } 7236 * 7237 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7238 * to enforce a loop type: 7239 * {@snippet lang="java" : 7240 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7241 * // => a variation on a well known theme 7242 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7243 * // assume MH_step is a handle to the method above 7244 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7245 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7246 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7247 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7248 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7249 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7250 * } 7251 * 7252 * @apiNote The implementation of this method can be expressed as follows: 7253 * {@snippet lang="java" : 7254 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7255 * return countedLoop(empty(iterations.type()), iterations, init, body); 7256 * } 7257 * } 7258 * 7259 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7260 * result type must be {@code int}. See above for other constraints. 7261 * @param init optional initializer, providing the initial value of the loop variable. 7262 * May be {@code null}, implying a default initial value. See above for other constraints. 7263 * @param body body of the loop, which may not be {@code null}. 7264 * It controls the loop parameters and result type in the standard case (see above for details). 7265 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7266 * and may accept any number of additional types. 7267 * See above for other constraints. 7268 * 7269 * @return a method handle representing the loop. 7270 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7271 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7272 * 7273 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7274 * @since 9 7275 */ 7276 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7277 return countedLoop(empty(iterations.type()), iterations, init, body); 7278 } 7279 7280 /** 7281 * Constructs a loop that counts over a range of numbers. 7282 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7283 * <p> 7284 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7285 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7286 * values of the loop counter. 7287 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7288 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7289 * <p> 7290 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7291 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7292 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7293 * <p> 7294 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7295 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7296 * iteration variable. 7297 * The result of the loop handle execution will be the final {@code V} value of that variable 7298 * (or {@code void} if there is no {@code V} variable). 7299 * <p> 7300 * The following rules hold for the argument handles:<ul> 7301 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7302 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7303 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7304 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7305 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7306 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7307 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7308 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7309 * of types called the <em>internal parameter list</em>. 7310 * It will constrain the parameter lists of the other loop parts. 7311 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7312 * with no additional {@code A} types, then the internal parameter list is extended by 7313 * the argument types {@code A...} of the {@code end} handle. 7314 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7315 * list {@code (A...)} is called the <em>external parameter list</em>. 7316 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7317 * additional state variable of the loop. 7318 * The body must both accept a leading parameter and return a value of this type {@code V}. 7319 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7320 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7321 * <a href="MethodHandles.html#effid">effectively identical</a> 7322 * to the external parameter list {@code (A...)}. 7323 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7324 * {@linkplain #empty default value}. 7325 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7326 * effectively identical to the external parameter list {@code (A...)}. 7327 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7328 * to the external parameter list. 7329 * </ul> 7330 * <p> 7331 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7332 * <li>The loop handle's result type is the result type {@code V} of the body. 7333 * <li>The loop handle's parameter types are the types {@code (A...)}, 7334 * from the external parameter list. 7335 * </ul> 7336 * <p> 7337 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7338 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7339 * arguments passed to the loop. 7340 * {@snippet lang="java" : 7341 * int start(A...); 7342 * int end(A...); 7343 * V init(A...); 7344 * V body(V, int, A...); 7345 * V countedLoop(A... a...) { 7346 * int e = end(a...); 7347 * int s = start(a...); 7348 * V v = init(a...); 7349 * for (int i = s; i < e; ++i) { 7350 * v = body(v, i, a...); 7351 * } 7352 * return v; 7353 * } 7354 * } 7355 * 7356 * @apiNote The implementation of this method can be expressed as follows: 7357 * {@snippet lang="java" : 7358 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7359 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7360 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7361 * // the following semantics: 7362 * // MH_increment: (int limit, int counter) -> counter + 1 7363 * // MH_predicate: (int limit, int counter) -> counter < limit 7364 * Class<?> counterType = start.type().returnType(); // int 7365 * Class<?> returnType = body.type().returnType(); 7366 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7367 * if (returnType != void.class) { // ignore the V variable 7368 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7369 * pred = dropArguments(pred, 1, returnType); // ditto 7370 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7371 * } 7372 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7373 * MethodHandle[] 7374 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7375 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7376 * indexVar = { start, incr }; // i = start(); i = i + 1 7377 * return loop(loopLimit, bodyClause, indexVar); 7378 * } 7379 * } 7380 * 7381 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7382 * See above for other constraints. 7383 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7384 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7385 * @param init optional initializer, providing the initial value of the loop variable. 7386 * May be {@code null}, implying a default initial value. See above for other constraints. 7387 * @param body body of the loop, which may not be {@code null}. 7388 * It controls the loop parameters and result type in the standard case (see above for details). 7389 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7390 * and may accept any number of additional types. 7391 * See above for other constraints. 7392 * 7393 * @return a method handle representing the loop. 7394 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7395 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7396 * 7397 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7398 * @since 9 7399 */ 7400 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7401 countedLoopChecks(start, end, init, body); 7402 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7403 Class<?> limitType = end.type().returnType(); // yes, int again 7404 Class<?> returnType = body.type().returnType(); 7405 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7406 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7407 MethodHandle retv = null; 7408 if (returnType != void.class) { 7409 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7410 pred = dropArguments(pred, 1, returnType); // ditto 7411 retv = dropArguments(identity(returnType), 0, counterType); 7412 } 7413 body = dropArguments(body, 0, counterType); // ignore the limit variable 7414 MethodHandle[] 7415 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7416 bodyClause = { init, body }, // v = init(); v = body(v, i) 7417 indexVar = { start, incr }; // i = start(); i = i + 1 7418 return loop(loopLimit, bodyClause, indexVar); 7419 } 7420 7421 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7422 Objects.requireNonNull(start); 7423 Objects.requireNonNull(end); 7424 Objects.requireNonNull(body); 7425 Class<?> counterType = start.type().returnType(); 7426 if (counterType != int.class) { 7427 MethodType expected = start.type().changeReturnType(int.class); 7428 throw misMatchedTypes("start function", start.type(), expected); 7429 } else if (end.type().returnType() != counterType) { 7430 MethodType expected = end.type().changeReturnType(counterType); 7431 throw misMatchedTypes("end function", end.type(), expected); 7432 } 7433 MethodType bodyType = body.type(); 7434 Class<?> returnType = bodyType.returnType(); 7435 List<Class<?>> innerList = bodyType.parameterList(); 7436 // strip leading V value if present 7437 int vsize = (returnType == void.class ? 0 : 1); 7438 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7439 // argument list has no "V" => error 7440 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7441 throw misMatchedTypes("body function", bodyType, expected); 7442 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7443 // missing I type => error 7444 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7445 throw misMatchedTypes("body function", bodyType, expected); 7446 } 7447 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7448 if (outerList.isEmpty()) { 7449 // special case; take lists from end handle 7450 outerList = end.type().parameterList(); 7451 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7452 } 7453 MethodType expected = methodType(counterType, outerList); 7454 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7455 throw misMatchedTypes("start parameter types", start.type(), expected); 7456 } 7457 if (end.type() != start.type() && 7458 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7459 throw misMatchedTypes("end parameter types", end.type(), expected); 7460 } 7461 if (init != null) { 7462 MethodType initType = init.type(); 7463 if (initType.returnType() != returnType || 7464 !initType.effectivelyIdenticalParameters(0, outerList)) { 7465 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7466 } 7467 } 7468 } 7469 7470 /** 7471 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7472 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7473 * <p> 7474 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7475 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7476 * <p> 7477 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7478 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7479 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7480 * <p> 7481 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7482 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7483 * iteration variable. 7484 * The result of the loop handle execution will be the final {@code V} value of that variable 7485 * (or {@code void} if there is no {@code V} variable). 7486 * <p> 7487 * The following rules hold for the argument handles:<ul> 7488 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7489 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7490 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7491 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7492 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7493 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7494 * of types called the <em>internal parameter list</em>. 7495 * It will constrain the parameter lists of the other loop parts. 7496 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7497 * with no additional {@code A} types, then the internal parameter list is extended by 7498 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7499 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7500 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7501 * list {@code (A...)} is called the <em>external parameter list</em>. 7502 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7503 * additional state variable of the loop. 7504 * The body must both accept a leading parameter and return a value of this type {@code V}. 7505 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7506 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7507 * <a href="MethodHandles.html#effid">effectively identical</a> 7508 * to the external parameter list {@code (A...)}. 7509 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7510 * {@linkplain #empty default value}. 7511 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7512 * type {@code java.util.Iterator} or a subtype thereof. 7513 * The iterator it produces when the loop is executed will be assumed 7514 * to yield values which can be converted to type {@code T}. 7515 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7516 * effectively identical to the external parameter list {@code (A...)}. 7517 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7518 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7519 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7520 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7521 * the {@link MethodHandle#asType asType} conversion method. 7522 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7523 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7524 * </ul> 7525 * <p> 7526 * The type {@code T} may be either a primitive or reference. 7527 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7528 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7529 * as if by the {@link MethodHandle#asType asType} conversion method. 7530 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7531 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7532 * <p> 7533 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7534 * <li>The loop handle's result type is the result type {@code V} of the body. 7535 * <li>The loop handle's parameter types are the types {@code (A...)}, 7536 * from the external parameter list. 7537 * </ul> 7538 * <p> 7539 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7540 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7541 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7542 * {@snippet lang="java" : 7543 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7544 * V init(A...); 7545 * V body(V,T,A...); 7546 * V iteratedLoop(A... a...) { 7547 * Iterator<T> it = iterator(a...); 7548 * V v = init(a...); 7549 * while (it.hasNext()) { 7550 * T t = it.next(); 7551 * v = body(v, t, a...); 7552 * } 7553 * return v; 7554 * } 7555 * } 7556 * 7557 * @apiNote Example: 7558 * {@snippet lang="java" : 7559 * // get an iterator from a list 7560 * static List<String> reverseStep(List<String> r, String e) { 7561 * r.add(0, e); 7562 * return r; 7563 * } 7564 * static List<String> newArrayList() { return new ArrayList<>(); } 7565 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7566 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7567 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7568 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7569 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7570 * } 7571 * 7572 * @apiNote The implementation of this method can be expressed approximately as follows: 7573 * {@snippet lang="java" : 7574 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7575 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7576 * Class<?> returnType = body.type().returnType(); 7577 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7578 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7579 * MethodHandle retv = null, step = body, startIter = iterator; 7580 * if (returnType != void.class) { 7581 * // the simple thing first: in (I V A...), drop the I to get V 7582 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7583 * // body type signature (V T A...), internal loop types (I V A...) 7584 * step = swapArguments(body, 0, 1); // swap V <-> T 7585 * } 7586 * if (startIter == null) startIter = MH_getIter; 7587 * MethodHandle[] 7588 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7589 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7590 * return loop(iterVar, bodyClause); 7591 * } 7592 * } 7593 * 7594 * @param iterator an optional handle to return the iterator to start the loop. 7595 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7596 * See above for other constraints. 7597 * @param init optional initializer, providing the initial value of the loop variable. 7598 * May be {@code null}, implying a default initial value. See above for other constraints. 7599 * @param body body of the loop, which may not be {@code null}. 7600 * It controls the loop parameters and result type in the standard case (see above for details). 7601 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7602 * and may accept any number of additional types. 7603 * See above for other constraints. 7604 * 7605 * @return a method handle embodying the iteration loop functionality. 7606 * @throws NullPointerException if the {@code body} handle is {@code null}. 7607 * @throws IllegalArgumentException if any argument violates the above requirements. 7608 * 7609 * @since 9 7610 */ 7611 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7612 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7613 Class<?> returnType = body.type().returnType(); 7614 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7615 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7616 MethodHandle startIter; 7617 MethodHandle nextVal; 7618 { 7619 MethodType iteratorType; 7620 if (iterator == null) { 7621 // derive argument type from body, if available, else use Iterable 7622 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7623 iteratorType = startIter.type().changeParameterType(0, iterableType); 7624 } else { 7625 // force return type to the internal iterator class 7626 iteratorType = iterator.type().changeReturnType(Iterator.class); 7627 startIter = iterator; 7628 } 7629 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7630 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7631 7632 // perform the asType transforms under an exception transformer, as per spec.: 7633 try { 7634 startIter = startIter.asType(iteratorType); 7635 nextVal = nextRaw.asType(nextValType); 7636 } catch (WrongMethodTypeException ex) { 7637 throw new IllegalArgumentException(ex); 7638 } 7639 } 7640 7641 MethodHandle retv = null, step = body; 7642 if (returnType != void.class) { 7643 // the simple thing first: in (I V A...), drop the I to get V 7644 retv = dropArguments(identity(returnType), 0, Iterator.class); 7645 // body type signature (V T A...), internal loop types (I V A...) 7646 step = swapArguments(body, 0, 1); // swap V <-> T 7647 } 7648 7649 MethodHandle[] 7650 iterVar = { startIter, null, hasNext, retv }, 7651 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7652 return loop(iterVar, bodyClause); 7653 } 7654 7655 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7656 Objects.requireNonNull(body); 7657 MethodType bodyType = body.type(); 7658 Class<?> returnType = bodyType.returnType(); 7659 List<Class<?>> internalParamList = bodyType.parameterList(); 7660 // strip leading V value if present 7661 int vsize = (returnType == void.class ? 0 : 1); 7662 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7663 // argument list has no "V" => error 7664 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7665 throw misMatchedTypes("body function", bodyType, expected); 7666 } else if (internalParamList.size() <= vsize) { 7667 // missing T type => error 7668 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7669 throw misMatchedTypes("body function", bodyType, expected); 7670 } 7671 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7672 Class<?> iterableType = null; 7673 if (iterator != null) { 7674 // special case; if the body handle only declares V and T then 7675 // the external parameter list is obtained from iterator handle 7676 if (externalParamList.isEmpty()) { 7677 externalParamList = iterator.type().parameterList(); 7678 } 7679 MethodType itype = iterator.type(); 7680 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7681 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7682 } 7683 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7684 MethodType expected = methodType(itype.returnType(), externalParamList); 7685 throw misMatchedTypes("iterator parameters", itype, expected); 7686 } 7687 } else { 7688 if (externalParamList.isEmpty()) { 7689 // special case; if the iterator handle is null and the body handle 7690 // only declares V and T then the external parameter list consists 7691 // of Iterable 7692 externalParamList = List.of(Iterable.class); 7693 iterableType = Iterable.class; 7694 } else { 7695 // special case; if the iterator handle is null and the external 7696 // parameter list is not empty then the first parameter must be 7697 // assignable to Iterable 7698 iterableType = externalParamList.get(0); 7699 if (!Iterable.class.isAssignableFrom(iterableType)) { 7700 throw newIllegalArgumentException( 7701 "inferred first loop argument must inherit from Iterable: " + iterableType); 7702 } 7703 } 7704 } 7705 if (init != null) { 7706 MethodType initType = init.type(); 7707 if (initType.returnType() != returnType || 7708 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7709 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7710 } 7711 } 7712 return iterableType; // help the caller a bit 7713 } 7714 7715 /*non-public*/ 7716 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7717 // there should be a better way to uncross my wires 7718 int arity = mh.type().parameterCount(); 7719 int[] order = new int[arity]; 7720 for (int k = 0; k < arity; k++) order[k] = k; 7721 order[i] = j; order[j] = i; 7722 Class<?>[] types = mh.type().parameterArray(); 7723 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7724 MethodType swapType = methodType(mh.type().returnType(), types); 7725 return permuteArguments(mh, swapType, order); 7726 } 7727 7728 /** 7729 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7730 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7731 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7732 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7733 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7734 * {@code try-finally} handle. 7735 * <p> 7736 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7737 * The first is the exception thrown during the 7738 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7739 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7740 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7741 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7742 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7743 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7744 * <p> 7745 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7746 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7747 * two extra leading parameters:<ul> 7748 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7749 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7750 * the result from the execution of the {@code target} handle. 7751 * This parameter is not present if the {@code target} returns {@code void}. 7752 * </ul> 7753 * <p> 7754 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7755 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7756 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7757 * the cleanup. 7758 * {@snippet lang="java" : 7759 * V target(A..., B...); 7760 * V cleanup(Throwable, V, A...); 7761 * V adapter(A... a, B... b) { 7762 * V result = (zero value for V); 7763 * Throwable throwable = null; 7764 * try { 7765 * result = target(a..., b...); 7766 * } catch (Throwable t) { 7767 * throwable = t; 7768 * throw t; 7769 * } finally { 7770 * result = cleanup(throwable, result, a...); 7771 * } 7772 * return result; 7773 * } 7774 * } 7775 * <p> 7776 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7777 * be modified by execution of the target, and so are passed unchanged 7778 * from the caller to the cleanup, if it is invoked. 7779 * <p> 7780 * The target and cleanup must return the same type, even if the cleanup 7781 * always throws. 7782 * To create such a throwing cleanup, compose the cleanup logic 7783 * with {@link #throwException throwException}, 7784 * in order to create a method handle of the correct return type. 7785 * <p> 7786 * Note that {@code tryFinally} never converts exceptions into normal returns. 7787 * In rare cases where exceptions must be converted in that way, first wrap 7788 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7789 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7790 * <p> 7791 * It is recommended that the first parameter type of {@code cleanup} be 7792 * declared {@code Throwable} rather than a narrower subtype. This ensures 7793 * {@code cleanup} will always be invoked with whatever exception that 7794 * {@code target} throws. Declaring a narrower type may result in a 7795 * {@code ClassCastException} being thrown by the {@code try-finally} 7796 * handle if the type of the exception thrown by {@code target} is not 7797 * assignable to the first parameter type of {@code cleanup}. Note that 7798 * various exception types of {@code VirtualMachineError}, 7799 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7800 * thrown by almost any kind of Java code, and a finally clause that 7801 * catches (say) only {@code IOException} would mask any of the others 7802 * behind a {@code ClassCastException}. 7803 * 7804 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7805 * @param cleanup the handle that is invoked in the finally block. 7806 * 7807 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7808 * @throws NullPointerException if any argument is null 7809 * @throws IllegalArgumentException if {@code cleanup} does not accept 7810 * the required leading arguments, or if the method handle types do 7811 * not match in their return types and their 7812 * corresponding trailing parameters 7813 * 7814 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7815 * @since 9 7816 */ 7817 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7818 Class<?>[] targetParamTypes = target.type().ptypes(); 7819 Class<?> rtype = target.type().returnType(); 7820 7821 tryFinallyChecks(target, cleanup); 7822 7823 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7824 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7825 // target parameter list. 7826 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7827 7828 // Ensure that the intrinsic type checks the instance thrown by the 7829 // target against the first parameter of cleanup 7830 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7831 7832 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7833 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7834 } 7835 7836 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7837 Class<?> rtype = target.type().returnType(); 7838 if (rtype != cleanup.type().returnType()) { 7839 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7840 } 7841 MethodType cleanupType = cleanup.type(); 7842 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7843 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7844 } 7845 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7846 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7847 } 7848 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7849 // target parameter list. 7850 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7851 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7852 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7853 cleanup.type(), target.type()); 7854 } 7855 } 7856 7857 /** 7858 * Creates a table switch method handle, which can be used to switch over a set of target 7859 * method handles, based on a given target index, called selector. 7860 * <p> 7861 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7862 * and where {@code N} is the number of target method handles, the table switch method 7863 * handle will invoke the n-th target method handle from the list of target method handles. 7864 * <p> 7865 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7866 * method handle will invoke the given fallback method handle. 7867 * <p> 7868 * All method handles passed to this method must have the same type, with the additional 7869 * requirement that the leading parameter be of type {@code int}. The leading parameter 7870 * represents the selector. 7871 * <p> 7872 * Any trailing parameters present in the type will appear on the returned table switch 7873 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7874 * together with the selector value, to the selected method handle when invoking it. 7875 * 7876 * @apiNote Example: 7877 * The cases each drop the {@code selector} value they are given, and take an additional 7878 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7879 * to a specific constant label string for each case: 7880 * {@snippet lang="java" : 7881 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7882 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7883 * MethodType.methodType(String.class, String.class)); 7884 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7885 * 7886 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7887 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7888 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7889 * 7890 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7891 * caseDefault, 7892 * case0, 7893 * case1 7894 * ); 7895 * 7896 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7897 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7898 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7899 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7900 * } 7901 * 7902 * @param fallback the fallback method handle that is called when the selector is not 7903 * within the range {@code [0, N)}. 7904 * @param targets array of target method handles. 7905 * @return the table switch method handle. 7906 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7907 * any of the elements of the {@code targets} array are 7908 * {@code null}. 7909 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7910 * parameter of the fallback handle or any of the target 7911 * handles is not {@code int}, or if the types of 7912 * the fallback handle and all of target handles are 7913 * not the same. 7914 * 7915 * @since 17 7916 */ 7917 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7918 Objects.requireNonNull(fallback); 7919 Objects.requireNonNull(targets); 7920 targets = targets.clone(); 7921 MethodType type = tableSwitchChecks(fallback, targets); 7922 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7923 } 7924 7925 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7926 if (caseActions.length == 0) 7927 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7928 7929 MethodType expectedType = defaultCase.type(); 7930 7931 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7932 throw new IllegalArgumentException( 7933 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7934 7935 for (MethodHandle mh : caseActions) { 7936 Objects.requireNonNull(mh); 7937 if (mh.type() != expectedType) 7938 throw new IllegalArgumentException( 7939 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7940 } 7941 7942 return expectedType; 7943 } 7944 7945 /** 7946 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7947 * <p> 7948 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7949 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7950 * to the target var handle. 7951 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7952 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7953 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7954 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7955 * <p> 7956 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7957 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7958 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7959 * will be appended to the coordinates of the target var handle). 7960 * <p> 7961 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7962 * throw an {@link IllegalStateException}. 7963 * <p> 7964 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7965 * atomic access guarantees as those featured by the target var handle. 7966 * 7967 * @param target the target var handle 7968 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7969 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7970 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7971 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7972 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7973 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7974 * @throws NullPointerException if any of the arguments is {@code null}. 7975 * @since 22 7976 */ 7977 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7978 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7979 } 7980 7981 /** 7982 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7983 * <p> 7984 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7985 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7986 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7987 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7988 * by the adaptation) to the target var handle. 7989 * <p> 7990 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7991 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7992 * <p> 7993 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7994 * throw an {@link IllegalStateException}. 7995 * <p> 7996 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7997 * atomic access guarantees as those featured by the target var handle. 7998 * 7999 * @param target the target var handle 8000 * @param pos the position of the first coordinate to be transformed 8001 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 8002 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 8003 * to the new coordinate values. 8004 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 8005 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 8006 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8007 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 8008 * or if it's determined that any of the filters throws any checked exceptions. 8009 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 8010 * @since 22 8011 */ 8012 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8013 return VarHandles.filterCoordinates(target, pos, filters); 8014 } 8015 8016 /** 8017 * Provides a target var handle with one or more <em>bound coordinates</em> 8018 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8019 * coordinate types than the target var handle. 8020 * <p> 8021 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8022 * are joined with bound coordinate values, and then passed to the target var handle. 8023 * <p> 8024 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8025 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8026 * <p> 8027 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8028 * atomic access guarantees as those featured by the target var handle. 8029 * 8030 * @param target the var handle to invoke after the bound coordinates are inserted 8031 * @param pos the position of the first coordinate to be inserted 8032 * @param values the series of bound coordinates to insert 8033 * @return an adapter var handle which inserts additional coordinates, 8034 * before calling the target var handle 8035 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8036 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8037 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8038 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8039 * of the target var handle. 8040 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8041 * @since 22 8042 */ 8043 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8044 return VarHandles.insertCoordinates(target, pos, values); 8045 } 8046 8047 /** 8048 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8049 * so that the new coordinates match the provided ones. 8050 * <p> 8051 * The given array controls the reordering. 8052 * Call {@code #I} the number of incoming coordinates (the value 8053 * {@code newCoordinates.size()}), and call {@code #O} the number 8054 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8055 * Then the length of the reordering array must be {@code #O}, 8056 * and each element must be a non-negative number less than {@code #I}. 8057 * For every {@code N} less than {@code #O}, the {@code N}-th 8058 * outgoing coordinate will be taken from the {@code I}-th incoming 8059 * coordinate, where {@code I} is {@code reorder[N]}. 8060 * <p> 8061 * No coordinate value conversions are applied. 8062 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8063 * must be identical to the type of the corresponding outgoing coordinate 8064 * in the target var handle. 8065 * <p> 8066 * The reordering array need not specify an actual permutation. 8067 * An incoming coordinate will be duplicated if its index appears 8068 * more than once in the array, and an incoming coordinate will be dropped 8069 * if its index does not appear in the array. 8070 * <p> 8071 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8072 * atomic access guarantees as those featured by the target var handle. 8073 * @param target the var handle to invoke after the coordinates have been reordered 8074 * @param newCoordinates the new coordinate types 8075 * @param reorder an index array which controls the reordering 8076 * @return an adapter var handle which re-arranges the incoming coordinate values, 8077 * before calling the target var handle 8078 * @throws IllegalArgumentException if the index array length is not equal to 8079 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8080 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8081 * the target var handle and in {@code newCoordinates} are not identical. 8082 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8083 * @since 22 8084 */ 8085 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8086 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8087 } 8088 8089 /** 8090 * Adapts a target var handle by pre-processing 8091 * a sub-sequence of its coordinate values with a filter (a method handle). 8092 * The pre-processed coordinates are replaced by the result (if any) of the 8093 * filter function and the target var handle is then called on the modified (usually shortened) 8094 * coordinate list. 8095 * <p> 8096 * If {@code R} is the return type of the filter, then: 8097 * <ul> 8098 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 8099 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 8100 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 8101 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 8102 * target var handle.</li> 8103 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 8104 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 8105 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 8106 * downstream invocation of the target var handle.</li> 8107 * </ul> 8108 * <p> 8109 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8110 * throw an {@link IllegalStateException}. 8111 * <p> 8112 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8113 * atomic access guarantees as those featured by the target var handle. 8114 * 8115 * @param target the var handle to invoke after the coordinates have been filtered 8116 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 8117 * @param filter the filter method handle 8118 * @return an adapter var handle which filters the incoming coordinate values, 8119 * before calling the target var handle 8120 * @throws IllegalArgumentException if the return type of {@code filter} 8121 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 8122 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8123 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8124 * or if it's determined that {@code filter} throws any checked exceptions. 8125 * @throws NullPointerException if any of the arguments is {@code null}. 8126 * @since 22 8127 */ 8128 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8129 return VarHandles.collectCoordinates(target, pos, filter); 8130 } 8131 8132 /** 8133 * Returns a var handle which will discard some dummy coordinates before delegating to the 8134 * target var handle. As a consequence, the resulting var handle will feature more 8135 * coordinate types than the target var handle. 8136 * <p> 8137 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8138 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8139 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8140 * <p> 8141 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8142 * atomic access guarantees as those featured by the target var handle. 8143 * 8144 * @param target the var handle to invoke after the dummy coordinates are dropped 8145 * @param pos position of the first coordinate to drop (zero for the leftmost) 8146 * @param valueTypes the type(s) of the coordinate(s) to drop 8147 * @return an adapter var handle which drops some dummy coordinates, 8148 * before calling the target var handle 8149 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8150 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8151 * @since 22 8152 */ 8153 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8154 return VarHandles.dropCoordinates(target, pos, valueTypes); 8155 } 8156 }