1 /* 2 * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.access.SharedSecrets; 29 import jdk.internal.misc.Unsafe; 30 import jdk.internal.misc.VM; 31 import jdk.internal.reflect.CallerSensitive; 32 import jdk.internal.reflect.CallerSensitiveAdapter; 33 import jdk.internal.reflect.Reflection; 34 import jdk.internal.util.ClassFileDumper; 35 import jdk.internal.vm.annotation.ForceInline; 36 import sun.invoke.util.ValueConversions; 37 import sun.invoke.util.VerifyAccess; 38 import sun.invoke.util.Wrapper; 39 import sun.reflect.misc.ReflectUtil; 40 import sun.security.util.SecurityConstants; 41 42 import java.lang.classfile.ClassFile; 43 import java.lang.classfile.ClassModel; 44 import java.lang.constant.ClassDesc; 45 import java.lang.constant.ConstantDescs; 46 import java.lang.invoke.LambdaForm.BasicType; 47 import java.lang.invoke.MethodHandleImpl.Intrinsic; 48 import java.lang.reflect.Constructor; 49 import java.lang.reflect.Field; 50 import java.lang.reflect.Member; 51 import java.lang.reflect.Method; 52 import java.lang.reflect.Modifier; 53 import java.nio.ByteOrder; 54 import java.security.ProtectionDomain; 55 import java.util.ArrayList; 56 import java.util.Arrays; 57 import java.util.BitSet; 58 import java.util.Comparator; 59 import java.util.Iterator; 60 import java.util.List; 61 import java.util.Objects; 62 import java.util.Set; 63 import java.util.concurrent.ConcurrentHashMap; 64 import java.util.stream.Stream; 65 66 import static java.lang.classfile.ClassFile.*; 67 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 68 import static java.lang.invoke.MethodHandleNatives.Constants.*; 69 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 70 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 71 import static java.lang.invoke.MethodHandleStatics.newInternalError; 72 import static java.lang.invoke.MethodType.methodType; 73 74 /** 75 * This class consists exclusively of static methods that operate on or return 76 * method handles. They fall into several categories: 77 * <ul> 78 * <li>Lookup methods which help create method handles for methods and fields. 79 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 80 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 81 * </ul> 82 * A lookup, combinator, or factory method will fail and throw an 83 * {@code IllegalArgumentException} if the created method handle's type 84 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 85 * 86 * @author John Rose, JSR 292 EG 87 * @since 1.7 88 */ 89 public class MethodHandles { 90 91 private MethodHandles() { } // do not instantiate 92 93 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 94 95 // See IMPL_LOOKUP below. 96 97 //--- Method handle creation from ordinary methods. 98 99 /** 100 * Returns a {@link Lookup lookup object} with 101 * full capabilities to emulate all supported bytecode behaviors of the caller. 102 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 103 * Factory methods on the lookup object can create 104 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 105 * for any member that the caller has access to via bytecodes, 106 * including protected and private fields and methods. 107 * This lookup object is created by the original lookup class 108 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 109 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 110 * Do not store it in place where untrusted code can access it. 111 * <p> 112 * This method is caller sensitive, which means that it may return different 113 * values to different callers. 114 * In cases where {@code MethodHandles.lookup} is called from a context where 115 * there is no caller frame on the stack (e.g. when called directly 116 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 117 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 118 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 119 * to obtain a low-privileged lookup instead. 120 * @return a lookup object for the caller of this method, with 121 * {@linkplain Lookup#ORIGINAL original} and 122 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 123 * @throws IllegalCallerException if there is no caller frame on the stack. 124 */ 125 @CallerSensitive 126 @ForceInline // to ensure Reflection.getCallerClass optimization 127 public static Lookup lookup() { 128 final Class<?> c = Reflection.getCallerClass(); 129 if (c == null) { 130 throw new IllegalCallerException("no caller frame"); 131 } 132 return new Lookup(c); 133 } 134 135 /** 136 * This lookup method is the alternate implementation of 137 * the lookup method with a leading caller class argument which is 138 * non-caller-sensitive. This method is only invoked by reflection 139 * and method handle. 140 */ 141 @CallerSensitiveAdapter 142 private static Lookup lookup(Class<?> caller) { 143 if (caller.getClassLoader() == null) { 144 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 145 } 146 return new Lookup(caller); 147 } 148 149 /** 150 * Returns a {@link Lookup lookup object} which is trusted minimally. 151 * The lookup has the {@code UNCONDITIONAL} mode. 152 * It can only be used to create method handles to public members of 153 * public classes in packages that are exported unconditionally. 154 * <p> 155 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 156 * of this lookup object will be {@link java.lang.Object}. 157 * 158 * @apiNote The use of Object is conventional, and because the lookup modes are 159 * limited, there is no special access provided to the internals of Object, its package 160 * or its module. This public lookup object or other lookup object with 161 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 162 * is not used to determine the lookup context. 163 * 164 * <p style="font-size:smaller;"> 165 * <em>Discussion:</em> 166 * The lookup class can be changed to any other class {@code C} using an expression of the form 167 * {@link Lookup#in publicLookup().in(C.class)}. 168 * A public lookup object is always subject to 169 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 170 * Also, it cannot access 171 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 172 * @return a lookup object which is trusted minimally 173 */ 174 public static Lookup publicLookup() { 175 return Lookup.PUBLIC_LOOKUP; 176 } 177 178 /** 179 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 180 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 181 * The returned lookup object can provide access to classes in modules and packages, 182 * and members of those classes, outside the normal rules of Java access control, 183 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 184 * <p> 185 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 186 * allowed to do deep reflection on module {@code M2} and package of the target class 187 * if and only if all of the following conditions are {@code true}: 188 * <ul> 189 * <li>If there is a security manager, its {@code checkPermission} method is 190 * called to check {@code ReflectPermission("suppressAccessChecks")} and 191 * that must return normally. 192 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 193 * full privilege access}. Specifically: 194 * <ul> 195 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 196 * (This is because otherwise there would be no way to ensure the original lookup 197 * creator was a member of any particular module, and so any subsequent checks 198 * for readability and qualified exports would become ineffective.) 199 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 200 * (This is because an application intending to share intra-module access 201 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 202 * deep reflection to its own module.) 203 * </ul> 204 * <li>The target class must be a proper class, not a primitive or array class. 205 * (Thus, {@code M2} is well-defined.) 206 * <li>If the caller module {@code M1} differs from 207 * the target module {@code M2} then both of the following must be true: 208 * <ul> 209 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 210 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 211 * containing the target class to at least {@code M1}.</li> 212 * </ul> 213 * </ul> 214 * <p> 215 * If any of the above checks is violated, this method fails with an 216 * exception. 217 * <p> 218 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 219 * returns a {@code Lookup} on {@code targetClass} with 220 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 221 * with {@code null} previous lookup class. 222 * <p> 223 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 224 * returns a {@code Lookup} on {@code targetClass} that records 225 * the lookup class of the caller as the new previous lookup class with 226 * {@code PRIVATE} access but no {@code MODULE} access. 227 * <p> 228 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 229 * 230 * @apiNote The {@code Lookup} object returned by this method is allowed to 231 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 232 * of {@code targetClass}. Extreme caution should be taken when opening a package 233 * to another module as such defined classes have the same full privilege 234 * access as other members in {@code targetClass}'s module. 235 * 236 * @param targetClass the target class 237 * @param caller the caller lookup object 238 * @return a lookup object for the target class, with private access 239 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 240 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 241 * @throws SecurityException if denied by the security manager 242 * @throws IllegalAccessException if any of the other access checks specified above fails 243 * @since 9 244 * @see Lookup#dropLookupMode 245 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 246 */ 247 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 248 if (caller.allowedModes == Lookup.TRUSTED) { 249 return new Lookup(targetClass); 250 } 251 252 @SuppressWarnings("removal") 253 SecurityManager sm = System.getSecurityManager(); 254 if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION); 255 if (targetClass.isPrimitive()) 256 throw new IllegalArgumentException(targetClass + " is a primitive class"); 257 if (targetClass.isArray()) 258 throw new IllegalArgumentException(targetClass + " is an array class"); 259 // Ensure that we can reason accurately about private and module access. 260 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 261 if ((caller.lookupModes() & requireAccess) != requireAccess) 262 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 263 264 // previous lookup class is never set if it has MODULE access 265 assert caller.previousLookupClass() == null; 266 267 Class<?> callerClass = caller.lookupClass(); 268 Module callerModule = callerClass.getModule(); // M1 269 Module targetModule = targetClass.getModule(); // M2 270 Class<?> newPreviousClass = null; 271 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 272 273 if (targetModule != callerModule) { 274 if (!callerModule.canRead(targetModule)) 275 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 276 if (targetModule.isNamed()) { 277 String pn = targetClass.getPackageName(); 278 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 279 if (!targetModule.isOpen(pn, callerModule)) 280 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 281 } 282 283 // M2 != M1, set previous lookup class to M1 and drop MODULE access 284 newPreviousClass = callerClass; 285 newModes &= ~Lookup.MODULE; 286 } 287 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 288 } 289 290 /** 291 * Returns the <em>class data</em> associated with the lookup class 292 * of the given {@code caller} lookup object, or {@code null}. 293 * 294 * <p> A hidden class with class data can be created by calling 295 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 296 * Lookup::defineHiddenClassWithClassData}. 297 * This method will cause the static class initializer of the lookup 298 * class of the given {@code caller} lookup object be executed if 299 * it has not been initialized. 300 * 301 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 302 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 303 * {@code null} is returned if this method is called on the lookup object 304 * on these classes. 305 * 306 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 307 * must have {@linkplain Lookup#ORIGINAL original access} 308 * in order to retrieve the class data. 309 * 310 * @apiNote 311 * This method can be called as a bootstrap method for a dynamically computed 312 * constant. A framework can create a hidden class with class data, for 313 * example that can be {@code Class} or {@code MethodHandle} object. 314 * The class data is accessible only to the lookup object 315 * created by the original caller but inaccessible to other members 316 * in the same nest. If a framework passes security sensitive objects 317 * to a hidden class via class data, it is recommended to load the value 318 * of class data as a dynamically computed constant instead of storing 319 * the class data in private static field(s) which are accessible to 320 * other nestmates. 321 * 322 * @param <T> the type to cast the class data object to 323 * @param caller the lookup context describing the class performing the 324 * operation (normally stacked by the JVM) 325 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 326 * ({@code "_"}) 327 * @param type the type of the class data 328 * @return the value of the class data if present in the lookup class; 329 * otherwise {@code null} 330 * @throws IllegalArgumentException if name is not {@code "_"} 331 * @throws IllegalAccessException if the lookup context does not have 332 * {@linkplain Lookup#ORIGINAL original} access 333 * @throws ClassCastException if the class data cannot be converted to 334 * the given {@code type} 335 * @throws NullPointerException if {@code caller} or {@code type} argument 336 * is {@code null} 337 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 338 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 339 * @since 16 340 * @jvms 5.5 Initialization 341 */ 342 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 343 Objects.requireNonNull(caller); 344 Objects.requireNonNull(type); 345 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 346 throw new IllegalArgumentException("name must be \"_\": " + name); 347 } 348 349 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 350 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 351 } 352 353 Object classdata = classData(caller.lookupClass()); 354 if (classdata == null) return null; 355 356 try { 357 return BootstrapMethodInvoker.widenAndCast(classdata, type); 358 } catch (RuntimeException|Error e) { 359 throw e; // let CCE and other runtime exceptions through 360 } catch (Throwable e) { 361 throw new InternalError(e); 362 } 363 } 364 365 /* 366 * Returns the class data set by the VM in the Class::classData field. 367 * 368 * This is also invoked by LambdaForms as it cannot use condy via 369 * MethodHandles::classData due to bootstrapping issue. 370 */ 371 static Object classData(Class<?> c) { 372 UNSAFE.ensureClassInitialized(c); 373 return SharedSecrets.getJavaLangAccess().classData(c); 374 } 375 376 /** 377 * Returns the element at the specified index in the 378 * {@linkplain #classData(Lookup, String, Class) class data}, 379 * if the class data associated with the lookup class 380 * of the given {@code caller} lookup object is a {@code List}. 381 * If the class data is not present in this lookup class, this method 382 * returns {@code null}. 383 * 384 * <p> A hidden class with class data can be created by calling 385 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 386 * Lookup::defineHiddenClassWithClassData}. 387 * This method will cause the static class initializer of the lookup 388 * class of the given {@code caller} lookup object be executed if 389 * it has not been initialized. 390 * 391 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 392 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 393 * {@code null} is returned if this method is called on the lookup object 394 * on these classes. 395 * 396 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 397 * must have {@linkplain Lookup#ORIGINAL original access} 398 * in order to retrieve the class data. 399 * 400 * @apiNote 401 * This method can be called as a bootstrap method for a dynamically computed 402 * constant. A framework can create a hidden class with class data, for 403 * example that can be {@code List.of(o1, o2, o3....)} containing more than 404 * one object and use this method to load one element at a specific index. 405 * The class data is accessible only to the lookup object 406 * created by the original caller but inaccessible to other members 407 * in the same nest. If a framework passes security sensitive objects 408 * to a hidden class via class data, it is recommended to load the value 409 * of class data as a dynamically computed constant instead of storing 410 * the class data in private static field(s) which are accessible to other 411 * nestmates. 412 * 413 * @param <T> the type to cast the result object to 414 * @param caller the lookup context describing the class performing the 415 * operation (normally stacked by the JVM) 416 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 417 * ({@code "_"}) 418 * @param type the type of the element at the given index in the class data 419 * @param index index of the element in the class data 420 * @return the element at the given index in the class data 421 * if the class data is present; otherwise {@code null} 422 * @throws IllegalArgumentException if name is not {@code "_"} 423 * @throws IllegalAccessException if the lookup context does not have 424 * {@linkplain Lookup#ORIGINAL original} access 425 * @throws ClassCastException if the class data cannot be converted to {@code List} 426 * or the element at the specified index cannot be converted to the given type 427 * @throws IndexOutOfBoundsException if the index is out of range 428 * @throws NullPointerException if {@code caller} or {@code type} argument is 429 * {@code null}; or if unboxing operation fails because 430 * the element at the given index is {@code null} 431 * 432 * @since 16 433 * @see #classData(Lookup, String, Class) 434 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 435 */ 436 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 437 throws IllegalAccessException 438 { 439 @SuppressWarnings("unchecked") 440 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 441 if (classdata == null) return null; 442 443 try { 444 Object element = classdata.get(index); 445 return BootstrapMethodInvoker.widenAndCast(element, type); 446 } catch (RuntimeException|Error e) { 447 throw e; // let specified exceptions and other runtime exceptions/errors through 448 } catch (Throwable e) { 449 throw new InternalError(e); 450 } 451 } 452 453 /** 454 * Performs an unchecked "crack" of a 455 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 456 * The result is as if the user had obtained a lookup object capable enough 457 * to crack the target method handle, called 458 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 459 * on the target to obtain its symbolic reference, and then called 460 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 461 * to resolve the symbolic reference to a member. 462 * <p> 463 * If there is a security manager, its {@code checkPermission} method 464 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 465 * @param <T> the desired type of the result, either {@link Member} or a subtype 466 * @param target a direct method handle to crack into symbolic reference components 467 * @param expected a class object representing the desired result type {@code T} 468 * @return a reference to the method, constructor, or field object 469 * @throws SecurityException if the caller is not privileged to call {@code setAccessible} 470 * @throws NullPointerException if either argument is {@code null} 471 * @throws IllegalArgumentException if the target is not a direct method handle 472 * @throws ClassCastException if the member is not of the expected type 473 * @since 1.8 474 */ 475 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 476 @SuppressWarnings("removal") 477 SecurityManager smgr = System.getSecurityManager(); 478 if (smgr != null) smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION); 479 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 480 return lookup.revealDirect(target).reflectAs(expected, lookup); 481 } 482 483 /** 484 * A <em>lookup object</em> is a factory for creating method handles, 485 * when the creation requires access checking. 486 * Method handles do not perform 487 * access checks when they are called, but rather when they are created. 488 * Therefore, method handle access 489 * restrictions must be enforced when a method handle is created. 490 * The caller class against which those restrictions are enforced 491 * is known as the {@linkplain #lookupClass() lookup class}. 492 * <p> 493 * A lookup class which needs to create method handles will call 494 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 495 * When the {@code Lookup} factory object is created, the identity of the lookup class is 496 * determined, and securely stored in the {@code Lookup} object. 497 * The lookup class (or its delegates) may then use factory methods 498 * on the {@code Lookup} object to create method handles for access-checked members. 499 * This includes all methods, constructors, and fields which are allowed to the lookup class, 500 * even private ones. 501 * 502 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 503 * The factory methods on a {@code Lookup} object correspond to all major 504 * use cases for methods, constructors, and fields. 505 * Each method handle created by a factory method is the functional 506 * equivalent of a particular <em>bytecode behavior</em>. 507 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 508 * the Java Virtual Machine Specification.) 509 * Here is a summary of the correspondence between these factory methods and 510 * the behavior of the resulting method handles: 511 * <table class="striped"> 512 * <caption style="display:none">lookup method behaviors</caption> 513 * <thead> 514 * <tr> 515 * <th scope="col"><a id="equiv"></a>lookup expression</th> 516 * <th scope="col">member</th> 517 * <th scope="col">bytecode behavior</th> 518 * </tr> 519 * </thead> 520 * <tbody> 521 * <tr> 522 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 523 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 524 * </tr> 525 * <tr> 526 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 527 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 528 * </tr> 529 * <tr> 530 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 531 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 532 * </tr> 533 * <tr> 534 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 535 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 536 * </tr> 537 * <tr> 538 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 539 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 540 * </tr> 541 * <tr> 542 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 543 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 544 * </tr> 545 * <tr> 546 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 547 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 548 * </tr> 549 * <tr> 550 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 551 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 552 * </tr> 553 * <tr> 554 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 555 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 556 * </tr> 557 * <tr> 558 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 559 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 560 * </tr> 561 * <tr> 562 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 563 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 564 * </tr> 565 * <tr> 566 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 567 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 568 * </tr> 569 * <tr> 570 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 571 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 572 * </tr> 573 * <tr> 574 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 575 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 576 * </tr> 577 * </tbody> 578 * </table> 579 * 580 * Here, the type {@code C} is the class or interface being searched for a member, 581 * documented as a parameter named {@code refc} in the lookup methods. 582 * The method type {@code MT} is composed from the return type {@code T} 583 * and the sequence of argument types {@code A*}. 584 * The constructor also has a sequence of argument types {@code A*} and 585 * is deemed to return the newly-created object of type {@code C}. 586 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 587 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 588 * if it is present, it is always the leading argument to the method handle invocation. 589 * (In the case of some {@code protected} members, {@code this} may be 590 * restricted in type to the lookup class; see below.) 591 * The name {@code arg} stands for all the other method handle arguments. 592 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 593 * stands for a null reference if the accessed method or field is static, 594 * and {@code this} otherwise. 595 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 596 * for reflective objects corresponding to the given members declared in type {@code C}. 597 * <p> 598 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 599 * as if by {@code ldc CONSTANT_Class}. 600 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 601 * <p> 602 * In cases where the given member is of variable arity (i.e., a method or constructor) 603 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 604 * In all other cases, the returned method handle will be of fixed arity. 605 * <p style="font-size:smaller;"> 606 * <em>Discussion:</em> 607 * The equivalence between looked-up method handles and underlying 608 * class members and bytecode behaviors 609 * can break down in a few ways: 610 * <ul style="font-size:smaller;"> 611 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 612 * the lookup can still succeed, even when there is no equivalent 613 * Java expression or bytecoded constant. 614 * <li>Likewise, if {@code T} or {@code MT} 615 * is not symbolically accessible from the lookup class's loader, 616 * the lookup can still succeed. 617 * For example, lookups for {@code MethodHandle.invokeExact} and 618 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 619 * <li>If there is a security manager installed, it can forbid the lookup 620 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 621 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 622 * constant is not subject to security manager checks. 623 * <li>If the looked-up method has a 624 * <a href="MethodHandle.html#maxarity">very large arity</a>, 625 * the method handle creation may fail with an 626 * {@code IllegalArgumentException}, due to the method handle type having 627 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 628 * </ul> 629 * 630 * <h2><a id="access"></a>Access checking</h2> 631 * Access checks are applied in the factory methods of {@code Lookup}, 632 * when a method handle is created. 633 * This is a key difference from the Core Reflection API, since 634 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 635 * performs access checking against every caller, on every call. 636 * <p> 637 * All access checks start from a {@code Lookup} object, which 638 * compares its recorded lookup class against all requests to 639 * create method handles. 640 * A single {@code Lookup} object can be used to create any number 641 * of access-checked method handles, all checked against a single 642 * lookup class. 643 * <p> 644 * A {@code Lookup} object can be shared with other trusted code, 645 * such as a metaobject protocol. 646 * A shared {@code Lookup} object delegates the capability 647 * to create method handles on private members of the lookup class. 648 * Even if privileged code uses the {@code Lookup} object, 649 * the access checking is confined to the privileges of the 650 * original lookup class. 651 * <p> 652 * A lookup can fail, because 653 * the containing class is not accessible to the lookup class, or 654 * because the desired class member is missing, or because the 655 * desired class member is not accessible to the lookup class, or 656 * because the lookup object is not trusted enough to access the member. 657 * In the case of a field setter function on a {@code final} field, 658 * finality enforcement is treated as a kind of access control, 659 * and the lookup will fail, except in special cases of 660 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 661 * In any of these cases, a {@code ReflectiveOperationException} will be 662 * thrown from the attempted lookup. The exact class will be one of 663 * the following: 664 * <ul> 665 * <li>NoSuchMethodException — if a method is requested but does not exist 666 * <li>NoSuchFieldException — if a field is requested but does not exist 667 * <li>IllegalAccessException — if the member exists but an access check fails 668 * </ul> 669 * <p> 670 * In general, the conditions under which a method handle may be 671 * looked up for a method {@code M} are no more restrictive than the conditions 672 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 673 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 674 * a method handle lookup will generally raise a corresponding 675 * checked exception, such as {@code NoSuchMethodException}. 676 * And the effect of invoking the method handle resulting from the lookup 677 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 678 * to executing the compiled, verified, and resolved call to {@code M}. 679 * The same point is true of fields and constructors. 680 * <p style="font-size:smaller;"> 681 * <em>Discussion:</em> 682 * Access checks only apply to named and reflected methods, 683 * constructors, and fields. 684 * Other method handle creation methods, such as 685 * {@link MethodHandle#asType MethodHandle.asType}, 686 * do not require any access checks, and are used 687 * independently of any {@code Lookup} object. 688 * <p> 689 * If the desired member is {@code protected}, the usual JVM rules apply, 690 * including the requirement that the lookup class must either be in the 691 * same package as the desired member, or must inherit that member. 692 * (See the Java Virtual Machine Specification, sections {@jvms 693 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 694 * In addition, if the desired member is a non-static field or method 695 * in a different package, the resulting method handle may only be applied 696 * to objects of the lookup class or one of its subclasses. 697 * This requirement is enforced by narrowing the type of the leading 698 * {@code this} parameter from {@code C} 699 * (which will necessarily be a superclass of the lookup class) 700 * to the lookup class itself. 701 * <p> 702 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 703 * that the receiver argument must match both the resolved method <em>and</em> 704 * the current class. Again, this requirement is enforced by narrowing the 705 * type of the leading parameter to the resulting method handle. 706 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 707 * <p> 708 * The JVM represents constructors and static initializer blocks as internal methods 709 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 710 * ConstantDescs#CLASS_INIT_NAME}). 711 * The internal syntax of invocation instructions allows them to refer to such internal 712 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 713 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 714 * <p> 715 * If the relationship between nested types is expressed directly through the 716 * {@code NestHost} and {@code NestMembers} attributes 717 * (see the Java Virtual Machine Specification, sections {@jvms 718 * 4.7.28} and {@jvms 4.7.29}), 719 * then the associated {@code Lookup} object provides direct access to 720 * the lookup class and all of its nestmates 721 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 722 * Otherwise, access between nested classes is obtained by the Java compiler creating 723 * a wrapper method to access a private method of another class in the same nest. 724 * For example, a nested class {@code C.D} 725 * can access private members within other related classes such as 726 * {@code C}, {@code C.D.E}, or {@code C.B}, 727 * but the Java compiler may need to generate wrapper methods in 728 * those related classes. In such cases, a {@code Lookup} object on 729 * {@code C.E} would be unable to access those private members. 730 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 731 * which can transform a lookup on {@code C.E} into one on any of those other 732 * classes, without special elevation of privilege. 733 * <p> 734 * The accesses permitted to a given lookup object may be limited, 735 * according to its set of {@link #lookupModes lookupModes}, 736 * to a subset of members normally accessible to the lookup class. 737 * For example, the {@link MethodHandles#publicLookup publicLookup} 738 * method produces a lookup object which is only allowed to access 739 * public members in public classes of exported packages. 740 * The caller sensitive method {@link MethodHandles#lookup lookup} 741 * produces a lookup object with full capabilities relative to 742 * its caller class, to emulate all supported bytecode behaviors. 743 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 744 * with fewer access modes than the original lookup object. 745 * 746 * <p style="font-size:smaller;"> 747 * <a id="privacc"></a> 748 * <em>Discussion of private and module access:</em> 749 * We say that a lookup has <em>private access</em> 750 * if its {@linkplain #lookupModes lookup modes} 751 * include the possibility of accessing {@code private} members 752 * (which includes the private members of nestmates). 753 * As documented in the relevant methods elsewhere, 754 * only lookups with private access possess the following capabilities: 755 * <ul style="font-size:smaller;"> 756 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 757 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 758 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 759 * for classes accessible to the lookup class 760 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 761 * within the same package member 762 * </ul> 763 * <p style="font-size:smaller;"> 764 * Similarly, a lookup with module access ensures that the original lookup creator was 765 * a member in the same module as the lookup class. 766 * <p style="font-size:smaller;"> 767 * Private and module access are independently determined modes; a lookup may have 768 * either or both or neither. A lookup which possesses both access modes is said to 769 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 770 * <p style="font-size:smaller;"> 771 * A lookup with <em>original access</em> ensures that this lookup is created by 772 * the original lookup class and the bootstrap method invoked by the VM. 773 * Such a lookup with original access also has private and module access 774 * which has the following additional capability: 775 * <ul style="font-size:smaller;"> 776 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 777 * such as {@code Class.forName} 778 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 779 * class data} associated with the lookup class</li> 780 * </ul> 781 * <p style="font-size:smaller;"> 782 * Each of these permissions is a consequence of the fact that a lookup object 783 * with private access can be securely traced back to an originating class, 784 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 785 * can be reliably determined and emulated by method handles. 786 * 787 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 788 * When a lookup class in one module {@code M1} accesses a class in another module 789 * {@code M2}, extra access checking is performed beyond the access mode bits. 790 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 791 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 792 * and when the type is in a package of {@code M2} that is exported to 793 * at least {@code M1}. 794 * <p> 795 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 796 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 797 * MethodHandles.privateLookupIn} methods. 798 * Teleporting across modules will always record the original lookup class as 799 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 800 * and drops {@link Lookup#MODULE MODULE} access. 801 * If the target class is in the same module as the lookup class {@code C}, 802 * then the target class becomes the new lookup class 803 * and there is no change to the previous lookup class. 804 * If the target class is in a different module from {@code M1} ({@code C}'s module), 805 * {@code C} becomes the new previous lookup class 806 * and the target class becomes the new lookup class. 807 * In that case, if there was already a previous lookup class in {@code M0}, 808 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 809 * drops all privileges. 810 * For example, 811 * {@snippet lang="java" : 812 * Lookup lookup = MethodHandles.lookup(); // in class C 813 * Lookup lookup2 = lookup.in(D.class); 814 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 815 * } 816 * <p> 817 * The {@link #lookup()} factory method produces a {@code Lookup} object 818 * with {@code null} previous lookup class. 819 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 820 * to class {@code D} without elevation of privileges. 821 * If {@code C} and {@code D} are in the same module, 822 * {@code lookup2} records {@code D} as the new lookup class and keeps the 823 * same previous lookup class as the original {@code lookup}, or 824 * {@code null} if not present. 825 * <p> 826 * When a {@code Lookup} teleports from a class 827 * in one nest to another nest, {@code PRIVATE} access is dropped. 828 * When a {@code Lookup} teleports from a class in one package to 829 * another package, {@code PACKAGE} access is dropped. 830 * When a {@code Lookup} teleports from a class in one module to another module, 831 * {@code MODULE} access is dropped. 832 * Teleporting across modules drops the ability to access non-exported classes 833 * in both the module of the new lookup class and the module of the old lookup class 834 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 835 * A {@code Lookup} can teleport back and forth to a class in the module of 836 * the lookup class and the module of the previous class lookup. 837 * Teleporting across modules can only decrease access but cannot increase it. 838 * Teleporting to some third module drops all accesses. 839 * <p> 840 * In the above example, if {@code C} and {@code D} are in different modules, 841 * {@code lookup2} records {@code D} as its lookup class and 842 * {@code C} as its previous lookup class and {@code lookup2} has only 843 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 844 * {@code C}'s module and {@code D}'s module. 845 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 846 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 847 * class {@code D} is recorded as its previous lookup class. 848 * <p> 849 * Teleporting across modules restricts access to the public types that 850 * both the lookup class and the previous lookup class can equally access 851 * (see below). 852 * <p> 853 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 854 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 855 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 856 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 857 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 858 * to call {@code privateLookupIn}. 859 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 860 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 861 * produces a new {@code Lookup} on {@code T} with full capabilities. 862 * A {@code lookup} on {@code C} is also allowed 863 * to do deep reflection on {@code T} in another module {@code M2} if 864 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 865 * the package containing {@code T} to at least {@code M1}. 866 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 867 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 868 * The resulting {@code Lookup} can be used to do member lookup or teleport 869 * to another lookup class by calling {@link #in Lookup::in}. But 870 * it cannot be used to obtain another private {@code Lookup} by calling 871 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 872 * because it has no {@code MODULE} access. 873 * <p> 874 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 875 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 876 * of {@code T}. Extreme caution should be taken when opening a package 877 * to another module as such defined classes have the same full privilege 878 * access as other members in {@code M2}. 879 * 880 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 881 * 882 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 883 * allows cross-module access. The access checking is performed with respect 884 * to both the lookup class and the previous lookup class if present. 885 * <p> 886 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 887 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 888 * exported unconditionally}. 889 * <p> 890 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 891 * the lookup with {@link #PUBLIC} mode can access all public types in modules 892 * that are readable to {@code M1} and the type is in a package that is exported 893 * at least to {@code M1}. 894 * <p> 895 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 896 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 897 * the intersection of all public types that are accessible to {@code M1} 898 * with all public types that are accessible to {@code M0}. {@code M0} 899 * reads {@code M1} and hence the set of accessible types includes: 900 * 901 * <ul> 902 * <li>unconditional-exported packages from {@code M1}</li> 903 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 904 * <li> 905 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 906 * and {@code M1} read {@code M2} 907 * </li> 908 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 909 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 910 * <li> 911 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 912 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 913 * </li> 914 * </ul> 915 * 916 * <h2><a id="access-modes"></a>Access modes</h2> 917 * 918 * The table below shows the access modes of a {@code Lookup} produced by 919 * any of the following factory or transformation methods: 920 * <ul> 921 * <li>{@link #lookup() MethodHandles::lookup}</li> 922 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 923 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 924 * <li>{@link Lookup#in Lookup::in}</li> 925 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 926 * </ul> 927 * 928 * <table class="striped"> 929 * <caption style="display:none"> 930 * Access mode summary 931 * </caption> 932 * <thead> 933 * <tr> 934 * <th scope="col">Lookup object</th> 935 * <th style="text-align:center">original</th> 936 * <th style="text-align:center">protected</th> 937 * <th style="text-align:center">private</th> 938 * <th style="text-align:center">package</th> 939 * <th style="text-align:center">module</th> 940 * <th style="text-align:center">public</th> 941 * </tr> 942 * </thead> 943 * <tbody> 944 * <tr> 945 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 946 * <td style="text-align:center">ORI</td> 947 * <td style="text-align:center">PRO</td> 948 * <td style="text-align:center">PRI</td> 949 * <td style="text-align:center">PAC</td> 950 * <td style="text-align:center">MOD</td> 951 * <td style="text-align:center">1R</td> 952 * </tr> 953 * <tr> 954 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 955 * <td></td> 956 * <td></td> 957 * <td></td> 958 * <td style="text-align:center">PAC</td> 959 * <td style="text-align:center">MOD</td> 960 * <td style="text-align:center">1R</td> 961 * </tr> 962 * <tr> 963 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 964 * <td></td> 965 * <td></td> 966 * <td></td> 967 * <td></td> 968 * <td style="text-align:center">MOD</td> 969 * <td style="text-align:center">1R</td> 970 * </tr> 971 * <tr> 972 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 973 * <td></td> 974 * <td></td> 975 * <td></td> 976 * <td></td> 977 * <td></td> 978 * <td style="text-align:center">2R</td> 979 * </tr> 980 * <tr> 981 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 982 * <td></td> 983 * <td></td> 984 * <td></td> 985 * <td></td> 986 * <td></td> 987 * <td style="text-align:center">2R</td> 988 * </tr> 989 * <tr> 990 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 991 * <td></td> 992 * <td style="text-align:center">PRO</td> 993 * <td style="text-align:center">PRI</td> 994 * <td style="text-align:center">PAC</td> 995 * <td style="text-align:center">MOD</td> 996 * <td style="text-align:center">1R</td> 997 * </tr> 998 * <tr> 999 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 1000 * <td></td> 1001 * <td style="text-align:center">PRO</td> 1002 * <td style="text-align:center">PRI</td> 1003 * <td style="text-align:center">PAC</td> 1004 * <td style="text-align:center">MOD</td> 1005 * <td style="text-align:center">1R</td> 1006 * </tr> 1007 * <tr> 1008 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1009 * <td></td> 1010 * <td></td> 1011 * <td></td> 1012 * <td style="text-align:center">PAC</td> 1013 * <td style="text-align:center">MOD</td> 1014 * <td style="text-align:center">1R</td> 1015 * </tr> 1016 * <tr> 1017 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1018 * <td></td> 1019 * <td></td> 1020 * <td></td> 1021 * <td></td> 1022 * <td style="text-align:center">MOD</td> 1023 * <td style="text-align:center">1R</td> 1024 * </tr> 1025 * <tr> 1026 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1027 * <td></td> 1028 * <td></td> 1029 * <td></td> 1030 * <td></td> 1031 * <td></td> 1032 * <td style="text-align:center">2R</td> 1033 * </tr> 1034 * <tr> 1035 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1036 * <td></td> 1037 * <td></td> 1038 * <td style="text-align:center">PRI</td> 1039 * <td style="text-align:center">PAC</td> 1040 * <td style="text-align:center">MOD</td> 1041 * <td style="text-align:center">1R</td> 1042 * </tr> 1043 * <tr> 1044 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1045 * <td></td> 1046 * <td></td> 1047 * <td></td> 1048 * <td style="text-align:center">PAC</td> 1049 * <td style="text-align:center">MOD</td> 1050 * <td style="text-align:center">1R</td> 1051 * </tr> 1052 * <tr> 1053 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1054 * <td></td> 1055 * <td></td> 1056 * <td></td> 1057 * <td></td> 1058 * <td style="text-align:center">MOD</td> 1059 * <td style="text-align:center">1R</td> 1060 * </tr> 1061 * <tr> 1062 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1063 * <td></td> 1064 * <td></td> 1065 * <td></td> 1066 * <td></td> 1067 * <td></td> 1068 * <td style="text-align:center">1R</td> 1069 * </tr> 1070 * <tr> 1071 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1072 * <td></td> 1073 * <td></td> 1074 * <td></td> 1075 * <td></td> 1076 * <td></td> 1077 * <td style="text-align:center">none</td> 1078 * <tr> 1079 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1080 * <td></td> 1081 * <td style="text-align:center">PRO</td> 1082 * <td style="text-align:center">PRI</td> 1083 * <td style="text-align:center">PAC</td> 1084 * <td></td> 1085 * <td style="text-align:center">2R</td> 1086 * </tr> 1087 * <tr> 1088 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1089 * <td></td> 1090 * <td style="text-align:center">PRO</td> 1091 * <td style="text-align:center">PRI</td> 1092 * <td style="text-align:center">PAC</td> 1093 * <td></td> 1094 * <td style="text-align:center">2R</td> 1095 * </tr> 1096 * <tr> 1097 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1098 * <td></td> 1099 * <td></td> 1100 * <td></td> 1101 * <td></td> 1102 * <td></td> 1103 * <td style="text-align:center">IAE</td> 1104 * </tr> 1105 * <tr> 1106 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1107 * <td></td> 1108 * <td></td> 1109 * <td></td> 1110 * <td style="text-align:center">PAC</td> 1111 * <td></td> 1112 * <td style="text-align:center">2R</td> 1113 * </tr> 1114 * <tr> 1115 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1116 * <td></td> 1117 * <td></td> 1118 * <td></td> 1119 * <td></td> 1120 * <td></td> 1121 * <td style="text-align:center">2R</td> 1122 * </tr> 1123 * <tr> 1124 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1125 * <td></td> 1126 * <td></td> 1127 * <td></td> 1128 * <td></td> 1129 * <td></td> 1130 * <td style="text-align:center">2R</td> 1131 * </tr> 1132 * <tr> 1133 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1134 * <td></td> 1135 * <td></td> 1136 * <td></td> 1137 * <td></td> 1138 * <td></td> 1139 * <td style="text-align:center">none</td> 1140 * </tr> 1141 * <tr> 1142 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1143 * <td></td> 1144 * <td></td> 1145 * <td style="text-align:center">PRI</td> 1146 * <td style="text-align:center">PAC</td> 1147 * <td></td> 1148 * <td style="text-align:center">2R</td> 1149 * </tr> 1150 * <tr> 1151 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1152 * <td></td> 1153 * <td></td> 1154 * <td></td> 1155 * <td style="text-align:center">PAC</td> 1156 * <td></td> 1157 * <td style="text-align:center">2R</td> 1158 * </tr> 1159 * <tr> 1160 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1161 * <td></td> 1162 * <td></td> 1163 * <td></td> 1164 * <td></td> 1165 * <td></td> 1166 * <td style="text-align:center">2R</td> 1167 * </tr> 1168 * <tr> 1169 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1170 * <td></td> 1171 * <td></td> 1172 * <td></td> 1173 * <td></td> 1174 * <td></td> 1175 * <td style="text-align:center">2R</td> 1176 * </tr> 1177 * <tr> 1178 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1179 * <td></td> 1180 * <td></td> 1181 * <td></td> 1182 * <td></td> 1183 * <td></td> 1184 * <td style="text-align:center">none</td> 1185 * </tr> 1186 * <tr> 1187 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1188 * <td></td> 1189 * <td></td> 1190 * <td style="text-align:center">PRI</td> 1191 * <td style="text-align:center">PAC</td> 1192 * <td style="text-align:center">MOD</td> 1193 * <td style="text-align:center">1R</td> 1194 * </tr> 1195 * <tr> 1196 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1197 * <td></td> 1198 * <td></td> 1199 * <td></td> 1200 * <td style="text-align:center">PAC</td> 1201 * <td style="text-align:center">MOD</td> 1202 * <td style="text-align:center">1R</td> 1203 * </tr> 1204 * <tr> 1205 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1206 * <td></td> 1207 * <td></td> 1208 * <td></td> 1209 * <td></td> 1210 * <td style="text-align:center">MOD</td> 1211 * <td style="text-align:center">1R</td> 1212 * </tr> 1213 * <tr> 1214 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1215 * <td></td> 1216 * <td></td> 1217 * <td></td> 1218 * <td></td> 1219 * <td></td> 1220 * <td style="text-align:center">1R</td> 1221 * </tr> 1222 * <tr> 1223 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1224 * <td></td> 1225 * <td></td> 1226 * <td></td> 1227 * <td></td> 1228 * <td></td> 1229 * <td style="text-align:center">none</td> 1230 * </tr> 1231 * <tr> 1232 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1233 * <td></td> 1234 * <td></td> 1235 * <td></td> 1236 * <td></td> 1237 * <td></td> 1238 * <td style="text-align:center">U</td> 1239 * </tr> 1240 * <tr> 1241 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1242 * <td></td> 1243 * <td></td> 1244 * <td></td> 1245 * <td></td> 1246 * <td></td> 1247 * <td style="text-align:center">U</td> 1248 * </tr> 1249 * <tr> 1250 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1251 * <td></td> 1252 * <td></td> 1253 * <td></td> 1254 * <td></td> 1255 * <td></td> 1256 * <td style="text-align:center">U</td> 1257 * </tr> 1258 * <tr> 1259 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1260 * <td></td> 1261 * <td></td> 1262 * <td></td> 1263 * <td></td> 1264 * <td></td> 1265 * <td style="text-align:center">none</td> 1266 * </tr> 1267 * <tr> 1268 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1269 * <td></td> 1270 * <td></td> 1271 * <td></td> 1272 * <td></td> 1273 * <td></td> 1274 * <td style="text-align:center">IAE</td> 1275 * </tr> 1276 * <tr> 1277 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1278 * <td></td> 1279 * <td></td> 1280 * <td></td> 1281 * <td></td> 1282 * <td></td> 1283 * <td style="text-align:center">none</td> 1284 * </tr> 1285 * </tbody> 1286 * </table> 1287 * 1288 * <p> 1289 * Notes: 1290 * <ul> 1291 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1292 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1293 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1294 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1295 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1296 * {@code PRO} indicates {@link #PROTECTED} bit set, 1297 * {@code PRI} indicates {@link #PRIVATE} bit set, 1298 * {@code PAC} indicates {@link #PACKAGE} bit set, 1299 * {@code MOD} indicates {@link #MODULE} bit set, 1300 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1301 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1302 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1303 * <li>Public access comes in three kinds: 1304 * <ul> 1305 * <li>unconditional ({@code U}): the lookup assumes readability. 1306 * The lookup has {@code null} previous lookup class. 1307 * <li>one-module-reads ({@code 1R}): the module access checking is 1308 * performed with respect to the lookup class. The lookup has {@code null} 1309 * previous lookup class. 1310 * <li>two-module-reads ({@code 2R}): the module access checking is 1311 * performed with respect to the lookup class and the previous lookup class. 1312 * The lookup has a non-null previous lookup class which is in a 1313 * different module from the current lookup class. 1314 * </ul> 1315 * <li>Any attempt to reach a third module loses all access.</li> 1316 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1317 * all access modes are dropped.</li> 1318 * </ul> 1319 * 1320 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1321 * Although bytecode instructions can only refer to classes in 1322 * a related class loader, this API can search for methods in any 1323 * class, as long as a reference to its {@code Class} object is 1324 * available. Such cross-loader references are also possible with the 1325 * Core Reflection API, and are impossible to bytecode instructions 1326 * such as {@code invokestatic} or {@code getfield}. 1327 * There is a {@linkplain java.lang.SecurityManager security manager API} 1328 * to allow applications to check such cross-loader references. 1329 * These checks apply to both the {@code MethodHandles.Lookup} API 1330 * and the Core Reflection API 1331 * (as found on {@link java.lang.Class Class}). 1332 * <p> 1333 * If a security manager is present, member and class lookups are subject to 1334 * additional checks. 1335 * From one to three calls are made to the security manager. 1336 * Any of these calls can refuse access by throwing a 1337 * {@link java.lang.SecurityException SecurityException}. 1338 * Define {@code smgr} as the security manager, 1339 * {@code lookc} as the lookup class of the current lookup object, 1340 * {@code refc} as the containing class in which the member 1341 * is being sought, and {@code defc} as the class in which the 1342 * member is actually defined. 1343 * (If a class or other type is being accessed, 1344 * the {@code refc} and {@code defc} values are the class itself.) 1345 * The value {@code lookc} is defined as <em>not present</em> 1346 * if the current lookup object does not have 1347 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1348 * The calls are made according to the following rules: 1349 * <ul> 1350 * <li><b>Step 1:</b> 1351 * If {@code lookc} is not present, or if its class loader is not 1352 * the same as or an ancestor of the class loader of {@code refc}, 1353 * then {@link SecurityManager#checkPackageAccess 1354 * smgr.checkPackageAccess(refcPkg)} is called, 1355 * where {@code refcPkg} is the package of {@code refc}. 1356 * <li><b>Step 2a:</b> 1357 * If the retrieved member is not public and 1358 * {@code lookc} is not present, then 1359 * {@link SecurityManager#checkPermission smgr.checkPermission} 1360 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1361 * <li><b>Step 2b:</b> 1362 * If the retrieved class has a {@code null} class loader, 1363 * and {@code lookc} is not present, then 1364 * {@link SecurityManager#checkPermission smgr.checkPermission} 1365 * with {@code RuntimePermission("getClassLoader")} is called. 1366 * <li><b>Step 3:</b> 1367 * If the retrieved member is not public, 1368 * and if {@code lookc} is not present, 1369 * and if {@code defc} and {@code refc} are different, 1370 * then {@link SecurityManager#checkPackageAccess 1371 * smgr.checkPackageAccess(defcPkg)} is called, 1372 * where {@code defcPkg} is the package of {@code defc}. 1373 * </ul> 1374 * Security checks are performed after other access checks have passed. 1375 * Therefore, the above rules presuppose a member or class that is public, 1376 * or else that is being accessed from a lookup class that has 1377 * rights to access the member or class. 1378 * <p> 1379 * If a security manager is present and the current lookup object does not have 1380 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1381 * {@link #defineClass(byte[]) defineClass}, 1382 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1383 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1384 * defineHiddenClassWithClassData} 1385 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1386 * with {@code RuntimePermission("defineClass")}. 1387 * 1388 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1389 * A small number of Java methods have a special property called caller sensitivity. 1390 * A <em>caller-sensitive</em> method can behave differently depending on the 1391 * identity of its immediate caller. 1392 * <p> 1393 * If a method handle for a caller-sensitive method is requested, 1394 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1395 * but they take account of the lookup class in a special way. 1396 * The resulting method handle behaves as if it were called 1397 * from an instruction contained in the lookup class, 1398 * so that the caller-sensitive method detects the lookup class. 1399 * (By contrast, the invoker of the method handle is disregarded.) 1400 * Thus, in the case of caller-sensitive methods, 1401 * different lookup classes may give rise to 1402 * differently behaving method handles. 1403 * <p> 1404 * In cases where the lookup object is 1405 * {@link MethodHandles#publicLookup() publicLookup()}, 1406 * or some other lookup object without the 1407 * {@linkplain #ORIGINAL original access}, 1408 * the lookup class is disregarded. 1409 * In such cases, no caller-sensitive method handle can be created, 1410 * access is forbidden, and the lookup fails with an 1411 * {@code IllegalAccessException}. 1412 * <p style="font-size:smaller;"> 1413 * <em>Discussion:</em> 1414 * For example, the caller-sensitive method 1415 * {@link java.lang.Class#forName(String) Class.forName(x)} 1416 * can return varying classes or throw varying exceptions, 1417 * depending on the class loader of the class that calls it. 1418 * A public lookup of {@code Class.forName} will fail, because 1419 * there is no reasonable way to determine its bytecode behavior. 1420 * <p style="font-size:smaller;"> 1421 * If an application caches method handles for broad sharing, 1422 * it should use {@code publicLookup()} to create them. 1423 * If there is a lookup of {@code Class.forName}, it will fail, 1424 * and the application must take appropriate action in that case. 1425 * It may be that a later lookup, perhaps during the invocation of a 1426 * bootstrap method, can incorporate the specific identity 1427 * of the caller, making the method accessible. 1428 * <p style="font-size:smaller;"> 1429 * The function {@code MethodHandles.lookup} is caller sensitive 1430 * so that there can be a secure foundation for lookups. 1431 * Nearly all other methods in the JSR 292 API rely on lookup 1432 * objects to check access requests. 1433 */ 1434 public static final 1435 class Lookup { 1436 /** The class on behalf of whom the lookup is being performed. */ 1437 private final Class<?> lookupClass; 1438 1439 /** previous lookup class */ 1440 private final Class<?> prevLookupClass; 1441 1442 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1443 private final int allowedModes; 1444 1445 static { 1446 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1447 } 1448 1449 /** A single-bit mask representing {@code public} access, 1450 * which may contribute to the result of {@link #lookupModes lookupModes}. 1451 * The value, {@code 0x01}, happens to be the same as the value of the 1452 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1453 * <p> 1454 * A {@code Lookup} with this lookup mode performs cross-module access check 1455 * with respect to the {@linkplain #lookupClass() lookup class} and 1456 * {@linkplain #previousLookupClass() previous lookup class} if present. 1457 */ 1458 public static final int PUBLIC = Modifier.PUBLIC; 1459 1460 /** A single-bit mask representing {@code private} access, 1461 * which may contribute to the result of {@link #lookupModes lookupModes}. 1462 * The value, {@code 0x02}, happens to be the same as the value of the 1463 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1464 */ 1465 public static final int PRIVATE = Modifier.PRIVATE; 1466 1467 /** A single-bit mask representing {@code protected} access, 1468 * which may contribute to the result of {@link #lookupModes lookupModes}. 1469 * The value, {@code 0x04}, happens to be the same as the value of the 1470 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1471 */ 1472 public static final int PROTECTED = Modifier.PROTECTED; 1473 1474 /** A single-bit mask representing {@code package} access (default access), 1475 * which may contribute to the result of {@link #lookupModes lookupModes}. 1476 * The value is {@code 0x08}, which does not correspond meaningfully to 1477 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1478 */ 1479 public static final int PACKAGE = Modifier.STATIC; 1480 1481 /** A single-bit mask representing {@code module} access, 1482 * which may contribute to the result of {@link #lookupModes lookupModes}. 1483 * The value is {@code 0x10}, which does not correspond meaningfully to 1484 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1485 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1486 * with this lookup mode can access all public types in the module of the 1487 * lookup class and public types in packages exported by other modules 1488 * to the module of the lookup class. 1489 * <p> 1490 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1491 * previous lookup class} is always {@code null}. 1492 * 1493 * @since 9 1494 */ 1495 public static final int MODULE = PACKAGE << 1; 1496 1497 /** A single-bit mask representing {@code unconditional} access 1498 * which may contribute to the result of {@link #lookupModes lookupModes}. 1499 * The value is {@code 0x20}, which does not correspond meaningfully to 1500 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1501 * A {@code Lookup} with this lookup mode assumes {@linkplain 1502 * java.lang.Module#canRead(java.lang.Module) readability}. 1503 * This lookup mode can access all public members of public types 1504 * of all modules when the type is in a package that is {@link 1505 * java.lang.Module#isExported(String) exported unconditionally}. 1506 * 1507 * <p> 1508 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1509 * previous lookup class} is always {@code null}. 1510 * 1511 * @since 9 1512 * @see #publicLookup() 1513 */ 1514 public static final int UNCONDITIONAL = PACKAGE << 2; 1515 1516 /** A single-bit mask representing {@code original} access 1517 * which may contribute to the result of {@link #lookupModes lookupModes}. 1518 * The value is {@code 0x40}, which does not correspond meaningfully to 1519 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1520 * 1521 * <p> 1522 * If this lookup mode is set, the {@code Lookup} object must be 1523 * created by the original lookup class by calling 1524 * {@link MethodHandles#lookup()} method or by a bootstrap method 1525 * invoked by the VM. The {@code Lookup} object with this lookup 1526 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1527 * 1528 * @since 16 1529 */ 1530 public static final int ORIGINAL = PACKAGE << 3; 1531 1532 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1533 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1534 private static final int TRUSTED = -1; 1535 1536 /* 1537 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1538 * Adjust 0 => PACKAGE 1539 */ 1540 private static int fixmods(int mods) { 1541 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1542 if (Modifier.isPublic(mods)) 1543 mods |= UNCONDITIONAL; 1544 return (mods != 0) ? mods : PACKAGE; 1545 } 1546 1547 /** Tells which class is performing the lookup. It is this class against 1548 * which checks are performed for visibility and access permissions. 1549 * <p> 1550 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1551 * access checks are performed against both the lookup class and the previous lookup class. 1552 * <p> 1553 * The class implies a maximum level of access permission, 1554 * but the permissions may be additionally limited by the bitmask 1555 * {@link #lookupModes lookupModes}, which controls whether non-public members 1556 * can be accessed. 1557 * @return the lookup class, on behalf of which this lookup object finds members 1558 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1559 */ 1560 public Class<?> lookupClass() { 1561 return lookupClass; 1562 } 1563 1564 /** Reports a lookup class in another module that this lookup object 1565 * was previously teleported from, or {@code null}. 1566 * <p> 1567 * A {@code Lookup} object produced by the factory methods, such as the 1568 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1569 * has {@code null} previous lookup class. 1570 * A {@code Lookup} object has a non-null previous lookup class 1571 * when this lookup was teleported from an old lookup class 1572 * in one module to a new lookup class in another module. 1573 * 1574 * @return the lookup class in another module that this lookup object was 1575 * previously teleported from, or {@code null} 1576 * @since 14 1577 * @see #in(Class) 1578 * @see MethodHandles#privateLookupIn(Class, Lookup) 1579 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1580 */ 1581 public Class<?> previousLookupClass() { 1582 return prevLookupClass; 1583 } 1584 1585 // This is just for calling out to MethodHandleImpl. 1586 private Class<?> lookupClassOrNull() { 1587 return (allowedModes == TRUSTED) ? null : lookupClass; 1588 } 1589 1590 /** Tells which access-protection classes of members this lookup object can produce. 1591 * The result is a bit-mask of the bits 1592 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1593 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1594 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1595 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1596 * {@linkplain #MODULE MODULE (0x10)}, 1597 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1598 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1599 * <p> 1600 * A freshly-created lookup object 1601 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1602 * all possible bits set, except {@code UNCONDITIONAL}. 1603 * A lookup object on a new lookup class 1604 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1605 * may have some mode bits set to zero. 1606 * Mode bits can also be 1607 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1608 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1609 * The purpose of this is to restrict access via the new lookup object, 1610 * so that it can access only names which can be reached by the original 1611 * lookup object, and also by the new lookup class. 1612 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1613 * @see #in 1614 * @see #dropLookupMode 1615 */ 1616 public int lookupModes() { 1617 return allowedModes & ALL_MODES; 1618 } 1619 1620 /** Embody the current class (the lookupClass) as a lookup class 1621 * for method handle creation. 1622 * Must be called by from a method in this package, 1623 * which in turn is called by a method not in this package. 1624 */ 1625 Lookup(Class<?> lookupClass) { 1626 this(lookupClass, null, FULL_POWER_MODES); 1627 } 1628 1629 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1630 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1631 && prevLookupClass.getModule() != lookupClass.getModule()); 1632 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1633 this.lookupClass = lookupClass; 1634 this.prevLookupClass = prevLookupClass; 1635 this.allowedModes = allowedModes; 1636 } 1637 1638 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1639 // make sure we haven't accidentally picked up a privileged class: 1640 checkUnprivilegedlookupClass(lookupClass); 1641 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1642 } 1643 1644 /** 1645 * Creates a lookup on the specified new lookup class. 1646 * The resulting object will report the specified 1647 * class as its own {@link #lookupClass() lookupClass}. 1648 * 1649 * <p> 1650 * However, the resulting {@code Lookup} object is guaranteed 1651 * to have no more access capabilities than the original. 1652 * In particular, access capabilities can be lost as follows:<ul> 1653 * <li>If the new lookup class is different from the old lookup class, 1654 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1655 * <li>If the new lookup class is in a different module from the old one, 1656 * i.e. {@link #MODULE MODULE} access is lost. 1657 * <li>If the new lookup class is in a different package 1658 * than the old one, protected and default (package) members will not be accessible, 1659 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1660 * <li>If the new lookup class is not within the same package member 1661 * as the old one, private members will not be accessible, and protected members 1662 * will not be accessible by virtue of inheritance, 1663 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1664 * (Protected members may continue to be accessible because of package sharing.) 1665 * <li>If the new lookup class is not 1666 * {@linkplain #accessClass(Class) accessible} to this lookup, 1667 * then no members, not even public members, will be accessible 1668 * i.e. all access modes are lost. 1669 * <li>If the new lookup class, the old lookup class and the previous lookup class 1670 * are all in different modules i.e. teleporting to a third module, 1671 * all access modes are lost. 1672 * </ul> 1673 * <p> 1674 * The new previous lookup class is chosen as follows: 1675 * <ul> 1676 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1677 * the new previous lookup class is {@code null}. 1678 * <li>If the new lookup class is in the same module as the old lookup class, 1679 * the new previous lookup class is the old previous lookup class. 1680 * <li>If the new lookup class is in a different module from the old lookup class, 1681 * the new previous lookup class is the old lookup class. 1682 *</ul> 1683 * <p> 1684 * The resulting lookup's capabilities for loading classes 1685 * (used during {@link #findClass} invocations) 1686 * are determined by the lookup class' loader, 1687 * which may change due to this operation. 1688 * 1689 * @param requestedLookupClass the desired lookup class for the new lookup object 1690 * @return a lookup object which reports the desired lookup class, or the same object 1691 * if there is no change 1692 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1693 * @throws NullPointerException if the argument is null 1694 * 1695 * @see #accessClass(Class) 1696 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1697 */ 1698 public Lookup in(Class<?> requestedLookupClass) { 1699 Objects.requireNonNull(requestedLookupClass); 1700 if (requestedLookupClass.isPrimitive()) 1701 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1702 if (requestedLookupClass.isArray()) 1703 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1704 1705 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1706 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1707 if (requestedLookupClass == this.lookupClass) 1708 return this; // keep same capabilities 1709 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1710 Module fromModule = this.lookupClass.getModule(); 1711 Module targetModule = requestedLookupClass.getModule(); 1712 Class<?> plc = this.previousLookupClass(); 1713 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1714 assert plc == null; 1715 newModes = UNCONDITIONAL; 1716 } else if (fromModule != targetModule) { 1717 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1718 // allow hopping back and forth between fromModule and plc's module 1719 // but not the third module 1720 newModes = 0; 1721 } 1722 // drop MODULE access 1723 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1724 // teleport from this lookup class 1725 plc = this.lookupClass; 1726 } 1727 if ((newModes & PACKAGE) != 0 1728 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1729 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1730 } 1731 // Allow nestmate lookups to be created without special privilege: 1732 if ((newModes & PRIVATE) != 0 1733 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1734 newModes &= ~(PRIVATE|PROTECTED); 1735 } 1736 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1737 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1738 // The requested class it not accessible from the lookup class. 1739 // No permissions. 1740 newModes = 0; 1741 } 1742 return newLookup(requestedLookupClass, plc, newModes); 1743 } 1744 1745 /** 1746 * Creates a lookup on the same lookup class which this lookup object 1747 * finds members, but with a lookup mode that has lost the given lookup mode. 1748 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1749 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1750 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1751 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1752 * 1753 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1754 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1755 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1756 * lookup has no access. 1757 * 1758 * <p> If this lookup is not a public lookup, then the following applies 1759 * regardless of its {@linkplain #lookupModes() lookup modes}. 1760 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1761 * dropped and so the resulting lookup mode will never have these access 1762 * capabilities. When dropping {@code PACKAGE} 1763 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1764 * access. When dropping {@code MODULE} then the resulting lookup will not 1765 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1766 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1767 * 1768 * @apiNote 1769 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1770 * delegate non-public access within the package of the lookup class without 1771 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1772 * A lookup with {@code MODULE} but not 1773 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1774 * the module of the lookup class without conferring package access. 1775 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1776 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1777 * to public classes accessible to both the module of the lookup class 1778 * and the module of the previous lookup class. 1779 * 1780 * @param modeToDrop the lookup mode to drop 1781 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1782 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1783 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1784 * or {@code UNCONDITIONAL} 1785 * @see MethodHandles#privateLookupIn 1786 * @since 9 1787 */ 1788 public Lookup dropLookupMode(int modeToDrop) { 1789 int oldModes = lookupModes(); 1790 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1791 switch (modeToDrop) { 1792 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1793 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1794 case PACKAGE: newModes &= ~(PRIVATE); break; 1795 case PROTECTED: 1796 case PRIVATE: 1797 case ORIGINAL: 1798 case UNCONDITIONAL: break; 1799 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1800 } 1801 if (newModes == oldModes) return this; // return self if no change 1802 return newLookup(lookupClass(), previousLookupClass(), newModes); 1803 } 1804 1805 /** 1806 * Creates and links a class or interface from {@code bytes} 1807 * with the same class loader and in the same runtime package and 1808 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1809 * {@linkplain #lookupClass() lookup class} as if calling 1810 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1811 * ClassLoader::defineClass}. 1812 * 1813 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1814 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1815 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1816 * that the lookup object was created by a caller in the runtime package (or derived 1817 * from a lookup originally created by suitably privileged code to a target class in 1818 * the runtime package). </p> 1819 * 1820 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1821 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1822 * same package as the lookup class. </p> 1823 * 1824 * <p> This method does not run the class initializer. The class initializer may 1825 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1826 * Specification</em>. </p> 1827 * 1828 * <p> If there is a security manager and this lookup does not have {@linkplain 1829 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1830 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1831 * 1832 * @param bytes the class bytes 1833 * @return the {@code Class} object for the class 1834 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1835 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1836 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1837 * than the lookup class or {@code bytes} is not a class or interface 1838 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1839 * @throws VerifyError if the newly created class cannot be verified 1840 * @throws LinkageError if the newly created class cannot be linked for any other reason 1841 * @throws SecurityException if a security manager is present and it 1842 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1843 * @throws NullPointerException if {@code bytes} is {@code null} 1844 * @since 9 1845 * @see MethodHandles#privateLookupIn 1846 * @see Lookup#dropLookupMode 1847 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1848 */ 1849 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1850 ensureDefineClassPermission(); 1851 if ((lookupModes() & PACKAGE) == 0) 1852 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1853 return makeClassDefiner(bytes.clone()).defineClass(false); 1854 } 1855 1856 private void ensureDefineClassPermission() { 1857 if (allowedModes == TRUSTED) return; 1858 1859 if (!hasFullPrivilegeAccess()) { 1860 @SuppressWarnings("removal") 1861 SecurityManager sm = System.getSecurityManager(); 1862 if (sm != null) 1863 sm.checkPermission(new RuntimePermission("defineClass")); 1864 } 1865 } 1866 1867 /** 1868 * The set of class options that specify whether a hidden class created by 1869 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1870 * Lookup::defineHiddenClass} method is dynamically added as a new member 1871 * to the nest of a lookup class and/or whether a hidden class has 1872 * a strong relationship with the class loader marked as its defining loader. 1873 * 1874 * @since 15 1875 */ 1876 public enum ClassOption { 1877 /** 1878 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1879 * of a lookup class as a nestmate. 1880 * 1881 * <p> A hidden nestmate class has access to the private members of all 1882 * classes and interfaces in the same nest. 1883 * 1884 * @see Class#getNestHost() 1885 */ 1886 NESTMATE(NESTMATE_CLASS), 1887 1888 /** 1889 * Specifies that a hidden class has a <em>strong</em> 1890 * relationship with the class loader marked as its defining loader, 1891 * as a normal class or interface has with its own defining loader. 1892 * This means that the hidden class may be unloaded if and only if 1893 * its defining loader is not reachable and thus may be reclaimed 1894 * by a garbage collector (JLS {@jls 12.7}). 1895 * 1896 * <p> By default, a hidden class or interface may be unloaded 1897 * even if the class loader that is marked as its defining loader is 1898 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1899 1900 * 1901 * @jls 12.7 Unloading of Classes and Interfaces 1902 */ 1903 STRONG(STRONG_LOADER_LINK); 1904 1905 /* the flag value is used by VM at define class time */ 1906 private final int flag; 1907 ClassOption(int flag) { 1908 this.flag = flag; 1909 } 1910 1911 static int optionsToFlag(ClassOption[] options) { 1912 int flags = 0; 1913 for (ClassOption cp : options) { 1914 if ((flags & cp.flag) != 0) { 1915 throw new IllegalArgumentException("Duplicate ClassOption " + cp); 1916 } 1917 flags |= cp.flag; 1918 } 1919 return flags; 1920 } 1921 } 1922 1923 /** 1924 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1925 * returning a {@code Lookup} on the newly created class or interface. 1926 * 1927 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1928 * which either defines {@code C} directly or delegates to another class loader. 1929 * A class loader defines {@code C} directly by invoking 1930 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1931 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1932 * to derive {@code C} from a purported representation in {@code class} file format. 1933 * In situations where use of a class loader is undesirable, a class or interface 1934 * {@code C} can be created by this method instead. This method is capable of 1935 * defining {@code C}, and thereby creating it, without invoking 1936 * {@code ClassLoader::defineClass}. 1937 * Instead, this method defines {@code C} as if by arranging for 1938 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1939 * from a purported representation in {@code class} file format 1940 * using the following rules: 1941 * 1942 * <ol> 1943 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1944 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1945 * This level of access is needed to create {@code C} in the module 1946 * of the lookup class of this {@code Lookup}.</li> 1947 * 1948 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1949 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1950 * The major and minor version may differ from the {@code class} file version 1951 * of the lookup class of this {@code Lookup}.</li> 1952 * 1953 * <li> The value of {@code this_class} must be a valid index in the 1954 * {@code constant_pool} table, and the entry at that index must be a valid 1955 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1956 * encoded in internal form that is specified by this structure. {@code N} must 1957 * denote a class or interface in the same package as the lookup class.</li> 1958 * 1959 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1960 * where {@code <suffix>} is an unqualified name. 1961 * 1962 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1963 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1964 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1965 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1966 * refers to the new {@code CONSTANT_Utf8_info} structure. 1967 * 1968 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1969 * 1970 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1971 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1972 * with the following adjustments: 1973 * <ul> 1974 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1975 * that includes a single {@code "."} character, even though this is not a valid 1976 * binary class or interface name in internal form.</li> 1977 * 1978 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1979 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1980 * 1981 * <li> {@code C} is considered to have the same runtime 1982 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1983 * and {@linkplain java.security.ProtectionDomain protection domain} 1984 * as the lookup class of this {@code Lookup}. 1985 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1986 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1987 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1988 * <ul> 1989 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1990 * even though this is not a valid binary class or interface name.</li> 1991 * <li> {@link Class#descriptorString()} returns the string 1992 * {@code "L" + N + "." + <suffix> + ";"}, 1993 * even though this is not a valid type descriptor name.</li> 1994 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1995 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1996 * </ul> 1997 * </ul> 1998 * </li> 1999 * </ol> 2000 * 2001 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 2002 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 2003 * <ul> 2004 * <li> During verification, whenever it is necessary to load the class named 2005 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2006 * made of any class loader.</li> 2007 * 2008 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2009 * by {@code this_class}, the symbolic reference is considered to be resolved to 2010 * {@code C} and resolution always succeeds immediately.</li> 2011 * </ul> 2012 * 2013 * <p> If the {@code initialize} parameter is {@code true}, 2014 * then {@code C} is initialized by the Java Virtual Machine. 2015 * 2016 * <p> The newly created class or interface {@code C} serves as the 2017 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2018 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2019 * no other class or interface can refer to {@code C} via a constant pool entry. 2020 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2021 * a method parameter type, or a method return type by any other class. 2022 * This is because a hidden class or interface does not have a binary name, so 2023 * there is no internal form available to record in any class's constant pool. 2024 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2025 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2026 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2027 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2028 * JVM Tool Interface</a>. 2029 * 2030 * <p> A class or interface created by 2031 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2032 * a class loader} has a strong relationship with that class loader. 2033 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2034 * that {@linkplain Class#getClassLoader() defined it}. 2035 * This means that a class created by a class loader may be unloaded if and 2036 * only if its defining loader is not reachable and thus may be reclaimed 2037 * by a garbage collector (JLS {@jls 12.7}). 2038 * 2039 * By default, however, a hidden class or interface may be unloaded even if 2040 * the class loader that is marked as its defining loader is 2041 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2042 * This behavior is useful when a hidden class or interface serves multiple 2043 * classes defined by arbitrary class loaders. In other cases, a hidden 2044 * class or interface may be linked to a single class (or a small number of classes) 2045 * with the same defining loader as the hidden class or interface. 2046 * In such cases, where the hidden class or interface must be coterminous 2047 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2048 * option may be passed in {@code options}. 2049 * This arranges for a hidden class to have the same strong relationship 2050 * with the class loader marked as its defining loader, 2051 * as a normal class or interface has with its own defining loader. 2052 * 2053 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2054 * may still prevent a hidden class or interface from being 2055 * unloaded by ensuring that the {@code Class} object is reachable. 2056 * 2057 * <p> The unloading characteristics are set for each hidden class when it is 2058 * defined, and cannot be changed later. An advantage of allowing hidden classes 2059 * to be unloaded independently of the class loader marked as their defining loader 2060 * is that a very large number of hidden classes may be created by an application. 2061 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2062 * just as if normal classes were created by class loaders. 2063 * 2064 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2065 * their private members. The nest relationship is determined by 2066 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2067 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2068 * By default, a hidden class belongs to a nest consisting only of itself 2069 * because a hidden class has no binary name. 2070 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2071 * to create a hidden class or interface {@code C} as a member of a nest. 2072 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2073 * in the {@code ClassFile} structure from which {@code C} was derived. 2074 * Instead, the following rules determine the nest host of {@code C}: 2075 * <ul> 2076 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2077 * been determined, then let {@code H} be the nest host of the lookup class. 2078 * Otherwise, the nest host of the lookup class is determined using the 2079 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2080 * <li>The nest host of {@code C} is determined to be {@code H}, 2081 * the nest host of the lookup class.</li> 2082 * </ul> 2083 * 2084 * <p> A hidden class or interface may be serializable, but this requires a custom 2085 * serialization mechanism in order to ensure that instances are properly serialized 2086 * and deserialized. The default serialization mechanism supports only classes and 2087 * interfaces that are discoverable by their class name. 2088 * 2089 * @param bytes the bytes that make up the class data, 2090 * in the format of a valid {@code class} file as defined by 2091 * <cite>The Java Virtual Machine Specification</cite>. 2092 * @param initialize if {@code true} the class will be initialized. 2093 * @param options {@linkplain ClassOption class options} 2094 * @return the {@code Lookup} object on the hidden class, 2095 * with {@linkplain #ORIGINAL original} and 2096 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2097 * 2098 * @throws IllegalAccessException if this {@code Lookup} does not have 2099 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2100 * @throws SecurityException if a security manager is present and it 2101 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2102 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2103 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2104 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2105 * than the lookup class or {@code bytes} is not a class or interface 2106 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2107 * @throws IncompatibleClassChangeError if the class or interface named as 2108 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2109 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2110 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2111 * {@code C} is {@code C} itself 2112 * @throws VerifyError if the newly created class cannot be verified 2113 * @throws LinkageError if the newly created class cannot be linked for any other reason 2114 * @throws NullPointerException if any parameter is {@code null} 2115 * 2116 * @since 15 2117 * @see Class#isHidden() 2118 * @jvms 4.2.1 Binary Class and Interface Names 2119 * @jvms 4.2.2 Unqualified Names 2120 * @jvms 4.7.28 The {@code NestHost} Attribute 2121 * @jvms 4.7.29 The {@code NestMembers} Attribute 2122 * @jvms 5.4.3.1 Class and Interface Resolution 2123 * @jvms 5.4.4 Access Control 2124 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2125 * @jvms 5.4 Linking 2126 * @jvms 5.5 Initialization 2127 * @jls 12.7 Unloading of Classes and Interfaces 2128 */ 2129 @SuppressWarnings("doclint:reference") // cross-module links 2130 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2131 throws IllegalAccessException 2132 { 2133 Objects.requireNonNull(bytes); 2134 int flags = ClassOption.optionsToFlag(options); 2135 ensureDefineClassPermission(); 2136 if (!hasFullPrivilegeAccess()) { 2137 throw new IllegalAccessException(this + " does not have full privilege access"); 2138 } 2139 2140 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize); 2141 } 2142 2143 /** 2144 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2145 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2146 * returning a {@code Lookup} on the newly created class or interface. 2147 * 2148 * <p> This method is equivalent to calling 2149 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2150 * as if the hidden class is injected with a private static final <i>unnamed</i> 2151 * field which is initialized with the given {@code classData} at 2152 * the first instruction of the class initializer. 2153 * The newly created class is linked by the Java Virtual Machine. 2154 * 2155 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2156 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2157 * methods can be used to retrieve the {@code classData}. 2158 * 2159 * @apiNote 2160 * A framework can create a hidden class with class data with one or more 2161 * objects and load the class data as dynamically-computed constant(s) 2162 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2163 * Class data} is accessible only to the lookup object created by the newly 2164 * defined hidden class but inaccessible to other members in the same nest 2165 * (unlike private static fields that are accessible to nestmates). 2166 * Care should be taken w.r.t. mutability for example when passing 2167 * an array or other mutable structure through the class data. 2168 * Changing any value stored in the class data at runtime may lead to 2169 * unpredictable behavior. 2170 * If the class data is a {@code List}, it is good practice to make it 2171 * unmodifiable for example via {@link List#of List::of}. 2172 * 2173 * @param bytes the class bytes 2174 * @param classData pre-initialized class data 2175 * @param initialize if {@code true} the class will be initialized. 2176 * @param options {@linkplain ClassOption class options} 2177 * @return the {@code Lookup} object on the hidden class, 2178 * with {@linkplain #ORIGINAL original} and 2179 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2180 * 2181 * @throws IllegalAccessException if this {@code Lookup} does not have 2182 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2183 * @throws SecurityException if a security manager is present and it 2184 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2185 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2186 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2187 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2188 * than the lookup class or {@code bytes} is not a class or interface 2189 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2190 * @throws IncompatibleClassChangeError if the class or interface named as 2191 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2192 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2193 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2194 * {@code C} is {@code C} itself 2195 * @throws VerifyError if the newly created class cannot be verified 2196 * @throws LinkageError if the newly created class cannot be linked for any other reason 2197 * @throws NullPointerException if any parameter is {@code null} 2198 * 2199 * @since 16 2200 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2201 * @see Class#isHidden() 2202 * @see MethodHandles#classData(Lookup, String, Class) 2203 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2204 * @jvms 4.2.1 Binary Class and Interface Names 2205 * @jvms 4.2.2 Unqualified Names 2206 * @jvms 4.7.28 The {@code NestHost} Attribute 2207 * @jvms 4.7.29 The {@code NestMembers} Attribute 2208 * @jvms 5.4.3.1 Class and Interface Resolution 2209 * @jvms 5.4.4 Access Control 2210 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2211 * @jvms 5.4 Linking 2212 * @jvms 5.5 Initialization 2213 * @jls 12.7 Unloading of Classes and Interfaces 2214 */ 2215 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2216 throws IllegalAccessException 2217 { 2218 Objects.requireNonNull(bytes); 2219 Objects.requireNonNull(classData); 2220 2221 int flags = ClassOption.optionsToFlag(options); 2222 2223 ensureDefineClassPermission(); 2224 if (!hasFullPrivilegeAccess()) { 2225 throw new IllegalAccessException(this + " does not have full privilege access"); 2226 } 2227 2228 return makeHiddenClassDefiner(bytes.clone(), false, flags) 2229 .defineClassAsLookup(initialize, classData); 2230 } 2231 2232 // A default dumper for writing class files passed to Lookup::defineClass 2233 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2234 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2235 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2236 // 2237 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2238 // and LambdaForms and method handle internals. They are dumped via 2239 // different ClassFileDumpers. 2240 private static ClassFileDumper defaultDumper() { 2241 return DEFAULT_DUMPER; 2242 } 2243 2244 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2245 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2246 2247 /** 2248 * This method checks the class file version and the structure of `this_class`. 2249 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2250 * that is in the named package. 2251 * 2252 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2253 * or the class is not in the given package name. 2254 */ 2255 static String validateAndFindInternalName(byte[] bytes, String pkgName) { 2256 int magic = readInt(bytes, 0); 2257 if (magic != ClassFile.MAGIC_NUMBER) { 2258 throw new ClassFormatError("Incompatible magic value: " + magic); 2259 } 2260 // We have to read major and minor this way as ClassFile API throws IAE 2261 // yet we want distinct ClassFormatError and UnsupportedClassVersionError 2262 int minor = readUnsignedShort(bytes, 4); 2263 int major = readUnsignedShort(bytes, 6); 2264 2265 if (!VM.isSupportedClassFileVersion(major, minor)) { 2266 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2267 } 2268 2269 String name; 2270 ClassDesc sym; 2271 int accessFlags; 2272 try { 2273 ClassModel cm = ClassFile.of().parse(bytes); 2274 var thisClass = cm.thisClass(); 2275 name = thisClass.asInternalName(); 2276 sym = thisClass.asSymbol(); 2277 accessFlags = cm.flags().flagsMask(); 2278 } catch (IllegalArgumentException e) { 2279 ClassFormatError cfe = new ClassFormatError(); 2280 cfe.initCause(e); 2281 throw cfe; 2282 } 2283 // must be a class or interface 2284 if ((accessFlags & ACC_MODULE) != 0) { 2285 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2286 } 2287 2288 String pn = sym.packageName(); 2289 if (!pn.equals(pkgName)) { 2290 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2291 } 2292 2293 return name; 2294 } 2295 2296 private static int readInt(byte[] bytes, int offset) { 2297 if ((offset + 4) > bytes.length) { 2298 throw new ClassFormatError("Invalid ClassFile structure"); 2299 } 2300 return ((bytes[offset] & 0xFF) << 24) 2301 | ((bytes[offset + 1] & 0xFF) << 16) 2302 | ((bytes[offset + 2] & 0xFF) << 8) 2303 | (bytes[offset + 3] & 0xFF); 2304 } 2305 2306 private static int readUnsignedShort(byte[] bytes, int offset) { 2307 if ((offset+2) > bytes.length) { 2308 throw new ClassFormatError("Invalid ClassFile structure"); 2309 } 2310 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2311 } 2312 2313 /* 2314 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2315 * from the given bytes. 2316 * 2317 * Caller should make a defensive copy of the arguments if needed 2318 * before calling this factory method. 2319 * 2320 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2321 * {@code bytes} denotes a class in a different package than the lookup class 2322 */ 2323 private ClassDefiner makeClassDefiner(byte[] bytes) { 2324 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2325 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper()); 2326 } 2327 2328 /** 2329 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2330 * from the given bytes. No package name check on the given bytes. 2331 * 2332 * @param internalName internal name 2333 * @param bytes class bytes 2334 * @param dumper dumper to write the given bytes to the dumper's output directory 2335 * @return ClassDefiner that defines a normal class of the given bytes. 2336 */ 2337 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2338 // skip package name validation 2339 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper); 2340 } 2341 2342 /** 2343 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2344 * from the given bytes. The name must be in the same package as the lookup class. 2345 * 2346 * Caller should make a defensive copy of the arguments if needed 2347 * before calling this factory method. 2348 * 2349 * @param bytes class bytes 2350 * @param dumper dumper to write the given bytes to the dumper's output directory 2351 * @return ClassDefiner that defines a hidden class of the given bytes. 2352 * 2353 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2354 * {@code bytes} denotes a class in a different package than the lookup class 2355 */ 2356 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2357 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2358 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2359 } 2360 2361 /** 2362 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2363 * from the given bytes and options. 2364 * The name must be in the same package as the lookup class. 2365 * 2366 * Caller should make a defensive copy of the arguments if needed 2367 * before calling this factory method. 2368 * 2369 * @param bytes class bytes 2370 * @param flags class option flag mask 2371 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2372 * @return ClassDefiner that defines a hidden class of the given bytes and options 2373 * 2374 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2375 * {@code bytes} denotes a class in a different package than the lookup class 2376 */ 2377 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2378 boolean accessVmAnnotations, 2379 int flags) { 2380 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2381 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags); 2382 } 2383 2384 /** 2385 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2386 * from the given bytes and the given options. No package name check on the given bytes. 2387 * 2388 * @param internalName internal name that specifies the prefix of the hidden class 2389 * @param bytes class bytes 2390 * @param dumper dumper to write the given bytes to the dumper's output directory 2391 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2392 */ 2393 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2394 Objects.requireNonNull(dumper); 2395 // skip name and access flags validation 2396 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2397 } 2398 2399 /** 2400 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2401 * from the given bytes and the given options. No package name check on the given bytes. 2402 * 2403 * @param internalName internal name that specifies the prefix of the hidden class 2404 * @param bytes class bytes 2405 * @param flags class options flag mask 2406 * @param dumper dumper to write the given bytes to the dumper's output directory 2407 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2408 */ 2409 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) { 2410 Objects.requireNonNull(dumper); 2411 // skip name and access flags validation 2412 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags); 2413 } 2414 2415 /** 2416 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2417 * from the given class file and options. 2418 * 2419 * @param internalName internal name 2420 * @param bytes Class byte array 2421 * @param flags class option flag mask 2422 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2423 * @param dumper dumper to write the given bytes to the dumper's output directory 2424 */ 2425 private ClassDefiner makeHiddenClassDefiner(String internalName, 2426 byte[] bytes, 2427 boolean accessVmAnnotations, 2428 ClassFileDumper dumper, 2429 int flags) { 2430 flags |= HIDDEN_CLASS; 2431 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2432 // jdk.internal.vm.annotations are permitted for classes 2433 // defined to boot loader and platform loader 2434 flags |= ACCESS_VM_ANNOTATIONS; 2435 } 2436 2437 return new ClassDefiner(this, internalName, bytes, flags, dumper); 2438 } 2439 2440 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) { 2441 ClassDefiner { 2442 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2443 } 2444 2445 Class<?> defineClass(boolean initialize) { 2446 return defineClass(initialize, null); 2447 } 2448 2449 Lookup defineClassAsLookup(boolean initialize) { 2450 Class<?> c = defineClass(initialize, null); 2451 return new Lookup(c, null, FULL_POWER_MODES); 2452 } 2453 2454 /** 2455 * Defines the class of the given bytes and the given classData. 2456 * If {@code initialize} parameter is true, then the class will be initialized. 2457 * 2458 * @param initialize true if the class to be initialized 2459 * @param classData classData or null 2460 * @return the class 2461 * 2462 * @throws LinkageError linkage error 2463 */ 2464 Class<?> defineClass(boolean initialize, Object classData) { 2465 Class<?> lookupClass = lookup.lookupClass(); 2466 ClassLoader loader = lookupClass.getClassLoader(); 2467 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2468 Class<?> c = null; 2469 try { 2470 c = SharedSecrets.getJavaLangAccess() 2471 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData); 2472 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2473 return c; 2474 } finally { 2475 // dump the classfile for debugging 2476 if (dumper.isEnabled()) { 2477 String name = internalName(); 2478 if (c != null) { 2479 dumper.dumpClass(name, c, bytes); 2480 } else { 2481 dumper.dumpFailedClass(name, bytes); 2482 } 2483 } 2484 } 2485 } 2486 2487 /** 2488 * Defines the class of the given bytes and the given classData. 2489 * If {@code initialize} parameter is true, then the class will be initialized. 2490 * 2491 * @param initialize true if the class to be initialized 2492 * @param classData classData or null 2493 * @return a Lookup for the defined class 2494 * 2495 * @throws LinkageError linkage error 2496 */ 2497 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2498 Class<?> c = defineClass(initialize, classData); 2499 return new Lookup(c, null, FULL_POWER_MODES); 2500 } 2501 2502 private boolean isNestmate() { 2503 return (classFlags & NESTMATE_CLASS) != 0; 2504 } 2505 } 2506 2507 private ProtectionDomain lookupClassProtectionDomain() { 2508 ProtectionDomain pd = cachedProtectionDomain; 2509 if (pd == null) { 2510 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2511 } 2512 return pd; 2513 } 2514 2515 // cached protection domain 2516 private volatile ProtectionDomain cachedProtectionDomain; 2517 2518 // Make sure outer class is initialized first. 2519 static { IMPL_NAMES.getClass(); } 2520 2521 /** Package-private version of lookup which is trusted. */ 2522 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2523 2524 /** Version of lookup which is trusted minimally. 2525 * It can only be used to create method handles to publicly accessible 2526 * members in packages that are exported unconditionally. 2527 */ 2528 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2529 2530 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2531 String name = lookupClass.getName(); 2532 if (name.startsWith("java.lang.invoke.")) 2533 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2534 } 2535 2536 /** 2537 * Displays the name of the class from which lookups are to be made, 2538 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2539 * previous lookup class} if present. 2540 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2541 * If there are restrictions on the access permitted to this lookup, 2542 * this is indicated by adding a suffix to the class name, consisting 2543 * of a slash and a keyword. The keyword represents the strongest 2544 * allowed access, and is chosen as follows: 2545 * <ul> 2546 * <li>If no access is allowed, the suffix is "/noaccess". 2547 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2548 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2549 * <li>If only public and module access are allowed, the suffix is "/module". 2550 * <li>If public and package access are allowed, the suffix is "/package". 2551 * <li>If public, package, and private access are allowed, the suffix is "/private". 2552 * </ul> 2553 * If none of the above cases apply, it is the case that 2554 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2555 * (public, module, package, private, and protected) is allowed. 2556 * In this case, no suffix is added. 2557 * This is true only of an object obtained originally from 2558 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2559 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2560 * always have restricted access, and will display a suffix. 2561 * <p> 2562 * (It may seem strange that protected access should be 2563 * stronger than private access. Viewed independently from 2564 * package access, protected access is the first to be lost, 2565 * because it requires a direct subclass relationship between 2566 * caller and callee.) 2567 * @see #in 2568 */ 2569 @Override 2570 public String toString() { 2571 String cname = lookupClass.getName(); 2572 if (prevLookupClass != null) 2573 cname += "/" + prevLookupClass.getName(); 2574 switch (allowedModes) { 2575 case 0: // no privileges 2576 return cname + "/noaccess"; 2577 case UNCONDITIONAL: 2578 return cname + "/publicLookup"; 2579 case PUBLIC: 2580 return cname + "/public"; 2581 case PUBLIC|MODULE: 2582 return cname + "/module"; 2583 case PUBLIC|PACKAGE: 2584 case PUBLIC|MODULE|PACKAGE: 2585 return cname + "/package"; 2586 case PUBLIC|PACKAGE|PRIVATE: 2587 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2588 return cname + "/private"; 2589 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2590 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2591 case FULL_POWER_MODES: 2592 return cname; 2593 case TRUSTED: 2594 return "/trusted"; // internal only; not exported 2595 default: // Should not happen, but it's a bitfield... 2596 cname = cname + "/" + Integer.toHexString(allowedModes); 2597 assert(false) : cname; 2598 return cname; 2599 } 2600 } 2601 2602 /** 2603 * Produces a method handle for a static method. 2604 * The type of the method handle will be that of the method. 2605 * (Since static methods do not take receivers, there is no 2606 * additional receiver argument inserted into the method handle type, 2607 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2608 * The method and all its argument types must be accessible to the lookup object. 2609 * <p> 2610 * The returned method handle will have 2611 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2612 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2613 * <p> 2614 * If the returned method handle is invoked, the method's class will 2615 * be initialized, if it has not already been initialized. 2616 * <p><b>Example:</b> 2617 * {@snippet lang="java" : 2618 import static java.lang.invoke.MethodHandles.*; 2619 import static java.lang.invoke.MethodType.*; 2620 ... 2621 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2622 "asList", methodType(List.class, Object[].class)); 2623 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2624 * } 2625 * @param refc the class from which the method is accessed 2626 * @param name the name of the method 2627 * @param type the type of the method 2628 * @return the desired method handle 2629 * @throws NoSuchMethodException if the method does not exist 2630 * @throws IllegalAccessException if access checking fails, 2631 * or if the method is not {@code static}, 2632 * or if the method's variable arity modifier bit 2633 * is set and {@code asVarargsCollector} fails 2634 * @throws SecurityException if a security manager is present and it 2635 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2636 * @throws NullPointerException if any argument is null 2637 */ 2638 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2639 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2640 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2641 } 2642 2643 /** 2644 * Produces a method handle for a virtual method. 2645 * The type of the method handle will be that of the method, 2646 * with the receiver type (usually {@code refc}) prepended. 2647 * The method and all its argument types must be accessible to the lookup object. 2648 * <p> 2649 * When called, the handle will treat the first argument as a receiver 2650 * and, for non-private methods, dispatch on the receiver's type to determine which method 2651 * implementation to enter. 2652 * For private methods the named method in {@code refc} will be invoked on the receiver. 2653 * (The dispatching action is identical with that performed by an 2654 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2655 * <p> 2656 * The first argument will be of type {@code refc} if the lookup 2657 * class has full privileges to access the member. Otherwise 2658 * the member must be {@code protected} and the first argument 2659 * will be restricted in type to the lookup class. 2660 * <p> 2661 * The returned method handle will have 2662 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2663 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2664 * <p> 2665 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2666 * instructions and method handles produced by {@code findVirtual}, 2667 * if the class is {@code MethodHandle} and the name string is 2668 * {@code invokeExact} or {@code invoke}, the resulting 2669 * method handle is equivalent to one produced by 2670 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2671 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2672 * with the same {@code type} argument. 2673 * <p> 2674 * If the class is {@code VarHandle} and the name string corresponds to 2675 * the name of a signature-polymorphic access mode method, the resulting 2676 * method handle is equivalent to one produced by 2677 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2678 * the access mode corresponding to the name string and with the same 2679 * {@code type} arguments. 2680 * <p> 2681 * <b>Example:</b> 2682 * {@snippet lang="java" : 2683 import static java.lang.invoke.MethodHandles.*; 2684 import static java.lang.invoke.MethodType.*; 2685 ... 2686 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2687 "concat", methodType(String.class, String.class)); 2688 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2689 "hashCode", methodType(int.class)); 2690 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2691 "hashCode", methodType(int.class)); 2692 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2693 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2694 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2695 // interface method: 2696 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2697 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2698 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2699 // constructor "internal method" must be accessed differently: 2700 MethodType MT_newString = methodType(void.class); //()V for new String() 2701 try { assertEquals("impossible", lookup() 2702 .findVirtual(String.class, "<init>", MT_newString)); 2703 } catch (NoSuchMethodException ex) { } // OK 2704 MethodHandle MH_newString = publicLookup() 2705 .findConstructor(String.class, MT_newString); 2706 assertEquals("", (String) MH_newString.invokeExact()); 2707 * } 2708 * 2709 * @param refc the class or interface from which the method is accessed 2710 * @param name the name of the method 2711 * @param type the type of the method, with the receiver argument omitted 2712 * @return the desired method handle 2713 * @throws NoSuchMethodException if the method does not exist 2714 * @throws IllegalAccessException if access checking fails, 2715 * or if the method is {@code static}, 2716 * or if the method's variable arity modifier bit 2717 * is set and {@code asVarargsCollector} fails 2718 * @throws SecurityException if a security manager is present and it 2719 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2720 * @throws NullPointerException if any argument is null 2721 */ 2722 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2723 if (refc == MethodHandle.class) { 2724 MethodHandle mh = findVirtualForMH(name, type); 2725 if (mh != null) return mh; 2726 } else if (refc == VarHandle.class) { 2727 MethodHandle mh = findVirtualForVH(name, type); 2728 if (mh != null) return mh; 2729 } 2730 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2731 MemberName method = resolveOrFail(refKind, refc, name, type); 2732 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2733 } 2734 private MethodHandle findVirtualForMH(String name, MethodType type) { 2735 // these names require special lookups because of the implicit MethodType argument 2736 if ("invoke".equals(name)) 2737 return invoker(type); 2738 if ("invokeExact".equals(name)) 2739 return exactInvoker(type); 2740 assert(!MemberName.isMethodHandleInvokeName(name)); 2741 return null; 2742 } 2743 private MethodHandle findVirtualForVH(String name, MethodType type) { 2744 try { 2745 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2746 } catch (IllegalArgumentException e) { 2747 return null; 2748 } 2749 } 2750 2751 /** 2752 * Produces a method handle which creates an object and initializes it, using 2753 * the constructor of the specified type. 2754 * The parameter types of the method handle will be those of the constructor, 2755 * while the return type will be a reference to the constructor's class. 2756 * The constructor and all its argument types must be accessible to the lookup object. 2757 * <p> 2758 * The requested type must have a return type of {@code void}. 2759 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2760 * <p> 2761 * The returned method handle will have 2762 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2763 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2764 * <p> 2765 * If the returned method handle is invoked, the constructor's class will 2766 * be initialized, if it has not already been initialized. 2767 * <p><b>Example:</b> 2768 * {@snippet lang="java" : 2769 import static java.lang.invoke.MethodHandles.*; 2770 import static java.lang.invoke.MethodType.*; 2771 ... 2772 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2773 ArrayList.class, methodType(void.class, Collection.class)); 2774 Collection orig = Arrays.asList("x", "y"); 2775 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2776 assert(orig != copy); 2777 assertEquals(orig, copy); 2778 // a variable-arity constructor: 2779 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2780 ProcessBuilder.class, methodType(void.class, String[].class)); 2781 ProcessBuilder pb = (ProcessBuilder) 2782 MH_newProcessBuilder.invoke("x", "y", "z"); 2783 assertEquals("[x, y, z]", pb.command().toString()); 2784 * } 2785 * 2786 * 2787 * @param refc the class or interface from which the method is accessed 2788 * @param type the type of the method, with the receiver argument omitted, and a void return type 2789 * @return the desired method handle 2790 * @throws NoSuchMethodException if the constructor does not exist 2791 * @throws IllegalAccessException if access checking fails 2792 * or if the method's variable arity modifier bit 2793 * is set and {@code asVarargsCollector} fails 2794 * @throws SecurityException if a security manager is present and it 2795 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2796 * @throws NullPointerException if any argument is null 2797 */ 2798 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2799 if (refc.isArray()) { 2800 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2801 } 2802 if (type.returnType() != void.class) { 2803 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName()); 2804 } 2805 String name = ConstantDescs.INIT_NAME; 2806 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2807 return getDirectConstructor(refc, ctor); 2808 } 2809 2810 /** 2811 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2812 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2813 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2814 * and then determines whether the class is accessible to this lookup object. 2815 * <p> 2816 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2817 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2818 * of {@code '['} and followed by the element type as encoded in the 2819 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2820 * <p> 2821 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2822 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2823 * 2824 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2825 * or the string representing an array class 2826 * @return the requested class. 2827 * @throws SecurityException if a security manager is present and it 2828 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2829 * @throws LinkageError if the linkage fails 2830 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2831 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2832 * modes. 2833 * @throws NullPointerException if {@code targetName} is null 2834 * @since 9 2835 * @jvms 5.4.3.1 Class and Interface Resolution 2836 */ 2837 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2838 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2839 return accessClass(targetClass); 2840 } 2841 2842 /** 2843 * Ensures that {@code targetClass} has been initialized. The class 2844 * to be initialized must be {@linkplain #accessClass accessible} 2845 * to this {@code Lookup} object. This method causes {@code targetClass} 2846 * to be initialized if it has not been already initialized, 2847 * as specified in JVMS {@jvms 5.5}. 2848 * 2849 * <p> 2850 * This method returns when {@code targetClass} is fully initialized, or 2851 * when {@code targetClass} is being initialized by the current thread. 2852 * 2853 * @param <T> the type of the class to be initialized 2854 * @param targetClass the class to be initialized 2855 * @return {@code targetClass} that has been initialized, or that is being 2856 * initialized by the current thread. 2857 * 2858 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2859 * or array class 2860 * @throws IllegalAccessException if {@code targetClass} is not 2861 * {@linkplain #accessClass accessible} to this lookup 2862 * @throws ExceptionInInitializerError if the class initialization provoked 2863 * by this method fails 2864 * @throws SecurityException if a security manager is present and it 2865 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2866 * @since 15 2867 * @jvms 5.5 Initialization 2868 */ 2869 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2870 if (targetClass.isPrimitive()) 2871 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2872 if (targetClass.isArray()) 2873 throw new IllegalArgumentException(targetClass + " is an array class"); 2874 2875 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2876 throw makeAccessException(targetClass); 2877 } 2878 checkSecurityManager(targetClass); 2879 2880 // ensure class initialization 2881 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2882 return targetClass; 2883 } 2884 2885 /* 2886 * Returns IllegalAccessException due to access violation to the given targetClass. 2887 * 2888 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2889 * which verifies access to a class rather a member. 2890 */ 2891 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2892 String message = "access violation: "+ targetClass; 2893 if (this == MethodHandles.publicLookup()) { 2894 message += ", from public Lookup"; 2895 } else { 2896 Module m = lookupClass().getModule(); 2897 message += ", from " + lookupClass() + " (" + m + ")"; 2898 if (prevLookupClass != null) { 2899 message += ", previous lookup " + 2900 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2901 } 2902 } 2903 return new IllegalAccessException(message); 2904 } 2905 2906 /** 2907 * Determines if a class can be accessed from the lookup context defined by 2908 * this {@code Lookup} object. The static initializer of the class is not run. 2909 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2910 * if the element type of the array class is accessible. Otherwise, 2911 * {@code targetClass} is determined as accessible as follows. 2912 * 2913 * <p> 2914 * If {@code targetClass} is in the same module as the lookup class, 2915 * the lookup class is {@code LC} in module {@code M1} and 2916 * the previous lookup class is in module {@code M0} or 2917 * {@code null} if not present, 2918 * {@code targetClass} is accessible if and only if one of the following is true: 2919 * <ul> 2920 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2921 * {@code LC} or other class in the same nest of {@code LC}.</li> 2922 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2923 * in the same runtime package of {@code LC}.</li> 2924 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2925 * a public type in {@code M1}.</li> 2926 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2927 * a public type in a package exported by {@code M1} to at least {@code M0} 2928 * if the previous lookup class is present; otherwise, {@code targetClass} 2929 * is a public type in a package exported by {@code M1} unconditionally.</li> 2930 * </ul> 2931 * 2932 * <p> 2933 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2934 * can access public types in all modules when the type is in a package 2935 * that is exported unconditionally. 2936 * <p> 2937 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2938 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2939 * is inaccessible. 2940 * <p> 2941 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2942 * {@code M1} is the module containing {@code lookupClass} and 2943 * {@code M2} is the module containing {@code targetClass}, 2944 * then {@code targetClass} is accessible if and only if 2945 * <ul> 2946 * <li>{@code M1} reads {@code M2}, and 2947 * <li>{@code targetClass} is public and in a package exported by 2948 * {@code M2} at least to {@code M1}. 2949 * </ul> 2950 * <p> 2951 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2952 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2953 * containing the previous lookup class, then {@code targetClass} is accessible 2954 * if and only if one of the following is true: 2955 * <ul> 2956 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2957 * {@linkplain Module#reads reads} {@code M0} and the type is 2958 * in a package that is exported to at least {@code M1}. 2959 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2960 * {@linkplain Module#reads reads} {@code M1} and the type is 2961 * in a package that is exported to at least {@code M0}. 2962 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2963 * and {@code M1} reads {@code M2} and the type is in a package 2964 * that is exported to at least both {@code M0} and {@code M2}. 2965 * </ul> 2966 * <p> 2967 * Otherwise, {@code targetClass} is not accessible. 2968 * 2969 * @param <T> the type of the class to be access-checked 2970 * @param targetClass the class to be access-checked 2971 * @return {@code targetClass} that has been access-checked 2972 * @throws IllegalAccessException if the class is not accessible from the lookup class 2973 * and previous lookup class, if present, using the allowed access modes. 2974 * @throws SecurityException if a security manager is present and it 2975 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2976 * @throws NullPointerException if {@code targetClass} is {@code null} 2977 * @since 9 2978 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2979 */ 2980 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2981 if (!isClassAccessible(targetClass)) { 2982 throw makeAccessException(targetClass); 2983 } 2984 checkSecurityManager(targetClass); 2985 return targetClass; 2986 } 2987 2988 /** 2989 * Produces an early-bound method handle for a virtual method. 2990 * It will bypass checks for overriding methods on the receiver, 2991 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2992 * instruction from within the explicitly specified {@code specialCaller}. 2993 * The type of the method handle will be that of the method, 2994 * with a suitably restricted receiver type prepended. 2995 * (The receiver type will be {@code specialCaller} or a subtype.) 2996 * The method and all its argument types must be accessible 2997 * to the lookup object. 2998 * <p> 2999 * Before method resolution, 3000 * if the explicitly specified caller class is not identical with the 3001 * lookup class, or if this lookup object does not have 3002 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3003 * privileges, the access fails. 3004 * <p> 3005 * The returned method handle will have 3006 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3007 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3008 * <p style="font-size:smaller;"> 3009 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 3010 * are not visible to this API, 3011 * even though the {@code invokespecial} instruction can refer to them 3012 * in special circumstances. Use {@link #findConstructor findConstructor} 3013 * to access instance initialization methods in a safe manner.)</em> 3014 * <p><b>Example:</b> 3015 * {@snippet lang="java" : 3016 import static java.lang.invoke.MethodHandles.*; 3017 import static java.lang.invoke.MethodType.*; 3018 ... 3019 static class Listie extends ArrayList { 3020 public String toString() { return "[wee Listie]"; } 3021 static Lookup lookup() { return MethodHandles.lookup(); } 3022 } 3023 ... 3024 // no access to constructor via invokeSpecial: 3025 MethodHandle MH_newListie = Listie.lookup() 3026 .findConstructor(Listie.class, methodType(void.class)); 3027 Listie l = (Listie) MH_newListie.invokeExact(); 3028 try { assertEquals("impossible", Listie.lookup().findSpecial( 3029 Listie.class, "<init>", methodType(void.class), Listie.class)); 3030 } catch (NoSuchMethodException ex) { } // OK 3031 // access to super and self methods via invokeSpecial: 3032 MethodHandle MH_super = Listie.lookup().findSpecial( 3033 ArrayList.class, "toString" , methodType(String.class), Listie.class); 3034 MethodHandle MH_this = Listie.lookup().findSpecial( 3035 Listie.class, "toString" , methodType(String.class), Listie.class); 3036 MethodHandle MH_duper = Listie.lookup().findSpecial( 3037 Object.class, "toString" , methodType(String.class), Listie.class); 3038 assertEquals("[]", (String) MH_super.invokeExact(l)); 3039 assertEquals(""+l, (String) MH_this.invokeExact(l)); 3040 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 3041 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 3042 String.class, "toString", methodType(String.class), Listie.class)); 3043 } catch (IllegalAccessException ex) { } // OK 3044 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 3045 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 3046 * } 3047 * 3048 * @param refc the class or interface from which the method is accessed 3049 * @param name the name of the method (which must not be "<init>") 3050 * @param type the type of the method, with the receiver argument omitted 3051 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 3052 * @return the desired method handle 3053 * @throws NoSuchMethodException if the method does not exist 3054 * @throws IllegalAccessException if access checking fails, 3055 * or if the method is {@code static}, 3056 * or if the method's variable arity modifier bit 3057 * is set and {@code asVarargsCollector} fails 3058 * @throws SecurityException if a security manager is present and it 3059 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3060 * @throws NullPointerException if any argument is null 3061 */ 3062 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3063 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3064 checkSpecialCaller(specialCaller, refc); 3065 Lookup specialLookup = this.in(specialCaller); 3066 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3067 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3068 } 3069 3070 /** 3071 * Produces a method handle giving read access to a non-static field. 3072 * The type of the method handle will have a return type of the field's 3073 * value type. 3074 * The method handle's single argument will be the instance containing 3075 * the field. 3076 * Access checking is performed immediately on behalf of the lookup class. 3077 * @param refc the class or interface from which the method is accessed 3078 * @param name the field's name 3079 * @param type the field's type 3080 * @return a method handle which can load values from the field 3081 * @throws NoSuchFieldException if the field does not exist 3082 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3083 * @throws SecurityException if a security manager is present and it 3084 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3085 * @throws NullPointerException if any argument is null 3086 * @see #findVarHandle(Class, String, Class) 3087 */ 3088 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3089 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3090 return getDirectField(REF_getField, refc, field); 3091 } 3092 3093 /** 3094 * Produces a method handle giving write access to a non-static field. 3095 * The type of the method handle will have a void return type. 3096 * The method handle will take two arguments, the instance containing 3097 * the field, and the value to be stored. 3098 * The second argument will be of the field's value type. 3099 * Access checking is performed immediately on behalf of the lookup class. 3100 * @param refc the class or interface from which the method is accessed 3101 * @param name the field's name 3102 * @param type the field's type 3103 * @return a method handle which can store values into the field 3104 * @throws NoSuchFieldException if the field does not exist 3105 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3106 * or {@code final} 3107 * @throws SecurityException if a security manager is present and it 3108 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3109 * @throws NullPointerException if any argument is null 3110 * @see #findVarHandle(Class, String, Class) 3111 */ 3112 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3113 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3114 return getDirectField(REF_putField, refc, field); 3115 } 3116 3117 /** 3118 * Produces a VarHandle giving access to a non-static field {@code name} 3119 * of type {@code type} declared in a class of type {@code recv}. 3120 * The VarHandle's variable type is {@code type} and it has one 3121 * coordinate type, {@code recv}. 3122 * <p> 3123 * Access checking is performed immediately on behalf of the lookup 3124 * class. 3125 * <p> 3126 * Certain access modes of the returned VarHandle are unsupported under 3127 * the following conditions: 3128 * <ul> 3129 * <li>if the field is declared {@code final}, then the write, atomic 3130 * update, numeric atomic update, and bitwise atomic update access 3131 * modes are unsupported. 3132 * <li>if the field type is anything other than {@code byte}, 3133 * {@code short}, {@code char}, {@code int}, {@code long}, 3134 * {@code float}, or {@code double} then numeric atomic update 3135 * access modes are unsupported. 3136 * <li>if the field type is anything other than {@code boolean}, 3137 * {@code byte}, {@code short}, {@code char}, {@code int} or 3138 * {@code long} then bitwise atomic update access modes are 3139 * unsupported. 3140 * </ul> 3141 * <p> 3142 * If the field is declared {@code volatile} then the returned VarHandle 3143 * will override access to the field (effectively ignore the 3144 * {@code volatile} declaration) in accordance to its specified 3145 * access modes. 3146 * <p> 3147 * If the field type is {@code float} or {@code double} then numeric 3148 * and atomic update access modes compare values using their bitwise 3149 * representation (see {@link Float#floatToRawIntBits} and 3150 * {@link Double#doubleToRawLongBits}, respectively). 3151 * @apiNote 3152 * Bitwise comparison of {@code float} values or {@code double} values, 3153 * as performed by the numeric and atomic update access modes, differ 3154 * from the primitive {@code ==} operator and the {@link Float#equals} 3155 * and {@link Double#equals} methods, specifically with respect to 3156 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3157 * Care should be taken when performing a compare and set or a compare 3158 * and exchange operation with such values since the operation may 3159 * unexpectedly fail. 3160 * There are many possible NaN values that are considered to be 3161 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3162 * provided by Java can distinguish between them. Operation failure can 3163 * occur if the expected or witness value is a NaN value and it is 3164 * transformed (perhaps in a platform specific manner) into another NaN 3165 * value, and thus has a different bitwise representation (see 3166 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3167 * details). 3168 * The values {@code -0.0} and {@code +0.0} have different bitwise 3169 * representations but are considered equal when using the primitive 3170 * {@code ==} operator. Operation failure can occur if, for example, a 3171 * numeric algorithm computes an expected value to be say {@code -0.0} 3172 * and previously computed the witness value to be say {@code +0.0}. 3173 * @param recv the receiver class, of type {@code R}, that declares the 3174 * non-static field 3175 * @param name the field's name 3176 * @param type the field's type, of type {@code T} 3177 * @return a VarHandle giving access to non-static fields. 3178 * @throws NoSuchFieldException if the field does not exist 3179 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3180 * @throws SecurityException if a security manager is present and it 3181 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3182 * @throws NullPointerException if any argument is null 3183 * @since 9 3184 */ 3185 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3186 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3187 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3188 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3189 } 3190 3191 /** 3192 * Produces a method handle giving read access to a static field. 3193 * The type of the method handle will have a return type of the field's 3194 * value type. 3195 * The method handle will take no arguments. 3196 * Access checking is performed immediately on behalf of the lookup class. 3197 * <p> 3198 * If the returned method handle is invoked, the field's class will 3199 * be initialized, if it has not already been initialized. 3200 * @param refc the class or interface from which the method is accessed 3201 * @param name the field's name 3202 * @param type the field's type 3203 * @return a method handle which can load values from the field 3204 * @throws NoSuchFieldException if the field does not exist 3205 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3206 * @throws SecurityException if a security manager is present and it 3207 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3208 * @throws NullPointerException if any argument is null 3209 */ 3210 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3211 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3212 return getDirectField(REF_getStatic, refc, field); 3213 } 3214 3215 /** 3216 * Produces a method handle giving write access to a static field. 3217 * The type of the method handle will have a void return type. 3218 * The method handle will take a single 3219 * argument, of the field's value type, the value to be stored. 3220 * Access checking is performed immediately on behalf of the lookup class. 3221 * <p> 3222 * If the returned method handle is invoked, the field's class will 3223 * be initialized, if it has not already been initialized. 3224 * @param refc the class or interface from which the method is accessed 3225 * @param name the field's name 3226 * @param type the field's type 3227 * @return a method handle which can store values into the field 3228 * @throws NoSuchFieldException if the field does not exist 3229 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3230 * or is {@code final} 3231 * @throws SecurityException if a security manager is present and it 3232 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3233 * @throws NullPointerException if any argument is null 3234 */ 3235 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3236 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3237 return getDirectField(REF_putStatic, refc, field); 3238 } 3239 3240 /** 3241 * Produces a VarHandle giving access to a static field {@code name} of 3242 * type {@code type} declared in a class of type {@code decl}. 3243 * The VarHandle's variable type is {@code type} and it has no 3244 * coordinate types. 3245 * <p> 3246 * Access checking is performed immediately on behalf of the lookup 3247 * class. 3248 * <p> 3249 * If the returned VarHandle is operated on, the declaring class will be 3250 * initialized, if it has not already been initialized. 3251 * <p> 3252 * Certain access modes of the returned VarHandle are unsupported under 3253 * the following conditions: 3254 * <ul> 3255 * <li>if the field is declared {@code final}, then the write, atomic 3256 * update, numeric atomic update, and bitwise atomic update access 3257 * modes are unsupported. 3258 * <li>if the field type is anything other than {@code byte}, 3259 * {@code short}, {@code char}, {@code int}, {@code long}, 3260 * {@code float}, or {@code double}, then numeric atomic update 3261 * access modes are unsupported. 3262 * <li>if the field type is anything other than {@code boolean}, 3263 * {@code byte}, {@code short}, {@code char}, {@code int} or 3264 * {@code long} then bitwise atomic update access modes are 3265 * unsupported. 3266 * </ul> 3267 * <p> 3268 * If the field is declared {@code volatile} then the returned VarHandle 3269 * will override access to the field (effectively ignore the 3270 * {@code volatile} declaration) in accordance to its specified 3271 * access modes. 3272 * <p> 3273 * If the field type is {@code float} or {@code double} then numeric 3274 * and atomic update access modes compare values using their bitwise 3275 * representation (see {@link Float#floatToRawIntBits} and 3276 * {@link Double#doubleToRawLongBits}, respectively). 3277 * @apiNote 3278 * Bitwise comparison of {@code float} values or {@code double} values, 3279 * as performed by the numeric and atomic update access modes, differ 3280 * from the primitive {@code ==} operator and the {@link Float#equals} 3281 * and {@link Double#equals} methods, specifically with respect to 3282 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3283 * Care should be taken when performing a compare and set or a compare 3284 * and exchange operation with such values since the operation may 3285 * unexpectedly fail. 3286 * There are many possible NaN values that are considered to be 3287 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3288 * provided by Java can distinguish between them. Operation failure can 3289 * occur if the expected or witness value is a NaN value and it is 3290 * transformed (perhaps in a platform specific manner) into another NaN 3291 * value, and thus has a different bitwise representation (see 3292 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3293 * details). 3294 * The values {@code -0.0} and {@code +0.0} have different bitwise 3295 * representations but are considered equal when using the primitive 3296 * {@code ==} operator. Operation failure can occur if, for example, a 3297 * numeric algorithm computes an expected value to be say {@code -0.0} 3298 * and previously computed the witness value to be say {@code +0.0}. 3299 * @param decl the class that declares the static field 3300 * @param name the field's name 3301 * @param type the field's type, of type {@code T} 3302 * @return a VarHandle giving access to a static field 3303 * @throws NoSuchFieldException if the field does not exist 3304 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3305 * @throws SecurityException if a security manager is present and it 3306 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3307 * @throws NullPointerException if any argument is null 3308 * @since 9 3309 */ 3310 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3311 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3312 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3313 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3314 } 3315 3316 /** 3317 * Produces an early-bound method handle for a non-static method. 3318 * The receiver must have a supertype {@code defc} in which a method 3319 * of the given name and type is accessible to the lookup class. 3320 * The method and all its argument types must be accessible to the lookup object. 3321 * The type of the method handle will be that of the method, 3322 * without any insertion of an additional receiver parameter. 3323 * The given receiver will be bound into the method handle, 3324 * so that every call to the method handle will invoke the 3325 * requested method on the given receiver. 3326 * <p> 3327 * The returned method handle will have 3328 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3329 * the method's variable arity modifier bit ({@code 0x0080}) is set 3330 * <em>and</em> the trailing array argument is not the only argument. 3331 * (If the trailing array argument is the only argument, 3332 * the given receiver value will be bound to it.) 3333 * <p> 3334 * This is almost equivalent to the following code, with some differences noted below: 3335 * {@snippet lang="java" : 3336 import static java.lang.invoke.MethodHandles.*; 3337 import static java.lang.invoke.MethodType.*; 3338 ... 3339 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3340 MethodHandle mh1 = mh0.bindTo(receiver); 3341 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3342 return mh1; 3343 * } 3344 * where {@code defc} is either {@code receiver.getClass()} or a super 3345 * type of that class, in which the requested method is accessible 3346 * to the lookup class. 3347 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3348 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3349 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3350 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3351 * @param receiver the object from which the method is accessed 3352 * @param name the name of the method 3353 * @param type the type of the method, with the receiver argument omitted 3354 * @return the desired method handle 3355 * @throws NoSuchMethodException if the method does not exist 3356 * @throws IllegalAccessException if access checking fails 3357 * or if the method's variable arity modifier bit 3358 * is set and {@code asVarargsCollector} fails 3359 * @throws SecurityException if a security manager is present and it 3360 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3361 * @throws NullPointerException if any argument is null 3362 * @see MethodHandle#bindTo 3363 * @see #findVirtual 3364 */ 3365 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3366 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3367 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3368 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3369 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3370 throw new IllegalAccessException("The restricted defining class " + 3371 mh.type().leadingReferenceParameter().getName() + 3372 " is not assignable from receiver class " + 3373 receiver.getClass().getName()); 3374 } 3375 return mh.bindArgumentL(0, receiver).setVarargs(method); 3376 } 3377 3378 /** 3379 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3380 * to <i>m</i>, if the lookup class has permission. 3381 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3382 * If <i>m</i> is virtual, overriding is respected on every call. 3383 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3384 * The type of the method handle will be that of the method, 3385 * with the receiver type prepended (but only if it is non-static). 3386 * If the method's {@code accessible} flag is not set, 3387 * access checking is performed immediately on behalf of the lookup class. 3388 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3389 * <p> 3390 * The returned method handle will have 3391 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3392 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3393 * <p> 3394 * If <i>m</i> is static, and 3395 * if the returned method handle is invoked, the method's class will 3396 * be initialized, if it has not already been initialized. 3397 * @param m the reflected method 3398 * @return a method handle which can invoke the reflected method 3399 * @throws IllegalAccessException if access checking fails 3400 * or if the method's variable arity modifier bit 3401 * is set and {@code asVarargsCollector} fails 3402 * @throws NullPointerException if the argument is null 3403 */ 3404 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3405 if (m.getDeclaringClass() == MethodHandle.class) { 3406 MethodHandle mh = unreflectForMH(m); 3407 if (mh != null) return mh; 3408 } 3409 if (m.getDeclaringClass() == VarHandle.class) { 3410 MethodHandle mh = unreflectForVH(m); 3411 if (mh != null) return mh; 3412 } 3413 MemberName method = new MemberName(m); 3414 byte refKind = method.getReferenceKind(); 3415 if (refKind == REF_invokeSpecial) 3416 refKind = REF_invokeVirtual; 3417 assert(method.isMethod()); 3418 @SuppressWarnings("deprecation") 3419 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3420 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3421 } 3422 private MethodHandle unreflectForMH(Method m) { 3423 // these names require special lookups because they throw UnsupportedOperationException 3424 if (MemberName.isMethodHandleInvokeName(m.getName())) 3425 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3426 return null; 3427 } 3428 private MethodHandle unreflectForVH(Method m) { 3429 // these names require special lookups because they throw UnsupportedOperationException 3430 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3431 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3432 return null; 3433 } 3434 3435 /** 3436 * Produces a method handle for a reflected method. 3437 * It will bypass checks for overriding methods on the receiver, 3438 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3439 * instruction from within the explicitly specified {@code specialCaller}. 3440 * The type of the method handle will be that of the method, 3441 * with a suitably restricted receiver type prepended. 3442 * (The receiver type will be {@code specialCaller} or a subtype.) 3443 * If the method's {@code accessible} flag is not set, 3444 * access checking is performed immediately on behalf of the lookup class, 3445 * as if {@code invokespecial} instruction were being linked. 3446 * <p> 3447 * Before method resolution, 3448 * if the explicitly specified caller class is not identical with the 3449 * lookup class, or if this lookup object does not have 3450 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3451 * privileges, the access fails. 3452 * <p> 3453 * The returned method handle will have 3454 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3455 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3456 * @param m the reflected method 3457 * @param specialCaller the class nominally calling the method 3458 * @return a method handle which can invoke the reflected method 3459 * @throws IllegalAccessException if access checking fails, 3460 * or if the method is {@code static}, 3461 * or if the method's variable arity modifier bit 3462 * is set and {@code asVarargsCollector} fails 3463 * @throws NullPointerException if any argument is null 3464 */ 3465 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3466 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3467 Lookup specialLookup = this.in(specialCaller); 3468 MemberName method = new MemberName(m, true); 3469 assert(method.isMethod()); 3470 // ignore m.isAccessible: this is a new kind of access 3471 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3472 } 3473 3474 /** 3475 * Produces a method handle for a reflected constructor. 3476 * The type of the method handle will be that of the constructor, 3477 * with the return type changed to the declaring class. 3478 * The method handle will perform a {@code newInstance} operation, 3479 * creating a new instance of the constructor's class on the 3480 * arguments passed to the method handle. 3481 * <p> 3482 * If the constructor's {@code accessible} flag is not set, 3483 * access checking is performed immediately on behalf of the lookup class. 3484 * <p> 3485 * The returned method handle will have 3486 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3487 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3488 * <p> 3489 * If the returned method handle is invoked, the constructor's class will 3490 * be initialized, if it has not already been initialized. 3491 * @param c the reflected constructor 3492 * @return a method handle which can invoke the reflected constructor 3493 * @throws IllegalAccessException if access checking fails 3494 * or if the method's variable arity modifier bit 3495 * is set and {@code asVarargsCollector} fails 3496 * @throws NullPointerException if the argument is null 3497 */ 3498 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3499 MemberName ctor = new MemberName(c); 3500 assert(ctor.isConstructor()); 3501 @SuppressWarnings("deprecation") 3502 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3503 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3504 } 3505 3506 /* 3507 * Produces a method handle that is capable of creating instances of the given class 3508 * and instantiated by the given constructor. No security manager check. 3509 * 3510 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3511 */ 3512 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3513 MemberName ctor = new MemberName(c); 3514 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3515 checkAccess(REF_newInvokeSpecial, decl, ctor); 3516 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3517 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3518 } 3519 3520 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3521 if (decl == ctor.getDeclaringClass()) 3522 return true; 3523 3524 Class<?> cl = decl; 3525 while ((cl = cl.getSuperclass()) != null) { 3526 if (cl == ctor.getDeclaringClass()) { 3527 return true; 3528 } 3529 } 3530 return false; 3531 } 3532 3533 /** 3534 * Produces a method handle giving read access to a reflected field. 3535 * The type of the method handle will have a return type of the field's 3536 * value type. 3537 * If the field is {@code static}, the method handle will take no arguments. 3538 * Otherwise, its single argument will be the instance containing 3539 * the field. 3540 * If the {@code Field} object's {@code accessible} flag is not set, 3541 * access checking is performed immediately on behalf of the lookup class. 3542 * <p> 3543 * If the field is static, and 3544 * if the returned method handle is invoked, the field's class will 3545 * be initialized, if it has not already been initialized. 3546 * @param f the reflected field 3547 * @return a method handle which can load values from the reflected field 3548 * @throws IllegalAccessException if access checking fails 3549 * @throws NullPointerException if the argument is null 3550 */ 3551 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3552 return unreflectField(f, false); 3553 } 3554 3555 /** 3556 * Produces a method handle giving write access to a reflected field. 3557 * The type of the method handle will have a void return type. 3558 * If the field is {@code static}, the method handle will take a single 3559 * argument, of the field's value type, the value to be stored. 3560 * Otherwise, the two arguments will be the instance containing 3561 * the field, and the value to be stored. 3562 * If the {@code Field} object's {@code accessible} flag is not set, 3563 * access checking is performed immediately on behalf of the lookup class. 3564 * <p> 3565 * If the field is {@code final}, write access will not be 3566 * allowed and access checking will fail, except under certain 3567 * narrow circumstances documented for {@link Field#set Field.set}. 3568 * A method handle is returned only if a corresponding call to 3569 * the {@code Field} object's {@code set} method could return 3570 * normally. In particular, fields which are both {@code static} 3571 * and {@code final} may never be set. 3572 * <p> 3573 * If the field is {@code static}, and 3574 * if the returned method handle is invoked, the field's class will 3575 * be initialized, if it has not already been initialized. 3576 * @param f the reflected field 3577 * @return a method handle which can store values into the reflected field 3578 * @throws IllegalAccessException if access checking fails, 3579 * or if the field is {@code final} and write access 3580 * is not enabled on the {@code Field} object 3581 * @throws NullPointerException if the argument is null 3582 */ 3583 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3584 return unreflectField(f, true); 3585 } 3586 3587 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3588 MemberName field = new MemberName(f, isSetter); 3589 if (isSetter && field.isFinal()) { 3590 if (field.isTrustedFinalField()) { 3591 String msg = field.isStatic() ? "static final field has no write access" 3592 : "final field has no write access"; 3593 throw field.makeAccessException(msg, this); 3594 } 3595 } 3596 assert(isSetter 3597 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3598 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3599 @SuppressWarnings("deprecation") 3600 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3601 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3602 } 3603 3604 /** 3605 * Produces a VarHandle giving access to a reflected field {@code f} 3606 * of type {@code T} declared in a class of type {@code R}. 3607 * The VarHandle's variable type is {@code T}. 3608 * If the field is non-static the VarHandle has one coordinate type, 3609 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3610 * coordinate types. 3611 * <p> 3612 * Access checking is performed immediately on behalf of the lookup 3613 * class, regardless of the value of the field's {@code accessible} 3614 * flag. 3615 * <p> 3616 * If the field is static, and if the returned VarHandle is operated 3617 * on, the field's declaring class will be initialized, if it has not 3618 * already been initialized. 3619 * <p> 3620 * Certain access modes of the returned VarHandle are unsupported under 3621 * the following conditions: 3622 * <ul> 3623 * <li>if the field is declared {@code final}, then the write, atomic 3624 * update, numeric atomic update, and bitwise atomic update access 3625 * modes are unsupported. 3626 * <li>if the field type is anything other than {@code byte}, 3627 * {@code short}, {@code char}, {@code int}, {@code long}, 3628 * {@code float}, or {@code double} then numeric atomic update 3629 * access modes are unsupported. 3630 * <li>if the field type is anything other than {@code boolean}, 3631 * {@code byte}, {@code short}, {@code char}, {@code int} or 3632 * {@code long} then bitwise atomic update access modes are 3633 * unsupported. 3634 * </ul> 3635 * <p> 3636 * If the field is declared {@code volatile} then the returned VarHandle 3637 * will override access to the field (effectively ignore the 3638 * {@code volatile} declaration) in accordance to its specified 3639 * access modes. 3640 * <p> 3641 * If the field type is {@code float} or {@code double} then numeric 3642 * and atomic update access modes compare values using their bitwise 3643 * representation (see {@link Float#floatToRawIntBits} and 3644 * {@link Double#doubleToRawLongBits}, respectively). 3645 * @apiNote 3646 * Bitwise comparison of {@code float} values or {@code double} values, 3647 * as performed by the numeric and atomic update access modes, differ 3648 * from the primitive {@code ==} operator and the {@link Float#equals} 3649 * and {@link Double#equals} methods, specifically with respect to 3650 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3651 * Care should be taken when performing a compare and set or a compare 3652 * and exchange operation with such values since the operation may 3653 * unexpectedly fail. 3654 * There are many possible NaN values that are considered to be 3655 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3656 * provided by Java can distinguish between them. Operation failure can 3657 * occur if the expected or witness value is a NaN value and it is 3658 * transformed (perhaps in a platform specific manner) into another NaN 3659 * value, and thus has a different bitwise representation (see 3660 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3661 * details). 3662 * The values {@code -0.0} and {@code +0.0} have different bitwise 3663 * representations but are considered equal when using the primitive 3664 * {@code ==} operator. Operation failure can occur if, for example, a 3665 * numeric algorithm computes an expected value to be say {@code -0.0} 3666 * and previously computed the witness value to be say {@code +0.0}. 3667 * @param f the reflected field, with a field of type {@code T}, and 3668 * a declaring class of type {@code R} 3669 * @return a VarHandle giving access to non-static fields or a static 3670 * field 3671 * @throws IllegalAccessException if access checking fails 3672 * @throws NullPointerException if the argument is null 3673 * @since 9 3674 */ 3675 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3676 MemberName getField = new MemberName(f, false); 3677 MemberName putField = new MemberName(f, true); 3678 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3679 f.getDeclaringClass(), getField, putField); 3680 } 3681 3682 /** 3683 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3684 * created by this lookup object or a similar one. 3685 * Security and access checks are performed to ensure that this lookup object 3686 * is capable of reproducing the target method handle. 3687 * This means that the cracking may fail if target is a direct method handle 3688 * but was created by an unrelated lookup object. 3689 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3690 * and was created by a lookup object for a different class. 3691 * @param target a direct method handle to crack into symbolic reference components 3692 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3693 * @throws SecurityException if a security manager is present and it 3694 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3695 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3696 * @throws NullPointerException if the target is {@code null} 3697 * @see MethodHandleInfo 3698 * @since 1.8 3699 */ 3700 public MethodHandleInfo revealDirect(MethodHandle target) { 3701 if (!target.isCrackable()) { 3702 throw newIllegalArgumentException("not a direct method handle"); 3703 } 3704 MemberName member = target.internalMemberName(); 3705 Class<?> defc = member.getDeclaringClass(); 3706 byte refKind = member.getReferenceKind(); 3707 assert(MethodHandleNatives.refKindIsValid(refKind)); 3708 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3709 // Devirtualized method invocation is usually formally virtual. 3710 // To avoid creating extra MemberName objects for this common case, 3711 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3712 refKind = REF_invokeVirtual; 3713 if (refKind == REF_invokeVirtual && defc.isInterface()) 3714 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3715 refKind = REF_invokeInterface; 3716 // Check SM permissions and member access before cracking. 3717 try { 3718 checkAccess(refKind, defc, member); 3719 checkSecurityManager(defc, member); 3720 } catch (IllegalAccessException ex) { 3721 throw new IllegalArgumentException(ex); 3722 } 3723 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3724 Class<?> callerClass = target.internalCallerClass(); 3725 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3726 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3727 } 3728 // Produce the handle to the results. 3729 return new InfoFromMemberName(this, member, refKind); 3730 } 3731 3732 //--- Helper methods, all package-private. 3733 3734 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3735 checkSymbolicClass(refc); // do this before attempting to resolve 3736 Objects.requireNonNull(name); 3737 Objects.requireNonNull(type); 3738 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3739 NoSuchFieldException.class); 3740 } 3741 3742 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3743 checkSymbolicClass(refc); // do this before attempting to resolve 3744 Objects.requireNonNull(type); 3745 checkMethodName(refKind, name); // implicit null-check of name 3746 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3747 NoSuchMethodException.class); 3748 } 3749 3750 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3751 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3752 Objects.requireNonNull(member.getName()); 3753 Objects.requireNonNull(member.getType()); 3754 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3755 ReflectiveOperationException.class); 3756 } 3757 3758 MemberName resolveOrNull(byte refKind, MemberName member) { 3759 // do this before attempting to resolve 3760 if (!isClassAccessible(member.getDeclaringClass())) { 3761 return null; 3762 } 3763 Objects.requireNonNull(member.getName()); 3764 Objects.requireNonNull(member.getType()); 3765 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3766 } 3767 3768 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3769 // do this before attempting to resolve 3770 if (!isClassAccessible(refc)) { 3771 return null; 3772 } 3773 Objects.requireNonNull(type); 3774 // implicit null-check of name 3775 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3776 return null; 3777 } 3778 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3779 } 3780 3781 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3782 if (!isClassAccessible(refc)) { 3783 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3784 } 3785 } 3786 3787 boolean isClassAccessible(Class<?> refc) { 3788 Objects.requireNonNull(refc); 3789 Class<?> caller = lookupClassOrNull(); 3790 Class<?> type = refc; 3791 while (type.isArray()) { 3792 type = type.getComponentType(); 3793 } 3794 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3795 } 3796 3797 /** Check name for an illegal leading "<" character. */ 3798 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3799 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3800 throw new NoSuchMethodException("illegal method name: "+name); 3801 } 3802 3803 /** 3804 * Find my trustable caller class if m is a caller sensitive method. 3805 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3806 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3807 */ 3808 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3809 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3810 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3811 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3812 } 3813 return this; 3814 } 3815 3816 /** 3817 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3818 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3819 * 3820 * @deprecated This method was originally designed to test {@code PRIVATE} access 3821 * that implies full privilege access but {@code MODULE} access has since become 3822 * independent of {@code PRIVATE} access. It is recommended to call 3823 * {@link #hasFullPrivilegeAccess()} instead. 3824 * @since 9 3825 */ 3826 @Deprecated(since="14") 3827 public boolean hasPrivateAccess() { 3828 return hasFullPrivilegeAccess(); 3829 } 3830 3831 /** 3832 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3833 * i.e. {@code PRIVATE} and {@code MODULE} access. 3834 * A {@code Lookup} object must have full privilege access in order to 3835 * access all members that are allowed to the 3836 * {@linkplain #lookupClass() lookup class}. 3837 * 3838 * @return {@code true} if this lookup has full privilege access. 3839 * @since 14 3840 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3841 */ 3842 public boolean hasFullPrivilegeAccess() { 3843 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3844 } 3845 3846 /** 3847 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3848 * for ensureInitialized, findClass or accessClass. 3849 */ 3850 void checkSecurityManager(Class<?> refc) { 3851 if (allowedModes == TRUSTED) return; 3852 3853 @SuppressWarnings("removal") 3854 SecurityManager smgr = System.getSecurityManager(); 3855 if (smgr == null) return; 3856 3857 // Step 1: 3858 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3859 if (!fullPrivilegeLookup || 3860 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3861 ReflectUtil.checkPackageAccess(refc); 3862 } 3863 3864 // Step 2b: 3865 if (!fullPrivilegeLookup) { 3866 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3867 } 3868 } 3869 3870 /** 3871 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3872 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3873 * If this lookup object has full privilege access except original access, 3874 * then the caller class is the lookupClass. 3875 * 3876 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3877 * from the same module skips the security permission check. 3878 */ 3879 void checkSecurityManager(Class<?> refc, MemberName m) { 3880 Objects.requireNonNull(refc); 3881 Objects.requireNonNull(m); 3882 3883 if (allowedModes == TRUSTED) return; 3884 3885 @SuppressWarnings("removal") 3886 SecurityManager smgr = System.getSecurityManager(); 3887 if (smgr == null) return; 3888 3889 // Step 1: 3890 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3891 if (!fullPrivilegeLookup || 3892 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3893 ReflectUtil.checkPackageAccess(refc); 3894 } 3895 3896 // Step 2a: 3897 if (m.isPublic()) return; 3898 if (!fullPrivilegeLookup) { 3899 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3900 } 3901 3902 // Step 3: 3903 Class<?> defc = m.getDeclaringClass(); 3904 if (!fullPrivilegeLookup && defc != refc) { 3905 ReflectUtil.checkPackageAccess(defc); 3906 } 3907 } 3908 3909 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3910 boolean wantStatic = (refKind == REF_invokeStatic); 3911 String message; 3912 if (m.isConstructor()) 3913 message = "expected a method, not a constructor"; 3914 else if (!m.isMethod()) 3915 message = "expected a method"; 3916 else if (wantStatic != m.isStatic()) 3917 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3918 else 3919 { checkAccess(refKind, refc, m); return; } 3920 throw m.makeAccessException(message, this); 3921 } 3922 3923 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3924 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3925 String message; 3926 if (wantStatic != m.isStatic()) 3927 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3928 else 3929 { checkAccess(refKind, refc, m); return; } 3930 throw m.makeAccessException(message, this); 3931 } 3932 3933 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3934 return Modifier.isProtected(m.getModifiers()) && 3935 refKind == REF_invokeVirtual && 3936 m.getDeclaringClass() == Object.class && 3937 m.getName().equals("clone") && 3938 refc.isArray(); 3939 } 3940 3941 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3942 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3943 assert(m.referenceKindIsConsistentWith(refKind) && 3944 MethodHandleNatives.refKindIsValid(refKind) && 3945 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3946 int allowedModes = this.allowedModes; 3947 if (allowedModes == TRUSTED) return; 3948 int mods = m.getModifiers(); 3949 if (isArrayClone(refKind, refc, m)) { 3950 // The JVM does this hack also. 3951 // (See ClassVerifier::verify_invoke_instructions 3952 // and LinkResolver::check_method_accessability.) 3953 // Because the JVM does not allow separate methods on array types, 3954 // there is no separate method for int[].clone. 3955 // All arrays simply inherit Object.clone. 3956 // But for access checking logic, we make Object.clone 3957 // (normally protected) appear to be public. 3958 // Later on, when the DirectMethodHandle is created, 3959 // its leading argument will be restricted to the 3960 // requested array type. 3961 // N.B. The return type is not adjusted, because 3962 // that is *not* the bytecode behavior. 3963 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3964 } 3965 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3966 // cannot "new" a protected ctor in a different package 3967 mods ^= Modifier.PROTECTED; 3968 } 3969 if (Modifier.isFinal(mods) && 3970 MethodHandleNatives.refKindIsSetter(refKind)) 3971 throw m.makeAccessException("unexpected set of a final field", this); 3972 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3973 if ((requestedModes & allowedModes) != 0) { 3974 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3975 mods, lookupClass(), previousLookupClass(), allowedModes)) 3976 return; 3977 } else { 3978 // Protected members can also be checked as if they were package-private. 3979 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3980 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3981 return; 3982 } 3983 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3984 } 3985 3986 String accessFailedMessage(Class<?> refc, MemberName m) { 3987 Class<?> defc = m.getDeclaringClass(); 3988 int mods = m.getModifiers(); 3989 // check the class first: 3990 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3991 (defc == refc || 3992 Modifier.isPublic(refc.getModifiers()))); 3993 if (!classOK && (allowedModes & PACKAGE) != 0) { 3994 // ignore previous lookup class to check if default package access 3995 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3996 (defc == refc || 3997 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3998 } 3999 if (!classOK) 4000 return "class is not public"; 4001 if (Modifier.isPublic(mods)) 4002 return "access to public member failed"; // (how?, module not readable?) 4003 if (Modifier.isPrivate(mods)) 4004 return "member is private"; 4005 if (Modifier.isProtected(mods)) 4006 return "member is protected"; 4007 return "member is private to package"; 4008 } 4009 4010 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 4011 int allowedModes = this.allowedModes; 4012 if (allowedModes == TRUSTED) return; 4013 if ((lookupModes() & PRIVATE) == 0 4014 || (specialCaller != lookupClass() 4015 // ensure non-abstract methods in superinterfaces can be special-invoked 4016 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 4017 throw new MemberName(specialCaller). 4018 makeAccessException("no private access for invokespecial", this); 4019 } 4020 4021 private boolean restrictProtectedReceiver(MemberName method) { 4022 // The accessing class only has the right to use a protected member 4023 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 4024 if (!method.isProtected() || method.isStatic() 4025 || allowedModes == TRUSTED 4026 || method.getDeclaringClass() == lookupClass() 4027 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 4028 return false; 4029 return true; 4030 } 4031 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 4032 assert(!method.isStatic()); 4033 // receiver type of mh is too wide; narrow to caller 4034 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 4035 throw method.makeAccessException("caller class must be a subclass below the method", caller); 4036 } 4037 MethodType rawType = mh.type(); 4038 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 4039 MethodType narrowType = rawType.changeParameterType(0, caller); 4040 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 4041 assert(mh.viewAsTypeChecks(narrowType, true)); 4042 return mh.copyWith(narrowType, mh.form); 4043 } 4044 4045 /** Check access and get the requested method. */ 4046 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4047 final boolean doRestrict = true; 4048 final boolean checkSecurity = true; 4049 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4050 } 4051 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 4052 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4053 final boolean doRestrict = false; 4054 final boolean checkSecurity = true; 4055 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 4056 } 4057 /** Check access and get the requested method, eliding security manager checks. */ 4058 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4059 final boolean doRestrict = true; 4060 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4061 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4062 } 4063 /** Common code for all methods; do not call directly except from immediately above. */ 4064 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 4065 boolean checkSecurity, 4066 boolean doRestrict, 4067 Lookup boundCaller) throws IllegalAccessException { 4068 checkMethod(refKind, refc, method); 4069 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4070 if (checkSecurity) 4071 checkSecurityManager(refc, method); 4072 assert(!method.isMethodHandleInvoke()); 4073 if (refKind == REF_invokeSpecial && 4074 refc != lookupClass() && 4075 !refc.isInterface() && !lookupClass().isInterface() && 4076 refc != lookupClass().getSuperclass() && 4077 refc.isAssignableFrom(lookupClass())) { 4078 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 4079 4080 // Per JVMS 6.5, desc. of invokespecial instruction: 4081 // If the method is in a superclass of the LC, 4082 // and if our original search was above LC.super, 4083 // repeat the search (symbolic lookup) from LC.super 4084 // and continue with the direct superclass of that class, 4085 // and so forth, until a match is found or no further superclasses exist. 4086 // FIXME: MemberName.resolve should handle this instead. 4087 Class<?> refcAsSuper = lookupClass(); 4088 MemberName m2; 4089 do { 4090 refcAsSuper = refcAsSuper.getSuperclass(); 4091 m2 = new MemberName(refcAsSuper, 4092 method.getName(), 4093 method.getMethodType(), 4094 REF_invokeSpecial); 4095 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4096 } while (m2 == null && // no method is found yet 4097 refc != refcAsSuper); // search up to refc 4098 if (m2 == null) throw new InternalError(method.toString()); 4099 method = m2; 4100 refc = refcAsSuper; 4101 // redo basic checks 4102 checkMethod(refKind, refc, method); 4103 } 4104 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4105 MethodHandle mh = dmh; 4106 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4107 if ((doRestrict && refKind == REF_invokeSpecial) || 4108 (MethodHandleNatives.refKindHasReceiver(refKind) && 4109 restrictProtectedReceiver(method) && 4110 // All arrays simply inherit the protected Object.clone method. 4111 // The leading argument is already restricted to the requested 4112 // array type (not the lookup class). 4113 !isArrayClone(refKind, refc, method))) { 4114 mh = restrictReceiver(method, dmh, lookupClass()); 4115 } 4116 mh = maybeBindCaller(method, mh, boundCaller); 4117 mh = mh.setVarargs(method); 4118 return mh; 4119 } 4120 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4121 throws IllegalAccessException { 4122 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4123 return mh; 4124 4125 // boundCaller must have full privilege access. 4126 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4127 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4128 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4129 4130 assert boundCaller.hasFullPrivilegeAccess(); 4131 4132 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4133 // Note: caller will apply varargs after this step happens. 4134 return cbmh; 4135 } 4136 4137 /** Check access and get the requested field. */ 4138 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4139 final boolean checkSecurity = true; 4140 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4141 } 4142 /** Check access and get the requested field, eliding security manager checks. */ 4143 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4144 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4145 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4146 } 4147 /** Common code for all fields; do not call directly except from immediately above. */ 4148 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4149 boolean checkSecurity) throws IllegalAccessException { 4150 checkField(refKind, refc, field); 4151 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4152 if (checkSecurity) 4153 checkSecurityManager(refc, field); 4154 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4155 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4156 restrictProtectedReceiver(field)); 4157 if (doRestrict) 4158 return restrictReceiver(field, dmh, lookupClass()); 4159 return dmh; 4160 } 4161 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4162 Class<?> refc, MemberName getField, MemberName putField) 4163 throws IllegalAccessException { 4164 final boolean checkSecurity = true; 4165 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4166 } 4167 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4168 Class<?> refc, MemberName getField, MemberName putField) 4169 throws IllegalAccessException { 4170 final boolean checkSecurity = false; 4171 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4172 } 4173 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4174 Class<?> refc, MemberName getField, MemberName putField, 4175 boolean checkSecurity) throws IllegalAccessException { 4176 assert getField.isStatic() == putField.isStatic(); 4177 assert getField.isGetter() && putField.isSetter(); 4178 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4179 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4180 4181 checkField(getRefKind, refc, getField); 4182 if (checkSecurity) 4183 checkSecurityManager(refc, getField); 4184 4185 if (!putField.isFinal()) { 4186 // A VarHandle does not support updates to final fields, any 4187 // such VarHandle to a final field will be read-only and 4188 // therefore the following write-based accessibility checks are 4189 // only required for non-final fields 4190 checkField(putRefKind, refc, putField); 4191 if (checkSecurity) 4192 checkSecurityManager(refc, putField); 4193 } 4194 4195 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4196 restrictProtectedReceiver(getField)); 4197 if (doRestrict) { 4198 assert !getField.isStatic(); 4199 // receiver type of VarHandle is too wide; narrow to caller 4200 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4201 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4202 } 4203 refc = lookupClass(); 4204 } 4205 return VarHandles.makeFieldHandle(getField, refc, 4206 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4207 } 4208 /** Check access and get the requested constructor. */ 4209 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4210 final boolean checkSecurity = true; 4211 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4212 } 4213 /** Check access and get the requested constructor, eliding security manager checks. */ 4214 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4215 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4216 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4217 } 4218 /** Common code for all constructors; do not call directly except from immediately above. */ 4219 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4220 boolean checkSecurity) throws IllegalAccessException { 4221 assert(ctor.isConstructor()); 4222 checkAccess(REF_newInvokeSpecial, refc, ctor); 4223 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4224 if (checkSecurity) 4225 checkSecurityManager(refc, ctor); 4226 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4227 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4228 } 4229 4230 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4231 */ 4232 /*non-public*/ 4233 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4234 throws ReflectiveOperationException { 4235 if (!(type instanceof Class || type instanceof MethodType)) 4236 throw new InternalError("unresolved MemberName"); 4237 MemberName member = new MemberName(refKind, defc, name, type); 4238 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4239 if (mh != null) { 4240 checkSymbolicClass(defc); 4241 return mh; 4242 } 4243 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4244 // Treat MethodHandle.invoke and invokeExact specially. 4245 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4246 if (mh != null) { 4247 return mh; 4248 } 4249 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4250 // Treat signature-polymorphic methods on VarHandle specially. 4251 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4252 if (mh != null) { 4253 return mh; 4254 } 4255 } 4256 MemberName resolved = resolveOrFail(refKind, member); 4257 mh = getDirectMethodForConstant(refKind, defc, resolved); 4258 if (mh instanceof DirectMethodHandle dmh 4259 && canBeCached(refKind, defc, resolved)) { 4260 MemberName key = mh.internalMemberName(); 4261 if (key != null) { 4262 key = key.asNormalOriginal(); 4263 } 4264 if (member.equals(key)) { // better safe than sorry 4265 LOOKASIDE_TABLE.put(key, dmh); 4266 } 4267 } 4268 return mh; 4269 } 4270 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4271 if (refKind == REF_invokeSpecial) { 4272 return false; 4273 } 4274 if (!Modifier.isPublic(defc.getModifiers()) || 4275 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4276 !member.isPublic() || 4277 member.isCallerSensitive()) { 4278 return false; 4279 } 4280 ClassLoader loader = defc.getClassLoader(); 4281 if (loader != null) { 4282 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4283 boolean found = false; 4284 while (sysl != null) { 4285 if (loader == sysl) { found = true; break; } 4286 sysl = sysl.getParent(); 4287 } 4288 if (!found) { 4289 return false; 4290 } 4291 } 4292 try { 4293 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4294 new MemberName(refKind, defc, member.getName(), member.getType())); 4295 if (resolved2 == null) { 4296 return false; 4297 } 4298 checkSecurityManager(defc, resolved2); 4299 } catch (SecurityException ex) { 4300 return false; 4301 } 4302 return true; 4303 } 4304 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4305 throws ReflectiveOperationException { 4306 if (MethodHandleNatives.refKindIsField(refKind)) { 4307 return getDirectFieldNoSecurityManager(refKind, defc, member); 4308 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4309 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4310 } else if (refKind == REF_newInvokeSpecial) { 4311 return getDirectConstructorNoSecurityManager(defc, member); 4312 } 4313 // oops 4314 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4315 } 4316 4317 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4318 } 4319 4320 /** 4321 * Produces a method handle constructing arrays of a desired type, 4322 * as if by the {@code anewarray} bytecode. 4323 * The return type of the method handle will be the array type. 4324 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4325 * 4326 * <p> If the returned method handle is invoked with a negative 4327 * array size, a {@code NegativeArraySizeException} will be thrown. 4328 * 4329 * @param arrayClass an array type 4330 * @return a method handle which can create arrays of the given type 4331 * @throws NullPointerException if the argument is {@code null} 4332 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4333 * @see java.lang.reflect.Array#newInstance(Class, int) 4334 * @jvms 6.5 {@code anewarray} Instruction 4335 * @since 9 4336 */ 4337 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4338 if (!arrayClass.isArray()) { 4339 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4340 } 4341 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4342 bindTo(arrayClass.getComponentType()); 4343 return ani.asType(ani.type().changeReturnType(arrayClass)); 4344 } 4345 4346 /** 4347 * Produces a method handle returning the length of an array, 4348 * as if by the {@code arraylength} bytecode. 4349 * The type of the method handle will have {@code int} as return type, 4350 * and its sole argument will be the array type. 4351 * 4352 * <p> If the returned method handle is invoked with a {@code null} 4353 * array reference, a {@code NullPointerException} will be thrown. 4354 * 4355 * @param arrayClass an array type 4356 * @return a method handle which can retrieve the length of an array of the given array type 4357 * @throws NullPointerException if the argument is {@code null} 4358 * @throws IllegalArgumentException if arrayClass is not an array type 4359 * @jvms 6.5 {@code arraylength} Instruction 4360 * @since 9 4361 */ 4362 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4363 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4364 } 4365 4366 /** 4367 * Produces a method handle giving read access to elements of an array, 4368 * as if by the {@code aaload} bytecode. 4369 * The type of the method handle will have a return type of the array's 4370 * element type. Its first argument will be the array type, 4371 * and the second will be {@code int}. 4372 * 4373 * <p> When the returned method handle is invoked, 4374 * the array reference and array index are checked. 4375 * A {@code NullPointerException} will be thrown if the array reference 4376 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4377 * thrown if the index is negative or if it is greater than or equal to 4378 * the length of the array. 4379 * 4380 * @param arrayClass an array type 4381 * @return a method handle which can load values from the given array type 4382 * @throws NullPointerException if the argument is null 4383 * @throws IllegalArgumentException if arrayClass is not an array type 4384 * @jvms 6.5 {@code aaload} Instruction 4385 */ 4386 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4387 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4388 } 4389 4390 /** 4391 * Produces a method handle giving write access to elements of an array, 4392 * as if by the {@code astore} bytecode. 4393 * The type of the method handle will have a void return type. 4394 * Its last argument will be the array's element type. 4395 * The first and second arguments will be the array type and int. 4396 * 4397 * <p> When the returned method handle is invoked, 4398 * the array reference and array index are checked. 4399 * A {@code NullPointerException} will be thrown if the array reference 4400 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4401 * thrown if the index is negative or if it is greater than or equal to 4402 * the length of the array. 4403 * 4404 * @param arrayClass the class of an array 4405 * @return a method handle which can store values into the array type 4406 * @throws NullPointerException if the argument is null 4407 * @throws IllegalArgumentException if arrayClass is not an array type 4408 * @jvms 6.5 {@code aastore} Instruction 4409 */ 4410 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4411 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4412 } 4413 4414 /** 4415 * Produces a VarHandle giving access to elements of an array of type 4416 * {@code arrayClass}. The VarHandle's variable type is the component type 4417 * of {@code arrayClass} and the list of coordinate types is 4418 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4419 * corresponds to an argument that is an index into an array. 4420 * <p> 4421 * Certain access modes of the returned VarHandle are unsupported under 4422 * the following conditions: 4423 * <ul> 4424 * <li>if the component type is anything other than {@code byte}, 4425 * {@code short}, {@code char}, {@code int}, {@code long}, 4426 * {@code float}, or {@code double} then numeric atomic update access 4427 * modes are unsupported. 4428 * <li>if the component type is anything other than {@code boolean}, 4429 * {@code byte}, {@code short}, {@code char}, {@code int} or 4430 * {@code long} then bitwise atomic update access modes are 4431 * unsupported. 4432 * </ul> 4433 * <p> 4434 * If the component type is {@code float} or {@code double} then numeric 4435 * and atomic update access modes compare values using their bitwise 4436 * representation (see {@link Float#floatToRawIntBits} and 4437 * {@link Double#doubleToRawLongBits}, respectively). 4438 * 4439 * <p> When the returned {@code VarHandle} is invoked, 4440 * the array reference and array index are checked. 4441 * A {@code NullPointerException} will be thrown if the array reference 4442 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4443 * thrown if the index is negative or if it is greater than or equal to 4444 * the length of the array. 4445 * 4446 * @apiNote 4447 * Bitwise comparison of {@code float} values or {@code double} values, 4448 * as performed by the numeric and atomic update access modes, differ 4449 * from the primitive {@code ==} operator and the {@link Float#equals} 4450 * and {@link Double#equals} methods, specifically with respect to 4451 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4452 * Care should be taken when performing a compare and set or a compare 4453 * and exchange operation with such values since the operation may 4454 * unexpectedly fail. 4455 * There are many possible NaN values that are considered to be 4456 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4457 * provided by Java can distinguish between them. Operation failure can 4458 * occur if the expected or witness value is a NaN value and it is 4459 * transformed (perhaps in a platform specific manner) into another NaN 4460 * value, and thus has a different bitwise representation (see 4461 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4462 * details). 4463 * The values {@code -0.0} and {@code +0.0} have different bitwise 4464 * representations but are considered equal when using the primitive 4465 * {@code ==} operator. Operation failure can occur if, for example, a 4466 * numeric algorithm computes an expected value to be say {@code -0.0} 4467 * and previously computed the witness value to be say {@code +0.0}. 4468 * @param arrayClass the class of an array, of type {@code T[]} 4469 * @return a VarHandle giving access to elements of an array 4470 * @throws NullPointerException if the arrayClass is null 4471 * @throws IllegalArgumentException if arrayClass is not an array type 4472 * @since 9 4473 */ 4474 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4475 return VarHandles.makeArrayElementHandle(arrayClass); 4476 } 4477 4478 /** 4479 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4480 * viewed as if it were a different primitive array type, such as 4481 * {@code int[]} or {@code long[]}. 4482 * The VarHandle's variable type is the component type of 4483 * {@code viewArrayClass} and the list of coordinate types is 4484 * {@code (byte[], int)}, where the {@code int} coordinate type 4485 * corresponds to an argument that is an index into a {@code byte[]} array. 4486 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4487 * array, composing bytes to or from a value of the component type of 4488 * {@code viewArrayClass} according to the given endianness. 4489 * <p> 4490 * The supported component types (variables types) are {@code short}, 4491 * {@code char}, {@code int}, {@code long}, {@code float} and 4492 * {@code double}. 4493 * <p> 4494 * Access of bytes at a given index will result in an 4495 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4496 * or greater than the {@code byte[]} array length minus the size (in bytes) 4497 * of {@code T}. 4498 * <p> 4499 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4500 * access modes are supported by the returned var handle. For all other access modes, an 4501 * {@link UnsupportedOperationException} will be thrown. 4502 * 4503 * @apiNote if access modes other than plain access are required, clients should 4504 * consider using off-heap memory through 4505 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4506 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4507 * or memory segments backed by a 4508 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4509 * for which stronger alignment guarantees can be made. 4510 * 4511 * @param viewArrayClass the view array class, with a component type of 4512 * type {@code T} 4513 * @param byteOrder the endianness of the view array elements, as 4514 * stored in the underlying {@code byte} array 4515 * @return a VarHandle giving access to elements of a {@code byte[]} array 4516 * viewed as if elements corresponding to the components type of the view 4517 * array class 4518 * @throws NullPointerException if viewArrayClass or byteOrder is null 4519 * @throws IllegalArgumentException if viewArrayClass is not an array type 4520 * @throws UnsupportedOperationException if the component type of 4521 * viewArrayClass is not supported as a variable type 4522 * @since 9 4523 */ 4524 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4525 ByteOrder byteOrder) throws IllegalArgumentException { 4526 Objects.requireNonNull(byteOrder); 4527 return VarHandles.byteArrayViewHandle(viewArrayClass, 4528 byteOrder == ByteOrder.BIG_ENDIAN); 4529 } 4530 4531 /** 4532 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4533 * viewed as if it were an array of elements of a different primitive 4534 * component type to that of {@code byte}, such as {@code int[]} or 4535 * {@code long[]}. 4536 * The VarHandle's variable type is the component type of 4537 * {@code viewArrayClass} and the list of coordinate types is 4538 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4539 * corresponds to an argument that is an index into a {@code byte[]} array. 4540 * The returned VarHandle accesses bytes at an index in a 4541 * {@code ByteBuffer}, composing bytes to or from a value of the component 4542 * type of {@code viewArrayClass} according to the given endianness. 4543 * <p> 4544 * The supported component types (variables types) are {@code short}, 4545 * {@code char}, {@code int}, {@code long}, {@code float} and 4546 * {@code double}. 4547 * <p> 4548 * Access will result in a {@code ReadOnlyBufferException} for anything 4549 * other than the read access modes if the {@code ByteBuffer} is read-only. 4550 * <p> 4551 * Access of bytes at a given index will result in an 4552 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4553 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4554 * {@code T}. 4555 * <p> 4556 * For heap byte buffers, access is always unaligned. As a result, only the plain 4557 * {@linkplain VarHandle.AccessMode#GET get} 4558 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4559 * returned var handle. For all other access modes, an {@link IllegalStateException} 4560 * will be thrown. 4561 * <p> 4562 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4563 * with respect to the underlying memory address, {@code A} say, associated 4564 * with the {@code ByteBuffer} and index. 4565 * If access is misaligned then access for anything other than the 4566 * {@code get} and {@code set} access modes will result in an 4567 * {@code IllegalStateException}. In such cases atomic access is only 4568 * guaranteed with respect to the largest power of two that divides the GCD 4569 * of {@code A} and the size (in bytes) of {@code T}. 4570 * If access is aligned then following access modes are supported and are 4571 * guaranteed to support atomic access: 4572 * <ul> 4573 * <li>read write access modes for all {@code T}, with the exception of 4574 * access modes {@code get} and {@code set} for {@code long} and 4575 * {@code double} on 32-bit platforms. 4576 * <li>atomic update access modes for {@code int}, {@code long}, 4577 * {@code float} or {@code double}. 4578 * (Future major platform releases of the JDK may support additional 4579 * types for certain currently unsupported access modes.) 4580 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4581 * (Future major platform releases of the JDK may support additional 4582 * numeric types for certain currently unsupported access modes.) 4583 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4584 * (Future major platform releases of the JDK may support additional 4585 * numeric types for certain currently unsupported access modes.) 4586 * </ul> 4587 * <p> 4588 * Misaligned access, and therefore atomicity guarantees, may be determined 4589 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4590 * {@code index}, {@code T} and its corresponding boxed type, 4591 * {@code T_BOX}, as follows: 4592 * <pre>{@code 4593 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4594 * ByteBuffer bb = ... 4595 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4596 * boolean isMisaligned = misalignedAtIndex != 0; 4597 * }</pre> 4598 * <p> 4599 * If the variable type is {@code float} or {@code double} then atomic 4600 * update access modes compare values using their bitwise representation 4601 * (see {@link Float#floatToRawIntBits} and 4602 * {@link Double#doubleToRawLongBits}, respectively). 4603 * @param viewArrayClass the view array class, with a component type of 4604 * type {@code T} 4605 * @param byteOrder the endianness of the view array elements, as 4606 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4607 * endianness of a {@code ByteBuffer}) 4608 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4609 * viewed as if elements corresponding to the components type of the view 4610 * array class 4611 * @throws NullPointerException if viewArrayClass or byteOrder is null 4612 * @throws IllegalArgumentException if viewArrayClass is not an array type 4613 * @throws UnsupportedOperationException if the component type of 4614 * viewArrayClass is not supported as a variable type 4615 * @since 9 4616 */ 4617 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4618 ByteOrder byteOrder) throws IllegalArgumentException { 4619 Objects.requireNonNull(byteOrder); 4620 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4621 byteOrder == ByteOrder.BIG_ENDIAN); 4622 } 4623 4624 4625 //--- method handle invocation (reflective style) 4626 4627 /** 4628 * Produces a method handle which will invoke any method handle of the 4629 * given {@code type}, with a given number of trailing arguments replaced by 4630 * a single trailing {@code Object[]} array. 4631 * The resulting invoker will be a method handle with the following 4632 * arguments: 4633 * <ul> 4634 * <li>a single {@code MethodHandle} target 4635 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4636 * <li>an {@code Object[]} array containing trailing arguments 4637 * </ul> 4638 * <p> 4639 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4640 * the indicated {@code type}. 4641 * That is, if the target is exactly of the given {@code type}, it will behave 4642 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4643 * is used to convert the target to the required {@code type}. 4644 * <p> 4645 * The type of the returned invoker will not be the given {@code type}, but rather 4646 * will have all parameters except the first {@code leadingArgCount} 4647 * replaced by a single array of type {@code Object[]}, which will be 4648 * the final parameter. 4649 * <p> 4650 * Before invoking its target, the invoker will spread the final array, apply 4651 * reference casts as necessary, and unbox and widen primitive arguments. 4652 * If, when the invoker is called, the supplied array argument does 4653 * not have the correct number of elements, the invoker will throw 4654 * an {@link IllegalArgumentException} instead of invoking the target. 4655 * <p> 4656 * This method is equivalent to the following code (though it may be more efficient): 4657 * {@snippet lang="java" : 4658 MethodHandle invoker = MethodHandles.invoker(type); 4659 int spreadArgCount = type.parameterCount() - leadingArgCount; 4660 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4661 return invoker; 4662 * } 4663 * This method throws no reflective or security exceptions. 4664 * @param type the desired target type 4665 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4666 * @return a method handle suitable for invoking any method handle of the given type 4667 * @throws NullPointerException if {@code type} is null 4668 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4669 * the range from 0 to {@code type.parameterCount()} inclusive, 4670 * or if the resulting method handle's type would have 4671 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4672 */ 4673 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4674 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4675 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4676 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4677 return type.invokers().spreadInvoker(leadingArgCount); 4678 } 4679 4680 /** 4681 * Produces a special <em>invoker method handle</em> which can be used to 4682 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4683 * The resulting invoker will have a type which is 4684 * exactly equal to the desired type, except that it will accept 4685 * an additional leading argument of type {@code MethodHandle}. 4686 * <p> 4687 * This method is equivalent to the following code (though it may be more efficient): 4688 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4689 * 4690 * <p style="font-size:smaller;"> 4691 * <em>Discussion:</em> 4692 * Invoker method handles can be useful when working with variable method handles 4693 * of unknown types. 4694 * For example, to emulate an {@code invokeExact} call to a variable method 4695 * handle {@code M}, extract its type {@code T}, 4696 * look up the invoker method {@code X} for {@code T}, 4697 * and call the invoker method, as {@code X.invoke(T, A...)}. 4698 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4699 * is unknown.) 4700 * If spreading, collecting, or other argument transformations are required, 4701 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4702 * method handle values, as long as they are compatible with the type of {@code X}. 4703 * <p style="font-size:smaller;"> 4704 * <em>(Note: The invoker method is not available via the Core Reflection API. 4705 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4706 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4707 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4708 * <p> 4709 * This method throws no reflective or security exceptions. 4710 * @param type the desired target type 4711 * @return a method handle suitable for invoking any method handle of the given type 4712 * @throws IllegalArgumentException if the resulting method handle's type would have 4713 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4714 */ 4715 public static MethodHandle exactInvoker(MethodType type) { 4716 return type.invokers().exactInvoker(); 4717 } 4718 4719 /** 4720 * Produces a special <em>invoker method handle</em> which can be used to 4721 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4722 * The resulting invoker will have a type which is 4723 * exactly equal to the desired type, except that it will accept 4724 * an additional leading argument of type {@code MethodHandle}. 4725 * <p> 4726 * Before invoking its target, if the target differs from the expected type, 4727 * the invoker will apply reference casts as 4728 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4729 * Similarly, the return value will be converted as necessary. 4730 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4731 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4732 * <p> 4733 * This method is equivalent to the following code (though it may be more efficient): 4734 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4735 * <p style="font-size:smaller;"> 4736 * <em>Discussion:</em> 4737 * A {@linkplain MethodType#genericMethodType general method type} is one which 4738 * mentions only {@code Object} arguments and return values. 4739 * An invoker for such a type is capable of calling any method handle 4740 * of the same arity as the general type. 4741 * <p style="font-size:smaller;"> 4742 * <em>(Note: The invoker method is not available via the Core Reflection API. 4743 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4744 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4745 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4746 * <p> 4747 * This method throws no reflective or security exceptions. 4748 * @param type the desired target type 4749 * @return a method handle suitable for invoking any method handle convertible to the given type 4750 * @throws IllegalArgumentException if the resulting method handle's type would have 4751 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4752 */ 4753 public static MethodHandle invoker(MethodType type) { 4754 return type.invokers().genericInvoker(); 4755 } 4756 4757 /** 4758 * Produces a special <em>invoker method handle</em> which can be used to 4759 * invoke a signature-polymorphic access mode method on any VarHandle whose 4760 * associated access mode type is compatible with the given type. 4761 * The resulting invoker will have a type which is exactly equal to the 4762 * desired given type, except that it will accept an additional leading 4763 * argument of type {@code VarHandle}. 4764 * 4765 * @param accessMode the VarHandle access mode 4766 * @param type the desired target type 4767 * @return a method handle suitable for invoking an access mode method of 4768 * any VarHandle whose access mode type is of the given type. 4769 * @since 9 4770 */ 4771 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4772 return type.invokers().varHandleMethodExactInvoker(accessMode); 4773 } 4774 4775 /** 4776 * Produces a special <em>invoker method handle</em> which can be used to 4777 * invoke a signature-polymorphic access mode method on any VarHandle whose 4778 * associated access mode type is compatible with the given type. 4779 * The resulting invoker will have a type which is exactly equal to the 4780 * desired given type, except that it will accept an additional leading 4781 * argument of type {@code VarHandle}. 4782 * <p> 4783 * Before invoking its target, if the access mode type differs from the 4784 * desired given type, the invoker will apply reference casts as necessary 4785 * and box, unbox, or widen primitive values, as if by 4786 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4787 * converted as necessary. 4788 * <p> 4789 * This method is equivalent to the following code (though it may be more 4790 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4791 * 4792 * @param accessMode the VarHandle access mode 4793 * @param type the desired target type 4794 * @return a method handle suitable for invoking an access mode method of 4795 * any VarHandle whose access mode type is convertible to the given 4796 * type. 4797 * @since 9 4798 */ 4799 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4800 return type.invokers().varHandleMethodInvoker(accessMode); 4801 } 4802 4803 /*non-public*/ 4804 static MethodHandle basicInvoker(MethodType type) { 4805 return type.invokers().basicInvoker(); 4806 } 4807 4808 //--- method handle modification (creation from other method handles) 4809 4810 /** 4811 * Produces a method handle which adapts the type of the 4812 * given method handle to a new type by pairwise argument and return type conversion. 4813 * The original type and new type must have the same number of arguments. 4814 * The resulting method handle is guaranteed to report a type 4815 * which is equal to the desired new type. 4816 * <p> 4817 * If the original type and new type are equal, returns target. 4818 * <p> 4819 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4820 * and some additional conversions are also applied if those conversions fail. 4821 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4822 * if possible, before or instead of any conversions done by {@code asType}: 4823 * <ul> 4824 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4825 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4826 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4827 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4828 * the boolean is converted to a byte value, 1 for true, 0 for false. 4829 * (This treatment follows the usage of the bytecode verifier.) 4830 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4831 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4832 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4833 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4834 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4835 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4836 * widening and/or narrowing.) 4837 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4838 * conversion will be applied at runtime, possibly followed 4839 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4840 * possibly followed by a conversion from byte to boolean by testing 4841 * the low-order bit. 4842 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4843 * and if the reference is null at runtime, a zero value is introduced. 4844 * </ul> 4845 * @param target the method handle to invoke after arguments are retyped 4846 * @param newType the expected type of the new method handle 4847 * @return a method handle which delegates to the target after performing 4848 * any necessary argument conversions, and arranges for any 4849 * necessary return value conversions 4850 * @throws NullPointerException if either argument is null 4851 * @throws WrongMethodTypeException if the conversion cannot be made 4852 * @see MethodHandle#asType 4853 */ 4854 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4855 explicitCastArgumentsChecks(target, newType); 4856 // use the asTypeCache when possible: 4857 MethodType oldType = target.type(); 4858 if (oldType == newType) return target; 4859 if (oldType.explicitCastEquivalentToAsType(newType)) { 4860 return target.asFixedArity().asType(newType); 4861 } 4862 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4863 } 4864 4865 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4866 if (target.type().parameterCount() != newType.parameterCount()) { 4867 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4868 } 4869 } 4870 4871 /** 4872 * Produces a method handle which adapts the calling sequence of the 4873 * given method handle to a new type, by reordering the arguments. 4874 * The resulting method handle is guaranteed to report a type 4875 * which is equal to the desired new type. 4876 * <p> 4877 * The given array controls the reordering. 4878 * Call {@code #I} the number of incoming parameters (the value 4879 * {@code newType.parameterCount()}, and call {@code #O} the number 4880 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4881 * Then the length of the reordering array must be {@code #O}, 4882 * and each element must be a non-negative number less than {@code #I}. 4883 * For every {@code N} less than {@code #O}, the {@code N}-th 4884 * outgoing argument will be taken from the {@code I}-th incoming 4885 * argument, where {@code I} is {@code reorder[N]}. 4886 * <p> 4887 * No argument or return value conversions are applied. 4888 * The type of each incoming argument, as determined by {@code newType}, 4889 * must be identical to the type of the corresponding outgoing parameter 4890 * or parameters in the target method handle. 4891 * The return type of {@code newType} must be identical to the return 4892 * type of the original target. 4893 * <p> 4894 * The reordering array need not specify an actual permutation. 4895 * An incoming argument will be duplicated if its index appears 4896 * more than once in the array, and an incoming argument will be dropped 4897 * if its index does not appear in the array. 4898 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4899 * incoming arguments which are not mentioned in the reordering array 4900 * may be of any type, as determined only by {@code newType}. 4901 * {@snippet lang="java" : 4902 import static java.lang.invoke.MethodHandles.*; 4903 import static java.lang.invoke.MethodType.*; 4904 ... 4905 MethodType intfn1 = methodType(int.class, int.class); 4906 MethodType intfn2 = methodType(int.class, int.class, int.class); 4907 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4908 assert(sub.type().equals(intfn2)); 4909 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4910 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4911 assert((int)rsub.invokeExact(1, 100) == 99); 4912 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4913 assert(add.type().equals(intfn2)); 4914 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4915 assert(twice.type().equals(intfn1)); 4916 assert((int)twice.invokeExact(21) == 42); 4917 * } 4918 * <p> 4919 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4920 * variable-arity method handle}, even if the original target method handle was. 4921 * @param target the method handle to invoke after arguments are reordered 4922 * @param newType the expected type of the new method handle 4923 * @param reorder an index array which controls the reordering 4924 * @return a method handle which delegates to the target after it 4925 * drops unused arguments and moves and/or duplicates the other arguments 4926 * @throws NullPointerException if any argument is null 4927 * @throws IllegalArgumentException if the index array length is not equal to 4928 * the arity of the target, or if any index array element 4929 * not a valid index for a parameter of {@code newType}, 4930 * or if two corresponding parameter types in 4931 * {@code target.type()} and {@code newType} are not identical, 4932 */ 4933 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4934 reorder = reorder.clone(); // get a private copy 4935 MethodType oldType = target.type(); 4936 permuteArgumentChecks(reorder, newType, oldType); 4937 // first detect dropped arguments and handle them separately 4938 int[] originalReorder = reorder; 4939 BoundMethodHandle result = target.rebind(); 4940 LambdaForm form = result.form; 4941 int newArity = newType.parameterCount(); 4942 // Normalize the reordering into a real permutation, 4943 // by removing duplicates and adding dropped elements. 4944 // This somewhat improves lambda form caching, as well 4945 // as simplifying the transform by breaking it up into steps. 4946 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4947 if (ddIdx > 0) { 4948 // We found a duplicated entry at reorder[ddIdx]. 4949 // Example: (x,y,z)->asList(x,y,z) 4950 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4951 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4952 // The starred element corresponds to the argument 4953 // deleted by the dupArgumentForm transform. 4954 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4955 boolean killFirst = false; 4956 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4957 // Set killFirst if the dup is larger than an intervening position. 4958 // This will remove at least one inversion from the permutation. 4959 if (dupVal > val) killFirst = true; 4960 } 4961 if (!killFirst) { 4962 srcPos = dstPos; 4963 dstPos = ddIdx; 4964 } 4965 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4966 assert (reorder[srcPos] == reorder[dstPos]); 4967 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4968 // contract the reordering by removing the element at dstPos 4969 int tailPos = dstPos + 1; 4970 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4971 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4972 } else { 4973 int dropVal = ~ddIdx, insPos = 0; 4974 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4975 // Find first element of reorder larger than dropVal. 4976 // This is where we will insert the dropVal. 4977 insPos += 1; 4978 } 4979 Class<?> ptype = newType.parameterType(dropVal); 4980 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4981 oldType = oldType.insertParameterTypes(insPos, ptype); 4982 // expand the reordering by inserting an element at insPos 4983 int tailPos = insPos + 1; 4984 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4985 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4986 reorder[insPos] = dropVal; 4987 } 4988 assert (permuteArgumentChecks(reorder, newType, oldType)); 4989 } 4990 assert (reorder.length == newArity); // a perfect permutation 4991 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4992 form = form.editor().permuteArgumentsForm(1, reorder); 4993 if (newType == result.type() && form == result.internalForm()) 4994 return result; 4995 return result.copyWith(newType, form); 4996 } 4997 4998 /** 4999 * Return an indication of any duplicate or omission in reorder. 5000 * If the reorder contains a duplicate entry, return the index of the second occurrence. 5001 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 5002 * Otherwise, return zero. 5003 * If an element not in [0..newArity-1] is encountered, return reorder.length. 5004 */ 5005 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 5006 final int BIT_LIMIT = 63; // max number of bits in bit mask 5007 if (newArity < BIT_LIMIT) { 5008 long mask = 0; 5009 for (int i = 0; i < reorder.length; i++) { 5010 int arg = reorder[i]; 5011 if (arg >= newArity) { 5012 return reorder.length; 5013 } 5014 long bit = 1L << arg; 5015 if ((mask & bit) != 0) { 5016 return i; // >0 indicates a dup 5017 } 5018 mask |= bit; 5019 } 5020 if (mask == (1L << newArity) - 1) { 5021 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 5022 return 0; 5023 } 5024 // find first zero 5025 long zeroBit = Long.lowestOneBit(~mask); 5026 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 5027 assert(zeroPos <= newArity); 5028 if (zeroPos == newArity) { 5029 return 0; 5030 } 5031 return ~zeroPos; 5032 } else { 5033 // same algorithm, different bit set 5034 BitSet mask = new BitSet(newArity); 5035 for (int i = 0; i < reorder.length; i++) { 5036 int arg = reorder[i]; 5037 if (arg >= newArity) { 5038 return reorder.length; 5039 } 5040 if (mask.get(arg)) { 5041 return i; // >0 indicates a dup 5042 } 5043 mask.set(arg); 5044 } 5045 int zeroPos = mask.nextClearBit(0); 5046 assert(zeroPos <= newArity); 5047 if (zeroPos == newArity) { 5048 return 0; 5049 } 5050 return ~zeroPos; 5051 } 5052 } 5053 5054 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 5055 if (newType.returnType() != oldType.returnType()) 5056 throw newIllegalArgumentException("return types do not match", 5057 oldType, newType); 5058 if (reorder.length != oldType.parameterCount()) 5059 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 5060 oldType, Arrays.toString(reorder)); 5061 5062 int limit = newType.parameterCount(); 5063 for (int j = 0; j < reorder.length; j++) { 5064 int i = reorder[j]; 5065 if (i < 0 || i >= limit) { 5066 throw newIllegalArgumentException("index is out of bounds for new type", 5067 i, newType); 5068 } 5069 Class<?> src = newType.parameterType(i); 5070 Class<?> dst = oldType.parameterType(j); 5071 if (src != dst) 5072 throw newIllegalArgumentException("parameter types do not match after reorder", 5073 oldType, newType); 5074 } 5075 return true; 5076 } 5077 5078 /** 5079 * Produces a method handle of the requested return type which returns the given 5080 * constant value every time it is invoked. 5081 * <p> 5082 * Before the method handle is returned, the passed-in value is converted to the requested type. 5083 * If the requested type is primitive, widening primitive conversions are attempted, 5084 * else reference conversions are attempted. 5085 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5086 * @param type the return type of the desired method handle 5087 * @param value the value to return 5088 * @return a method handle of the given return type and no arguments, which always returns the given value 5089 * @throws NullPointerException if the {@code type} argument is null 5090 * @throws ClassCastException if the value cannot be converted to the required return type 5091 * @throws IllegalArgumentException if the given type is {@code void.class} 5092 */ 5093 public static MethodHandle constant(Class<?> type, Object value) { 5094 if (type.isPrimitive()) { 5095 if (type == void.class) 5096 throw newIllegalArgumentException("void type"); 5097 Wrapper w = Wrapper.forPrimitiveType(type); 5098 value = w.convert(value, type); 5099 if (w.zero().equals(value)) 5100 return zero(w, type); 5101 return insertArguments(identity(type), 0, value); 5102 } else { 5103 if (value == null) 5104 return zero(Wrapper.OBJECT, type); 5105 return identity(type).bindTo(value); 5106 } 5107 } 5108 5109 /** 5110 * Produces a method handle which returns its sole argument when invoked. 5111 * @param type the type of the sole parameter and return value of the desired method handle 5112 * @return a unary method handle which accepts and returns the given type 5113 * @throws NullPointerException if the argument is null 5114 * @throws IllegalArgumentException if the given type is {@code void.class} 5115 */ 5116 public static MethodHandle identity(Class<?> type) { 5117 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5118 int pos = btw.ordinal(); 5119 MethodHandle ident = IDENTITY_MHS[pos]; 5120 if (ident == null) { 5121 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5122 } 5123 if (ident.type().returnType() == type) 5124 return ident; 5125 // something like identity(Foo.class); do not bother to intern these 5126 assert (btw == Wrapper.OBJECT); 5127 return makeIdentity(type); 5128 } 5129 5130 /** 5131 * Produces a constant method handle of the requested return type which 5132 * returns the default value for that type every time it is invoked. 5133 * The resulting constant method handle will have no side effects. 5134 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5135 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5136 * since {@code explicitCastArguments} converts {@code null} to default values. 5137 * @param type the expected return type of the desired method handle 5138 * @return a constant method handle that takes no arguments 5139 * and returns the default value of the given type (or void, if the type is void) 5140 * @throws NullPointerException if the argument is null 5141 * @see MethodHandles#constant 5142 * @see MethodHandles#empty 5143 * @see MethodHandles#explicitCastArguments 5144 * @since 9 5145 */ 5146 public static MethodHandle zero(Class<?> type) { 5147 Objects.requireNonNull(type); 5148 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5149 } 5150 5151 private static MethodHandle identityOrVoid(Class<?> type) { 5152 return type == void.class ? zero(type) : identity(type); 5153 } 5154 5155 /** 5156 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5157 * and returns a suitable default depending on the return type. 5158 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5159 * <p>The returned method handle is equivalent to 5160 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5161 * 5162 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5163 * {@code guardWithTest(pred, target, empty(target.type())}. 5164 * @param type the type of the desired method handle 5165 * @return a constant method handle of the given type, which returns a default value of the given return type 5166 * @throws NullPointerException if the argument is null 5167 * @see MethodHandles#zero 5168 * @see MethodHandles#constant 5169 * @since 9 5170 */ 5171 public static MethodHandle empty(MethodType type) { 5172 Objects.requireNonNull(type); 5173 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5174 } 5175 5176 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5177 private static MethodHandle makeIdentity(Class<?> ptype) { 5178 MethodType mtype = methodType(ptype, ptype); 5179 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5180 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5181 } 5182 5183 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5184 int pos = btw.ordinal(); 5185 MethodHandle zero = ZERO_MHS[pos]; 5186 if (zero == null) { 5187 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5188 } 5189 if (zero.type().returnType() == rtype) 5190 return zero; 5191 assert(btw == Wrapper.OBJECT); 5192 return makeZero(rtype); 5193 } 5194 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5195 private static MethodHandle makeZero(Class<?> rtype) { 5196 MethodType mtype = methodType(rtype); 5197 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5198 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5199 } 5200 5201 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5202 // Simulate a CAS, to avoid racy duplication of results. 5203 MethodHandle prev = cache[pos]; 5204 if (prev != null) return prev; 5205 return cache[pos] = value; 5206 } 5207 5208 /** 5209 * Provides a target method handle with one or more <em>bound arguments</em> 5210 * in advance of the method handle's invocation. 5211 * The formal parameters to the target corresponding to the bound 5212 * arguments are called <em>bound parameters</em>. 5213 * Returns a new method handle which saves away the bound arguments. 5214 * When it is invoked, it receives arguments for any non-bound parameters, 5215 * binds the saved arguments to their corresponding parameters, 5216 * and calls the original target. 5217 * <p> 5218 * The type of the new method handle will drop the types for the bound 5219 * parameters from the original target type, since the new method handle 5220 * will no longer require those arguments to be supplied by its callers. 5221 * <p> 5222 * Each given argument object must match the corresponding bound parameter type. 5223 * If a bound parameter type is a primitive, the argument object 5224 * must be a wrapper, and will be unboxed to produce the primitive value. 5225 * <p> 5226 * The {@code pos} argument selects which parameters are to be bound. 5227 * It may range between zero and <i>N-L</i> (inclusively), 5228 * where <i>N</i> is the arity of the target method handle 5229 * and <i>L</i> is the length of the values array. 5230 * <p> 5231 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5232 * variable-arity method handle}, even if the original target method handle was. 5233 * @param target the method handle to invoke after the argument is inserted 5234 * @param pos where to insert the argument (zero for the first) 5235 * @param values the series of arguments to insert 5236 * @return a method handle which inserts an additional argument, 5237 * before calling the original method handle 5238 * @throws NullPointerException if the target or the {@code values} array is null 5239 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 5240 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5241 * is the length of the values array. 5242 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5243 * type. 5244 * @see MethodHandle#bindTo 5245 */ 5246 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5247 int insCount = values.length; 5248 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5249 if (insCount == 0) return target; 5250 BoundMethodHandle result = target.rebind(); 5251 for (int i = 0; i < insCount; i++) { 5252 Object value = values[i]; 5253 Class<?> ptype = ptypes[pos+i]; 5254 if (ptype.isPrimitive()) { 5255 result = insertArgumentPrimitive(result, pos, ptype, value); 5256 } else { 5257 value = ptype.cast(value); // throw CCE if needed 5258 result = result.bindArgumentL(pos, value); 5259 } 5260 } 5261 return result; 5262 } 5263 5264 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5265 Class<?> ptype, Object value) { 5266 Wrapper w = Wrapper.forPrimitiveType(ptype); 5267 // perform unboxing and/or primitive conversion 5268 value = w.convert(value, ptype); 5269 return switch (w) { 5270 case INT -> result.bindArgumentI(pos, (int) value); 5271 case LONG -> result.bindArgumentJ(pos, (long) value); 5272 case FLOAT -> result.bindArgumentF(pos, (float) value); 5273 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5274 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5275 }; 5276 } 5277 5278 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5279 MethodType oldType = target.type(); 5280 int outargs = oldType.parameterCount(); 5281 int inargs = outargs - insCount; 5282 if (inargs < 0) 5283 throw newIllegalArgumentException("too many values to insert"); 5284 if (pos < 0 || pos > inargs) 5285 throw newIllegalArgumentException("no argument type to append"); 5286 return oldType.ptypes(); 5287 } 5288 5289 /** 5290 * Produces a method handle which will discard some dummy arguments 5291 * before calling some other specified <i>target</i> method handle. 5292 * The type of the new method handle will be the same as the target's type, 5293 * except it will also include the dummy argument types, 5294 * at some given position. 5295 * <p> 5296 * The {@code pos} argument may range between zero and <i>N</i>, 5297 * where <i>N</i> is the arity of the target. 5298 * If {@code pos} is zero, the dummy arguments will precede 5299 * the target's real arguments; if {@code pos} is <i>N</i> 5300 * they will come after. 5301 * <p> 5302 * <b>Example:</b> 5303 * {@snippet lang="java" : 5304 import static java.lang.invoke.MethodHandles.*; 5305 import static java.lang.invoke.MethodType.*; 5306 ... 5307 MethodHandle cat = lookup().findVirtual(String.class, 5308 "concat", methodType(String.class, String.class)); 5309 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5310 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5311 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5312 assertEquals(bigType, d0.type()); 5313 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5314 * } 5315 * <p> 5316 * This method is also equivalent to the following code: 5317 * <blockquote><pre> 5318 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5319 * </pre></blockquote> 5320 * @param target the method handle to invoke after the arguments are dropped 5321 * @param pos position of first argument to drop (zero for the leftmost) 5322 * @param valueTypes the type(s) of the argument(s) to drop 5323 * @return a method handle which drops arguments of the given types, 5324 * before calling the original method handle 5325 * @throws NullPointerException if the target is null, 5326 * or if the {@code valueTypes} list or any of its elements is null 5327 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5328 * or if {@code pos} is negative or greater than the arity of the target, 5329 * or if the new method handle's type would have too many parameters 5330 */ 5331 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5332 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5333 } 5334 5335 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5336 MethodType oldType = target.type(); // get NPE 5337 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5338 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5339 if (dropped == 0) return target; 5340 BoundMethodHandle result = target.rebind(); 5341 LambdaForm lform = result.form; 5342 int insertFormArg = 1 + pos; 5343 for (Class<?> ptype : valueTypes) { 5344 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5345 } 5346 result = result.copyWith(newType, lform); 5347 return result; 5348 } 5349 5350 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5351 int dropped = valueTypes.length; 5352 MethodType.checkSlotCount(dropped); 5353 int outargs = oldType.parameterCount(); 5354 int inargs = outargs + dropped; 5355 if (pos < 0 || pos > outargs) 5356 throw newIllegalArgumentException("no argument type to remove" 5357 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5358 ); 5359 return dropped; 5360 } 5361 5362 /** 5363 * Produces a method handle which will discard some dummy arguments 5364 * before calling some other specified <i>target</i> method handle. 5365 * The type of the new method handle will be the same as the target's type, 5366 * except it will also include the dummy argument types, 5367 * at some given position. 5368 * <p> 5369 * The {@code pos} argument may range between zero and <i>N</i>, 5370 * where <i>N</i> is the arity of the target. 5371 * If {@code pos} is zero, the dummy arguments will precede 5372 * the target's real arguments; if {@code pos} is <i>N</i> 5373 * they will come after. 5374 * @apiNote 5375 * {@snippet lang="java" : 5376 import static java.lang.invoke.MethodHandles.*; 5377 import static java.lang.invoke.MethodType.*; 5378 ... 5379 MethodHandle cat = lookup().findVirtual(String.class, 5380 "concat", methodType(String.class, String.class)); 5381 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5382 MethodHandle d0 = dropArguments(cat, 0, String.class); 5383 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5384 MethodHandle d1 = dropArguments(cat, 1, String.class); 5385 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5386 MethodHandle d2 = dropArguments(cat, 2, String.class); 5387 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5388 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5389 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5390 * } 5391 * <p> 5392 * This method is also equivalent to the following code: 5393 * <blockquote><pre> 5394 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5395 * </pre></blockquote> 5396 * @param target the method handle to invoke after the arguments are dropped 5397 * @param pos position of first argument to drop (zero for the leftmost) 5398 * @param valueTypes the type(s) of the argument(s) to drop 5399 * @return a method handle which drops arguments of the given types, 5400 * before calling the original method handle 5401 * @throws NullPointerException if the target is null, 5402 * or if the {@code valueTypes} array or any of its elements is null 5403 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5404 * or if {@code pos} is negative or greater than the arity of the target, 5405 * or if the new method handle's type would have 5406 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5407 */ 5408 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5409 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5410 } 5411 5412 /* Convenience overloads for trusting internal low-arity call-sites */ 5413 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5414 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5415 } 5416 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5417 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5418 } 5419 5420 // private version which allows caller some freedom with error handling 5421 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5422 boolean nullOnFailure) { 5423 Class<?>[] oldTypes = target.type().ptypes(); 5424 int match = oldTypes.length; 5425 if (skip != 0) { 5426 if (skip < 0 || skip > match) { 5427 throw newIllegalArgumentException("illegal skip", skip, target); 5428 } 5429 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5430 match -= skip; 5431 } 5432 Class<?>[] addTypes = newTypes; 5433 int add = addTypes.length; 5434 if (pos != 0) { 5435 if (pos < 0 || pos > add) { 5436 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5437 } 5438 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5439 add -= pos; 5440 assert(addTypes.length == add); 5441 } 5442 // Do not add types which already match the existing arguments. 5443 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5444 if (nullOnFailure) { 5445 return null; 5446 } 5447 throw newIllegalArgumentException("argument lists do not match", 5448 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5449 } 5450 addTypes = Arrays.copyOfRange(addTypes, match, add); 5451 add -= match; 5452 assert(addTypes.length == add); 5453 // newTypes: ( P*[pos], M*[match], A*[add] ) 5454 // target: ( S*[skip], M*[match] ) 5455 MethodHandle adapter = target; 5456 if (add > 0) { 5457 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5458 } 5459 // adapter: (S*[skip], M*[match], A*[add] ) 5460 if (pos > 0) { 5461 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5462 } 5463 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5464 return adapter; 5465 } 5466 5467 /** 5468 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5469 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5470 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5471 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5472 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5473 * {@link #dropArguments(MethodHandle, int, Class[])}. 5474 * <p> 5475 * The resulting handle will have the same return type as the target handle. 5476 * <p> 5477 * In more formal terms, assume these two type lists:<ul> 5478 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5479 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5480 * {@code newTypes}. 5481 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5482 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5483 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5484 * sub-list. 5485 * </ul> 5486 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5487 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5488 * {@link #dropArguments(MethodHandle, int, Class[])}. 5489 * 5490 * @apiNote 5491 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5492 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5493 * {@snippet lang="java" : 5494 import static java.lang.invoke.MethodHandles.*; 5495 import static java.lang.invoke.MethodType.*; 5496 ... 5497 ... 5498 MethodHandle h0 = constant(boolean.class, true); 5499 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5500 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5501 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5502 if (h1.type().parameterCount() < h2.type().parameterCount()) 5503 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5504 else 5505 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5506 MethodHandle h3 = guardWithTest(h0, h1, h2); 5507 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5508 * } 5509 * @param target the method handle to adapt 5510 * @param skip number of targets parameters to disregard (they will be unchanged) 5511 * @param newTypes the list of types to match {@code target}'s parameter type list to 5512 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5513 * @return a possibly adapted method handle 5514 * @throws NullPointerException if either argument is null 5515 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5516 * or if {@code skip} is negative or greater than the arity of the target, 5517 * or if {@code pos} is negative or greater than the newTypes list size, 5518 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5519 * {@code pos}. 5520 * @since 9 5521 */ 5522 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5523 Objects.requireNonNull(target); 5524 Objects.requireNonNull(newTypes); 5525 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5526 } 5527 5528 /** 5529 * Drop the return value of the target handle (if any). 5530 * The returned method handle will have a {@code void} return type. 5531 * 5532 * @param target the method handle to adapt 5533 * @return a possibly adapted method handle 5534 * @throws NullPointerException if {@code target} is null 5535 * @since 16 5536 */ 5537 public static MethodHandle dropReturn(MethodHandle target) { 5538 Objects.requireNonNull(target); 5539 MethodType oldType = target.type(); 5540 Class<?> oldReturnType = oldType.returnType(); 5541 if (oldReturnType == void.class) 5542 return target; 5543 MethodType newType = oldType.changeReturnType(void.class); 5544 BoundMethodHandle result = target.rebind(); 5545 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5546 result = result.copyWith(newType, lform); 5547 return result; 5548 } 5549 5550 /** 5551 * Adapts a target method handle by pre-processing 5552 * one or more of its arguments, each with its own unary filter function, 5553 * and then calling the target with each pre-processed argument 5554 * replaced by the result of its corresponding filter function. 5555 * <p> 5556 * The pre-processing is performed by one or more method handles, 5557 * specified in the elements of the {@code filters} array. 5558 * The first element of the filter array corresponds to the {@code pos} 5559 * argument of the target, and so on in sequence. 5560 * The filter functions are invoked in left to right order. 5561 * <p> 5562 * Null arguments in the array are treated as identity functions, 5563 * and the corresponding arguments left unchanged. 5564 * (If there are no non-null elements in the array, the original target is returned.) 5565 * Each filter is applied to the corresponding argument of the adapter. 5566 * <p> 5567 * If a filter {@code F} applies to the {@code N}th argument of 5568 * the target, then {@code F} must be a method handle which 5569 * takes exactly one argument. The type of {@code F}'s sole argument 5570 * replaces the corresponding argument type of the target 5571 * in the resulting adapted method handle. 5572 * The return type of {@code F} must be identical to the corresponding 5573 * parameter type of the target. 5574 * <p> 5575 * It is an error if there are elements of {@code filters} 5576 * (null or not) 5577 * which do not correspond to argument positions in the target. 5578 * <p><b>Example:</b> 5579 * {@snippet lang="java" : 5580 import static java.lang.invoke.MethodHandles.*; 5581 import static java.lang.invoke.MethodType.*; 5582 ... 5583 MethodHandle cat = lookup().findVirtual(String.class, 5584 "concat", methodType(String.class, String.class)); 5585 MethodHandle upcase = lookup().findVirtual(String.class, 5586 "toUpperCase", methodType(String.class)); 5587 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5588 MethodHandle f0 = filterArguments(cat, 0, upcase); 5589 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5590 MethodHandle f1 = filterArguments(cat, 1, upcase); 5591 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5592 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5593 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5594 * } 5595 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5596 * denotes the return type of both the {@code target} and resulting adapter. 5597 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5598 * of the parameters and arguments that precede and follow the filter position 5599 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5600 * values of the filtered parameters and arguments; they also represent the 5601 * return types of the {@code filter[i]} handles. The latter accept arguments 5602 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5603 * the resulting adapter. 5604 * {@snippet lang="java" : 5605 * T target(P... p, A[i]... a[i], B... b); 5606 * A[i] filter[i](V[i]); 5607 * T adapter(P... p, V[i]... v[i], B... b) { 5608 * return target(p..., filter[i](v[i])..., b...); 5609 * } 5610 * } 5611 * <p> 5612 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5613 * variable-arity method handle}, even if the original target method handle was. 5614 * 5615 * @param target the method handle to invoke after arguments are filtered 5616 * @param pos the position of the first argument to filter 5617 * @param filters method handles to call initially on filtered arguments 5618 * @return method handle which incorporates the specified argument filtering logic 5619 * @throws NullPointerException if the target is null 5620 * or if the {@code filters} array is null 5621 * @throws IllegalArgumentException if a non-null element of {@code filters} 5622 * does not match a corresponding argument type of target as described above, 5623 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5624 * or if the resulting method handle's type would have 5625 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5626 */ 5627 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5628 // In method types arguments start at index 0, while the LF 5629 // editor have the MH receiver at position 0 - adjust appropriately. 5630 final int MH_RECEIVER_OFFSET = 1; 5631 filterArgumentsCheckArity(target, pos, filters); 5632 MethodHandle adapter = target; 5633 5634 // keep track of currently matched filters, as to optimize repeated filters 5635 int index = 0; 5636 int[] positions = new int[filters.length]; 5637 MethodHandle filter = null; 5638 5639 // process filters in reverse order so that the invocation of 5640 // the resulting adapter will invoke the filters in left-to-right order 5641 for (int i = filters.length - 1; i >= 0; --i) { 5642 MethodHandle newFilter = filters[i]; 5643 if (newFilter == null) continue; // ignore null elements of filters 5644 5645 // flush changes on update 5646 if (filter != newFilter) { 5647 if (filter != null) { 5648 if (index > 1) { 5649 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5650 } else { 5651 adapter = filterArgument(adapter, positions[0] - 1, filter); 5652 } 5653 } 5654 filter = newFilter; 5655 index = 0; 5656 } 5657 5658 filterArgumentChecks(target, pos + i, newFilter); 5659 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5660 } 5661 if (index > 1) { 5662 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5663 } else if (index == 1) { 5664 adapter = filterArgument(adapter, positions[0] - 1, filter); 5665 } 5666 return adapter; 5667 } 5668 5669 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5670 MethodType targetType = adapter.type(); 5671 MethodType filterType = filter.type(); 5672 BoundMethodHandle result = adapter.rebind(); 5673 Class<?> newParamType = filterType.parameterType(0); 5674 5675 Class<?>[] ptypes = targetType.ptypes().clone(); 5676 for (int pos : positions) { 5677 ptypes[pos - 1] = newParamType; 5678 } 5679 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5680 5681 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5682 return result.copyWithExtendL(newType, lform, filter); 5683 } 5684 5685 /*non-public*/ 5686 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5687 filterArgumentChecks(target, pos, filter); 5688 MethodType targetType = target.type(); 5689 MethodType filterType = filter.type(); 5690 BoundMethodHandle result = target.rebind(); 5691 Class<?> newParamType = filterType.parameterType(0); 5692 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5693 MethodType newType = targetType.changeParameterType(pos, newParamType); 5694 result = result.copyWithExtendL(newType, lform, filter); 5695 return result; 5696 } 5697 5698 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5699 MethodType targetType = target.type(); 5700 int maxPos = targetType.parameterCount(); 5701 if (pos + filters.length > maxPos) 5702 throw newIllegalArgumentException("too many filters"); 5703 } 5704 5705 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5706 MethodType targetType = target.type(); 5707 MethodType filterType = filter.type(); 5708 if (filterType.parameterCount() != 1 5709 || filterType.returnType() != targetType.parameterType(pos)) 5710 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5711 } 5712 5713 /** 5714 * Adapts a target method handle by pre-processing 5715 * a sub-sequence of its arguments with a filter (another method handle). 5716 * The pre-processed arguments are replaced by the result (if any) of the 5717 * filter function. 5718 * The target is then called on the modified (usually shortened) argument list. 5719 * <p> 5720 * If the filter returns a value, the target must accept that value as 5721 * its argument in position {@code pos}, preceded and/or followed by 5722 * any arguments not passed to the filter. 5723 * If the filter returns void, the target must accept all arguments 5724 * not passed to the filter. 5725 * No arguments are reordered, and a result returned from the filter 5726 * replaces (in order) the whole subsequence of arguments originally 5727 * passed to the adapter. 5728 * <p> 5729 * The argument types (if any) of the filter 5730 * replace zero or one argument types of the target, at position {@code pos}, 5731 * in the resulting adapted method handle. 5732 * The return type of the filter (if any) must be identical to the 5733 * argument type of the target at position {@code pos}, and that target argument 5734 * is supplied by the return value of the filter. 5735 * <p> 5736 * In all cases, {@code pos} must be greater than or equal to zero, and 5737 * {@code pos} must also be less than or equal to the target's arity. 5738 * <p><b>Example:</b> 5739 * {@snippet lang="java" : 5740 import static java.lang.invoke.MethodHandles.*; 5741 import static java.lang.invoke.MethodType.*; 5742 ... 5743 MethodHandle deepToString = publicLookup() 5744 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5745 5746 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5747 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5748 5749 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5750 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5751 5752 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5753 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5754 assertEquals("[top, [up, down], strange]", 5755 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5756 5757 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5758 assertEquals("[top, [up, down], [strange]]", 5759 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5760 5761 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5762 assertEquals("[top, [[up, down, strange], charm], bottom]", 5763 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5764 * } 5765 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5766 * represents the return type of the {@code target} and resulting adapter. 5767 * {@code V}/{@code v} stand for the return type and value of the 5768 * {@code filter}, which are also found in the signature and arguments of 5769 * the {@code target}, respectively, unless {@code V} is {@code void}. 5770 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5771 * and values preceding and following the collection position, {@code pos}, 5772 * in the {@code target}'s signature. They also turn up in the resulting 5773 * adapter's signature and arguments, where they surround 5774 * {@code B}/{@code b}, which represent the parameter types and arguments 5775 * to the {@code filter} (if any). 5776 * {@snippet lang="java" : 5777 * T target(A...,V,C...); 5778 * V filter(B...); 5779 * T adapter(A... a,B... b,C... c) { 5780 * V v = filter(b...); 5781 * return target(a...,v,c...); 5782 * } 5783 * // and if the filter has no arguments: 5784 * T target2(A...,V,C...); 5785 * V filter2(); 5786 * T adapter2(A... a,C... c) { 5787 * V v = filter2(); 5788 * return target2(a...,v,c...); 5789 * } 5790 * // and if the filter has a void return: 5791 * T target3(A...,C...); 5792 * void filter3(B...); 5793 * T adapter3(A... a,B... b,C... c) { 5794 * filter3(b...); 5795 * return target3(a...,c...); 5796 * } 5797 * } 5798 * <p> 5799 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5800 * one which first "folds" the affected arguments, and then drops them, in separate 5801 * steps as follows: 5802 * {@snippet lang="java" : 5803 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5804 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5805 * } 5806 * If the target method handle consumes no arguments besides than the result 5807 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5808 * is equivalent to {@code filterReturnValue(coll, mh)}. 5809 * If the filter method handle {@code coll} consumes one argument and produces 5810 * a non-void result, then {@code collectArguments(mh, N, coll)} 5811 * is equivalent to {@code filterArguments(mh, N, coll)}. 5812 * Other equivalences are possible but would require argument permutation. 5813 * <p> 5814 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5815 * variable-arity method handle}, even if the original target method handle was. 5816 * 5817 * @param target the method handle to invoke after filtering the subsequence of arguments 5818 * @param pos the position of the first adapter argument to pass to the filter, 5819 * and/or the target argument which receives the result of the filter 5820 * @param filter method handle to call on the subsequence of arguments 5821 * @return method handle which incorporates the specified argument subsequence filtering logic 5822 * @throws NullPointerException if either argument is null 5823 * @throws IllegalArgumentException if the return type of {@code filter} 5824 * is non-void and is not the same as the {@code pos} argument of the target, 5825 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5826 * or if the resulting method handle's type would have 5827 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5828 * @see MethodHandles#foldArguments 5829 * @see MethodHandles#filterArguments 5830 * @see MethodHandles#filterReturnValue 5831 */ 5832 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5833 MethodType newType = collectArgumentsChecks(target, pos, filter); 5834 MethodType collectorType = filter.type(); 5835 BoundMethodHandle result = target.rebind(); 5836 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5837 return result.copyWithExtendL(newType, lform, filter); 5838 } 5839 5840 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5841 MethodType targetType = target.type(); 5842 MethodType filterType = filter.type(); 5843 Class<?> rtype = filterType.returnType(); 5844 Class<?>[] filterArgs = filterType.ptypes(); 5845 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5846 (rtype != void.class && pos >= targetType.parameterCount())) { 5847 throw newIllegalArgumentException("position is out of range for target", target, pos); 5848 } 5849 if (rtype == void.class) { 5850 return targetType.insertParameterTypes(pos, filterArgs); 5851 } 5852 if (rtype != targetType.parameterType(pos)) { 5853 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5854 } 5855 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5856 } 5857 5858 /** 5859 * Adapts a target method handle by post-processing 5860 * its return value (if any) with a filter (another method handle). 5861 * The result of the filter is returned from the adapter. 5862 * <p> 5863 * If the target returns a value, the filter must accept that value as 5864 * its only argument. 5865 * If the target returns void, the filter must accept no arguments. 5866 * <p> 5867 * The return type of the filter 5868 * replaces the return type of the target 5869 * in the resulting adapted method handle. 5870 * The argument type of the filter (if any) must be identical to the 5871 * return type of the target. 5872 * <p><b>Example:</b> 5873 * {@snippet lang="java" : 5874 import static java.lang.invoke.MethodHandles.*; 5875 import static java.lang.invoke.MethodType.*; 5876 ... 5877 MethodHandle cat = lookup().findVirtual(String.class, 5878 "concat", methodType(String.class, String.class)); 5879 MethodHandle length = lookup().findVirtual(String.class, 5880 "length", methodType(int.class)); 5881 System.out.println((String) cat.invokeExact("x", "y")); // xy 5882 MethodHandle f0 = filterReturnValue(cat, length); 5883 System.out.println((int) f0.invokeExact("x", "y")); // 2 5884 * } 5885 * <p>Here is pseudocode for the resulting adapter. In the code, 5886 * {@code T}/{@code t} represent the result type and value of the 5887 * {@code target}; {@code V}, the result type of the {@code filter}; and 5888 * {@code A}/{@code a}, the types and values of the parameters and arguments 5889 * of the {@code target} as well as the resulting adapter. 5890 * {@snippet lang="java" : 5891 * T target(A...); 5892 * V filter(T); 5893 * V adapter(A... a) { 5894 * T t = target(a...); 5895 * return filter(t); 5896 * } 5897 * // and if the target has a void return: 5898 * void target2(A...); 5899 * V filter2(); 5900 * V adapter2(A... a) { 5901 * target2(a...); 5902 * return filter2(); 5903 * } 5904 * // and if the filter has a void return: 5905 * T target3(A...); 5906 * void filter3(V); 5907 * void adapter3(A... a) { 5908 * T t = target3(a...); 5909 * filter3(t); 5910 * } 5911 * } 5912 * <p> 5913 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5914 * variable-arity method handle}, even if the original target method handle was. 5915 * @param target the method handle to invoke before filtering the return value 5916 * @param filter method handle to call on the return value 5917 * @return method handle which incorporates the specified return value filtering logic 5918 * @throws NullPointerException if either argument is null 5919 * @throws IllegalArgumentException if the argument list of {@code filter} 5920 * does not match the return type of target as described above 5921 */ 5922 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5923 MethodType targetType = target.type(); 5924 MethodType filterType = filter.type(); 5925 filterReturnValueChecks(targetType, filterType); 5926 BoundMethodHandle result = target.rebind(); 5927 BasicType rtype = BasicType.basicType(filterType.returnType()); 5928 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5929 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5930 result = result.copyWithExtendL(newType, lform, filter); 5931 return result; 5932 } 5933 5934 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5935 Class<?> rtype = targetType.returnType(); 5936 int filterValues = filterType.parameterCount(); 5937 if (filterValues == 0 5938 ? (rtype != void.class) 5939 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5940 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5941 } 5942 5943 /** 5944 * Filter the return value of a target method handle with a filter function. The filter function is 5945 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5946 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5947 * as follows: 5948 * {@snippet lang="java" : 5949 * T target(A...) 5950 * V filter(B... , T) 5951 * V adapter(A... a, B... b) { 5952 * T t = target(a...); 5953 * return filter(b..., t); 5954 * } 5955 * } 5956 * <p> 5957 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5958 * 5959 * @param target the target method handle 5960 * @param filter the filter method handle 5961 * @return the adapter method handle 5962 */ 5963 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5964 MethodType targetType = target.type(); 5965 MethodType filterType = filter.type(); 5966 BoundMethodHandle result = target.rebind(); 5967 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5968 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5969 if (filterType.parameterCount() > 1) { 5970 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5971 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5972 } 5973 } 5974 result = result.copyWithExtendL(newType, lform, filter); 5975 return result; 5976 } 5977 5978 /** 5979 * Adapts a target method handle by pre-processing 5980 * some of its arguments, and then calling the target with 5981 * the result of the pre-processing, inserted into the original 5982 * sequence of arguments. 5983 * <p> 5984 * The pre-processing is performed by {@code combiner}, a second method handle. 5985 * Of the arguments passed to the adapter, the first {@code N} arguments 5986 * are copied to the combiner, which is then called. 5987 * (Here, {@code N} is defined as the parameter count of the combiner.) 5988 * After this, control passes to the target, with any result 5989 * from the combiner inserted before the original {@code N} incoming 5990 * arguments. 5991 * <p> 5992 * If the combiner returns a value, the first parameter type of the target 5993 * must be identical with the return type of the combiner, and the next 5994 * {@code N} parameter types of the target must exactly match the parameters 5995 * of the combiner. 5996 * <p> 5997 * If the combiner has a void return, no result will be inserted, 5998 * and the first {@code N} parameter types of the target 5999 * must exactly match the parameters of the combiner. 6000 * <p> 6001 * The resulting adapter is the same type as the target, except that the 6002 * first parameter type is dropped, 6003 * if it corresponds to the result of the combiner. 6004 * <p> 6005 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 6006 * that either the combiner or the target does not wish to receive. 6007 * If some of the incoming arguments are destined only for the combiner, 6008 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 6009 * arguments will not need to be live on the stack on entry to the 6010 * target.) 6011 * <p><b>Example:</b> 6012 * {@snippet lang="java" : 6013 import static java.lang.invoke.MethodHandles.*; 6014 import static java.lang.invoke.MethodType.*; 6015 ... 6016 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6017 "println", methodType(void.class, String.class)) 6018 .bindTo(System.out); 6019 MethodHandle cat = lookup().findVirtual(String.class, 6020 "concat", methodType(String.class, String.class)); 6021 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6022 MethodHandle catTrace = foldArguments(cat, trace); 6023 // also prints "boo": 6024 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6025 * } 6026 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6027 * represents the result type of the {@code target} and resulting adapter. 6028 * {@code V}/{@code v} represent the type and value of the parameter and argument 6029 * of {@code target} that precedes the folding position; {@code V} also is 6030 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6031 * types and values of the {@code N} parameters and arguments at the folding 6032 * position. {@code B}/{@code b} represent the types and values of the 6033 * {@code target} parameters and arguments that follow the folded parameters 6034 * and arguments. 6035 * {@snippet lang="java" : 6036 * // there are N arguments in A... 6037 * T target(V, A[N]..., B...); 6038 * V combiner(A...); 6039 * T adapter(A... a, B... b) { 6040 * V v = combiner(a...); 6041 * return target(v, a..., b...); 6042 * } 6043 * // and if the combiner has a void return: 6044 * T target2(A[N]..., B...); 6045 * void combiner2(A...); 6046 * T adapter2(A... a, B... b) { 6047 * combiner2(a...); 6048 * return target2(a..., b...); 6049 * } 6050 * } 6051 * <p> 6052 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6053 * variable-arity method handle}, even if the original target method handle was. 6054 * @param target the method handle to invoke after arguments are combined 6055 * @param combiner method handle to call initially on the incoming arguments 6056 * @return method handle which incorporates the specified argument folding logic 6057 * @throws NullPointerException if either argument is null 6058 * @throws IllegalArgumentException if {@code combiner}'s return type 6059 * is non-void and not the same as the first argument type of 6060 * the target, or if the initial {@code N} argument types 6061 * of the target 6062 * (skipping one matching the {@code combiner}'s return type) 6063 * are not identical with the argument types of {@code combiner} 6064 */ 6065 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 6066 return foldArguments(target, 0, combiner); 6067 } 6068 6069 /** 6070 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6071 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6072 * before the folded arguments. 6073 * <p> 6074 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6075 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6076 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6077 * 0. 6078 * 6079 * @apiNote Example: 6080 * {@snippet lang="java" : 6081 import static java.lang.invoke.MethodHandles.*; 6082 import static java.lang.invoke.MethodType.*; 6083 ... 6084 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6085 "println", methodType(void.class, String.class)) 6086 .bindTo(System.out); 6087 MethodHandle cat = lookup().findVirtual(String.class, 6088 "concat", methodType(String.class, String.class)); 6089 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6090 MethodHandle catTrace = foldArguments(cat, 1, trace); 6091 // also prints "jum": 6092 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6093 * } 6094 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6095 * represents the result type of the {@code target} and resulting adapter. 6096 * {@code V}/{@code v} represent the type and value of the parameter and argument 6097 * of {@code target} that precedes the folding position; {@code V} also is 6098 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6099 * types and values of the {@code N} parameters and arguments at the folding 6100 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6101 * and values of the {@code target} parameters and arguments that precede and 6102 * follow the folded parameters and arguments starting at {@code pos}, 6103 * respectively. 6104 * {@snippet lang="java" : 6105 * // there are N arguments in A... 6106 * T target(Z..., V, A[N]..., B...); 6107 * V combiner(A...); 6108 * T adapter(Z... z, A... a, B... b) { 6109 * V v = combiner(a...); 6110 * return target(z..., v, a..., b...); 6111 * } 6112 * // and if the combiner has a void return: 6113 * T target2(Z..., A[N]..., B...); 6114 * void combiner2(A...); 6115 * T adapter2(Z... z, A... a, B... b) { 6116 * combiner2(a...); 6117 * return target2(z..., a..., b...); 6118 * } 6119 * } 6120 * <p> 6121 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6122 * variable-arity method handle}, even if the original target method handle was. 6123 * 6124 * @param target the method handle to invoke after arguments are combined 6125 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6126 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6127 * @param combiner method handle to call initially on the incoming arguments 6128 * @return method handle which incorporates the specified argument folding logic 6129 * @throws NullPointerException if either argument is null 6130 * @throws IllegalArgumentException if either of the following two conditions holds: 6131 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6132 * {@code pos} of the target signature; 6133 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6134 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6135 * 6136 * @see #foldArguments(MethodHandle, MethodHandle) 6137 * @since 9 6138 */ 6139 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6140 MethodType targetType = target.type(); 6141 MethodType combinerType = combiner.type(); 6142 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6143 BoundMethodHandle result = target.rebind(); 6144 boolean dropResult = rtype == void.class; 6145 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6146 MethodType newType = targetType; 6147 if (!dropResult) { 6148 newType = newType.dropParameterTypes(pos, pos + 1); 6149 } 6150 result = result.copyWithExtendL(newType, lform, combiner); 6151 return result; 6152 } 6153 6154 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6155 int foldArgs = combinerType.parameterCount(); 6156 Class<?> rtype = combinerType.returnType(); 6157 int foldVals = rtype == void.class ? 0 : 1; 6158 int afterInsertPos = foldPos + foldVals; 6159 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6160 if (ok) { 6161 for (int i = 0; i < foldArgs; i++) { 6162 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6163 ok = false; 6164 break; 6165 } 6166 } 6167 } 6168 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6169 ok = false; 6170 if (!ok) 6171 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6172 return rtype; 6173 } 6174 6175 /** 6176 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6177 * of the pre-processing replacing the argument at the given position. 6178 * 6179 * @param target the method handle to invoke after arguments are combined 6180 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6181 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6182 * @param combiner method handle to call initially on the incoming arguments 6183 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6184 * @return method handle which incorporates the specified argument folding logic 6185 * @throws NullPointerException if either argument is null 6186 * @throws IllegalArgumentException if either of the following two conditions holds: 6187 * (1) {@code combiner}'s return type is not the same as the argument type at position 6188 * {@code pos} of the target signature; 6189 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6190 * not identical with the argument types of {@code combiner}. 6191 */ 6192 /*non-public*/ 6193 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6194 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6195 } 6196 6197 /** 6198 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6199 * the pre-processing inserted into the original sequence of arguments at the given position. 6200 * 6201 * @param target the method handle to invoke after arguments are combined 6202 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6203 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6204 * @param combiner method handle to call initially on the incoming arguments 6205 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6206 * @return method handle which incorporates the specified argument folding logic 6207 * @throws NullPointerException if either argument is null 6208 * @throws IllegalArgumentException if either of the following two conditions holds: 6209 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6210 * {@code pos} of the target signature; 6211 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6212 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6213 * with the argument types of {@code combiner}. 6214 */ 6215 /*non-public*/ 6216 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6217 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6218 } 6219 6220 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6221 MethodType targetType = target.type(); 6222 MethodType combinerType = combiner.type(); 6223 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6224 BoundMethodHandle result = target.rebind(); 6225 6226 MethodType newType = targetType; 6227 LambdaForm lform; 6228 if (filter) { 6229 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6230 } else { 6231 boolean dropResult = rtype == void.class; 6232 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6233 if (!dropResult) { 6234 newType = newType.dropParameterTypes(position, position + 1); 6235 } 6236 } 6237 result = result.copyWithExtendL(newType, lform, combiner); 6238 return result; 6239 } 6240 6241 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6242 int combinerArgs = combinerType.parameterCount(); 6243 if (argPos.length != combinerArgs) { 6244 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6245 } 6246 Class<?> rtype = combinerType.returnType(); 6247 6248 for (int i = 0; i < combinerArgs; i++) { 6249 int arg = argPos[i]; 6250 if (arg < 0 || arg > targetType.parameterCount()) { 6251 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6252 } 6253 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6254 throw newIllegalArgumentException("target argument type at position " + arg 6255 + " must match combiner argument type at index " + i + ": " + targetType 6256 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6257 } 6258 } 6259 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6260 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6261 } 6262 return rtype; 6263 } 6264 6265 /** 6266 * Makes a method handle which adapts a target method handle, 6267 * by guarding it with a test, a boolean-valued method handle. 6268 * If the guard fails, a fallback handle is called instead. 6269 * All three method handles must have the same corresponding 6270 * argument and return types, except that the return type 6271 * of the test must be boolean, and the test is allowed 6272 * to have fewer arguments than the other two method handles. 6273 * <p> 6274 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6275 * represents the uniform result type of the three involved handles; 6276 * {@code A}/{@code a}, the types and values of the {@code target} 6277 * parameters and arguments that are consumed by the {@code test}; and 6278 * {@code B}/{@code b}, those types and values of the {@code target} 6279 * parameters and arguments that are not consumed by the {@code test}. 6280 * {@snippet lang="java" : 6281 * boolean test(A...); 6282 * T target(A...,B...); 6283 * T fallback(A...,B...); 6284 * T adapter(A... a,B... b) { 6285 * if (test(a...)) 6286 * return target(a..., b...); 6287 * else 6288 * return fallback(a..., b...); 6289 * } 6290 * } 6291 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6292 * be modified by execution of the test, and so are passed unchanged 6293 * from the caller to the target or fallback as appropriate. 6294 * @param test method handle used for test, must return boolean 6295 * @param target method handle to call if test passes 6296 * @param fallback method handle to call if test fails 6297 * @return method handle which incorporates the specified if/then/else logic 6298 * @throws NullPointerException if any argument is null 6299 * @throws IllegalArgumentException if {@code test} does not return boolean, 6300 * or if all three method types do not match (with the return 6301 * type of {@code test} changed to match that of the target). 6302 */ 6303 public static MethodHandle guardWithTest(MethodHandle test, 6304 MethodHandle target, 6305 MethodHandle fallback) { 6306 MethodType gtype = test.type(); 6307 MethodType ttype = target.type(); 6308 MethodType ftype = fallback.type(); 6309 if (!ttype.equals(ftype)) 6310 throw misMatchedTypes("target and fallback types", ttype, ftype); 6311 if (gtype.returnType() != boolean.class) 6312 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6313 6314 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6315 if (test == null) { 6316 throw misMatchedTypes("target and test types", ttype, gtype); 6317 } 6318 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6319 } 6320 6321 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6322 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6323 } 6324 6325 /** 6326 * Makes a method handle which adapts a target method handle, 6327 * by running it inside an exception handler. 6328 * If the target returns normally, the adapter returns that value. 6329 * If an exception matching the specified type is thrown, the fallback 6330 * handle is called instead on the exception, plus the original arguments. 6331 * <p> 6332 * The target and handler must have the same corresponding 6333 * argument and return types, except that handler may omit trailing arguments 6334 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6335 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6336 * <p> 6337 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6338 * represents the return type of the {@code target} and {@code handler}, 6339 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6340 * the types and values of arguments to the resulting handle consumed by 6341 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6342 * resulting handle discarded by {@code handler}. 6343 * {@snippet lang="java" : 6344 * T target(A..., B...); 6345 * T handler(ExType, A...); 6346 * T adapter(A... a, B... b) { 6347 * try { 6348 * return target(a..., b...); 6349 * } catch (ExType ex) { 6350 * return handler(ex, a...); 6351 * } 6352 * } 6353 * } 6354 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6355 * be modified by execution of the target, and so are passed unchanged 6356 * from the caller to the handler, if the handler is invoked. 6357 * <p> 6358 * The target and handler must return the same type, even if the handler 6359 * always throws. (This might happen, for instance, because the handler 6360 * is simulating a {@code finally} clause). 6361 * To create such a throwing handler, compose the handler creation logic 6362 * with {@link #throwException throwException}, 6363 * in order to create a method handle of the correct return type. 6364 * @param target method handle to call 6365 * @param exType the type of exception which the handler will catch 6366 * @param handler method handle to call if a matching exception is thrown 6367 * @return method handle which incorporates the specified try/catch logic 6368 * @throws NullPointerException if any argument is null 6369 * @throws IllegalArgumentException if {@code handler} does not accept 6370 * the given exception type, or if the method handle types do 6371 * not match in their return types and their 6372 * corresponding parameters 6373 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6374 */ 6375 public static MethodHandle catchException(MethodHandle target, 6376 Class<? extends Throwable> exType, 6377 MethodHandle handler) { 6378 MethodType ttype = target.type(); 6379 MethodType htype = handler.type(); 6380 if (!Throwable.class.isAssignableFrom(exType)) 6381 throw new ClassCastException(exType.getName()); 6382 if (htype.parameterCount() < 1 || 6383 !htype.parameterType(0).isAssignableFrom(exType)) 6384 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6385 if (htype.returnType() != ttype.returnType()) 6386 throw misMatchedTypes("target and handler return types", ttype, htype); 6387 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6388 if (handler == null) { 6389 throw misMatchedTypes("target and handler types", ttype, htype); 6390 } 6391 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6392 } 6393 6394 /** 6395 * Produces a method handle which will throw exceptions of the given {@code exType}. 6396 * The method handle will accept a single argument of {@code exType}, 6397 * and immediately throw it as an exception. 6398 * The method type will nominally specify a return of {@code returnType}. 6399 * The return type may be anything convenient: It doesn't matter to the 6400 * method handle's behavior, since it will never return normally. 6401 * @param returnType the return type of the desired method handle 6402 * @param exType the parameter type of the desired method handle 6403 * @return method handle which can throw the given exceptions 6404 * @throws NullPointerException if either argument is null 6405 */ 6406 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6407 if (!Throwable.class.isAssignableFrom(exType)) 6408 throw new ClassCastException(exType.getName()); 6409 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6410 } 6411 6412 /** 6413 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6414 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6415 * delivers the loop's result, which is the return value of the resulting handle. 6416 * <p> 6417 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6418 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6419 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6420 * terms of method handles, each clause will specify up to four independent actions:<ul> 6421 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6422 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6423 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6424 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6425 * </ul> 6426 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6427 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6428 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6429 * <p> 6430 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6431 * this case. See below for a detailed description. 6432 * <p> 6433 * <em>Parameters optional everywhere:</em> 6434 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6435 * As an exception, the init functions cannot take any {@code v} parameters, 6436 * because those values are not yet computed when the init functions are executed. 6437 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6438 * In fact, any clause function may take no arguments at all. 6439 * <p> 6440 * <em>Loop parameters:</em> 6441 * A clause function may take all the iteration variable values it is entitled to, in which case 6442 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6443 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6444 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6445 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6446 * init function is automatically a loop parameter {@code a}.) 6447 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6448 * These loop parameters act as loop-invariant values visible across the whole loop. 6449 * <p> 6450 * <em>Parameters visible everywhere:</em> 6451 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6452 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6453 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6454 * Most clause functions will not need all of this information, but they will be formally connected to it 6455 * as if by {@link #dropArguments}. 6456 * <a id="astar"></a> 6457 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6458 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6459 * In that notation, the general form of an init function parameter list 6460 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6461 * <p> 6462 * <em>Checking clause structure:</em> 6463 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6464 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6465 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6466 * met by the inputs to the loop combinator. 6467 * <p> 6468 * <em>Effectively identical sequences:</em> 6469 * <a id="effid"></a> 6470 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6471 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6472 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6473 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6474 * that longest list. 6475 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6476 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6477 * <p> 6478 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6479 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6480 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6481 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6482 * four. Padding takes place by appending elements to the array. 6483 * <li>Clauses with all {@code null}s are disregarded. 6484 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6485 * </ol> 6486 * <p> 6487 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6488 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6489 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6490 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6491 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6492 * iteration variable type. 6493 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6494 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6495 * </ol> 6496 * <p> 6497 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6498 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6499 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6500 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6501 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6502 * (These types will be checked in step 2, along with all the clause function types.) 6503 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6504 * <li>All of the collected parameter lists must be effectively identical. 6505 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6506 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6507 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6508 * the "internal parameter list". 6509 * </ul> 6510 * <p> 6511 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6512 * <li>Examine fini function return types, disregarding omitted fini functions. 6513 * <li>If there are no fini functions, the loop return type is {@code void}. 6514 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6515 * type. 6516 * </ol> 6517 * <p> 6518 * <em>Step 1D: Check other types.</em><ol type="a"> 6519 * <li>There must be at least one non-omitted pred function. 6520 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6521 * </ol> 6522 * <p> 6523 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6524 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6525 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6526 * (Note that their parameter lists are already effectively identical to this list.) 6527 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6528 * effectively identical to the internal parameter list {@code (V... A...)}. 6529 * </ol> 6530 * <p> 6531 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6532 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6533 * type. 6534 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6535 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6536 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6537 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6538 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6539 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6540 * loop return type. 6541 * </ol> 6542 * <p> 6543 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6544 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6545 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6546 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6547 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6548 * pad out the end of the list. 6549 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6550 * </ol> 6551 * <p> 6552 * <em>Final observations.</em><ol type="a"> 6553 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6554 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6555 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6556 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6557 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6558 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6559 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6560 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6561 * </ol> 6562 * <p> 6563 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6564 * <ul> 6565 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6566 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6567 * (Only one {@code Pn} has to be non-{@code null}.) 6568 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6569 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6570 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6571 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6572 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6573 * the resulting loop handle's parameter types {@code (A...)}. 6574 * </ul> 6575 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6576 * which is natural if most of the loop computation happens in the steps. For some loops, 6577 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6578 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6579 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6580 * where the init functions will need the extra parameters. For such reasons, the rules for 6581 * determining these parameters are as symmetric as possible, across all clause parts. 6582 * In general, the loop parameters function as common invariant values across the whole 6583 * loop, while the iteration variables function as common variant values, or (if there is 6584 * no step function) as internal loop invariant temporaries. 6585 * <p> 6586 * <em>Loop execution.</em><ol type="a"> 6587 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6588 * every clause function. These locals are loop invariant. 6589 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6590 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6591 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6592 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6593 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6594 * (in argument order). 6595 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6596 * returns {@code false}. 6597 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6598 * sequence {@code (v...)} of loop variables. 6599 * The updated value is immediately visible to all subsequent function calls. 6600 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6601 * (of type {@code R}) is returned from the loop as a whole. 6602 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6603 * except by throwing an exception. 6604 * </ol> 6605 * <p> 6606 * <em>Usage tips.</em> 6607 * <ul> 6608 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6609 * sometimes a step function only needs to observe the current value of its own variable. 6610 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6611 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6612 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6613 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6614 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6615 * <li>If some of the clause functions are virtual methods on an instance, the instance 6616 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6617 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6618 * will be the first iteration variable value, and it will be easy to use virtual 6619 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6620 * </ul> 6621 * <p> 6622 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6623 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6624 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6625 * {@snippet lang="java" : 6626 * V... init...(A...); 6627 * boolean pred...(V..., A...); 6628 * V... step...(V..., A...); 6629 * R fini...(V..., A...); 6630 * R loop(A... a) { 6631 * V... v... = init...(a...); 6632 * for (;;) { 6633 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6634 * v = s(v..., a...); 6635 * if (!p(v..., a...)) { 6636 * return f(v..., a...); 6637 * } 6638 * } 6639 * } 6640 * } 6641 * } 6642 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6643 * to their full length, even though individual clause functions may neglect to take them all. 6644 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6645 * 6646 * @apiNote Example: 6647 * {@snippet lang="java" : 6648 * // iterative implementation of the factorial function as a loop handle 6649 * static int one(int k) { return 1; } 6650 * static int inc(int i, int acc, int k) { return i + 1; } 6651 * static int mult(int i, int acc, int k) { return i * acc; } 6652 * static boolean pred(int i, int acc, int k) { return i < k; } 6653 * static int fin(int i, int acc, int k) { return acc; } 6654 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6655 * // null initializer for counter, should initialize to 0 6656 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6657 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6658 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6659 * assertEquals(120, loop.invoke(5)); 6660 * } 6661 * The same example, dropping arguments and using combinators: 6662 * {@snippet lang="java" : 6663 * // simplified implementation of the factorial function as a loop handle 6664 * static int inc(int i) { return i + 1; } // drop acc, k 6665 * static int mult(int i, int acc) { return i * acc; } //drop k 6666 * static boolean cmp(int i, int k) { return i < k; } 6667 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6668 * // null initializer for counter, should initialize to 0 6669 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6670 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6671 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6672 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6673 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6674 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6675 * assertEquals(720, loop.invoke(6)); 6676 * } 6677 * A similar example, using a helper object to hold a loop parameter: 6678 * {@snippet lang="java" : 6679 * // instance-based implementation of the factorial function as a loop handle 6680 * static class FacLoop { 6681 * final int k; 6682 * FacLoop(int k) { this.k = k; } 6683 * int inc(int i) { return i + 1; } 6684 * int mult(int i, int acc) { return i * acc; } 6685 * boolean pred(int i) { return i < k; } 6686 * int fin(int i, int acc) { return acc; } 6687 * } 6688 * // assume MH_FacLoop is a handle to the constructor 6689 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6690 * // null initializer for counter, should initialize to 0 6691 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6692 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6693 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6694 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6695 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6696 * assertEquals(5040, loop.invoke(7)); 6697 * } 6698 * 6699 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6700 * 6701 * @return a method handle embodying the looping behavior as defined by the arguments. 6702 * 6703 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6704 * 6705 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6706 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6707 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6708 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6709 * @since 9 6710 */ 6711 public static MethodHandle loop(MethodHandle[]... clauses) { 6712 // Step 0: determine clause structure. 6713 loopChecks0(clauses); 6714 6715 List<MethodHandle> init = new ArrayList<>(); 6716 List<MethodHandle> step = new ArrayList<>(); 6717 List<MethodHandle> pred = new ArrayList<>(); 6718 List<MethodHandle> fini = new ArrayList<>(); 6719 6720 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6721 init.add(clause[0]); // all clauses have at least length 1 6722 step.add(clause.length <= 1 ? null : clause[1]); 6723 pred.add(clause.length <= 2 ? null : clause[2]); 6724 fini.add(clause.length <= 3 ? null : clause[3]); 6725 }); 6726 6727 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6728 final int nclauses = init.size(); 6729 6730 // Step 1A: determine iteration variables (V...). 6731 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6732 for (int i = 0; i < nclauses; ++i) { 6733 MethodHandle in = init.get(i); 6734 MethodHandle st = step.get(i); 6735 if (in == null && st == null) { 6736 iterationVariableTypes.add(void.class); 6737 } else if (in != null && st != null) { 6738 loopChecks1a(i, in, st); 6739 iterationVariableTypes.add(in.type().returnType()); 6740 } else { 6741 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6742 } 6743 } 6744 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6745 6746 // Step 1B: determine loop parameters (A...). 6747 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6748 loopChecks1b(init, commonSuffix); 6749 6750 // Step 1C: determine loop return type. 6751 // Step 1D: check other types. 6752 // local variable required here; see JDK-8223553 6753 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6754 .map(MethodType::returnType); 6755 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6756 loopChecks1cd(pred, fini, loopReturnType); 6757 6758 // Step 2: determine parameter lists. 6759 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6760 commonParameterSequence.addAll(commonSuffix); 6761 loopChecks2(step, pred, fini, commonParameterSequence); 6762 // Step 3: fill in omitted functions. 6763 for (int i = 0; i < nclauses; ++i) { 6764 Class<?> t = iterationVariableTypes.get(i); 6765 if (init.get(i) == null) { 6766 init.set(i, empty(methodType(t, commonSuffix))); 6767 } 6768 if (step.get(i) == null) { 6769 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6770 } 6771 if (pred.get(i) == null) { 6772 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6773 } 6774 if (fini.get(i) == null) { 6775 fini.set(i, empty(methodType(t, commonParameterSequence))); 6776 } 6777 } 6778 6779 // Step 4: fill in missing parameter types. 6780 // Also convert all handles to fixed-arity handles. 6781 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6782 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6783 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6784 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6785 6786 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6787 allMatch(pl -> pl.equals(commonSuffix)); 6788 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6789 allMatch(pl -> pl.equals(commonParameterSequence)); 6790 6791 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6792 } 6793 6794 private static void loopChecks0(MethodHandle[][] clauses) { 6795 if (clauses == null || clauses.length == 0) { 6796 throw newIllegalArgumentException("null or no clauses passed"); 6797 } 6798 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6799 throw newIllegalArgumentException("null clauses are not allowed"); 6800 } 6801 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6802 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6803 } 6804 } 6805 6806 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6807 if (in.type().returnType() != st.type().returnType()) { 6808 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6809 st.type().returnType()); 6810 } 6811 } 6812 6813 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6814 return mhs.filter(Objects::nonNull) 6815 // take only those that can contribute to a common suffix because they are longer than the prefix 6816 .map(MethodHandle::type) 6817 .filter(t -> t.parameterCount() > skipSize) 6818 .max(Comparator.comparingInt(MethodType::parameterCount)) 6819 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6820 .orElse(List.of()); 6821 } 6822 6823 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6824 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6825 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6826 return longest1.size() >= longest2.size() ? longest1 : longest2; 6827 } 6828 6829 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6830 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6831 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6832 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6833 " (common suffix: " + commonSuffix + ")"); 6834 } 6835 } 6836 6837 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6838 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6839 anyMatch(t -> t != loopReturnType)) { 6840 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6841 loopReturnType + ")"); 6842 } 6843 6844 if (pred.stream().noneMatch(Objects::nonNull)) { 6845 throw newIllegalArgumentException("no predicate found", pred); 6846 } 6847 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6848 anyMatch(t -> t != boolean.class)) { 6849 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6850 } 6851 } 6852 6853 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6854 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6855 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6856 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6857 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6858 } 6859 } 6860 6861 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6862 return hs.stream().map(h -> { 6863 int pc = h.type().parameterCount(); 6864 int tpsize = targetParams.size(); 6865 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6866 }).toList(); 6867 } 6868 6869 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6870 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6871 } 6872 6873 /** 6874 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6875 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6876 * <p> 6877 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6878 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6879 * evaluates to {@code true}). 6880 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6881 * <p> 6882 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6883 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6884 * and updated with the value returned from its invocation. The result of loop execution will be 6885 * the final value of the additional loop-local variable (if present). 6886 * <p> 6887 * The following rules hold for these argument handles:<ul> 6888 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6889 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6890 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6891 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6892 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6893 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6894 * It will constrain the parameter lists of the other loop parts. 6895 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6896 * list {@code (A...)} is called the <em>external parameter list</em>. 6897 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6898 * additional state variable of the loop. 6899 * The body must both accept and return a value of this type {@code V}. 6900 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6901 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6902 * <a href="MethodHandles.html#effid">effectively identical</a> 6903 * to the external parameter list {@code (A...)}. 6904 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6905 * {@linkplain #empty default value}. 6906 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6907 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6908 * effectively identical to the internal parameter list. 6909 * </ul> 6910 * <p> 6911 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6912 * <li>The loop handle's result type is the result type {@code V} of the body. 6913 * <li>The loop handle's parameter types are the types {@code (A...)}, 6914 * from the external parameter list. 6915 * </ul> 6916 * <p> 6917 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6918 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6919 * passed to the loop. 6920 * {@snippet lang="java" : 6921 * V init(A...); 6922 * boolean pred(V, A...); 6923 * V body(V, A...); 6924 * V whileLoop(A... a...) { 6925 * V v = init(a...); 6926 * while (pred(v, a...)) { 6927 * v = body(v, a...); 6928 * } 6929 * return v; 6930 * } 6931 * } 6932 * 6933 * @apiNote Example: 6934 * {@snippet lang="java" : 6935 * // implement the zip function for lists as a loop handle 6936 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6937 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6938 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6939 * zip.add(a.next()); 6940 * zip.add(b.next()); 6941 * return zip; 6942 * } 6943 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6944 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6945 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6946 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6947 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6948 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6949 * } 6950 * 6951 * 6952 * @apiNote The implementation of this method can be expressed as follows: 6953 * {@snippet lang="java" : 6954 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6955 * MethodHandle fini = (body.type().returnType() == void.class 6956 * ? null : identity(body.type().returnType())); 6957 * MethodHandle[] 6958 * checkExit = { null, null, pred, fini }, 6959 * varBody = { init, body }; 6960 * return loop(checkExit, varBody); 6961 * } 6962 * } 6963 * 6964 * @param init optional initializer, providing the initial value of the loop variable. 6965 * May be {@code null}, implying a default initial value. See above for other constraints. 6966 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6967 * above for other constraints. 6968 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6969 * See above for other constraints. 6970 * 6971 * @return a method handle implementing the {@code while} loop as described by the arguments. 6972 * @throws IllegalArgumentException if the rules for the arguments are violated. 6973 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6974 * 6975 * @see #loop(MethodHandle[][]) 6976 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6977 * @since 9 6978 */ 6979 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6980 whileLoopChecks(init, pred, body); 6981 MethodHandle fini = identityOrVoid(body.type().returnType()); 6982 MethodHandle[] checkExit = { null, null, pred, fini }; 6983 MethodHandle[] varBody = { init, body }; 6984 return loop(checkExit, varBody); 6985 } 6986 6987 /** 6988 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6989 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6990 * <p> 6991 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6992 * method will, in each iteration, first execute its body and then evaluate the predicate. 6993 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6994 * <p> 6995 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6996 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6997 * and updated with the value returned from its invocation. The result of loop execution will be 6998 * the final value of the additional loop-local variable (if present). 6999 * <p> 7000 * The following rules hold for these argument handles:<ul> 7001 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7002 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 7003 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7004 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 7005 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 7006 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 7007 * It will constrain the parameter lists of the other loop parts. 7008 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 7009 * list {@code (A...)} is called the <em>external parameter list</em>. 7010 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7011 * additional state variable of the loop. 7012 * The body must both accept and return a value of this type {@code V}. 7013 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7014 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7015 * <a href="MethodHandles.html#effid">effectively identical</a> 7016 * to the external parameter list {@code (A...)}. 7017 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7018 * {@linkplain #empty default value}. 7019 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 7020 * Its parameter list (either empty or of the form {@code (V A*)}) must be 7021 * effectively identical to the internal parameter list. 7022 * </ul> 7023 * <p> 7024 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7025 * <li>The loop handle's result type is the result type {@code V} of the body. 7026 * <li>The loop handle's parameter types are the types {@code (A...)}, 7027 * from the external parameter list. 7028 * </ul> 7029 * <p> 7030 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7031 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 7032 * passed to the loop. 7033 * {@snippet lang="java" : 7034 * V init(A...); 7035 * boolean pred(V, A...); 7036 * V body(V, A...); 7037 * V doWhileLoop(A... a...) { 7038 * V v = init(a...); 7039 * do { 7040 * v = body(v, a...); 7041 * } while (pred(v, a...)); 7042 * return v; 7043 * } 7044 * } 7045 * 7046 * @apiNote Example: 7047 * {@snippet lang="java" : 7048 * // int i = 0; while (i < limit) { ++i; } return i; => limit 7049 * static int zero(int limit) { return 0; } 7050 * static int step(int i, int limit) { return i + 1; } 7051 * static boolean pred(int i, int limit) { return i < limit; } 7052 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 7053 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 7054 * assertEquals(23, loop.invoke(23)); 7055 * } 7056 * 7057 * 7058 * @apiNote The implementation of this method can be expressed as follows: 7059 * {@snippet lang="java" : 7060 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7061 * MethodHandle fini = (body.type().returnType() == void.class 7062 * ? null : identity(body.type().returnType())); 7063 * MethodHandle[] clause = { init, body, pred, fini }; 7064 * return loop(clause); 7065 * } 7066 * } 7067 * 7068 * @param init optional initializer, providing the initial value of the loop variable. 7069 * May be {@code null}, implying a default initial value. See above for other constraints. 7070 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7071 * See above for other constraints. 7072 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7073 * above for other constraints. 7074 * 7075 * @return a method handle implementing the {@code while} loop as described by the arguments. 7076 * @throws IllegalArgumentException if the rules for the arguments are violated. 7077 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7078 * 7079 * @see #loop(MethodHandle[][]) 7080 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7081 * @since 9 7082 */ 7083 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7084 whileLoopChecks(init, pred, body); 7085 MethodHandle fini = identityOrVoid(body.type().returnType()); 7086 MethodHandle[] clause = {init, body, pred, fini }; 7087 return loop(clause); 7088 } 7089 7090 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7091 Objects.requireNonNull(pred); 7092 Objects.requireNonNull(body); 7093 MethodType bodyType = body.type(); 7094 Class<?> returnType = bodyType.returnType(); 7095 List<Class<?>> innerList = bodyType.parameterList(); 7096 List<Class<?>> outerList = innerList; 7097 if (returnType == void.class) { 7098 // OK 7099 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7100 // leading V argument missing => error 7101 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7102 throw misMatchedTypes("body function", bodyType, expected); 7103 } else { 7104 outerList = innerList.subList(1, innerList.size()); 7105 } 7106 MethodType predType = pred.type(); 7107 if (predType.returnType() != boolean.class || 7108 !predType.effectivelyIdenticalParameters(0, innerList)) { 7109 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7110 } 7111 if (init != null) { 7112 MethodType initType = init.type(); 7113 if (initType.returnType() != returnType || 7114 !initType.effectivelyIdenticalParameters(0, outerList)) { 7115 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7116 } 7117 } 7118 } 7119 7120 /** 7121 * Constructs a loop that runs a given number of iterations. 7122 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7123 * <p> 7124 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7125 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7126 * It will be initialized to 0 and incremented by 1 in each iteration. 7127 * <p> 7128 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7129 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7130 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7131 * <p> 7132 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7133 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7134 * iteration variable. 7135 * The result of the loop handle execution will be the final {@code V} value of that variable 7136 * (or {@code void} if there is no {@code V} variable). 7137 * <p> 7138 * The following rules hold for the argument handles:<ul> 7139 * <li>The {@code iterations} handle must not be {@code null}, and must return 7140 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7141 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7142 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7143 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7144 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7145 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7146 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7147 * of types called the <em>internal parameter list</em>. 7148 * It will constrain the parameter lists of the other loop parts. 7149 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7150 * with no additional {@code A} types, then the internal parameter list is extended by 7151 * the argument types {@code A...} of the {@code iterations} handle. 7152 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7153 * list {@code (A...)} is called the <em>external parameter list</em>. 7154 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7155 * additional state variable of the loop. 7156 * The body must both accept a leading parameter and return a value of this type {@code V}. 7157 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7158 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7159 * <a href="MethodHandles.html#effid">effectively identical</a> 7160 * to the external parameter list {@code (A...)}. 7161 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7162 * {@linkplain #empty default value}. 7163 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7164 * effectively identical to the external parameter list {@code (A...)}. 7165 * </ul> 7166 * <p> 7167 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7168 * <li>The loop handle's result type is the result type {@code V} of the body. 7169 * <li>The loop handle's parameter types are the types {@code (A...)}, 7170 * from the external parameter list. 7171 * </ul> 7172 * <p> 7173 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7174 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7175 * arguments passed to the loop. 7176 * {@snippet lang="java" : 7177 * int iterations(A...); 7178 * V init(A...); 7179 * V body(V, int, A...); 7180 * V countedLoop(A... a...) { 7181 * int end = iterations(a...); 7182 * V v = init(a...); 7183 * for (int i = 0; i < end; ++i) { 7184 * v = body(v, i, a...); 7185 * } 7186 * return v; 7187 * } 7188 * } 7189 * 7190 * @apiNote Example with a fully conformant body method: 7191 * {@snippet lang="java" : 7192 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7193 * // => a variation on a well known theme 7194 * static String step(String v, int counter, String init) { return "na " + v; } 7195 * // assume MH_step is a handle to the method above 7196 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7197 * MethodHandle start = MethodHandles.identity(String.class); 7198 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7199 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7200 * } 7201 * 7202 * @apiNote Example with the simplest possible body method type, 7203 * and passing the number of iterations to the loop invocation: 7204 * {@snippet lang="java" : 7205 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7206 * // => a variation on a well known theme 7207 * static String step(String v, int counter ) { return "na " + v; } 7208 * // assume MH_step is a handle to the method above 7209 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7210 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7211 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7212 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7213 * } 7214 * 7215 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7216 * as loop parameters: 7217 * {@snippet lang="java" : 7218 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7219 * // => a variation on a well known theme 7220 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 7221 * // assume MH_step is a handle to the method above 7222 * MethodHandle count = MethodHandles.identity(int.class); 7223 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7224 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7225 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7226 * } 7227 * 7228 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7229 * to enforce a loop type: 7230 * {@snippet lang="java" : 7231 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7232 * // => a variation on a well known theme 7233 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7234 * // assume MH_step is a handle to the method above 7235 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7236 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7237 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7238 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7239 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7240 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7241 * } 7242 * 7243 * @apiNote The implementation of this method can be expressed as follows: 7244 * {@snippet lang="java" : 7245 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7246 * return countedLoop(empty(iterations.type()), iterations, init, body); 7247 * } 7248 * } 7249 * 7250 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7251 * result type must be {@code int}. See above for other constraints. 7252 * @param init optional initializer, providing the initial value of the loop variable. 7253 * May be {@code null}, implying a default initial value. See above for other constraints. 7254 * @param body body of the loop, which may not be {@code null}. 7255 * It controls the loop parameters and result type in the standard case (see above for details). 7256 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7257 * and may accept any number of additional types. 7258 * See above for other constraints. 7259 * 7260 * @return a method handle representing the loop. 7261 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7262 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7263 * 7264 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7265 * @since 9 7266 */ 7267 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7268 return countedLoop(empty(iterations.type()), iterations, init, body); 7269 } 7270 7271 /** 7272 * Constructs a loop that counts over a range of numbers. 7273 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7274 * <p> 7275 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7276 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7277 * values of the loop counter. 7278 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7279 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7280 * <p> 7281 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7282 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7283 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7284 * <p> 7285 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7286 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7287 * iteration variable. 7288 * The result of the loop handle execution will be the final {@code V} value of that variable 7289 * (or {@code void} if there is no {@code V} variable). 7290 * <p> 7291 * The following rules hold for the argument handles:<ul> 7292 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7293 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7294 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7295 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7296 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7297 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7298 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7299 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7300 * of types called the <em>internal parameter list</em>. 7301 * It will constrain the parameter lists of the other loop parts. 7302 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7303 * with no additional {@code A} types, then the internal parameter list is extended by 7304 * the argument types {@code A...} of the {@code end} handle. 7305 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7306 * list {@code (A...)} is called the <em>external parameter list</em>. 7307 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7308 * additional state variable of the loop. 7309 * The body must both accept a leading parameter and return a value of this type {@code V}. 7310 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7311 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7312 * <a href="MethodHandles.html#effid">effectively identical</a> 7313 * to the external parameter list {@code (A...)}. 7314 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7315 * {@linkplain #empty default value}. 7316 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7317 * effectively identical to the external parameter list {@code (A...)}. 7318 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7319 * to the external parameter list. 7320 * </ul> 7321 * <p> 7322 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7323 * <li>The loop handle's result type is the result type {@code V} of the body. 7324 * <li>The loop handle's parameter types are the types {@code (A...)}, 7325 * from the external parameter list. 7326 * </ul> 7327 * <p> 7328 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7329 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7330 * arguments passed to the loop. 7331 * {@snippet lang="java" : 7332 * int start(A...); 7333 * int end(A...); 7334 * V init(A...); 7335 * V body(V, int, A...); 7336 * V countedLoop(A... a...) { 7337 * int e = end(a...); 7338 * int s = start(a...); 7339 * V v = init(a...); 7340 * for (int i = s; i < e; ++i) { 7341 * v = body(v, i, a...); 7342 * } 7343 * return v; 7344 * } 7345 * } 7346 * 7347 * @apiNote The implementation of this method can be expressed as follows: 7348 * {@snippet lang="java" : 7349 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7350 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7351 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7352 * // the following semantics: 7353 * // MH_increment: (int limit, int counter) -> counter + 1 7354 * // MH_predicate: (int limit, int counter) -> counter < limit 7355 * Class<?> counterType = start.type().returnType(); // int 7356 * Class<?> returnType = body.type().returnType(); 7357 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7358 * if (returnType != void.class) { // ignore the V variable 7359 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7360 * pred = dropArguments(pred, 1, returnType); // ditto 7361 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7362 * } 7363 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7364 * MethodHandle[] 7365 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7366 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7367 * indexVar = { start, incr }; // i = start(); i = i + 1 7368 * return loop(loopLimit, bodyClause, indexVar); 7369 * } 7370 * } 7371 * 7372 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7373 * See above for other constraints. 7374 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7375 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7376 * @param init optional initializer, providing the initial value of the loop variable. 7377 * May be {@code null}, implying a default initial value. See above for other constraints. 7378 * @param body body of the loop, which may not be {@code null}. 7379 * It controls the loop parameters and result type in the standard case (see above for details). 7380 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7381 * and may accept any number of additional types. 7382 * See above for other constraints. 7383 * 7384 * @return a method handle representing the loop. 7385 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7386 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7387 * 7388 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7389 * @since 9 7390 */ 7391 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7392 countedLoopChecks(start, end, init, body); 7393 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7394 Class<?> limitType = end.type().returnType(); // yes, int again 7395 Class<?> returnType = body.type().returnType(); 7396 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7397 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7398 MethodHandle retv = null; 7399 if (returnType != void.class) { 7400 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7401 pred = dropArguments(pred, 1, returnType); // ditto 7402 retv = dropArguments(identity(returnType), 0, counterType); 7403 } 7404 body = dropArguments(body, 0, counterType); // ignore the limit variable 7405 MethodHandle[] 7406 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7407 bodyClause = { init, body }, // v = init(); v = body(v, i) 7408 indexVar = { start, incr }; // i = start(); i = i + 1 7409 return loop(loopLimit, bodyClause, indexVar); 7410 } 7411 7412 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7413 Objects.requireNonNull(start); 7414 Objects.requireNonNull(end); 7415 Objects.requireNonNull(body); 7416 Class<?> counterType = start.type().returnType(); 7417 if (counterType != int.class) { 7418 MethodType expected = start.type().changeReturnType(int.class); 7419 throw misMatchedTypes("start function", start.type(), expected); 7420 } else if (end.type().returnType() != counterType) { 7421 MethodType expected = end.type().changeReturnType(counterType); 7422 throw misMatchedTypes("end function", end.type(), expected); 7423 } 7424 MethodType bodyType = body.type(); 7425 Class<?> returnType = bodyType.returnType(); 7426 List<Class<?>> innerList = bodyType.parameterList(); 7427 // strip leading V value if present 7428 int vsize = (returnType == void.class ? 0 : 1); 7429 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7430 // argument list has no "V" => error 7431 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7432 throw misMatchedTypes("body function", bodyType, expected); 7433 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7434 // missing I type => error 7435 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7436 throw misMatchedTypes("body function", bodyType, expected); 7437 } 7438 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7439 if (outerList.isEmpty()) { 7440 // special case; take lists from end handle 7441 outerList = end.type().parameterList(); 7442 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7443 } 7444 MethodType expected = methodType(counterType, outerList); 7445 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7446 throw misMatchedTypes("start parameter types", start.type(), expected); 7447 } 7448 if (end.type() != start.type() && 7449 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7450 throw misMatchedTypes("end parameter types", end.type(), expected); 7451 } 7452 if (init != null) { 7453 MethodType initType = init.type(); 7454 if (initType.returnType() != returnType || 7455 !initType.effectivelyIdenticalParameters(0, outerList)) { 7456 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7457 } 7458 } 7459 } 7460 7461 /** 7462 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7463 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7464 * <p> 7465 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7466 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7467 * <p> 7468 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7469 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7470 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7471 * <p> 7472 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7473 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7474 * iteration variable. 7475 * The result of the loop handle execution will be the final {@code V} value of that variable 7476 * (or {@code void} if there is no {@code V} variable). 7477 * <p> 7478 * The following rules hold for the argument handles:<ul> 7479 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7480 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7481 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7482 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7483 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7484 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7485 * of types called the <em>internal parameter list</em>. 7486 * It will constrain the parameter lists of the other loop parts. 7487 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7488 * with no additional {@code A} types, then the internal parameter list is extended by 7489 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7490 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7491 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7492 * list {@code (A...)} is called the <em>external parameter list</em>. 7493 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7494 * additional state variable of the loop. 7495 * The body must both accept a leading parameter and return a value of this type {@code V}. 7496 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7497 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7498 * <a href="MethodHandles.html#effid">effectively identical</a> 7499 * to the external parameter list {@code (A...)}. 7500 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7501 * {@linkplain #empty default value}. 7502 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7503 * type {@code java.util.Iterator} or a subtype thereof. 7504 * The iterator it produces when the loop is executed will be assumed 7505 * to yield values which can be converted to type {@code T}. 7506 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7507 * effectively identical to the external parameter list {@code (A...)}. 7508 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7509 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7510 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7511 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7512 * the {@link MethodHandle#asType asType} conversion method. 7513 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7514 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7515 * </ul> 7516 * <p> 7517 * The type {@code T} may be either a primitive or reference. 7518 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7519 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7520 * as if by the {@link MethodHandle#asType asType} conversion method. 7521 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7522 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7523 * <p> 7524 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7525 * <li>The loop handle's result type is the result type {@code V} of the body. 7526 * <li>The loop handle's parameter types are the types {@code (A...)}, 7527 * from the external parameter list. 7528 * </ul> 7529 * <p> 7530 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7531 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7532 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7533 * {@snippet lang="java" : 7534 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7535 * V init(A...); 7536 * V body(V,T,A...); 7537 * V iteratedLoop(A... a...) { 7538 * Iterator<T> it = iterator(a...); 7539 * V v = init(a...); 7540 * while (it.hasNext()) { 7541 * T t = it.next(); 7542 * v = body(v, t, a...); 7543 * } 7544 * return v; 7545 * } 7546 * } 7547 * 7548 * @apiNote Example: 7549 * {@snippet lang="java" : 7550 * // get an iterator from a list 7551 * static List<String> reverseStep(List<String> r, String e) { 7552 * r.add(0, e); 7553 * return r; 7554 * } 7555 * static List<String> newArrayList() { return new ArrayList<>(); } 7556 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7557 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7558 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7559 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7560 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7561 * } 7562 * 7563 * @apiNote The implementation of this method can be expressed approximately as follows: 7564 * {@snippet lang="java" : 7565 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7566 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7567 * Class<?> returnType = body.type().returnType(); 7568 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7569 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7570 * MethodHandle retv = null, step = body, startIter = iterator; 7571 * if (returnType != void.class) { 7572 * // the simple thing first: in (I V A...), drop the I to get V 7573 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7574 * // body type signature (V T A...), internal loop types (I V A...) 7575 * step = swapArguments(body, 0, 1); // swap V <-> T 7576 * } 7577 * if (startIter == null) startIter = MH_getIter; 7578 * MethodHandle[] 7579 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7580 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7581 * return loop(iterVar, bodyClause); 7582 * } 7583 * } 7584 * 7585 * @param iterator an optional handle to return the iterator to start the loop. 7586 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7587 * See above for other constraints. 7588 * @param init optional initializer, providing the initial value of the loop variable. 7589 * May be {@code null}, implying a default initial value. See above for other constraints. 7590 * @param body body of the loop, which may not be {@code null}. 7591 * It controls the loop parameters and result type in the standard case (see above for details). 7592 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7593 * and may accept any number of additional types. 7594 * See above for other constraints. 7595 * 7596 * @return a method handle embodying the iteration loop functionality. 7597 * @throws NullPointerException if the {@code body} handle is {@code null}. 7598 * @throws IllegalArgumentException if any argument violates the above requirements. 7599 * 7600 * @since 9 7601 */ 7602 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7603 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7604 Class<?> returnType = body.type().returnType(); 7605 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7606 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7607 MethodHandle startIter; 7608 MethodHandle nextVal; 7609 { 7610 MethodType iteratorType; 7611 if (iterator == null) { 7612 // derive argument type from body, if available, else use Iterable 7613 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7614 iteratorType = startIter.type().changeParameterType(0, iterableType); 7615 } else { 7616 // force return type to the internal iterator class 7617 iteratorType = iterator.type().changeReturnType(Iterator.class); 7618 startIter = iterator; 7619 } 7620 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7621 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7622 7623 // perform the asType transforms under an exception transformer, as per spec.: 7624 try { 7625 startIter = startIter.asType(iteratorType); 7626 nextVal = nextRaw.asType(nextValType); 7627 } catch (WrongMethodTypeException ex) { 7628 throw new IllegalArgumentException(ex); 7629 } 7630 } 7631 7632 MethodHandle retv = null, step = body; 7633 if (returnType != void.class) { 7634 // the simple thing first: in (I V A...), drop the I to get V 7635 retv = dropArguments(identity(returnType), 0, Iterator.class); 7636 // body type signature (V T A...), internal loop types (I V A...) 7637 step = swapArguments(body, 0, 1); // swap V <-> T 7638 } 7639 7640 MethodHandle[] 7641 iterVar = { startIter, null, hasNext, retv }, 7642 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7643 return loop(iterVar, bodyClause); 7644 } 7645 7646 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7647 Objects.requireNonNull(body); 7648 MethodType bodyType = body.type(); 7649 Class<?> returnType = bodyType.returnType(); 7650 List<Class<?>> internalParamList = bodyType.parameterList(); 7651 // strip leading V value if present 7652 int vsize = (returnType == void.class ? 0 : 1); 7653 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7654 // argument list has no "V" => error 7655 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7656 throw misMatchedTypes("body function", bodyType, expected); 7657 } else if (internalParamList.size() <= vsize) { 7658 // missing T type => error 7659 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7660 throw misMatchedTypes("body function", bodyType, expected); 7661 } 7662 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7663 Class<?> iterableType = null; 7664 if (iterator != null) { 7665 // special case; if the body handle only declares V and T then 7666 // the external parameter list is obtained from iterator handle 7667 if (externalParamList.isEmpty()) { 7668 externalParamList = iterator.type().parameterList(); 7669 } 7670 MethodType itype = iterator.type(); 7671 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7672 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7673 } 7674 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7675 MethodType expected = methodType(itype.returnType(), externalParamList); 7676 throw misMatchedTypes("iterator parameters", itype, expected); 7677 } 7678 } else { 7679 if (externalParamList.isEmpty()) { 7680 // special case; if the iterator handle is null and the body handle 7681 // only declares V and T then the external parameter list consists 7682 // of Iterable 7683 externalParamList = List.of(Iterable.class); 7684 iterableType = Iterable.class; 7685 } else { 7686 // special case; if the iterator handle is null and the external 7687 // parameter list is not empty then the first parameter must be 7688 // assignable to Iterable 7689 iterableType = externalParamList.get(0); 7690 if (!Iterable.class.isAssignableFrom(iterableType)) { 7691 throw newIllegalArgumentException( 7692 "inferred first loop argument must inherit from Iterable: " + iterableType); 7693 } 7694 } 7695 } 7696 if (init != null) { 7697 MethodType initType = init.type(); 7698 if (initType.returnType() != returnType || 7699 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7700 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7701 } 7702 } 7703 return iterableType; // help the caller a bit 7704 } 7705 7706 /*non-public*/ 7707 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7708 // there should be a better way to uncross my wires 7709 int arity = mh.type().parameterCount(); 7710 int[] order = new int[arity]; 7711 for (int k = 0; k < arity; k++) order[k] = k; 7712 order[i] = j; order[j] = i; 7713 Class<?>[] types = mh.type().parameterArray(); 7714 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7715 MethodType swapType = methodType(mh.type().returnType(), types); 7716 return permuteArguments(mh, swapType, order); 7717 } 7718 7719 /** 7720 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7721 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7722 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7723 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7724 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7725 * {@code try-finally} handle. 7726 * <p> 7727 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7728 * The first is the exception thrown during the 7729 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7730 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7731 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7732 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7733 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7734 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7735 * <p> 7736 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7737 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7738 * two extra leading parameters:<ul> 7739 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7740 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7741 * the result from the execution of the {@code target} handle. 7742 * This parameter is not present if the {@code target} returns {@code void}. 7743 * </ul> 7744 * <p> 7745 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7746 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7747 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7748 * the cleanup. 7749 * {@snippet lang="java" : 7750 * V target(A..., B...); 7751 * V cleanup(Throwable, V, A...); 7752 * V adapter(A... a, B... b) { 7753 * V result = (zero value for V); 7754 * Throwable throwable = null; 7755 * try { 7756 * result = target(a..., b...); 7757 * } catch (Throwable t) { 7758 * throwable = t; 7759 * throw t; 7760 * } finally { 7761 * result = cleanup(throwable, result, a...); 7762 * } 7763 * return result; 7764 * } 7765 * } 7766 * <p> 7767 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7768 * be modified by execution of the target, and so are passed unchanged 7769 * from the caller to the cleanup, if it is invoked. 7770 * <p> 7771 * The target and cleanup must return the same type, even if the cleanup 7772 * always throws. 7773 * To create such a throwing cleanup, compose the cleanup logic 7774 * with {@link #throwException throwException}, 7775 * in order to create a method handle of the correct return type. 7776 * <p> 7777 * Note that {@code tryFinally} never converts exceptions into normal returns. 7778 * In rare cases where exceptions must be converted in that way, first wrap 7779 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7780 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7781 * <p> 7782 * It is recommended that the first parameter type of {@code cleanup} be 7783 * declared {@code Throwable} rather than a narrower subtype. This ensures 7784 * {@code cleanup} will always be invoked with whatever exception that 7785 * {@code target} throws. Declaring a narrower type may result in a 7786 * {@code ClassCastException} being thrown by the {@code try-finally} 7787 * handle if the type of the exception thrown by {@code target} is not 7788 * assignable to the first parameter type of {@code cleanup}. Note that 7789 * various exception types of {@code VirtualMachineError}, 7790 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7791 * thrown by almost any kind of Java code, and a finally clause that 7792 * catches (say) only {@code IOException} would mask any of the others 7793 * behind a {@code ClassCastException}. 7794 * 7795 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7796 * @param cleanup the handle that is invoked in the finally block. 7797 * 7798 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7799 * @throws NullPointerException if any argument is null 7800 * @throws IllegalArgumentException if {@code cleanup} does not accept 7801 * the required leading arguments, or if the method handle types do 7802 * not match in their return types and their 7803 * corresponding trailing parameters 7804 * 7805 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7806 * @since 9 7807 */ 7808 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7809 Class<?>[] targetParamTypes = target.type().ptypes(); 7810 Class<?> rtype = target.type().returnType(); 7811 7812 tryFinallyChecks(target, cleanup); 7813 7814 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7815 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7816 // target parameter list. 7817 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7818 7819 // Ensure that the intrinsic type checks the instance thrown by the 7820 // target against the first parameter of cleanup 7821 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7822 7823 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7824 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7825 } 7826 7827 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7828 Class<?> rtype = target.type().returnType(); 7829 if (rtype != cleanup.type().returnType()) { 7830 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7831 } 7832 MethodType cleanupType = cleanup.type(); 7833 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7834 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7835 } 7836 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7837 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7838 } 7839 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7840 // target parameter list. 7841 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7842 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7843 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7844 cleanup.type(), target.type()); 7845 } 7846 } 7847 7848 /** 7849 * Creates a table switch method handle, which can be used to switch over a set of target 7850 * method handles, based on a given target index, called selector. 7851 * <p> 7852 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7853 * and where {@code N} is the number of target method handles, the table switch method 7854 * handle will invoke the n-th target method handle from the list of target method handles. 7855 * <p> 7856 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7857 * method handle will invoke the given fallback method handle. 7858 * <p> 7859 * All method handles passed to this method must have the same type, with the additional 7860 * requirement that the leading parameter be of type {@code int}. The leading parameter 7861 * represents the selector. 7862 * <p> 7863 * Any trailing parameters present in the type will appear on the returned table switch 7864 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7865 * together with the selector value, to the selected method handle when invoking it. 7866 * 7867 * @apiNote Example: 7868 * The cases each drop the {@code selector} value they are given, and take an additional 7869 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7870 * to a specific constant label string for each case: 7871 * {@snippet lang="java" : 7872 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7873 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7874 * MethodType.methodType(String.class, String.class)); 7875 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7876 * 7877 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7878 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7879 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7880 * 7881 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7882 * caseDefault, 7883 * case0, 7884 * case1 7885 * ); 7886 * 7887 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7888 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7889 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7890 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7891 * } 7892 * 7893 * @param fallback the fallback method handle that is called when the selector is not 7894 * within the range {@code [0, N)}. 7895 * @param targets array of target method handles. 7896 * @return the table switch method handle. 7897 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7898 * any of the elements of the {@code targets} array are 7899 * {@code null}. 7900 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7901 * parameter of the fallback handle or any of the target 7902 * handles is not {@code int}, or if the types of 7903 * the fallback handle and all of target handles are 7904 * not the same. 7905 * 7906 * @since 17 7907 */ 7908 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7909 Objects.requireNonNull(fallback); 7910 Objects.requireNonNull(targets); 7911 targets = targets.clone(); 7912 MethodType type = tableSwitchChecks(fallback, targets); 7913 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7914 } 7915 7916 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7917 if (caseActions.length == 0) 7918 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7919 7920 MethodType expectedType = defaultCase.type(); 7921 7922 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7923 throw new IllegalArgumentException( 7924 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7925 7926 for (MethodHandle mh : caseActions) { 7927 Objects.requireNonNull(mh); 7928 if (mh.type() != expectedType) 7929 throw new IllegalArgumentException( 7930 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7931 } 7932 7933 return expectedType; 7934 } 7935 7936 /** 7937 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7938 * <p> 7939 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7940 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7941 * to the target var handle. 7942 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7943 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7944 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7945 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7946 * <p> 7947 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7948 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7949 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7950 * will be appended to the coordinates of the target var handle). 7951 * <p> 7952 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7953 * throw an {@link IllegalStateException}. 7954 * <p> 7955 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7956 * atomic access guarantees as those featured by the target var handle. 7957 * 7958 * @param target the target var handle 7959 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7960 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7961 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7962 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7963 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7964 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7965 * @throws NullPointerException if any of the arguments is {@code null}. 7966 * @since 22 7967 */ 7968 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7969 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7970 } 7971 7972 /** 7973 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7974 * <p> 7975 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7976 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7977 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7978 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7979 * by the adaptation) to the target var handle. 7980 * <p> 7981 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7982 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7983 * <p> 7984 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7985 * throw an {@link IllegalStateException}. 7986 * <p> 7987 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7988 * atomic access guarantees as those featured by the target var handle. 7989 * 7990 * @param target the target var handle 7991 * @param pos the position of the first coordinate to be transformed 7992 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7993 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7994 * to the new coordinate values. 7995 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7996 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7997 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7998 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7999 * or if it's determined that any of the filters throws any checked exceptions. 8000 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 8001 * @since 22 8002 */ 8003 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8004 return VarHandles.filterCoordinates(target, pos, filters); 8005 } 8006 8007 /** 8008 * Provides a target var handle with one or more <em>bound coordinates</em> 8009 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8010 * coordinate types than the target var handle. 8011 * <p> 8012 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8013 * are joined with bound coordinate values, and then passed to the target var handle. 8014 * <p> 8015 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8016 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8017 * <p> 8018 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8019 * atomic access guarantees as those featured by the target var handle. 8020 * 8021 * @param target the var handle to invoke after the bound coordinates are inserted 8022 * @param pos the position of the first coordinate to be inserted 8023 * @param values the series of bound coordinates to insert 8024 * @return an adapter var handle which inserts additional coordinates, 8025 * before calling the target var handle 8026 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8027 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8028 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8029 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8030 * of the target var handle. 8031 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8032 * @since 22 8033 */ 8034 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8035 return VarHandles.insertCoordinates(target, pos, values); 8036 } 8037 8038 /** 8039 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8040 * so that the new coordinates match the provided ones. 8041 * <p> 8042 * The given array controls the reordering. 8043 * Call {@code #I} the number of incoming coordinates (the value 8044 * {@code newCoordinates.size()}), and call {@code #O} the number 8045 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8046 * Then the length of the reordering array must be {@code #O}, 8047 * and each element must be a non-negative number less than {@code #I}. 8048 * For every {@code N} less than {@code #O}, the {@code N}-th 8049 * outgoing coordinate will be taken from the {@code I}-th incoming 8050 * coordinate, where {@code I} is {@code reorder[N]}. 8051 * <p> 8052 * No coordinate value conversions are applied. 8053 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8054 * must be identical to the type of the corresponding outgoing coordinate 8055 * in the target var handle. 8056 * <p> 8057 * The reordering array need not specify an actual permutation. 8058 * An incoming coordinate will be duplicated if its index appears 8059 * more than once in the array, and an incoming coordinate will be dropped 8060 * if its index does not appear in the array. 8061 * <p> 8062 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8063 * atomic access guarantees as those featured by the target var handle. 8064 * @param target the var handle to invoke after the coordinates have been reordered 8065 * @param newCoordinates the new coordinate types 8066 * @param reorder an index array which controls the reordering 8067 * @return an adapter var handle which re-arranges the incoming coordinate values, 8068 * before calling the target var handle 8069 * @throws IllegalArgumentException if the index array length is not equal to 8070 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8071 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8072 * the target var handle and in {@code newCoordinates} are not identical. 8073 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8074 * @since 22 8075 */ 8076 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8077 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8078 } 8079 8080 /** 8081 * Adapts a target var handle by pre-processing 8082 * a sub-sequence of its coordinate values with a filter (a method handle). 8083 * The pre-processed coordinates are replaced by the result (if any) of the 8084 * filter function and the target var handle is then called on the modified (usually shortened) 8085 * coordinate list. 8086 * <p> 8087 * If {@code R} is the return type of the filter, then: 8088 * <ul> 8089 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 8090 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 8091 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 8092 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 8093 * target var handle.</li> 8094 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 8095 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 8096 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 8097 * downstream invocation of the target var handle.</li> 8098 * </ul> 8099 * <p> 8100 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8101 * throw an {@link IllegalStateException}. 8102 * <p> 8103 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8104 * atomic access guarantees as those featured by the target var handle. 8105 * 8106 * @param target the var handle to invoke after the coordinates have been filtered 8107 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 8108 * @param filter the filter method handle 8109 * @return an adapter var handle which filters the incoming coordinate values, 8110 * before calling the target var handle 8111 * @throws IllegalArgumentException if the return type of {@code filter} 8112 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 8113 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8114 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8115 * or if it's determined that {@code filter} throws any checked exceptions. 8116 * @throws NullPointerException if any of the arguments is {@code null}. 8117 * @since 22 8118 */ 8119 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8120 return VarHandles.collectCoordinates(target, pos, filter); 8121 } 8122 8123 /** 8124 * Returns a var handle which will discard some dummy coordinates before delegating to the 8125 * target var handle. As a consequence, the resulting var handle will feature more 8126 * coordinate types than the target var handle. 8127 * <p> 8128 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8129 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8130 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8131 * <p> 8132 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8133 * atomic access guarantees as those featured by the target var handle. 8134 * 8135 * @param target the var handle to invoke after the dummy coordinates are dropped 8136 * @param pos position of the first coordinate to drop (zero for the leftmost) 8137 * @param valueTypes the type(s) of the coordinate(s) to drop 8138 * @return an adapter var handle which drops some dummy coordinates, 8139 * before calling the target var handle 8140 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8141 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8142 * @since 22 8143 */ 8144 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8145 return VarHandles.dropCoordinates(target, pos, valueTypes); 8146 } 8147 }