1 /* 2 * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.access.SharedSecrets; 29 import jdk.internal.misc.Unsafe; 30 import jdk.internal.misc.VM; 31 import jdk.internal.org.objectweb.asm.ClassReader; 32 import jdk.internal.org.objectweb.asm.Opcodes; 33 import jdk.internal.org.objectweb.asm.Type; 34 import jdk.internal.reflect.CallerSensitive; 35 import jdk.internal.reflect.CallerSensitiveAdapter; 36 import jdk.internal.reflect.Reflection; 37 import jdk.internal.util.ClassFileDumper; 38 import jdk.internal.vm.annotation.ForceInline; 39 import sun.invoke.util.ValueConversions; 40 import sun.invoke.util.VerifyAccess; 41 import sun.invoke.util.Wrapper; 42 import sun.reflect.misc.ReflectUtil; 43 import sun.security.util.SecurityConstants; 44 45 import java.lang.constant.ConstantDescs; 46 import java.lang.invoke.LambdaForm.BasicType; 47 import java.lang.reflect.Constructor; 48 import java.lang.reflect.Field; 49 import java.lang.reflect.Member; 50 import java.lang.reflect.Method; 51 import java.lang.reflect.Modifier; 52 import java.nio.ByteOrder; 53 import java.security.ProtectionDomain; 54 import java.util.ArrayList; 55 import java.util.Arrays; 56 import java.util.BitSet; 57 import java.util.Comparator; 58 import java.util.Iterator; 59 import java.util.List; 60 import java.util.Objects; 61 import java.util.Set; 62 import java.util.concurrent.ConcurrentHashMap; 63 import java.util.stream.Stream; 64 65 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 66 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 67 import static java.lang.invoke.MethodHandleNatives.Constants.*; 68 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 69 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 70 import static java.lang.invoke.MethodHandleStatics.newInternalError; 71 import static java.lang.invoke.MethodType.methodType; 72 73 /** 74 * This class consists exclusively of static methods that operate on or return 75 * method handles. They fall into several categories: 76 * <ul> 77 * <li>Lookup methods which help create method handles for methods and fields. 78 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 79 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 80 * </ul> 81 * A lookup, combinator, or factory method will fail and throw an 82 * {@code IllegalArgumentException} if the created method handle's type 83 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 84 * 85 * @author John Rose, JSR 292 EG 86 * @since 1.7 87 */ 88 public class MethodHandles { 89 90 private MethodHandles() { } // do not instantiate 91 92 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 93 94 // See IMPL_LOOKUP below. 95 96 //// Method handle creation from ordinary methods. 97 98 /** 99 * Returns a {@link Lookup lookup object} with 100 * full capabilities to emulate all supported bytecode behaviors of the caller. 101 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 102 * Factory methods on the lookup object can create 103 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 104 * for any member that the caller has access to via bytecodes, 105 * including protected and private fields and methods. 106 * This lookup object is created by the original lookup class 107 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 108 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 109 * Do not store it in place where untrusted code can access it. 110 * <p> 111 * This method is caller sensitive, which means that it may return different 112 * values to different callers. 113 * In cases where {@code MethodHandles.lookup} is called from a context where 114 * there is no caller frame on the stack (e.g. when called directly 115 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 116 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 117 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 118 * to obtain a low-privileged lookup instead. 119 * @return a lookup object for the caller of this method, with 120 * {@linkplain Lookup#ORIGINAL original} and 121 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 122 * @throws IllegalCallerException if there is no caller frame on the stack. 123 */ 124 @CallerSensitive 125 @ForceInline // to ensure Reflection.getCallerClass optimization 126 public static Lookup lookup() { 127 final Class<?> c = Reflection.getCallerClass(); 128 if (c == null) { 129 throw new IllegalCallerException("no caller frame"); 130 } 131 return new Lookup(c); 132 } 133 134 /** 135 * This lookup method is the alternate implementation of 136 * the lookup method with a leading caller class argument which is 137 * non-caller-sensitive. This method is only invoked by reflection 138 * and method handle. 139 */ 140 @CallerSensitiveAdapter 141 private static Lookup lookup(Class<?> caller) { 142 if (caller.getClassLoader() == null) { 143 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 144 } 145 return new Lookup(caller); 146 } 147 148 /** 149 * Returns a {@link Lookup lookup object} which is trusted minimally. 150 * The lookup has the {@code UNCONDITIONAL} mode. 151 * It can only be used to create method handles to public members of 152 * public classes in packages that are exported unconditionally. 153 * <p> 154 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 155 * of this lookup object will be {@link java.lang.Object}. 156 * 157 * @apiNote The use of Object is conventional, and because the lookup modes are 158 * limited, there is no special access provided to the internals of Object, its package 159 * or its module. This public lookup object or other lookup object with 160 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 161 * is not used to determine the lookup context. 162 * 163 * <p style="font-size:smaller;"> 164 * <em>Discussion:</em> 165 * The lookup class can be changed to any other class {@code C} using an expression of the form 166 * {@link Lookup#in publicLookup().in(C.class)}. 167 * A public lookup object is always subject to 168 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 169 * Also, it cannot access 170 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 171 * @return a lookup object which is trusted minimally 172 */ 173 public static Lookup publicLookup() { 174 return Lookup.PUBLIC_LOOKUP; 175 } 176 177 /** 178 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 179 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 180 * The returned lookup object can provide access to classes in modules and packages, 181 * and members of those classes, outside the normal rules of Java access control, 182 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 183 * <p> 184 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 185 * allowed to do deep reflection on module {@code M2} and package of the target class 186 * if and only if all of the following conditions are {@code true}: 187 * <ul> 188 * <li>If there is a security manager, its {@code checkPermission} method is 189 * called to check {@code ReflectPermission("suppressAccessChecks")} and 190 * that must return normally. 191 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 192 * full privilege access}. Specifically: 193 * <ul> 194 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 195 * (This is because otherwise there would be no way to ensure the original lookup 196 * creator was a member of any particular module, and so any subsequent checks 197 * for readability and qualified exports would become ineffective.) 198 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 199 * (This is because an application intending to share intra-module access 200 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 201 * deep reflection to its own module.) 202 * </ul> 203 * <li>The target class must be a proper class, not a primitive or array class. 204 * (Thus, {@code M2} is well-defined.) 205 * <li>If the caller module {@code M1} differs from 206 * the target module {@code M2} then both of the following must be true: 207 * <ul> 208 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 209 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 210 * containing the target class to at least {@code M1}.</li> 211 * </ul> 212 * </ul> 213 * <p> 214 * If any of the above checks is violated, this method fails with an 215 * exception. 216 * <p> 217 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 218 * returns a {@code Lookup} on {@code targetClass} with 219 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 220 * with {@code null} previous lookup class. 221 * <p> 222 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 223 * returns a {@code Lookup} on {@code targetClass} that records 224 * the lookup class of the caller as the new previous lookup class with 225 * {@code PRIVATE} access but no {@code MODULE} access. 226 * <p> 227 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 228 * 229 * @apiNote The {@code Lookup} object returned by this method is allowed to 230 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 231 * of {@code targetClass}. Extreme caution should be taken when opening a package 232 * to another module as such defined classes have the same full privilege 233 * access as other members in {@code targetClass}'s module. 234 * 235 * @param targetClass the target class 236 * @param caller the caller lookup object 237 * @return a lookup object for the target class, with private access 238 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 239 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 240 * @throws SecurityException if denied by the security manager 241 * @throws IllegalAccessException if any of the other access checks specified above fails 242 * @since 9 243 * @see Lookup#dropLookupMode 244 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 245 */ 246 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 247 if (caller.allowedModes == Lookup.TRUSTED) { 248 return new Lookup(targetClass); 249 } 250 251 @SuppressWarnings("removal") 252 SecurityManager sm = System.getSecurityManager(); 253 if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION); 254 if (targetClass.isPrimitive()) 255 throw new IllegalArgumentException(targetClass + " is a primitive class"); 256 if (targetClass.isArray()) 257 throw new IllegalArgumentException(targetClass + " is an array class"); 258 // Ensure that we can reason accurately about private and module access. 259 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 260 if ((caller.lookupModes() & requireAccess) != requireAccess) 261 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 262 263 // previous lookup class is never set if it has MODULE access 264 assert caller.previousLookupClass() == null; 265 266 Class<?> callerClass = caller.lookupClass(); 267 Module callerModule = callerClass.getModule(); // M1 268 Module targetModule = targetClass.getModule(); // M2 269 Class<?> newPreviousClass = null; 270 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 271 272 if (targetModule != callerModule) { 273 if (!callerModule.canRead(targetModule)) 274 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 275 if (targetModule.isNamed()) { 276 String pn = targetClass.getPackageName(); 277 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 278 if (!targetModule.isOpen(pn, callerModule)) 279 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 280 } 281 282 // M2 != M1, set previous lookup class to M1 and drop MODULE access 283 newPreviousClass = callerClass; 284 newModes &= ~Lookup.MODULE; 285 } 286 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 287 } 288 289 /** 290 * Returns the <em>class data</em> associated with the lookup class 291 * of the given {@code caller} lookup object, or {@code null}. 292 * 293 * <p> A hidden class with class data can be created by calling 294 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 295 * Lookup::defineHiddenClassWithClassData}. 296 * This method will cause the static class initializer of the lookup 297 * class of the given {@code caller} lookup object be executed if 298 * it has not been initialized. 299 * 300 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 301 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 302 * {@code null} is returned if this method is called on the lookup object 303 * on these classes. 304 * 305 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 306 * must have {@linkplain Lookup#ORIGINAL original access} 307 * in order to retrieve the class data. 308 * 309 * @apiNote 310 * This method can be called as a bootstrap method for a dynamically computed 311 * constant. A framework can create a hidden class with class data, for 312 * example that can be {@code Class} or {@code MethodHandle} object. 313 * The class data is accessible only to the lookup object 314 * created by the original caller but inaccessible to other members 315 * in the same nest. If a framework passes security sensitive objects 316 * to a hidden class via class data, it is recommended to load the value 317 * of class data as a dynamically computed constant instead of storing 318 * the class data in private static field(s) which are accessible to 319 * other nestmates. 320 * 321 * @param <T> the type to cast the class data object to 322 * @param caller the lookup context describing the class performing the 323 * operation (normally stacked by the JVM) 324 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 325 * ({@code "_"}) 326 * @param type the type of the class data 327 * @return the value of the class data if present in the lookup class; 328 * otherwise {@code null} 329 * @throws IllegalArgumentException if name is not {@code "_"} 330 * @throws IllegalAccessException if the lookup context does not have 331 * {@linkplain Lookup#ORIGINAL original} access 332 * @throws ClassCastException if the class data cannot be converted to 333 * the given {@code type} 334 * @throws NullPointerException if {@code caller} or {@code type} argument 335 * is {@code null} 336 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 337 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 338 * @since 16 339 * @jvms 5.5 Initialization 340 */ 341 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 342 Objects.requireNonNull(caller); 343 Objects.requireNonNull(type); 344 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 345 throw new IllegalArgumentException("name must be \"_\": " + name); 346 } 347 348 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 349 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 350 } 351 352 Object classdata = classData(caller.lookupClass()); 353 if (classdata == null) return null; 354 355 try { 356 return BootstrapMethodInvoker.widenAndCast(classdata, type); 357 } catch (RuntimeException|Error e) { 358 throw e; // let CCE and other runtime exceptions through 359 } catch (Throwable e) { 360 throw new InternalError(e); 361 } 362 } 363 364 /* 365 * Returns the class data set by the VM in the Class::classData field. 366 * 367 * This is also invoked by LambdaForms as it cannot use condy via 368 * MethodHandles::classData due to bootstrapping issue. 369 */ 370 static Object classData(Class<?> c) { 371 UNSAFE.ensureClassInitialized(c); 372 return SharedSecrets.getJavaLangAccess().classData(c); 373 } 374 375 /** 376 * Returns the element at the specified index in the 377 * {@linkplain #classData(Lookup, String, Class) class data}, 378 * if the class data associated with the lookup class 379 * of the given {@code caller} lookup object is a {@code List}. 380 * If the class data is not present in this lookup class, this method 381 * returns {@code null}. 382 * 383 * <p> A hidden class with class data can be created by calling 384 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 385 * Lookup::defineHiddenClassWithClassData}. 386 * This method will cause the static class initializer of the lookup 387 * class of the given {@code caller} lookup object be executed if 388 * it has not been initialized. 389 * 390 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 391 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 392 * {@code null} is returned if this method is called on the lookup object 393 * on these classes. 394 * 395 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 396 * must have {@linkplain Lookup#ORIGINAL original access} 397 * in order to retrieve the class data. 398 * 399 * @apiNote 400 * This method can be called as a bootstrap method for a dynamically computed 401 * constant. A framework can create a hidden class with class data, for 402 * example that can be {@code List.of(o1, o2, o3....)} containing more than 403 * one object and use this method to load one element at a specific index. 404 * The class data is accessible only to the lookup object 405 * created by the original caller but inaccessible to other members 406 * in the same nest. If a framework passes security sensitive objects 407 * to a hidden class via class data, it is recommended to load the value 408 * of class data as a dynamically computed constant instead of storing 409 * the class data in private static field(s) which are accessible to other 410 * nestmates. 411 * 412 * @param <T> the type to cast the result object to 413 * @param caller the lookup context describing the class performing the 414 * operation (normally stacked by the JVM) 415 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 416 * ({@code "_"}) 417 * @param type the type of the element at the given index in the class data 418 * @param index index of the element in the class data 419 * @return the element at the given index in the class data 420 * if the class data is present; otherwise {@code null} 421 * @throws IllegalArgumentException if name is not {@code "_"} 422 * @throws IllegalAccessException if the lookup context does not have 423 * {@linkplain Lookup#ORIGINAL original} access 424 * @throws ClassCastException if the class data cannot be converted to {@code List} 425 * or the element at the specified index cannot be converted to the given type 426 * @throws IndexOutOfBoundsException if the index is out of range 427 * @throws NullPointerException if {@code caller} or {@code type} argument is 428 * {@code null}; or if unboxing operation fails because 429 * the element at the given index is {@code null} 430 * 431 * @since 16 432 * @see #classData(Lookup, String, Class) 433 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 434 */ 435 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 436 throws IllegalAccessException 437 { 438 @SuppressWarnings("unchecked") 439 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 440 if (classdata == null) return null; 441 442 try { 443 Object element = classdata.get(index); 444 return BootstrapMethodInvoker.widenAndCast(element, type); 445 } catch (RuntimeException|Error e) { 446 throw e; // let specified exceptions and other runtime exceptions/errors through 447 } catch (Throwable e) { 448 throw new InternalError(e); 449 } 450 } 451 452 /** 453 * Performs an unchecked "crack" of a 454 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 455 * The result is as if the user had obtained a lookup object capable enough 456 * to crack the target method handle, called 457 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 458 * on the target to obtain its symbolic reference, and then called 459 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 460 * to resolve the symbolic reference to a member. 461 * <p> 462 * If there is a security manager, its {@code checkPermission} method 463 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 464 * @param <T> the desired type of the result, either {@link Member} or a subtype 465 * @param target a direct method handle to crack into symbolic reference components 466 * @param expected a class object representing the desired result type {@code T} 467 * @return a reference to the method, constructor, or field object 468 * @throws SecurityException if the caller is not privileged to call {@code setAccessible} 469 * @throws NullPointerException if either argument is {@code null} 470 * @throws IllegalArgumentException if the target is not a direct method handle 471 * @throws ClassCastException if the member is not of the expected type 472 * @since 1.8 473 */ 474 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 475 @SuppressWarnings("removal") 476 SecurityManager smgr = System.getSecurityManager(); 477 if (smgr != null) smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION); 478 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 479 return lookup.revealDirect(target).reflectAs(expected, lookup); 480 } 481 482 /** 483 * A <em>lookup object</em> is a factory for creating method handles, 484 * when the creation requires access checking. 485 * Method handles do not perform 486 * access checks when they are called, but rather when they are created. 487 * Therefore, method handle access 488 * restrictions must be enforced when a method handle is created. 489 * The caller class against which those restrictions are enforced 490 * is known as the {@linkplain #lookupClass() lookup class}. 491 * <p> 492 * A lookup class which needs to create method handles will call 493 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 494 * When the {@code Lookup} factory object is created, the identity of the lookup class is 495 * determined, and securely stored in the {@code Lookup} object. 496 * The lookup class (or its delegates) may then use factory methods 497 * on the {@code Lookup} object to create method handles for access-checked members. 498 * This includes all methods, constructors, and fields which are allowed to the lookup class, 499 * even private ones. 500 * 501 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 502 * The factory methods on a {@code Lookup} object correspond to all major 503 * use cases for methods, constructors, and fields. 504 * Each method handle created by a factory method is the functional 505 * equivalent of a particular <em>bytecode behavior</em>. 506 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 507 * the Java Virtual Machine Specification.) 508 * Here is a summary of the correspondence between these factory methods and 509 * the behavior of the resulting method handles: 510 * <table class="striped"> 511 * <caption style="display:none">lookup method behaviors</caption> 512 * <thead> 513 * <tr> 514 * <th scope="col"><a id="equiv"></a>lookup expression</th> 515 * <th scope="col">member</th> 516 * <th scope="col">bytecode behavior</th> 517 * </tr> 518 * </thead> 519 * <tbody> 520 * <tr> 521 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 522 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 523 * </tr> 524 * <tr> 525 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 526 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 527 * </tr> 528 * <tr> 529 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 530 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 531 * </tr> 532 * <tr> 533 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 534 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 535 * </tr> 536 * <tr> 537 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 538 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 539 * </tr> 540 * <tr> 541 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 542 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 543 * </tr> 544 * <tr> 545 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 546 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 547 * </tr> 548 * <tr> 549 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 550 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 551 * </tr> 552 * <tr> 553 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 554 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 555 * </tr> 556 * <tr> 557 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 558 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 559 * </tr> 560 * <tr> 561 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 562 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 563 * </tr> 564 * <tr> 565 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 566 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 567 * </tr> 568 * <tr> 569 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 570 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 571 * </tr> 572 * <tr> 573 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 574 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 575 * </tr> 576 * </tbody> 577 * </table> 578 * 579 * Here, the type {@code C} is the class or interface being searched for a member, 580 * documented as a parameter named {@code refc} in the lookup methods. 581 * The method type {@code MT} is composed from the return type {@code T} 582 * and the sequence of argument types {@code A*}. 583 * The constructor also has a sequence of argument types {@code A*} and 584 * is deemed to return the newly-created object of type {@code C}. 585 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 586 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 587 * if it is present, it is always the leading argument to the method handle invocation. 588 * (In the case of some {@code protected} members, {@code this} may be 589 * restricted in type to the lookup class; see below.) 590 * The name {@code arg} stands for all the other method handle arguments. 591 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 592 * stands for a null reference if the accessed method or field is static, 593 * and {@code this} otherwise. 594 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 595 * for reflective objects corresponding to the given members declared in type {@code C}. 596 * <p> 597 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 598 * as if by {@code ldc CONSTANT_Class}. 599 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 600 * <p> 601 * In cases where the given member is of variable arity (i.e., a method or constructor) 602 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 603 * In all other cases, the returned method handle will be of fixed arity. 604 * <p style="font-size:smaller;"> 605 * <em>Discussion:</em> 606 * The equivalence between looked-up method handles and underlying 607 * class members and bytecode behaviors 608 * can break down in a few ways: 609 * <ul style="font-size:smaller;"> 610 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 611 * the lookup can still succeed, even when there is no equivalent 612 * Java expression or bytecoded constant. 613 * <li>Likewise, if {@code T} or {@code MT} 614 * is not symbolically accessible from the lookup class's loader, 615 * the lookup can still succeed. 616 * For example, lookups for {@code MethodHandle.invokeExact} and 617 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 618 * <li>If there is a security manager installed, it can forbid the lookup 619 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 620 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 621 * constant is not subject to security manager checks. 622 * <li>If the looked-up method has a 623 * <a href="MethodHandle.html#maxarity">very large arity</a>, 624 * the method handle creation may fail with an 625 * {@code IllegalArgumentException}, due to the method handle type having 626 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 627 * </ul> 628 * 629 * <h2><a id="access"></a>Access checking</h2> 630 * Access checks are applied in the factory methods of {@code Lookup}, 631 * when a method handle is created. 632 * This is a key difference from the Core Reflection API, since 633 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 634 * performs access checking against every caller, on every call. 635 * <p> 636 * All access checks start from a {@code Lookup} object, which 637 * compares its recorded lookup class against all requests to 638 * create method handles. 639 * A single {@code Lookup} object can be used to create any number 640 * of access-checked method handles, all checked against a single 641 * lookup class. 642 * <p> 643 * A {@code Lookup} object can be shared with other trusted code, 644 * such as a metaobject protocol. 645 * A shared {@code Lookup} object delegates the capability 646 * to create method handles on private members of the lookup class. 647 * Even if privileged code uses the {@code Lookup} object, 648 * the access checking is confined to the privileges of the 649 * original lookup class. 650 * <p> 651 * A lookup can fail, because 652 * the containing class is not accessible to the lookup class, or 653 * because the desired class member is missing, or because the 654 * desired class member is not accessible to the lookup class, or 655 * because the lookup object is not trusted enough to access the member. 656 * In the case of a field setter function on a {@code final} field, 657 * finality enforcement is treated as a kind of access control, 658 * and the lookup will fail, except in special cases of 659 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 660 * In any of these cases, a {@code ReflectiveOperationException} will be 661 * thrown from the attempted lookup. The exact class will be one of 662 * the following: 663 * <ul> 664 * <li>NoSuchMethodException — if a method is requested but does not exist 665 * <li>NoSuchFieldException — if a field is requested but does not exist 666 * <li>IllegalAccessException — if the member exists but an access check fails 667 * </ul> 668 * <p> 669 * In general, the conditions under which a method handle may be 670 * looked up for a method {@code M} are no more restrictive than the conditions 671 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 672 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 673 * a method handle lookup will generally raise a corresponding 674 * checked exception, such as {@code NoSuchMethodException}. 675 * And the effect of invoking the method handle resulting from the lookup 676 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 677 * to executing the compiled, verified, and resolved call to {@code M}. 678 * The same point is true of fields and constructors. 679 * <p style="font-size:smaller;"> 680 * <em>Discussion:</em> 681 * Access checks only apply to named and reflected methods, 682 * constructors, and fields. 683 * Other method handle creation methods, such as 684 * {@link MethodHandle#asType MethodHandle.asType}, 685 * do not require any access checks, and are used 686 * independently of any {@code Lookup} object. 687 * <p> 688 * If the desired member is {@code protected}, the usual JVM rules apply, 689 * including the requirement that the lookup class must either be in the 690 * same package as the desired member, or must inherit that member. 691 * (See the Java Virtual Machine Specification, sections {@jvms 692 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 693 * In addition, if the desired member is a non-static field or method 694 * in a different package, the resulting method handle may only be applied 695 * to objects of the lookup class or one of its subclasses. 696 * This requirement is enforced by narrowing the type of the leading 697 * {@code this} parameter from {@code C} 698 * (which will necessarily be a superclass of the lookup class) 699 * to the lookup class itself. 700 * <p> 701 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 702 * that the receiver argument must match both the resolved method <em>and</em> 703 * the current class. Again, this requirement is enforced by narrowing the 704 * type of the leading parameter to the resulting method handle. 705 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 706 * <p> 707 * The JVM represents constructors and static initializer blocks as internal methods 708 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 709 * ConstantDescs#CLASS_INIT_NAME}). 710 * The internal syntax of invocation instructions allows them to refer to such internal 711 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 712 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 713 * <p> 714 * If the relationship between nested types is expressed directly through the 715 * {@code NestHost} and {@code NestMembers} attributes 716 * (see the Java Virtual Machine Specification, sections {@jvms 717 * 4.7.28} and {@jvms 4.7.29}), 718 * then the associated {@code Lookup} object provides direct access to 719 * the lookup class and all of its nestmates 720 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 721 * Otherwise, access between nested classes is obtained by the Java compiler creating 722 * a wrapper method to access a private method of another class in the same nest. 723 * For example, a nested class {@code C.D} 724 * can access private members within other related classes such as 725 * {@code C}, {@code C.D.E}, or {@code C.B}, 726 * but the Java compiler may need to generate wrapper methods in 727 * those related classes. In such cases, a {@code Lookup} object on 728 * {@code C.E} would be unable to access those private members. 729 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 730 * which can transform a lookup on {@code C.E} into one on any of those other 731 * classes, without special elevation of privilege. 732 * <p> 733 * The accesses permitted to a given lookup object may be limited, 734 * according to its set of {@link #lookupModes lookupModes}, 735 * to a subset of members normally accessible to the lookup class. 736 * For example, the {@link MethodHandles#publicLookup publicLookup} 737 * method produces a lookup object which is only allowed to access 738 * public members in public classes of exported packages. 739 * The caller sensitive method {@link MethodHandles#lookup lookup} 740 * produces a lookup object with full capabilities relative to 741 * its caller class, to emulate all supported bytecode behaviors. 742 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 743 * with fewer access modes than the original lookup object. 744 * 745 * <p style="font-size:smaller;"> 746 * <a id="privacc"></a> 747 * <em>Discussion of private and module access:</em> 748 * We say that a lookup has <em>private access</em> 749 * if its {@linkplain #lookupModes lookup modes} 750 * include the possibility of accessing {@code private} members 751 * (which includes the private members of nestmates). 752 * As documented in the relevant methods elsewhere, 753 * only lookups with private access possess the following capabilities: 754 * <ul style="font-size:smaller;"> 755 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 756 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 757 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 758 * for classes accessible to the lookup class 759 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 760 * within the same package member 761 * </ul> 762 * <p style="font-size:smaller;"> 763 * Similarly, a lookup with module access ensures that the original lookup creator was 764 * a member in the same module as the lookup class. 765 * <p style="font-size:smaller;"> 766 * Private and module access are independently determined modes; a lookup may have 767 * either or both or neither. A lookup which possesses both access modes is said to 768 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 769 * <p style="font-size:smaller;"> 770 * A lookup with <em>original access</em> ensures that this lookup is created by 771 * the original lookup class and the bootstrap method invoked by the VM. 772 * Such a lookup with original access also has private and module access 773 * which has the following additional capability: 774 * <ul style="font-size:smaller;"> 775 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 776 * such as {@code Class.forName} 777 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 778 * class data} associated with the lookup class</li> 779 * </ul> 780 * <p style="font-size:smaller;"> 781 * Each of these permissions is a consequence of the fact that a lookup object 782 * with private access can be securely traced back to an originating class, 783 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 784 * can be reliably determined and emulated by method handles. 785 * 786 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 787 * When a lookup class in one module {@code M1} accesses a class in another module 788 * {@code M2}, extra access checking is performed beyond the access mode bits. 789 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 790 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 791 * and when the type is in a package of {@code M2} that is exported to 792 * at least {@code M1}. 793 * <p> 794 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 795 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 796 * MethodHandles.privateLookupIn} methods. 797 * Teleporting across modules will always record the original lookup class as 798 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 799 * and drops {@link Lookup#MODULE MODULE} access. 800 * If the target class is in the same module as the lookup class {@code C}, 801 * then the target class becomes the new lookup class 802 * and there is no change to the previous lookup class. 803 * If the target class is in a different module from {@code M1} ({@code C}'s module), 804 * {@code C} becomes the new previous lookup class 805 * and the target class becomes the new lookup class. 806 * In that case, if there was already a previous lookup class in {@code M0}, 807 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 808 * drops all privileges. 809 * For example, 810 * {@snippet lang="java" : 811 * Lookup lookup = MethodHandles.lookup(); // in class C 812 * Lookup lookup2 = lookup.in(D.class); 813 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 814 * } 815 * <p> 816 * The {@link #lookup()} factory method produces a {@code Lookup} object 817 * with {@code null} previous lookup class. 818 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 819 * to class {@code D} without elevation of privileges. 820 * If {@code C} and {@code D} are in the same module, 821 * {@code lookup2} records {@code D} as the new lookup class and keeps the 822 * same previous lookup class as the original {@code lookup}, or 823 * {@code null} if not present. 824 * <p> 825 * When a {@code Lookup} teleports from a class 826 * in one nest to another nest, {@code PRIVATE} access is dropped. 827 * When a {@code Lookup} teleports from a class in one package to 828 * another package, {@code PACKAGE} access is dropped. 829 * When a {@code Lookup} teleports from a class in one module to another module, 830 * {@code MODULE} access is dropped. 831 * Teleporting across modules drops the ability to access non-exported classes 832 * in both the module of the new lookup class and the module of the old lookup class 833 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 834 * A {@code Lookup} can teleport back and forth to a class in the module of 835 * the lookup class and the module of the previous class lookup. 836 * Teleporting across modules can only decrease access but cannot increase it. 837 * Teleporting to some third module drops all accesses. 838 * <p> 839 * In the above example, if {@code C} and {@code D} are in different modules, 840 * {@code lookup2} records {@code D} as its lookup class and 841 * {@code C} as its previous lookup class and {@code lookup2} has only 842 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 843 * {@code C}'s module and {@code D}'s module. 844 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 845 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 846 * class {@code D} is recorded as its previous lookup class. 847 * <p> 848 * Teleporting across modules restricts access to the public types that 849 * both the lookup class and the previous lookup class can equally access 850 * (see below). 851 * <p> 852 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 853 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 854 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 855 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 856 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 857 * to call {@code privateLookupIn}. 858 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 859 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 860 * produces a new {@code Lookup} on {@code T} with full capabilities. 861 * A {@code lookup} on {@code C} is also allowed 862 * to do deep reflection on {@code T} in another module {@code M2} if 863 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 864 * the package containing {@code T} to at least {@code M1}. 865 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 866 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 867 * The resulting {@code Lookup} can be used to do member lookup or teleport 868 * to another lookup class by calling {@link #in Lookup::in}. But 869 * it cannot be used to obtain another private {@code Lookup} by calling 870 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 871 * because it has no {@code MODULE} access. 872 * <p> 873 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 874 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 875 * of {@code T}. Extreme caution should be taken when opening a package 876 * to another module as such defined classes have the same full privilege 877 * access as other members in {@code M2}. 878 * 879 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 880 * 881 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 882 * allows cross-module access. The access checking is performed with respect 883 * to both the lookup class and the previous lookup class if present. 884 * <p> 885 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 886 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 887 * exported unconditionally}. 888 * <p> 889 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 890 * the lookup with {@link #PUBLIC} mode can access all public types in modules 891 * that are readable to {@code M1} and the type is in a package that is exported 892 * at least to {@code M1}. 893 * <p> 894 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 895 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 896 * the intersection of all public types that are accessible to {@code M1} 897 * with all public types that are accessible to {@code M0}. {@code M0} 898 * reads {@code M1} and hence the set of accessible types includes: 899 * 900 * <ul> 901 * <li>unconditional-exported packages from {@code M1}</li> 902 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 903 * <li> 904 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 905 * and {@code M1} read {@code M2} 906 * </li> 907 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 908 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 909 * <li> 910 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 911 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 912 * </li> 913 * </ul> 914 * 915 * <h2><a id="access-modes"></a>Access modes</h2> 916 * 917 * The table below shows the access modes of a {@code Lookup} produced by 918 * any of the following factory or transformation methods: 919 * <ul> 920 * <li>{@link #lookup() MethodHandles::lookup}</li> 921 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 922 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 923 * <li>{@link Lookup#in Lookup::in}</li> 924 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 925 * </ul> 926 * 927 * <table class="striped"> 928 * <caption style="display:none"> 929 * Access mode summary 930 * </caption> 931 * <thead> 932 * <tr> 933 * <th scope="col">Lookup object</th> 934 * <th style="text-align:center">original</th> 935 * <th style="text-align:center">protected</th> 936 * <th style="text-align:center">private</th> 937 * <th style="text-align:center">package</th> 938 * <th style="text-align:center">module</th> 939 * <th style="text-align:center">public</th> 940 * </tr> 941 * </thead> 942 * <tbody> 943 * <tr> 944 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 945 * <td style="text-align:center">ORI</td> 946 * <td style="text-align:center">PRO</td> 947 * <td style="text-align:center">PRI</td> 948 * <td style="text-align:center">PAC</td> 949 * <td style="text-align:center">MOD</td> 950 * <td style="text-align:center">1R</td> 951 * </tr> 952 * <tr> 953 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 954 * <td></td> 955 * <td></td> 956 * <td></td> 957 * <td style="text-align:center">PAC</td> 958 * <td style="text-align:center">MOD</td> 959 * <td style="text-align:center">1R</td> 960 * </tr> 961 * <tr> 962 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 963 * <td></td> 964 * <td></td> 965 * <td></td> 966 * <td></td> 967 * <td style="text-align:center">MOD</td> 968 * <td style="text-align:center">1R</td> 969 * </tr> 970 * <tr> 971 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 972 * <td></td> 973 * <td></td> 974 * <td></td> 975 * <td></td> 976 * <td></td> 977 * <td style="text-align:center">2R</td> 978 * </tr> 979 * <tr> 980 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 981 * <td></td> 982 * <td></td> 983 * <td></td> 984 * <td></td> 985 * <td></td> 986 * <td style="text-align:center">2R</td> 987 * </tr> 988 * <tr> 989 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 990 * <td></td> 991 * <td style="text-align:center">PRO</td> 992 * <td style="text-align:center">PRI</td> 993 * <td style="text-align:center">PAC</td> 994 * <td style="text-align:center">MOD</td> 995 * <td style="text-align:center">1R</td> 996 * </tr> 997 * <tr> 998 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 999 * <td></td> 1000 * <td style="text-align:center">PRO</td> 1001 * <td style="text-align:center">PRI</td> 1002 * <td style="text-align:center">PAC</td> 1003 * <td style="text-align:center">MOD</td> 1004 * <td style="text-align:center">1R</td> 1005 * </tr> 1006 * <tr> 1007 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1008 * <td></td> 1009 * <td></td> 1010 * <td></td> 1011 * <td style="text-align:center">PAC</td> 1012 * <td style="text-align:center">MOD</td> 1013 * <td style="text-align:center">1R</td> 1014 * </tr> 1015 * <tr> 1016 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1017 * <td></td> 1018 * <td></td> 1019 * <td></td> 1020 * <td></td> 1021 * <td style="text-align:center">MOD</td> 1022 * <td style="text-align:center">1R</td> 1023 * </tr> 1024 * <tr> 1025 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1026 * <td></td> 1027 * <td></td> 1028 * <td></td> 1029 * <td></td> 1030 * <td></td> 1031 * <td style="text-align:center">2R</td> 1032 * </tr> 1033 * <tr> 1034 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1035 * <td></td> 1036 * <td></td> 1037 * <td style="text-align:center">PRI</td> 1038 * <td style="text-align:center">PAC</td> 1039 * <td style="text-align:center">MOD</td> 1040 * <td style="text-align:center">1R</td> 1041 * </tr> 1042 * <tr> 1043 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1044 * <td></td> 1045 * <td></td> 1046 * <td></td> 1047 * <td style="text-align:center">PAC</td> 1048 * <td style="text-align:center">MOD</td> 1049 * <td style="text-align:center">1R</td> 1050 * </tr> 1051 * <tr> 1052 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1053 * <td></td> 1054 * <td></td> 1055 * <td></td> 1056 * <td></td> 1057 * <td style="text-align:center">MOD</td> 1058 * <td style="text-align:center">1R</td> 1059 * </tr> 1060 * <tr> 1061 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1062 * <td></td> 1063 * <td></td> 1064 * <td></td> 1065 * <td></td> 1066 * <td></td> 1067 * <td style="text-align:center">1R</td> 1068 * </tr> 1069 * <tr> 1070 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1071 * <td></td> 1072 * <td></td> 1073 * <td></td> 1074 * <td></td> 1075 * <td></td> 1076 * <td style="text-align:center">none</td> 1077 * <tr> 1078 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1079 * <td></td> 1080 * <td style="text-align:center">PRO</td> 1081 * <td style="text-align:center">PRI</td> 1082 * <td style="text-align:center">PAC</td> 1083 * <td></td> 1084 * <td style="text-align:center">2R</td> 1085 * </tr> 1086 * <tr> 1087 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1088 * <td></td> 1089 * <td style="text-align:center">PRO</td> 1090 * <td style="text-align:center">PRI</td> 1091 * <td style="text-align:center">PAC</td> 1092 * <td></td> 1093 * <td style="text-align:center">2R</td> 1094 * </tr> 1095 * <tr> 1096 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1097 * <td></td> 1098 * <td></td> 1099 * <td></td> 1100 * <td></td> 1101 * <td></td> 1102 * <td style="text-align:center">IAE</td> 1103 * </tr> 1104 * <tr> 1105 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1106 * <td></td> 1107 * <td></td> 1108 * <td></td> 1109 * <td style="text-align:center">PAC</td> 1110 * <td></td> 1111 * <td style="text-align:center">2R</td> 1112 * </tr> 1113 * <tr> 1114 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1115 * <td></td> 1116 * <td></td> 1117 * <td></td> 1118 * <td></td> 1119 * <td></td> 1120 * <td style="text-align:center">2R</td> 1121 * </tr> 1122 * <tr> 1123 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1124 * <td></td> 1125 * <td></td> 1126 * <td></td> 1127 * <td></td> 1128 * <td></td> 1129 * <td style="text-align:center">2R</td> 1130 * </tr> 1131 * <tr> 1132 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1133 * <td></td> 1134 * <td></td> 1135 * <td></td> 1136 * <td></td> 1137 * <td></td> 1138 * <td style="text-align:center">none</td> 1139 * </tr> 1140 * <tr> 1141 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1142 * <td></td> 1143 * <td></td> 1144 * <td style="text-align:center">PRI</td> 1145 * <td style="text-align:center">PAC</td> 1146 * <td></td> 1147 * <td style="text-align:center">2R</td> 1148 * </tr> 1149 * <tr> 1150 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1151 * <td></td> 1152 * <td></td> 1153 * <td></td> 1154 * <td style="text-align:center">PAC</td> 1155 * <td></td> 1156 * <td style="text-align:center">2R</td> 1157 * </tr> 1158 * <tr> 1159 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1160 * <td></td> 1161 * <td></td> 1162 * <td></td> 1163 * <td></td> 1164 * <td></td> 1165 * <td style="text-align:center">2R</td> 1166 * </tr> 1167 * <tr> 1168 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1169 * <td></td> 1170 * <td></td> 1171 * <td></td> 1172 * <td></td> 1173 * <td></td> 1174 * <td style="text-align:center">2R</td> 1175 * </tr> 1176 * <tr> 1177 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1178 * <td></td> 1179 * <td></td> 1180 * <td></td> 1181 * <td></td> 1182 * <td></td> 1183 * <td style="text-align:center">none</td> 1184 * </tr> 1185 * <tr> 1186 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1187 * <td></td> 1188 * <td></td> 1189 * <td style="text-align:center">PRI</td> 1190 * <td style="text-align:center">PAC</td> 1191 * <td style="text-align:center">MOD</td> 1192 * <td style="text-align:center">1R</td> 1193 * </tr> 1194 * <tr> 1195 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1196 * <td></td> 1197 * <td></td> 1198 * <td></td> 1199 * <td style="text-align:center">PAC</td> 1200 * <td style="text-align:center">MOD</td> 1201 * <td style="text-align:center">1R</td> 1202 * </tr> 1203 * <tr> 1204 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1205 * <td></td> 1206 * <td></td> 1207 * <td></td> 1208 * <td></td> 1209 * <td style="text-align:center">MOD</td> 1210 * <td style="text-align:center">1R</td> 1211 * </tr> 1212 * <tr> 1213 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1214 * <td></td> 1215 * <td></td> 1216 * <td></td> 1217 * <td></td> 1218 * <td></td> 1219 * <td style="text-align:center">1R</td> 1220 * </tr> 1221 * <tr> 1222 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1223 * <td></td> 1224 * <td></td> 1225 * <td></td> 1226 * <td></td> 1227 * <td></td> 1228 * <td style="text-align:center">none</td> 1229 * </tr> 1230 * <tr> 1231 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1232 * <td></td> 1233 * <td></td> 1234 * <td></td> 1235 * <td></td> 1236 * <td></td> 1237 * <td style="text-align:center">U</td> 1238 * </tr> 1239 * <tr> 1240 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1241 * <td></td> 1242 * <td></td> 1243 * <td></td> 1244 * <td></td> 1245 * <td></td> 1246 * <td style="text-align:center">U</td> 1247 * </tr> 1248 * <tr> 1249 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1250 * <td></td> 1251 * <td></td> 1252 * <td></td> 1253 * <td></td> 1254 * <td></td> 1255 * <td style="text-align:center">U</td> 1256 * </tr> 1257 * <tr> 1258 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1259 * <td></td> 1260 * <td></td> 1261 * <td></td> 1262 * <td></td> 1263 * <td></td> 1264 * <td style="text-align:center">none</td> 1265 * </tr> 1266 * <tr> 1267 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1268 * <td></td> 1269 * <td></td> 1270 * <td></td> 1271 * <td></td> 1272 * <td></td> 1273 * <td style="text-align:center">IAE</td> 1274 * </tr> 1275 * <tr> 1276 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1277 * <td></td> 1278 * <td></td> 1279 * <td></td> 1280 * <td></td> 1281 * <td></td> 1282 * <td style="text-align:center">none</td> 1283 * </tr> 1284 * </tbody> 1285 * </table> 1286 * 1287 * <p> 1288 * Notes: 1289 * <ul> 1290 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1291 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1292 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1293 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1294 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1295 * {@code PRO} indicates {@link #PROTECTED} bit set, 1296 * {@code PRI} indicates {@link #PRIVATE} bit set, 1297 * {@code PAC} indicates {@link #PACKAGE} bit set, 1298 * {@code MOD} indicates {@link #MODULE} bit set, 1299 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1300 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1301 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1302 * <li>Public access comes in three kinds: 1303 * <ul> 1304 * <li>unconditional ({@code U}): the lookup assumes readability. 1305 * The lookup has {@code null} previous lookup class. 1306 * <li>one-module-reads ({@code 1R}): the module access checking is 1307 * performed with respect to the lookup class. The lookup has {@code null} 1308 * previous lookup class. 1309 * <li>two-module-reads ({@code 2R}): the module access checking is 1310 * performed with respect to the lookup class and the previous lookup class. 1311 * The lookup has a non-null previous lookup class which is in a 1312 * different module from the current lookup class. 1313 * </ul> 1314 * <li>Any attempt to reach a third module loses all access.</li> 1315 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1316 * all access modes are dropped.</li> 1317 * </ul> 1318 * 1319 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1320 * Although bytecode instructions can only refer to classes in 1321 * a related class loader, this API can search for methods in any 1322 * class, as long as a reference to its {@code Class} object is 1323 * available. Such cross-loader references are also possible with the 1324 * Core Reflection API, and are impossible to bytecode instructions 1325 * such as {@code invokestatic} or {@code getfield}. 1326 * There is a {@linkplain java.lang.SecurityManager security manager API} 1327 * to allow applications to check such cross-loader references. 1328 * These checks apply to both the {@code MethodHandles.Lookup} API 1329 * and the Core Reflection API 1330 * (as found on {@link java.lang.Class Class}). 1331 * <p> 1332 * If a security manager is present, member and class lookups are subject to 1333 * additional checks. 1334 * From one to three calls are made to the security manager. 1335 * Any of these calls can refuse access by throwing a 1336 * {@link java.lang.SecurityException SecurityException}. 1337 * Define {@code smgr} as the security manager, 1338 * {@code lookc} as the lookup class of the current lookup object, 1339 * {@code refc} as the containing class in which the member 1340 * is being sought, and {@code defc} as the class in which the 1341 * member is actually defined. 1342 * (If a class or other type is being accessed, 1343 * the {@code refc} and {@code defc} values are the class itself.) 1344 * The value {@code lookc} is defined as <em>not present</em> 1345 * if the current lookup object does not have 1346 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1347 * The calls are made according to the following rules: 1348 * <ul> 1349 * <li><b>Step 1:</b> 1350 * If {@code lookc} is not present, or if its class loader is not 1351 * the same as or an ancestor of the class loader of {@code refc}, 1352 * then {@link SecurityManager#checkPackageAccess 1353 * smgr.checkPackageAccess(refcPkg)} is called, 1354 * where {@code refcPkg} is the package of {@code refc}. 1355 * <li><b>Step 2a:</b> 1356 * If the retrieved member is not public and 1357 * {@code lookc} is not present, then 1358 * {@link SecurityManager#checkPermission smgr.checkPermission} 1359 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1360 * <li><b>Step 2b:</b> 1361 * If the retrieved class has a {@code null} class loader, 1362 * and {@code lookc} is not present, then 1363 * {@link SecurityManager#checkPermission smgr.checkPermission} 1364 * with {@code RuntimePermission("getClassLoader")} is called. 1365 * <li><b>Step 3:</b> 1366 * If the retrieved member is not public, 1367 * and if {@code lookc} is not present, 1368 * and if {@code defc} and {@code refc} are different, 1369 * then {@link SecurityManager#checkPackageAccess 1370 * smgr.checkPackageAccess(defcPkg)} is called, 1371 * where {@code defcPkg} is the package of {@code defc}. 1372 * </ul> 1373 * Security checks are performed after other access checks have passed. 1374 * Therefore, the above rules presuppose a member or class that is public, 1375 * or else that is being accessed from a lookup class that has 1376 * rights to access the member or class. 1377 * <p> 1378 * If a security manager is present and the current lookup object does not have 1379 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1380 * {@link #defineClass(byte[]) defineClass}, 1381 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1382 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1383 * defineHiddenClassWithClassData} 1384 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1385 * with {@code RuntimePermission("defineClass")}. 1386 * 1387 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1388 * A small number of Java methods have a special property called caller sensitivity. 1389 * A <em>caller-sensitive</em> method can behave differently depending on the 1390 * identity of its immediate caller. 1391 * <p> 1392 * If a method handle for a caller-sensitive method is requested, 1393 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1394 * but they take account of the lookup class in a special way. 1395 * The resulting method handle behaves as if it were called 1396 * from an instruction contained in the lookup class, 1397 * so that the caller-sensitive method detects the lookup class. 1398 * (By contrast, the invoker of the method handle is disregarded.) 1399 * Thus, in the case of caller-sensitive methods, 1400 * different lookup classes may give rise to 1401 * differently behaving method handles. 1402 * <p> 1403 * In cases where the lookup object is 1404 * {@link MethodHandles#publicLookup() publicLookup()}, 1405 * or some other lookup object without the 1406 * {@linkplain #ORIGINAL original access}, 1407 * the lookup class is disregarded. 1408 * In such cases, no caller-sensitive method handle can be created, 1409 * access is forbidden, and the lookup fails with an 1410 * {@code IllegalAccessException}. 1411 * <p style="font-size:smaller;"> 1412 * <em>Discussion:</em> 1413 * For example, the caller-sensitive method 1414 * {@link java.lang.Class#forName(String) Class.forName(x)} 1415 * can return varying classes or throw varying exceptions, 1416 * depending on the class loader of the class that calls it. 1417 * A public lookup of {@code Class.forName} will fail, because 1418 * there is no reasonable way to determine its bytecode behavior. 1419 * <p style="font-size:smaller;"> 1420 * If an application caches method handles for broad sharing, 1421 * it should use {@code publicLookup()} to create them. 1422 * If there is a lookup of {@code Class.forName}, it will fail, 1423 * and the application must take appropriate action in that case. 1424 * It may be that a later lookup, perhaps during the invocation of a 1425 * bootstrap method, can incorporate the specific identity 1426 * of the caller, making the method accessible. 1427 * <p style="font-size:smaller;"> 1428 * The function {@code MethodHandles.lookup} is caller sensitive 1429 * so that there can be a secure foundation for lookups. 1430 * Nearly all other methods in the JSR 292 API rely on lookup 1431 * objects to check access requests. 1432 */ 1433 public static final 1434 class Lookup { 1435 /** The class on behalf of whom the lookup is being performed. */ 1436 private final Class<?> lookupClass; 1437 1438 /** previous lookup class */ 1439 private final Class<?> prevLookupClass; 1440 1441 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1442 private final int allowedModes; 1443 1444 static { 1445 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1446 } 1447 1448 /** A single-bit mask representing {@code public} access, 1449 * which may contribute to the result of {@link #lookupModes lookupModes}. 1450 * The value, {@code 0x01}, happens to be the same as the value of the 1451 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1452 * <p> 1453 * A {@code Lookup} with this lookup mode performs cross-module access check 1454 * with respect to the {@linkplain #lookupClass() lookup class} and 1455 * {@linkplain #previousLookupClass() previous lookup class} if present. 1456 */ 1457 public static final int PUBLIC = Modifier.PUBLIC; 1458 1459 /** A single-bit mask representing {@code private} access, 1460 * which may contribute to the result of {@link #lookupModes lookupModes}. 1461 * The value, {@code 0x02}, happens to be the same as the value of the 1462 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1463 */ 1464 public static final int PRIVATE = Modifier.PRIVATE; 1465 1466 /** A single-bit mask representing {@code protected} access, 1467 * which may contribute to the result of {@link #lookupModes lookupModes}. 1468 * The value, {@code 0x04}, happens to be the same as the value of the 1469 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1470 */ 1471 public static final int PROTECTED = Modifier.PROTECTED; 1472 1473 /** A single-bit mask representing {@code package} access (default access), 1474 * which may contribute to the result of {@link #lookupModes lookupModes}. 1475 * The value is {@code 0x08}, which does not correspond meaningfully to 1476 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1477 */ 1478 public static final int PACKAGE = Modifier.STATIC; 1479 1480 /** A single-bit mask representing {@code module} access, 1481 * which may contribute to the result of {@link #lookupModes lookupModes}. 1482 * The value is {@code 0x10}, which does not correspond meaningfully to 1483 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1484 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1485 * with this lookup mode can access all public types in the module of the 1486 * lookup class and public types in packages exported by other modules 1487 * to the module of the lookup class. 1488 * <p> 1489 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1490 * previous lookup class} is always {@code null}. 1491 * 1492 * @since 9 1493 */ 1494 public static final int MODULE = PACKAGE << 1; 1495 1496 /** A single-bit mask representing {@code unconditional} access 1497 * which may contribute to the result of {@link #lookupModes lookupModes}. 1498 * The value is {@code 0x20}, which does not correspond meaningfully to 1499 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1500 * A {@code Lookup} with this lookup mode assumes {@linkplain 1501 * java.lang.Module#canRead(java.lang.Module) readability}. 1502 * This lookup mode can access all public members of public types 1503 * of all modules when the type is in a package that is {@link 1504 * java.lang.Module#isExported(String) exported unconditionally}. 1505 * 1506 * <p> 1507 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1508 * previous lookup class} is always {@code null}. 1509 * 1510 * @since 9 1511 * @see #publicLookup() 1512 */ 1513 public static final int UNCONDITIONAL = PACKAGE << 2; 1514 1515 /** A single-bit mask representing {@code original} access 1516 * which may contribute to the result of {@link #lookupModes lookupModes}. 1517 * The value is {@code 0x40}, which does not correspond meaningfully to 1518 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1519 * 1520 * <p> 1521 * If this lookup mode is set, the {@code Lookup} object must be 1522 * created by the original lookup class by calling 1523 * {@link MethodHandles#lookup()} method or by a bootstrap method 1524 * invoked by the VM. The {@code Lookup} object with this lookup 1525 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1526 * 1527 * @since 16 1528 */ 1529 public static final int ORIGINAL = PACKAGE << 3; 1530 1531 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1532 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1533 private static final int TRUSTED = -1; 1534 1535 /* 1536 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1537 * Adjust 0 => PACKAGE 1538 */ 1539 private static int fixmods(int mods) { 1540 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1541 if (Modifier.isPublic(mods)) 1542 mods |= UNCONDITIONAL; 1543 return (mods != 0) ? mods : PACKAGE; 1544 } 1545 1546 /** Tells which class is performing the lookup. It is this class against 1547 * which checks are performed for visibility and access permissions. 1548 * <p> 1549 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1550 * access checks are performed against both the lookup class and the previous lookup class. 1551 * <p> 1552 * The class implies a maximum level of access permission, 1553 * but the permissions may be additionally limited by the bitmask 1554 * {@link #lookupModes lookupModes}, which controls whether non-public members 1555 * can be accessed. 1556 * @return the lookup class, on behalf of which this lookup object finds members 1557 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1558 */ 1559 public Class<?> lookupClass() { 1560 return lookupClass; 1561 } 1562 1563 /** Reports a lookup class in another module that this lookup object 1564 * was previously teleported from, or {@code null}. 1565 * <p> 1566 * A {@code Lookup} object produced by the factory methods, such as the 1567 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1568 * has {@code null} previous lookup class. 1569 * A {@code Lookup} object has a non-null previous lookup class 1570 * when this lookup was teleported from an old lookup class 1571 * in one module to a new lookup class in another module. 1572 * 1573 * @return the lookup class in another module that this lookup object was 1574 * previously teleported from, or {@code null} 1575 * @since 14 1576 * @see #in(Class) 1577 * @see MethodHandles#privateLookupIn(Class, Lookup) 1578 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1579 */ 1580 public Class<?> previousLookupClass() { 1581 return prevLookupClass; 1582 } 1583 1584 // This is just for calling out to MethodHandleImpl. 1585 private Class<?> lookupClassOrNull() { 1586 return (allowedModes == TRUSTED) ? null : lookupClass; 1587 } 1588 1589 /** Tells which access-protection classes of members this lookup object can produce. 1590 * The result is a bit-mask of the bits 1591 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1592 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1593 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1594 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1595 * {@linkplain #MODULE MODULE (0x10)}, 1596 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1597 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1598 * <p> 1599 * A freshly-created lookup object 1600 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1601 * all possible bits set, except {@code UNCONDITIONAL}. 1602 * A lookup object on a new lookup class 1603 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1604 * may have some mode bits set to zero. 1605 * Mode bits can also be 1606 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1607 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1608 * The purpose of this is to restrict access via the new lookup object, 1609 * so that it can access only names which can be reached by the original 1610 * lookup object, and also by the new lookup class. 1611 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1612 * @see #in 1613 * @see #dropLookupMode 1614 */ 1615 public int lookupModes() { 1616 return allowedModes & ALL_MODES; 1617 } 1618 1619 /** Embody the current class (the lookupClass) as a lookup class 1620 * for method handle creation. 1621 * Must be called by from a method in this package, 1622 * which in turn is called by a method not in this package. 1623 */ 1624 Lookup(Class<?> lookupClass) { 1625 this(lookupClass, null, FULL_POWER_MODES); 1626 } 1627 1628 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1629 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1630 && prevLookupClass.getModule() != lookupClass.getModule()); 1631 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1632 this.lookupClass = lookupClass; 1633 this.prevLookupClass = prevLookupClass; 1634 this.allowedModes = allowedModes; 1635 } 1636 1637 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1638 // make sure we haven't accidentally picked up a privileged class: 1639 checkUnprivilegedlookupClass(lookupClass); 1640 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1641 } 1642 1643 /** 1644 * Creates a lookup on the specified new lookup class. 1645 * The resulting object will report the specified 1646 * class as its own {@link #lookupClass() lookupClass}. 1647 * 1648 * <p> 1649 * However, the resulting {@code Lookup} object is guaranteed 1650 * to have no more access capabilities than the original. 1651 * In particular, access capabilities can be lost as follows:<ul> 1652 * <li>If the new lookup class is different from the old lookup class, 1653 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1654 * <li>If the new lookup class is in a different module from the old one, 1655 * i.e. {@link #MODULE MODULE} access is lost. 1656 * <li>If the new lookup class is in a different package 1657 * than the old one, protected and default (package) members will not be accessible, 1658 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1659 * <li>If the new lookup class is not within the same package member 1660 * as the old one, private members will not be accessible, and protected members 1661 * will not be accessible by virtue of inheritance, 1662 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1663 * (Protected members may continue to be accessible because of package sharing.) 1664 * <li>If the new lookup class is not 1665 * {@linkplain #accessClass(Class) accessible} to this lookup, 1666 * then no members, not even public members, will be accessible 1667 * i.e. all access modes are lost. 1668 * <li>If the new lookup class, the old lookup class and the previous lookup class 1669 * are all in different modules i.e. teleporting to a third module, 1670 * all access modes are lost. 1671 * </ul> 1672 * <p> 1673 * The new previous lookup class is chosen as follows: 1674 * <ul> 1675 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1676 * the new previous lookup class is {@code null}. 1677 * <li>If the new lookup class is in the same module as the old lookup class, 1678 * the new previous lookup class is the old previous lookup class. 1679 * <li>If the new lookup class is in a different module from the old lookup class, 1680 * the new previous lookup class is the old lookup class. 1681 *</ul> 1682 * <p> 1683 * The resulting lookup's capabilities for loading classes 1684 * (used during {@link #findClass} invocations) 1685 * are determined by the lookup class' loader, 1686 * which may change due to this operation. 1687 * 1688 * @param requestedLookupClass the desired lookup class for the new lookup object 1689 * @return a lookup object which reports the desired lookup class, or the same object 1690 * if there is no change 1691 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1692 * @throws NullPointerException if the argument is null 1693 * 1694 * @see #accessClass(Class) 1695 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1696 */ 1697 public Lookup in(Class<?> requestedLookupClass) { 1698 Objects.requireNonNull(requestedLookupClass); 1699 if (requestedLookupClass.isPrimitive()) 1700 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1701 if (requestedLookupClass.isArray()) 1702 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1703 1704 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1705 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1706 if (requestedLookupClass == this.lookupClass) 1707 return this; // keep same capabilities 1708 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1709 Module fromModule = this.lookupClass.getModule(); 1710 Module targetModule = requestedLookupClass.getModule(); 1711 Class<?> plc = this.previousLookupClass(); 1712 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1713 assert plc == null; 1714 newModes = UNCONDITIONAL; 1715 } else if (fromModule != targetModule) { 1716 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1717 // allow hopping back and forth between fromModule and plc's module 1718 // but not the third module 1719 newModes = 0; 1720 } 1721 // drop MODULE access 1722 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1723 // teleport from this lookup class 1724 plc = this.lookupClass; 1725 } 1726 if ((newModes & PACKAGE) != 0 1727 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1728 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1729 } 1730 // Allow nestmate lookups to be created without special privilege: 1731 if ((newModes & PRIVATE) != 0 1732 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1733 newModes &= ~(PRIVATE|PROTECTED); 1734 } 1735 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1736 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1737 // The requested class it not accessible from the lookup class. 1738 // No permissions. 1739 newModes = 0; 1740 } 1741 return newLookup(requestedLookupClass, plc, newModes); 1742 } 1743 1744 /** 1745 * Creates a lookup on the same lookup class which this lookup object 1746 * finds members, but with a lookup mode that has lost the given lookup mode. 1747 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1748 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1749 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1750 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1751 * 1752 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1753 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1754 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1755 * lookup has no access. 1756 * 1757 * <p> If this lookup is not a public lookup, then the following applies 1758 * regardless of its {@linkplain #lookupModes() lookup modes}. 1759 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1760 * dropped and so the resulting lookup mode will never have these access 1761 * capabilities. When dropping {@code PACKAGE} 1762 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1763 * access. When dropping {@code MODULE} then the resulting lookup will not 1764 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1765 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1766 * 1767 * @apiNote 1768 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1769 * delegate non-public access within the package of the lookup class without 1770 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1771 * A lookup with {@code MODULE} but not 1772 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1773 * the module of the lookup class without conferring package access. 1774 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1775 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1776 * to public classes accessible to both the module of the lookup class 1777 * and the module of the previous lookup class. 1778 * 1779 * @param modeToDrop the lookup mode to drop 1780 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1781 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1782 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1783 * or {@code UNCONDITIONAL} 1784 * @see MethodHandles#privateLookupIn 1785 * @since 9 1786 */ 1787 public Lookup dropLookupMode(int modeToDrop) { 1788 int oldModes = lookupModes(); 1789 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1790 switch (modeToDrop) { 1791 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1792 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1793 case PACKAGE: newModes &= ~(PRIVATE); break; 1794 case PROTECTED: 1795 case PRIVATE: 1796 case ORIGINAL: 1797 case UNCONDITIONAL: break; 1798 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1799 } 1800 if (newModes == oldModes) return this; // return self if no change 1801 return newLookup(lookupClass(), previousLookupClass(), newModes); 1802 } 1803 1804 /** 1805 * Creates and links a class or interface from {@code bytes} 1806 * with the same class loader and in the same runtime package and 1807 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1808 * {@linkplain #lookupClass() lookup class} as if calling 1809 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1810 * ClassLoader::defineClass}. 1811 * 1812 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1813 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1814 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1815 * that the lookup object was created by a caller in the runtime package (or derived 1816 * from a lookup originally created by suitably privileged code to a target class in 1817 * the runtime package). </p> 1818 * 1819 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1820 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1821 * same package as the lookup class. </p> 1822 * 1823 * <p> This method does not run the class initializer. The class initializer may 1824 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1825 * Specification</em>. </p> 1826 * 1827 * <p> If there is a security manager and this lookup does not have {@linkplain 1828 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1829 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1830 * 1831 * @param bytes the class bytes 1832 * @return the {@code Class} object for the class 1833 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1834 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1835 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1836 * than the lookup class or {@code bytes} is not a class or interface 1837 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1838 * @throws VerifyError if the newly created class cannot be verified 1839 * @throws LinkageError if the newly created class cannot be linked for any other reason 1840 * @throws SecurityException if a security manager is present and it 1841 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1842 * @throws NullPointerException if {@code bytes} is {@code null} 1843 * @since 9 1844 * @see MethodHandles#privateLookupIn 1845 * @see Lookup#dropLookupMode 1846 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1847 */ 1848 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1849 ensureDefineClassPermission(); 1850 if ((lookupModes() & PACKAGE) == 0) 1851 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1852 return makeClassDefiner(bytes.clone()).defineClass(false); 1853 } 1854 1855 private void ensureDefineClassPermission() { 1856 if (allowedModes == TRUSTED) return; 1857 1858 if (!hasFullPrivilegeAccess()) { 1859 @SuppressWarnings("removal") 1860 SecurityManager sm = System.getSecurityManager(); 1861 if (sm != null) 1862 sm.checkPermission(new RuntimePermission("defineClass")); 1863 } 1864 } 1865 1866 /** 1867 * The set of class options that specify whether a hidden class created by 1868 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1869 * Lookup::defineHiddenClass} method is dynamically added as a new member 1870 * to the nest of a lookup class and/or whether a hidden class has 1871 * a strong relationship with the class loader marked as its defining loader. 1872 * 1873 * @since 15 1874 */ 1875 public enum ClassOption { 1876 /** 1877 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1878 * of a lookup class as a nestmate. 1879 * 1880 * <p> A hidden nestmate class has access to the private members of all 1881 * classes and interfaces in the same nest. 1882 * 1883 * @see Class#getNestHost() 1884 */ 1885 NESTMATE(NESTMATE_CLASS), 1886 1887 /** 1888 * Specifies that a hidden class has a <em>strong</em> 1889 * relationship with the class loader marked as its defining loader, 1890 * as a normal class or interface has with its own defining loader. 1891 * This means that the hidden class may be unloaded if and only if 1892 * its defining loader is not reachable and thus may be reclaimed 1893 * by a garbage collector (JLS {@jls 12.7}). 1894 * 1895 * <p> By default, a hidden class or interface may be unloaded 1896 * even if the class loader that is marked as its defining loader is 1897 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1898 1899 * 1900 * @jls 12.7 Unloading of Classes and Interfaces 1901 */ 1902 STRONG(STRONG_LOADER_LINK); 1903 1904 /* the flag value is used by VM at define class time */ 1905 private final int flag; 1906 ClassOption(int flag) { 1907 this.flag = flag; 1908 } 1909 1910 static int optionsToFlag(Set<ClassOption> options) { 1911 int flags = 0; 1912 for (ClassOption cp : options) { 1913 flags |= cp.flag; 1914 } 1915 return flags; 1916 } 1917 } 1918 1919 /** 1920 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1921 * returning a {@code Lookup} on the newly created class or interface. 1922 * 1923 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1924 * which either defines {@code C} directly or delegates to another class loader. 1925 * A class loader defines {@code C} directly by invoking 1926 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1927 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1928 * to derive {@code C} from a purported representation in {@code class} file format. 1929 * In situations where use of a class loader is undesirable, a class or interface 1930 * {@code C} can be created by this method instead. This method is capable of 1931 * defining {@code C}, and thereby creating it, without invoking 1932 * {@code ClassLoader::defineClass}. 1933 * Instead, this method defines {@code C} as if by arranging for 1934 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1935 * from a purported representation in {@code class} file format 1936 * using the following rules: 1937 * 1938 * <ol> 1939 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1940 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1941 * This level of access is needed to create {@code C} in the module 1942 * of the lookup class of this {@code Lookup}.</li> 1943 * 1944 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1945 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1946 * The major and minor version may differ from the {@code class} file version 1947 * of the lookup class of this {@code Lookup}.</li> 1948 * 1949 * <li> The value of {@code this_class} must be a valid index in the 1950 * {@code constant_pool} table, and the entry at that index must be a valid 1951 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1952 * encoded in internal form that is specified by this structure. {@code N} must 1953 * denote a class or interface in the same package as the lookup class.</li> 1954 * 1955 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1956 * where {@code <suffix>} is an unqualified name. 1957 * 1958 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1959 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1960 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1961 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1962 * refers to the new {@code CONSTANT_Utf8_info} structure. 1963 * 1964 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1965 * 1966 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1967 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1968 * with the following adjustments: 1969 * <ul> 1970 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1971 * that includes a single {@code "."} character, even though this is not a valid 1972 * binary class or interface name in internal form.</li> 1973 * 1974 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1975 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1976 * 1977 * <li> {@code C} is considered to have the same runtime 1978 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1979 * and {@linkplain java.security.ProtectionDomain protection domain} 1980 * as the lookup class of this {@code Lookup}. 1981 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1982 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1983 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1984 * <ul> 1985 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1986 * even though this is not a valid binary class or interface name.</li> 1987 * <li> {@link Class#descriptorString()} returns the string 1988 * {@code "L" + N + "." + <suffix> + ";"}, 1989 * even though this is not a valid type descriptor name.</li> 1990 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1991 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1992 * </ul> 1993 * </ul> 1994 * </li> 1995 * </ol> 1996 * 1997 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1998 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1999 * <ul> 2000 * <li> During verification, whenever it is necessary to load the class named 2001 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2002 * made of any class loader.</li> 2003 * 2004 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2005 * by {@code this_class}, the symbolic reference is considered to be resolved to 2006 * {@code C} and resolution always succeeds immediately.</li> 2007 * </ul> 2008 * 2009 * <p> If the {@code initialize} parameter is {@code true}, 2010 * then {@code C} is initialized by the Java Virtual Machine. 2011 * 2012 * <p> The newly created class or interface {@code C} serves as the 2013 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2014 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2015 * no other class or interface can refer to {@code C} via a constant pool entry. 2016 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2017 * a method parameter type, or a method return type by any other class. 2018 * This is because a hidden class or interface does not have a binary name, so 2019 * there is no internal form available to record in any class's constant pool. 2020 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2021 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2022 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2023 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2024 * JVM Tool Interface</a>. 2025 * 2026 * <p> A class or interface created by 2027 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2028 * a class loader} has a strong relationship with that class loader. 2029 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2030 * that {@linkplain Class#getClassLoader() defined it}. 2031 * This means that a class created by a class loader may be unloaded if and 2032 * only if its defining loader is not reachable and thus may be reclaimed 2033 * by a garbage collector (JLS {@jls 12.7}). 2034 * 2035 * By default, however, a hidden class or interface may be unloaded even if 2036 * the class loader that is marked as its defining loader is 2037 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2038 * This behavior is useful when a hidden class or interface serves multiple 2039 * classes defined by arbitrary class loaders. In other cases, a hidden 2040 * class or interface may be linked to a single class (or a small number of classes) 2041 * with the same defining loader as the hidden class or interface. 2042 * In such cases, where the hidden class or interface must be coterminous 2043 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2044 * option may be passed in {@code options}. 2045 * This arranges for a hidden class to have the same strong relationship 2046 * with the class loader marked as its defining loader, 2047 * as a normal class or interface has with its own defining loader. 2048 * 2049 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2050 * may still prevent a hidden class or interface from being 2051 * unloaded by ensuring that the {@code Class} object is reachable. 2052 * 2053 * <p> The unloading characteristics are set for each hidden class when it is 2054 * defined, and cannot be changed later. An advantage of allowing hidden classes 2055 * to be unloaded independently of the class loader marked as their defining loader 2056 * is that a very large number of hidden classes may be created by an application. 2057 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2058 * just as if normal classes were created by class loaders. 2059 * 2060 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2061 * their private members. The nest relationship is determined by 2062 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2063 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2064 * By default, a hidden class belongs to a nest consisting only of itself 2065 * because a hidden class has no binary name. 2066 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2067 * to create a hidden class or interface {@code C} as a member of a nest. 2068 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2069 * in the {@code ClassFile} structure from which {@code C} was derived. 2070 * Instead, the following rules determine the nest host of {@code C}: 2071 * <ul> 2072 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2073 * been determined, then let {@code H} be the nest host of the lookup class. 2074 * Otherwise, the nest host of the lookup class is determined using the 2075 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2076 * <li>The nest host of {@code C} is determined to be {@code H}, 2077 * the nest host of the lookup class.</li> 2078 * </ul> 2079 * 2080 * <p> A hidden class or interface may be serializable, but this requires a custom 2081 * serialization mechanism in order to ensure that instances are properly serialized 2082 * and deserialized. The default serialization mechanism supports only classes and 2083 * interfaces that are discoverable by their class name. 2084 * 2085 * @param bytes the bytes that make up the class data, 2086 * in the format of a valid {@code class} file as defined by 2087 * <cite>The Java Virtual Machine Specification</cite>. 2088 * @param initialize if {@code true} the class will be initialized. 2089 * @param options {@linkplain ClassOption class options} 2090 * @return the {@code Lookup} object on the hidden class, 2091 * with {@linkplain #ORIGINAL original} and 2092 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2093 * 2094 * @throws IllegalAccessException if this {@code Lookup} does not have 2095 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2096 * @throws SecurityException if a security manager is present and it 2097 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2098 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2099 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2100 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2101 * than the lookup class or {@code bytes} is not a class or interface 2102 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2103 * @throws IncompatibleClassChangeError if the class or interface named as 2104 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2105 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2106 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2107 * {@code C} is {@code C} itself 2108 * @throws VerifyError if the newly created class cannot be verified 2109 * @throws LinkageError if the newly created class cannot be linked for any other reason 2110 * @throws NullPointerException if any parameter is {@code null} 2111 * 2112 * @since 15 2113 * @see Class#isHidden() 2114 * @jvms 4.2.1 Binary Class and Interface Names 2115 * @jvms 4.2.2 Unqualified Names 2116 * @jvms 4.7.28 The {@code NestHost} Attribute 2117 * @jvms 4.7.29 The {@code NestMembers} Attribute 2118 * @jvms 5.4.3.1 Class and Interface Resolution 2119 * @jvms 5.4.4 Access Control 2120 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2121 * @jvms 5.4 Linking 2122 * @jvms 5.5 Initialization 2123 * @jls 12.7 Unloading of Classes and Interfaces 2124 */ 2125 @SuppressWarnings("doclint:reference") // cross-module links 2126 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2127 throws IllegalAccessException 2128 { 2129 Objects.requireNonNull(bytes); 2130 Objects.requireNonNull(options); 2131 2132 ensureDefineClassPermission(); 2133 if (!hasFullPrivilegeAccess()) { 2134 throw new IllegalAccessException(this + " does not have full privilege access"); 2135 } 2136 2137 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize); 2138 } 2139 2140 /** 2141 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2142 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2143 * returning a {@code Lookup} on the newly created class or interface. 2144 * 2145 * <p> This method is equivalent to calling 2146 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2147 * as if the hidden class is injected with a private static final <i>unnamed</i> 2148 * field which is initialized with the given {@code classData} at 2149 * the first instruction of the class initializer. 2150 * The newly created class is linked by the Java Virtual Machine. 2151 * 2152 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2153 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2154 * methods can be used to retrieve the {@code classData}. 2155 * 2156 * @apiNote 2157 * A framework can create a hidden class with class data with one or more 2158 * objects and load the class data as dynamically-computed constant(s) 2159 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2160 * Class data} is accessible only to the lookup object created by the newly 2161 * defined hidden class but inaccessible to other members in the same nest 2162 * (unlike private static fields that are accessible to nestmates). 2163 * Care should be taken w.r.t. mutability for example when passing 2164 * an array or other mutable structure through the class data. 2165 * Changing any value stored in the class data at runtime may lead to 2166 * unpredictable behavior. 2167 * If the class data is a {@code List}, it is good practice to make it 2168 * unmodifiable for example via {@link List#of List::of}. 2169 * 2170 * @param bytes the class bytes 2171 * @param classData pre-initialized class data 2172 * @param initialize if {@code true} the class will be initialized. 2173 * @param options {@linkplain ClassOption class options} 2174 * @return the {@code Lookup} object on the hidden class, 2175 * with {@linkplain #ORIGINAL original} and 2176 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2177 * 2178 * @throws IllegalAccessException if this {@code Lookup} does not have 2179 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2180 * @throws SecurityException if a security manager is present and it 2181 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2182 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2183 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2184 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2185 * than the lookup class or {@code bytes} is not a class or interface 2186 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2187 * @throws IncompatibleClassChangeError if the class or interface named as 2188 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2189 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2190 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2191 * {@code C} is {@code C} itself 2192 * @throws VerifyError if the newly created class cannot be verified 2193 * @throws LinkageError if the newly created class cannot be linked for any other reason 2194 * @throws NullPointerException if any parameter is {@code null} 2195 * 2196 * @since 16 2197 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2198 * @see Class#isHidden() 2199 * @see MethodHandles#classData(Lookup, String, Class) 2200 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2201 * @jvms 4.2.1 Binary Class and Interface Names 2202 * @jvms 4.2.2 Unqualified Names 2203 * @jvms 4.7.28 The {@code NestHost} Attribute 2204 * @jvms 4.7.29 The {@code NestMembers} Attribute 2205 * @jvms 5.4.3.1 Class and Interface Resolution 2206 * @jvms 5.4.4 Access Control 2207 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2208 * @jvms 5.4 Linking 2209 * @jvms 5.5 Initialization 2210 * @jls 12.7 Unloading of Classes and Interface 2211 */ 2212 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2213 throws IllegalAccessException 2214 { 2215 Objects.requireNonNull(bytes); 2216 Objects.requireNonNull(classData); 2217 Objects.requireNonNull(options); 2218 2219 ensureDefineClassPermission(); 2220 if (!hasFullPrivilegeAccess()) { 2221 throw new IllegalAccessException(this + " does not have full privilege access"); 2222 } 2223 2224 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false) 2225 .defineClassAsLookup(initialize, classData); 2226 } 2227 2228 // A default dumper for writing class files passed to Lookup::defineClass 2229 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2230 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2231 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2232 // 2233 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2234 // and LambdaForms and method handle internals. They are dumped via 2235 // different ClassFileDumpers. 2236 private static ClassFileDumper defaultDumper() { 2237 return DEFAULT_DUMPER; 2238 } 2239 2240 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2241 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2242 2243 static class ClassFile { 2244 final String name; // internal name 2245 final int accessFlags; 2246 final byte[] bytes; 2247 ClassFile(String name, int accessFlags, byte[] bytes) { 2248 this.name = name; 2249 this.accessFlags = accessFlags; 2250 this.bytes = bytes; 2251 } 2252 2253 static ClassFile newInstanceNoCheck(String name, byte[] bytes) { 2254 return new ClassFile(name, 0, bytes); 2255 } 2256 2257 /** 2258 * This method checks the class file version and the structure of `this_class`. 2259 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2260 * that is in the named package. 2261 * 2262 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2263 * or the class is not in the given package name. 2264 */ 2265 static ClassFile newInstance(byte[] bytes, String pkgName) { 2266 var cf = readClassFile(bytes); 2267 2268 // check if it's in the named package 2269 int index = cf.name.lastIndexOf('/'); 2270 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.'); 2271 if (!pn.equals(pkgName)) { 2272 throw newIllegalArgumentException(cf.name + " not in same package as lookup class"); 2273 } 2274 return cf; 2275 } 2276 2277 private static ClassFile readClassFile(byte[] bytes) { 2278 int magic = readInt(bytes, 0); 2279 if (magic != 0xCAFEBABE) { 2280 throw new ClassFormatError("Incompatible magic value: " + magic); 2281 } 2282 int minor = readUnsignedShort(bytes, 4); 2283 int major = readUnsignedShort(bytes, 6); 2284 if (!VM.isSupportedClassFileVersion(major, minor)) { 2285 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2286 } 2287 2288 String name; 2289 int accessFlags; 2290 try { 2291 ClassReader reader = new ClassReader(bytes); 2292 // ClassReader does not check if `this_class` is CONSTANT_Class_info 2293 // workaround to read `this_class` using readConst and validate the value 2294 int thisClass = reader.readUnsignedShort(reader.header + 2); 2295 Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]); 2296 if (!(constant instanceof Type type)) { 2297 throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info"); 2298 } 2299 if (!type.getDescriptor().startsWith("L")) { 2300 throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info"); 2301 } 2302 name = type.getInternalName(); 2303 accessFlags = reader.readUnsignedShort(reader.header); 2304 } catch (RuntimeException e) { 2305 // ASM exceptions are poorly specified 2306 ClassFormatError cfe = new ClassFormatError(); 2307 cfe.initCause(e); 2308 throw cfe; 2309 } 2310 // must be a class or interface 2311 if ((accessFlags & Opcodes.ACC_MODULE) != 0) { 2312 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2313 } 2314 return new ClassFile(name, accessFlags, bytes); 2315 } 2316 2317 private static int readInt(byte[] bytes, int offset) { 2318 if ((offset+4) > bytes.length) { 2319 throw new ClassFormatError("Invalid ClassFile structure"); 2320 } 2321 return ((bytes[offset] & 0xFF) << 24) 2322 | ((bytes[offset + 1] & 0xFF) << 16) 2323 | ((bytes[offset + 2] & 0xFF) << 8) 2324 | (bytes[offset + 3] & 0xFF); 2325 } 2326 2327 private static int readUnsignedShort(byte[] bytes, int offset) { 2328 if ((offset+2) > bytes.length) { 2329 throw new ClassFormatError("Invalid ClassFile structure"); 2330 } 2331 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2332 } 2333 } 2334 2335 /* 2336 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2337 * from the given bytes. 2338 * 2339 * Caller should make a defensive copy of the arguments if needed 2340 * before calling this factory method. 2341 * 2342 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2343 * {@code bytes} denotes a class in a different package than the lookup class 2344 */ 2345 private ClassDefiner makeClassDefiner(byte[] bytes) { 2346 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2347 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper()); 2348 } 2349 2350 /** 2351 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2352 * from the given bytes. No package name check on the given bytes. 2353 * 2354 * @param name internal name 2355 * @param bytes class bytes 2356 * @param dumper dumper to write the given bytes to the dumper's output directory 2357 * @return ClassDefiner that defines a normal class of the given bytes. 2358 */ 2359 ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) { 2360 // skip package name validation 2361 ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes); 2362 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper); 2363 } 2364 2365 /** 2366 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2367 * from the given bytes. The name must be in the same package as the lookup class. 2368 * 2369 * Caller should make a defensive copy of the arguments if needed 2370 * before calling this factory method. 2371 * 2372 * @param bytes class bytes 2373 * @param dumper dumper to write the given bytes to the dumper's output directory 2374 * @return ClassDefiner that defines a hidden class of the given bytes. 2375 * 2376 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2377 * {@code bytes} denotes a class in a different package than the lookup class 2378 */ 2379 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2380 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2381 return makeHiddenClassDefiner(cf, Set.of(), false, dumper); 2382 } 2383 2384 /** 2385 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2386 * from the given bytes and options. 2387 * The name must be in the same package as the lookup class. 2388 * 2389 * Caller should make a defensive copy of the arguments if needed 2390 * before calling this factory method. 2391 * 2392 * @param bytes class bytes 2393 * @param options class options 2394 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2395 * @return ClassDefiner that defines a hidden class of the given bytes and options 2396 * 2397 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2398 * {@code bytes} denotes a class in a different package than the lookup class 2399 */ 2400 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2401 Set<ClassOption> options, 2402 boolean accessVmAnnotations) { 2403 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2404 return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper()); 2405 } 2406 2407 /** 2408 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2409 * from the given bytes and the given options. No package name check on the given bytes. 2410 * 2411 * @param name internal name that specifies the prefix of the hidden class 2412 * @param bytes class bytes 2413 * @param options class options 2414 * @param dumper dumper to write the given bytes to the dumper's output directory 2415 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2416 */ 2417 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) { 2418 Objects.requireNonNull(dumper); 2419 // skip name and access flags validation 2420 return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper); 2421 } 2422 2423 /** 2424 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2425 * from the given class file and options. 2426 * 2427 * @param cf ClassFile 2428 * @param options class options 2429 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2430 * @param dumper dumper to write the given bytes to the dumper's output directory 2431 */ 2432 private ClassDefiner makeHiddenClassDefiner(ClassFile cf, 2433 Set<ClassOption> options, 2434 boolean accessVmAnnotations, 2435 ClassFileDumper dumper) { 2436 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options); 2437 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2438 // jdk.internal.vm.annotations are permitted for classes 2439 // defined to boot loader and platform loader 2440 flags |= ACCESS_VM_ANNOTATIONS; 2441 } 2442 2443 return new ClassDefiner(this, cf, flags, dumper); 2444 } 2445 2446 static class ClassDefiner { 2447 private final Lookup lookup; 2448 private final String name; // internal name 2449 private final byte[] bytes; 2450 private final int classFlags; 2451 private final ClassFileDumper dumper; 2452 2453 private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) { 2454 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2455 this.lookup = lookup; 2456 this.bytes = cf.bytes; 2457 this.name = cf.name; 2458 this.classFlags = flags; 2459 this.dumper = dumper; 2460 } 2461 2462 String internalName() { 2463 return name; 2464 } 2465 2466 Class<?> defineClass(boolean initialize) { 2467 return defineClass(initialize, null); 2468 } 2469 2470 Lookup defineClassAsLookup(boolean initialize) { 2471 Class<?> c = defineClass(initialize, null); 2472 return new Lookup(c, null, FULL_POWER_MODES); 2473 } 2474 2475 /** 2476 * Defines the class of the given bytes and the given classData. 2477 * If {@code initialize} parameter is true, then the class will be initialized. 2478 * 2479 * @param initialize true if the class to be initialized 2480 * @param classData classData or null 2481 * @return the class 2482 * 2483 * @throws LinkageError linkage error 2484 */ 2485 Class<?> defineClass(boolean initialize, Object classData) { 2486 Class<?> lookupClass = lookup.lookupClass(); 2487 ClassLoader loader = lookupClass.getClassLoader(); 2488 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2489 Class<?> c = null; 2490 try { 2491 c = SharedSecrets.getJavaLangAccess() 2492 .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData); 2493 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2494 return c; 2495 } finally { 2496 // dump the classfile for debugging 2497 if (dumper.isEnabled()) { 2498 String name = internalName(); 2499 if (c != null) { 2500 dumper.dumpClass(name, c, bytes); 2501 } else { 2502 dumper.dumpFailedClass(name, bytes); 2503 } 2504 } 2505 } 2506 } 2507 2508 /** 2509 * Defines the class of the given bytes and the given classData. 2510 * If {@code initialize} parameter is true, then the class will be initialized. 2511 * 2512 * @param initialize true if the class to be initialized 2513 * @param classData classData or null 2514 * @return a Lookup for the defined class 2515 * 2516 * @throws LinkageError linkage error 2517 */ 2518 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2519 Class<?> c = defineClass(initialize, classData); 2520 return new Lookup(c, null, FULL_POWER_MODES); 2521 } 2522 2523 private boolean isNestmate() { 2524 return (classFlags & NESTMATE_CLASS) != 0; 2525 } 2526 } 2527 2528 private ProtectionDomain lookupClassProtectionDomain() { 2529 ProtectionDomain pd = cachedProtectionDomain; 2530 if (pd == null) { 2531 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2532 } 2533 return pd; 2534 } 2535 2536 // cached protection domain 2537 private volatile ProtectionDomain cachedProtectionDomain; 2538 2539 // Make sure outer class is initialized first. 2540 static { IMPL_NAMES.getClass(); } 2541 2542 /** Package-private version of lookup which is trusted. */ 2543 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2544 2545 /** Version of lookup which is trusted minimally. 2546 * It can only be used to create method handles to publicly accessible 2547 * members in packages that are exported unconditionally. 2548 */ 2549 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2550 2551 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2552 String name = lookupClass.getName(); 2553 if (name.startsWith("java.lang.invoke.")) 2554 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2555 } 2556 2557 /** 2558 * Displays the name of the class from which lookups are to be made, 2559 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2560 * previous lookup class} if present. 2561 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2562 * If there are restrictions on the access permitted to this lookup, 2563 * this is indicated by adding a suffix to the class name, consisting 2564 * of a slash and a keyword. The keyword represents the strongest 2565 * allowed access, and is chosen as follows: 2566 * <ul> 2567 * <li>If no access is allowed, the suffix is "/noaccess". 2568 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2569 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2570 * <li>If only public and module access are allowed, the suffix is "/module". 2571 * <li>If public and package access are allowed, the suffix is "/package". 2572 * <li>If public, package, and private access are allowed, the suffix is "/private". 2573 * </ul> 2574 * If none of the above cases apply, it is the case that 2575 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2576 * (public, module, package, private, and protected) is allowed. 2577 * In this case, no suffix is added. 2578 * This is true only of an object obtained originally from 2579 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2580 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2581 * always have restricted access, and will display a suffix. 2582 * <p> 2583 * (It may seem strange that protected access should be 2584 * stronger than private access. Viewed independently from 2585 * package access, protected access is the first to be lost, 2586 * because it requires a direct subclass relationship between 2587 * caller and callee.) 2588 * @see #in 2589 */ 2590 @Override 2591 public String toString() { 2592 String cname = lookupClass.getName(); 2593 if (prevLookupClass != null) 2594 cname += "/" + prevLookupClass.getName(); 2595 switch (allowedModes) { 2596 case 0: // no privileges 2597 return cname + "/noaccess"; 2598 case UNCONDITIONAL: 2599 return cname + "/publicLookup"; 2600 case PUBLIC: 2601 return cname + "/public"; 2602 case PUBLIC|MODULE: 2603 return cname + "/module"; 2604 case PUBLIC|PACKAGE: 2605 case PUBLIC|MODULE|PACKAGE: 2606 return cname + "/package"; 2607 case PUBLIC|PACKAGE|PRIVATE: 2608 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2609 return cname + "/private"; 2610 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2611 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2612 case FULL_POWER_MODES: 2613 return cname; 2614 case TRUSTED: 2615 return "/trusted"; // internal only; not exported 2616 default: // Should not happen, but it's a bitfield... 2617 cname = cname + "/" + Integer.toHexString(allowedModes); 2618 assert(false) : cname; 2619 return cname; 2620 } 2621 } 2622 2623 /** 2624 * Produces a method handle for a static method. 2625 * The type of the method handle will be that of the method. 2626 * (Since static methods do not take receivers, there is no 2627 * additional receiver argument inserted into the method handle type, 2628 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2629 * The method and all its argument types must be accessible to the lookup object. 2630 * <p> 2631 * The returned method handle will have 2632 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2633 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2634 * <p> 2635 * If the returned method handle is invoked, the method's class will 2636 * be initialized, if it has not already been initialized. 2637 * <p><b>Example:</b> 2638 * {@snippet lang="java" : 2639 import static java.lang.invoke.MethodHandles.*; 2640 import static java.lang.invoke.MethodType.*; 2641 ... 2642 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2643 "asList", methodType(List.class, Object[].class)); 2644 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2645 * } 2646 * @param refc the class from which the method is accessed 2647 * @param name the name of the method 2648 * @param type the type of the method 2649 * @return the desired method handle 2650 * @throws NoSuchMethodException if the method does not exist 2651 * @throws IllegalAccessException if access checking fails, 2652 * or if the method is not {@code static}, 2653 * or if the method's variable arity modifier bit 2654 * is set and {@code asVarargsCollector} fails 2655 * @throws SecurityException if a security manager is present and it 2656 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2657 * @throws NullPointerException if any argument is null 2658 */ 2659 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2660 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2661 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2662 } 2663 2664 /** 2665 * Produces a method handle for a virtual method. 2666 * The type of the method handle will be that of the method, 2667 * with the receiver type (usually {@code refc}) prepended. 2668 * The method and all its argument types must be accessible to the lookup object. 2669 * <p> 2670 * When called, the handle will treat the first argument as a receiver 2671 * and, for non-private methods, dispatch on the receiver's type to determine which method 2672 * implementation to enter. 2673 * For private methods the named method in {@code refc} will be invoked on the receiver. 2674 * (The dispatching action is identical with that performed by an 2675 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2676 * <p> 2677 * The first argument will be of type {@code refc} if the lookup 2678 * class has full privileges to access the member. Otherwise 2679 * the member must be {@code protected} and the first argument 2680 * will be restricted in type to the lookup class. 2681 * <p> 2682 * The returned method handle will have 2683 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2684 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2685 * <p> 2686 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2687 * instructions and method handles produced by {@code findVirtual}, 2688 * if the class is {@code MethodHandle} and the name string is 2689 * {@code invokeExact} or {@code invoke}, the resulting 2690 * method handle is equivalent to one produced by 2691 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2692 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2693 * with the same {@code type} argument. 2694 * <p> 2695 * If the class is {@code VarHandle} and the name string corresponds to 2696 * the name of a signature-polymorphic access mode method, the resulting 2697 * method handle is equivalent to one produced by 2698 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2699 * the access mode corresponding to the name string and with the same 2700 * {@code type} arguments. 2701 * <p> 2702 * <b>Example:</b> 2703 * {@snippet lang="java" : 2704 import static java.lang.invoke.MethodHandles.*; 2705 import static java.lang.invoke.MethodType.*; 2706 ... 2707 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2708 "concat", methodType(String.class, String.class)); 2709 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2710 "hashCode", methodType(int.class)); 2711 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2712 "hashCode", methodType(int.class)); 2713 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2714 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2715 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2716 // interface method: 2717 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2718 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2719 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2720 // constructor "internal method" must be accessed differently: 2721 MethodType MT_newString = methodType(void.class); //()V for new String() 2722 try { assertEquals("impossible", lookup() 2723 .findVirtual(String.class, "<init>", MT_newString)); 2724 } catch (NoSuchMethodException ex) { } // OK 2725 MethodHandle MH_newString = publicLookup() 2726 .findConstructor(String.class, MT_newString); 2727 assertEquals("", (String) MH_newString.invokeExact()); 2728 * } 2729 * 2730 * @param refc the class or interface from which the method is accessed 2731 * @param name the name of the method 2732 * @param type the type of the method, with the receiver argument omitted 2733 * @return the desired method handle 2734 * @throws NoSuchMethodException if the method does not exist 2735 * @throws IllegalAccessException if access checking fails, 2736 * or if the method is {@code static}, 2737 * or if the method's variable arity modifier bit 2738 * is set and {@code asVarargsCollector} fails 2739 * @throws SecurityException if a security manager is present and it 2740 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2741 * @throws NullPointerException if any argument is null 2742 */ 2743 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2744 if (refc == MethodHandle.class) { 2745 MethodHandle mh = findVirtualForMH(name, type); 2746 if (mh != null) return mh; 2747 } else if (refc == VarHandle.class) { 2748 MethodHandle mh = findVirtualForVH(name, type); 2749 if (mh != null) return mh; 2750 } 2751 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2752 MemberName method = resolveOrFail(refKind, refc, name, type); 2753 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2754 } 2755 private MethodHandle findVirtualForMH(String name, MethodType type) { 2756 // these names require special lookups because of the implicit MethodType argument 2757 if ("invoke".equals(name)) 2758 return invoker(type); 2759 if ("invokeExact".equals(name)) 2760 return exactInvoker(type); 2761 assert(!MemberName.isMethodHandleInvokeName(name)); 2762 return null; 2763 } 2764 private MethodHandle findVirtualForVH(String name, MethodType type) { 2765 try { 2766 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2767 } catch (IllegalArgumentException e) { 2768 return null; 2769 } 2770 } 2771 2772 /** 2773 * Produces a method handle which creates an object and initializes it, using 2774 * the constructor of the specified type. 2775 * The parameter types of the method handle will be those of the constructor, 2776 * while the return type will be a reference to the constructor's class. 2777 * The constructor and all its argument types must be accessible to the lookup object. 2778 * <p> 2779 * The requested type must have a return type of {@code void}. 2780 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2781 * <p> 2782 * The returned method handle will have 2783 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2784 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2785 * <p> 2786 * If the returned method handle is invoked, the constructor's class will 2787 * be initialized, if it has not already been initialized. 2788 * <p><b>Example:</b> 2789 * {@snippet lang="java" : 2790 import static java.lang.invoke.MethodHandles.*; 2791 import static java.lang.invoke.MethodType.*; 2792 ... 2793 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2794 ArrayList.class, methodType(void.class, Collection.class)); 2795 Collection orig = Arrays.asList("x", "y"); 2796 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2797 assert(orig != copy); 2798 assertEquals(orig, copy); 2799 // a variable-arity constructor: 2800 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2801 ProcessBuilder.class, methodType(void.class, String[].class)); 2802 ProcessBuilder pb = (ProcessBuilder) 2803 MH_newProcessBuilder.invoke("x", "y", "z"); 2804 assertEquals("[x, y, z]", pb.command().toString()); 2805 * } 2806 * @param refc the class or interface from which the method is accessed 2807 * @param type the type of the method, with the receiver argument omitted, and a void return type 2808 * @return the desired method handle 2809 * @throws NoSuchMethodException if the constructor does not exist 2810 * @throws IllegalAccessException if access checking fails 2811 * or if the method's variable arity modifier bit 2812 * is set and {@code asVarargsCollector} fails 2813 * @throws SecurityException if a security manager is present and it 2814 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2815 * @throws NullPointerException if any argument is null 2816 */ 2817 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2818 if (refc.isArray()) { 2819 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2820 } 2821 String name = ConstantDescs.INIT_NAME; 2822 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2823 return getDirectConstructor(refc, ctor); 2824 } 2825 2826 /** 2827 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2828 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2829 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2830 * and then determines whether the class is accessible to this lookup object. 2831 * <p> 2832 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2833 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2834 * of {@code '['} and followed by the element type as encoded in the 2835 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2836 * <p> 2837 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2838 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2839 * 2840 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2841 * or the string representing an array class 2842 * @return the requested class. 2843 * @throws SecurityException if a security manager is present and it 2844 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2845 * @throws LinkageError if the linkage fails 2846 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2847 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2848 * modes. 2849 * @throws NullPointerException if {@code targetName} is null 2850 * @since 9 2851 * @jvms 5.4.3.1 Class and Interface Resolution 2852 */ 2853 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2854 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2855 return accessClass(targetClass); 2856 } 2857 2858 /** 2859 * Ensures that {@code targetClass} has been initialized. The class 2860 * to be initialized must be {@linkplain #accessClass accessible} 2861 * to this {@code Lookup} object. This method causes {@code targetClass} 2862 * to be initialized if it has not been already initialized, 2863 * as specified in JVMS {@jvms 5.5}. 2864 * 2865 * <p> 2866 * This method returns when {@code targetClass} is fully initialized, or 2867 * when {@code targetClass} is being initialized by the current thread. 2868 * 2869 * @param <T> the type of the class to be initialized 2870 * @param targetClass the class to be initialized 2871 * @return {@code targetClass} that has been initialized, or that is being 2872 * initialized by the current thread. 2873 * 2874 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2875 * or array class 2876 * @throws IllegalAccessException if {@code targetClass} is not 2877 * {@linkplain #accessClass accessible} to this lookup 2878 * @throws ExceptionInInitializerError if the class initialization provoked 2879 * by this method fails 2880 * @throws SecurityException if a security manager is present and it 2881 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2882 * @since 15 2883 * @jvms 5.5 Initialization 2884 */ 2885 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2886 if (targetClass.isPrimitive()) 2887 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2888 if (targetClass.isArray()) 2889 throw new IllegalArgumentException(targetClass + " is an array class"); 2890 2891 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2892 throw makeAccessException(targetClass); 2893 } 2894 checkSecurityManager(targetClass); 2895 2896 // ensure class initialization 2897 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2898 return targetClass; 2899 } 2900 2901 /* 2902 * Returns IllegalAccessException due to access violation to the given targetClass. 2903 * 2904 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2905 * which verifies access to a class rather a member. 2906 */ 2907 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2908 String message = "access violation: "+ targetClass; 2909 if (this == MethodHandles.publicLookup()) { 2910 message += ", from public Lookup"; 2911 } else { 2912 Module m = lookupClass().getModule(); 2913 message += ", from " + lookupClass() + " (" + m + ")"; 2914 if (prevLookupClass != null) { 2915 message += ", previous lookup " + 2916 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2917 } 2918 } 2919 return new IllegalAccessException(message); 2920 } 2921 2922 /** 2923 * Determines if a class can be accessed from the lookup context defined by 2924 * this {@code Lookup} object. The static initializer of the class is not run. 2925 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2926 * if the element type of the array class is accessible. Otherwise, 2927 * {@code targetClass} is determined as accessible as follows. 2928 * 2929 * <p> 2930 * If {@code targetClass} is in the same module as the lookup class, 2931 * the lookup class is {@code LC} in module {@code M1} and 2932 * the previous lookup class is in module {@code M0} or 2933 * {@code null} if not present, 2934 * {@code targetClass} is accessible if and only if one of the following is true: 2935 * <ul> 2936 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2937 * {@code LC} or other class in the same nest of {@code LC}.</li> 2938 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2939 * in the same runtime package of {@code LC}.</li> 2940 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2941 * a public type in {@code M1}.</li> 2942 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2943 * a public type in a package exported by {@code M1} to at least {@code M0} 2944 * if the previous lookup class is present; otherwise, {@code targetClass} 2945 * is a public type in a package exported by {@code M1} unconditionally.</li> 2946 * </ul> 2947 * 2948 * <p> 2949 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2950 * can access public types in all modules when the type is in a package 2951 * that is exported unconditionally. 2952 * <p> 2953 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2954 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2955 * is inaccessible. 2956 * <p> 2957 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2958 * {@code M1} is the module containing {@code lookupClass} and 2959 * {@code M2} is the module containing {@code targetClass}, 2960 * then {@code targetClass} is accessible if and only if 2961 * <ul> 2962 * <li>{@code M1} reads {@code M2}, and 2963 * <li>{@code targetClass} is public and in a package exported by 2964 * {@code M2} at least to {@code M1}. 2965 * </ul> 2966 * <p> 2967 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2968 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2969 * containing the previous lookup class, then {@code targetClass} is accessible 2970 * if and only if one of the following is true: 2971 * <ul> 2972 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2973 * {@linkplain Module#reads reads} {@code M0} and the type is 2974 * in a package that is exported to at least {@code M1}. 2975 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2976 * {@linkplain Module#reads reads} {@code M1} and the type is 2977 * in a package that is exported to at least {@code M0}. 2978 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2979 * and {@code M1} reads {@code M2} and the type is in a package 2980 * that is exported to at least both {@code M0} and {@code M2}. 2981 * </ul> 2982 * <p> 2983 * Otherwise, {@code targetClass} is not accessible. 2984 * 2985 * @param <T> the type of the class to be access-checked 2986 * @param targetClass the class to be access-checked 2987 * @return {@code targetClass} that has been access-checked 2988 * @throws IllegalAccessException if the class is not accessible from the lookup class 2989 * and previous lookup class, if present, using the allowed access modes. 2990 * @throws SecurityException if a security manager is present and it 2991 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2992 * @throws NullPointerException if {@code targetClass} is {@code null} 2993 * @since 9 2994 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2995 */ 2996 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2997 if (!isClassAccessible(targetClass)) { 2998 throw makeAccessException(targetClass); 2999 } 3000 checkSecurityManager(targetClass); 3001 return targetClass; 3002 } 3003 3004 /** 3005 * Produces an early-bound method handle for a virtual method. 3006 * It will bypass checks for overriding methods on the receiver, 3007 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3008 * instruction from within the explicitly specified {@code specialCaller}. 3009 * The type of the method handle will be that of the method, 3010 * with a suitably restricted receiver type prepended. 3011 * (The receiver type will be {@code specialCaller} or a subtype.) 3012 * The method and all its argument types must be accessible 3013 * to the lookup object. 3014 * <p> 3015 * Before method resolution, 3016 * if the explicitly specified caller class is not identical with the 3017 * lookup class, or if this lookup object does not have 3018 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3019 * privileges, the access fails. 3020 * <p> 3021 * The returned method handle will have 3022 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3023 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3024 * <p style="font-size:smaller;"> 3025 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 3026 * are not visible to this API, 3027 * even though the {@code invokespecial} instruction can refer to them 3028 * in special circumstances. Use {@link #findConstructor findConstructor} 3029 * to access instance initialization methods in a safe manner.)</em> 3030 * <p><b>Example:</b> 3031 * {@snippet lang="java" : 3032 import static java.lang.invoke.MethodHandles.*; 3033 import static java.lang.invoke.MethodType.*; 3034 ... 3035 static class Listie extends ArrayList { 3036 public String toString() { return "[wee Listie]"; } 3037 static Lookup lookup() { return MethodHandles.lookup(); } 3038 } 3039 ... 3040 // no access to constructor via invokeSpecial: 3041 MethodHandle MH_newListie = Listie.lookup() 3042 .findConstructor(Listie.class, methodType(void.class)); 3043 Listie l = (Listie) MH_newListie.invokeExact(); 3044 try { assertEquals("impossible", Listie.lookup().findSpecial( 3045 Listie.class, "<init>", methodType(void.class), Listie.class)); 3046 } catch (NoSuchMethodException ex) { } // OK 3047 // access to super and self methods via invokeSpecial: 3048 MethodHandle MH_super = Listie.lookup().findSpecial( 3049 ArrayList.class, "toString" , methodType(String.class), Listie.class); 3050 MethodHandle MH_this = Listie.lookup().findSpecial( 3051 Listie.class, "toString" , methodType(String.class), Listie.class); 3052 MethodHandle MH_duper = Listie.lookup().findSpecial( 3053 Object.class, "toString" , methodType(String.class), Listie.class); 3054 assertEquals("[]", (String) MH_super.invokeExact(l)); 3055 assertEquals(""+l, (String) MH_this.invokeExact(l)); 3056 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 3057 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 3058 String.class, "toString", methodType(String.class), Listie.class)); 3059 } catch (IllegalAccessException ex) { } // OK 3060 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 3061 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 3062 * } 3063 * 3064 * @param refc the class or interface from which the method is accessed 3065 * @param name the name of the method (which must not be "<init>") 3066 * @param type the type of the method, with the receiver argument omitted 3067 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 3068 * @return the desired method handle 3069 * @throws NoSuchMethodException if the method does not exist 3070 * @throws IllegalAccessException if access checking fails, 3071 * or if the method is {@code static}, 3072 * or if the method's variable arity modifier bit 3073 * is set and {@code asVarargsCollector} fails 3074 * @throws SecurityException if a security manager is present and it 3075 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3076 * @throws NullPointerException if any argument is null 3077 */ 3078 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3079 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3080 checkSpecialCaller(specialCaller, refc); 3081 Lookup specialLookup = this.in(specialCaller); 3082 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3083 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3084 } 3085 3086 /** 3087 * Produces a method handle giving read access to a non-static field. 3088 * The type of the method handle will have a return type of the field's 3089 * value type. 3090 * The method handle's single argument will be the instance containing 3091 * the field. 3092 * Access checking is performed immediately on behalf of the lookup class. 3093 * @param refc the class or interface from which the method is accessed 3094 * @param name the field's name 3095 * @param type the field's type 3096 * @return a method handle which can load values from the field 3097 * @throws NoSuchFieldException if the field does not exist 3098 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3099 * @throws SecurityException if a security manager is present and it 3100 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3101 * @throws NullPointerException if any argument is null 3102 * @see #findVarHandle(Class, String, Class) 3103 */ 3104 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3105 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3106 return getDirectField(REF_getField, refc, field); 3107 } 3108 3109 /** 3110 * Produces a method handle giving write access to a non-static field. 3111 * The type of the method handle will have a void return type. 3112 * The method handle will take two arguments, the instance containing 3113 * the field, and the value to be stored. 3114 * The second argument will be of the field's value type. 3115 * Access checking is performed immediately on behalf of the lookup class. 3116 * @param refc the class or interface from which the method is accessed 3117 * @param name the field's name 3118 * @param type the field's type 3119 * @return a method handle which can store values into the field 3120 * @throws NoSuchFieldException if the field does not exist 3121 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3122 * or {@code final} 3123 * @throws SecurityException if a security manager is present and it 3124 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3125 * @throws NullPointerException if any argument is null 3126 * @see #findVarHandle(Class, String, Class) 3127 */ 3128 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3129 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3130 return getDirectField(REF_putField, refc, field); 3131 } 3132 3133 /** 3134 * Produces a VarHandle giving access to a non-static field {@code name} 3135 * of type {@code type} declared in a class of type {@code recv}. 3136 * The VarHandle's variable type is {@code type} and it has one 3137 * coordinate type, {@code recv}. 3138 * <p> 3139 * Access checking is performed immediately on behalf of the lookup 3140 * class. 3141 * <p> 3142 * Certain access modes of the returned VarHandle are unsupported under 3143 * the following conditions: 3144 * <ul> 3145 * <li>if the field is declared {@code final}, then the write, atomic 3146 * update, numeric atomic update, and bitwise atomic update access 3147 * modes are unsupported. 3148 * <li>if the field type is anything other than {@code byte}, 3149 * {@code short}, {@code char}, {@code int}, {@code long}, 3150 * {@code float}, or {@code double} then numeric atomic update 3151 * access modes are unsupported. 3152 * <li>if the field type is anything other than {@code boolean}, 3153 * {@code byte}, {@code short}, {@code char}, {@code int} or 3154 * {@code long} then bitwise atomic update access modes are 3155 * unsupported. 3156 * </ul> 3157 * <p> 3158 * If the field is declared {@code volatile} then the returned VarHandle 3159 * will override access to the field (effectively ignore the 3160 * {@code volatile} declaration) in accordance to its specified 3161 * access modes. 3162 * <p> 3163 * If the field type is {@code float} or {@code double} then numeric 3164 * and atomic update access modes compare values using their bitwise 3165 * representation (see {@link Float#floatToRawIntBits} and 3166 * {@link Double#doubleToRawLongBits}, respectively). 3167 * @apiNote 3168 * Bitwise comparison of {@code float} values or {@code double} values, 3169 * as performed by the numeric and atomic update access modes, differ 3170 * from the primitive {@code ==} operator and the {@link Float#equals} 3171 * and {@link Double#equals} methods, specifically with respect to 3172 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3173 * Care should be taken when performing a compare and set or a compare 3174 * and exchange operation with such values since the operation may 3175 * unexpectedly fail. 3176 * There are many possible NaN values that are considered to be 3177 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3178 * provided by Java can distinguish between them. Operation failure can 3179 * occur if the expected or witness value is a NaN value and it is 3180 * transformed (perhaps in a platform specific manner) into another NaN 3181 * value, and thus has a different bitwise representation (see 3182 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3183 * details). 3184 * The values {@code -0.0} and {@code +0.0} have different bitwise 3185 * representations but are considered equal when using the primitive 3186 * {@code ==} operator. Operation failure can occur if, for example, a 3187 * numeric algorithm computes an expected value to be say {@code -0.0} 3188 * and previously computed the witness value to be say {@code +0.0}. 3189 * @param recv the receiver class, of type {@code R}, that declares the 3190 * non-static field 3191 * @param name the field's name 3192 * @param type the field's type, of type {@code T} 3193 * @return a VarHandle giving access to non-static fields. 3194 * @throws NoSuchFieldException if the field does not exist 3195 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3196 * @throws SecurityException if a security manager is present and it 3197 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3198 * @throws NullPointerException if any argument is null 3199 * @since 9 3200 */ 3201 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3202 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3203 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3204 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3205 } 3206 3207 /** 3208 * Produces a method handle giving read access to a static field. 3209 * The type of the method handle will have a return type of the field's 3210 * value type. 3211 * The method handle will take no arguments. 3212 * Access checking is performed immediately on behalf of the lookup class. 3213 * <p> 3214 * If the returned method handle is invoked, the field's class will 3215 * be initialized, if it has not already been initialized. 3216 * @param refc the class or interface from which the method is accessed 3217 * @param name the field's name 3218 * @param type the field's type 3219 * @return a method handle which can load values from the field 3220 * @throws NoSuchFieldException if the field does not exist 3221 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3222 * @throws SecurityException if a security manager is present and it 3223 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3224 * @throws NullPointerException if any argument is null 3225 */ 3226 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3227 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3228 return getDirectField(REF_getStatic, refc, field); 3229 } 3230 3231 /** 3232 * Produces a method handle giving write access to a static field. 3233 * The type of the method handle will have a void return type. 3234 * The method handle will take a single 3235 * argument, of the field's value type, the value to be stored. 3236 * Access checking is performed immediately on behalf of the lookup class. 3237 * <p> 3238 * If the returned method handle is invoked, the field's class will 3239 * be initialized, if it has not already been initialized. 3240 * @param refc the class or interface from which the method is accessed 3241 * @param name the field's name 3242 * @param type the field's type 3243 * @return a method handle which can store values into the field 3244 * @throws NoSuchFieldException if the field does not exist 3245 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3246 * or is {@code final} 3247 * @throws SecurityException if a security manager is present and it 3248 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3249 * @throws NullPointerException if any argument is null 3250 */ 3251 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3252 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3253 return getDirectField(REF_putStatic, refc, field); 3254 } 3255 3256 /** 3257 * Produces a VarHandle giving access to a static field {@code name} of 3258 * type {@code type} declared in a class of type {@code decl}. 3259 * The VarHandle's variable type is {@code type} and it has no 3260 * coordinate types. 3261 * <p> 3262 * Access checking is performed immediately on behalf of the lookup 3263 * class. 3264 * <p> 3265 * If the returned VarHandle is operated on, the declaring class will be 3266 * initialized, if it has not already been initialized. 3267 * <p> 3268 * Certain access modes of the returned VarHandle are unsupported under 3269 * the following conditions: 3270 * <ul> 3271 * <li>if the field is declared {@code final}, then the write, atomic 3272 * update, numeric atomic update, and bitwise atomic update access 3273 * modes are unsupported. 3274 * <li>if the field type is anything other than {@code byte}, 3275 * {@code short}, {@code char}, {@code int}, {@code long}, 3276 * {@code float}, or {@code double}, then numeric atomic update 3277 * access modes are unsupported. 3278 * <li>if the field type is anything other than {@code boolean}, 3279 * {@code byte}, {@code short}, {@code char}, {@code int} or 3280 * {@code long} then bitwise atomic update access modes are 3281 * unsupported. 3282 * </ul> 3283 * <p> 3284 * If the field is declared {@code volatile} then the returned VarHandle 3285 * will override access to the field (effectively ignore the 3286 * {@code volatile} declaration) in accordance to its specified 3287 * access modes. 3288 * <p> 3289 * If the field type is {@code float} or {@code double} then numeric 3290 * and atomic update access modes compare values using their bitwise 3291 * representation (see {@link Float#floatToRawIntBits} and 3292 * {@link Double#doubleToRawLongBits}, respectively). 3293 * @apiNote 3294 * Bitwise comparison of {@code float} values or {@code double} values, 3295 * as performed by the numeric and atomic update access modes, differ 3296 * from the primitive {@code ==} operator and the {@link Float#equals} 3297 * and {@link Double#equals} methods, specifically with respect to 3298 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3299 * Care should be taken when performing a compare and set or a compare 3300 * and exchange operation with such values since the operation may 3301 * unexpectedly fail. 3302 * There are many possible NaN values that are considered to be 3303 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3304 * provided by Java can distinguish between them. Operation failure can 3305 * occur if the expected or witness value is a NaN value and it is 3306 * transformed (perhaps in a platform specific manner) into another NaN 3307 * value, and thus has a different bitwise representation (see 3308 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3309 * details). 3310 * The values {@code -0.0} and {@code +0.0} have different bitwise 3311 * representations but are considered equal when using the primitive 3312 * {@code ==} operator. Operation failure can occur if, for example, a 3313 * numeric algorithm computes an expected value to be say {@code -0.0} 3314 * and previously computed the witness value to be say {@code +0.0}. 3315 * @param decl the class that declares the static field 3316 * @param name the field's name 3317 * @param type the field's type, of type {@code T} 3318 * @return a VarHandle giving access to a static field 3319 * @throws NoSuchFieldException if the field does not exist 3320 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3321 * @throws SecurityException if a security manager is present and it 3322 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3323 * @throws NullPointerException if any argument is null 3324 * @since 9 3325 */ 3326 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3327 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3328 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3329 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3330 } 3331 3332 /** 3333 * Produces an early-bound method handle for a non-static method. 3334 * The receiver must have a supertype {@code defc} in which a method 3335 * of the given name and type is accessible to the lookup class. 3336 * The method and all its argument types must be accessible to the lookup object. 3337 * The type of the method handle will be that of the method, 3338 * without any insertion of an additional receiver parameter. 3339 * The given receiver will be bound into the method handle, 3340 * so that every call to the method handle will invoke the 3341 * requested method on the given receiver. 3342 * <p> 3343 * The returned method handle will have 3344 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3345 * the method's variable arity modifier bit ({@code 0x0080}) is set 3346 * <em>and</em> the trailing array argument is not the only argument. 3347 * (If the trailing array argument is the only argument, 3348 * the given receiver value will be bound to it.) 3349 * <p> 3350 * This is almost equivalent to the following code, with some differences noted below: 3351 * {@snippet lang="java" : 3352 import static java.lang.invoke.MethodHandles.*; 3353 import static java.lang.invoke.MethodType.*; 3354 ... 3355 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3356 MethodHandle mh1 = mh0.bindTo(receiver); 3357 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3358 return mh1; 3359 * } 3360 * where {@code defc} is either {@code receiver.getClass()} or a super 3361 * type of that class, in which the requested method is accessible 3362 * to the lookup class. 3363 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3364 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3365 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3366 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3367 * @param receiver the object from which the method is accessed 3368 * @param name the name of the method 3369 * @param type the type of the method, with the receiver argument omitted 3370 * @return the desired method handle 3371 * @throws NoSuchMethodException if the method does not exist 3372 * @throws IllegalAccessException if access checking fails 3373 * or if the method's variable arity modifier bit 3374 * is set and {@code asVarargsCollector} fails 3375 * @throws SecurityException if a security manager is present and it 3376 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3377 * @throws NullPointerException if any argument is null 3378 * @see MethodHandle#bindTo 3379 * @see #findVirtual 3380 */ 3381 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3382 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3383 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3384 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3385 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3386 throw new IllegalAccessException("The restricted defining class " + 3387 mh.type().leadingReferenceParameter().getName() + 3388 " is not assignable from receiver class " + 3389 receiver.getClass().getName()); 3390 } 3391 return mh.bindArgumentL(0, receiver).setVarargs(method); 3392 } 3393 3394 /** 3395 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3396 * to <i>m</i>, if the lookup class has permission. 3397 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3398 * If <i>m</i> is virtual, overriding is respected on every call. 3399 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3400 * The type of the method handle will be that of the method, 3401 * with the receiver type prepended (but only if it is non-static). 3402 * If the method's {@code accessible} flag is not set, 3403 * access checking is performed immediately on behalf of the lookup class. 3404 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3405 * <p> 3406 * The returned method handle will have 3407 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3408 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3409 * <p> 3410 * If <i>m</i> is static, and 3411 * if the returned method handle is invoked, the method's class will 3412 * be initialized, if it has not already been initialized. 3413 * @param m the reflected method 3414 * @return a method handle which can invoke the reflected method 3415 * @throws IllegalAccessException if access checking fails 3416 * or if the method's variable arity modifier bit 3417 * is set and {@code asVarargsCollector} fails 3418 * @throws NullPointerException if the argument is null 3419 */ 3420 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3421 if (m.getDeclaringClass() == MethodHandle.class) { 3422 MethodHandle mh = unreflectForMH(m); 3423 if (mh != null) return mh; 3424 } 3425 if (m.getDeclaringClass() == VarHandle.class) { 3426 MethodHandle mh = unreflectForVH(m); 3427 if (mh != null) return mh; 3428 } 3429 MemberName method = new MemberName(m); 3430 byte refKind = method.getReferenceKind(); 3431 if (refKind == REF_invokeSpecial) 3432 refKind = REF_invokeVirtual; 3433 assert(method.isMethod()); 3434 @SuppressWarnings("deprecation") 3435 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3436 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3437 } 3438 private MethodHandle unreflectForMH(Method m) { 3439 // these names require special lookups because they throw UnsupportedOperationException 3440 if (MemberName.isMethodHandleInvokeName(m.getName())) 3441 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3442 return null; 3443 } 3444 private MethodHandle unreflectForVH(Method m) { 3445 // these names require special lookups because they throw UnsupportedOperationException 3446 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3447 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3448 return null; 3449 } 3450 3451 /** 3452 * Produces a method handle for a reflected method. 3453 * It will bypass checks for overriding methods on the receiver, 3454 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3455 * instruction from within the explicitly specified {@code specialCaller}. 3456 * The type of the method handle will be that of the method, 3457 * with a suitably restricted receiver type prepended. 3458 * (The receiver type will be {@code specialCaller} or a subtype.) 3459 * If the method's {@code accessible} flag is not set, 3460 * access checking is performed immediately on behalf of the lookup class, 3461 * as if {@code invokespecial} instruction were being linked. 3462 * <p> 3463 * Before method resolution, 3464 * if the explicitly specified caller class is not identical with the 3465 * lookup class, or if this lookup object does not have 3466 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3467 * privileges, the access fails. 3468 * <p> 3469 * The returned method handle will have 3470 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3471 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3472 * @param m the reflected method 3473 * @param specialCaller the class nominally calling the method 3474 * @return a method handle which can invoke the reflected method 3475 * @throws IllegalAccessException if access checking fails, 3476 * or if the method is {@code static}, 3477 * or if the method's variable arity modifier bit 3478 * is set and {@code asVarargsCollector} fails 3479 * @throws NullPointerException if any argument is null 3480 */ 3481 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3482 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3483 Lookup specialLookup = this.in(specialCaller); 3484 MemberName method = new MemberName(m, true); 3485 assert(method.isMethod()); 3486 // ignore m.isAccessible: this is a new kind of access 3487 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3488 } 3489 3490 /** 3491 * Produces a method handle for a reflected constructor. 3492 * The type of the method handle will be that of the constructor, 3493 * with the return type changed to the declaring class. 3494 * The method handle will perform a {@code newInstance} operation, 3495 * creating a new instance of the constructor's class on the 3496 * arguments passed to the method handle. 3497 * <p> 3498 * If the constructor's {@code accessible} flag is not set, 3499 * access checking is performed immediately on behalf of the lookup class. 3500 * <p> 3501 * The returned method handle will have 3502 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3503 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3504 * <p> 3505 * If the returned method handle is invoked, the constructor's class will 3506 * be initialized, if it has not already been initialized. 3507 * @param c the reflected constructor 3508 * @return a method handle which can invoke the reflected constructor 3509 * @throws IllegalAccessException if access checking fails 3510 * or if the method's variable arity modifier bit 3511 * is set and {@code asVarargsCollector} fails 3512 * @throws NullPointerException if the argument is null 3513 */ 3514 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3515 MemberName ctor = new MemberName(c); 3516 assert(ctor.isConstructor()); 3517 @SuppressWarnings("deprecation") 3518 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3519 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3520 } 3521 3522 /* 3523 * Produces a method handle that is capable of creating instances of the given class 3524 * and instantiated by the given constructor. No security manager check. 3525 * 3526 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3527 */ 3528 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3529 MemberName ctor = new MemberName(c); 3530 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3531 checkAccess(REF_newInvokeSpecial, decl, ctor); 3532 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3533 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3534 } 3535 3536 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3537 if (decl == ctor.getDeclaringClass()) 3538 return true; 3539 3540 Class<?> cl = decl; 3541 while ((cl = cl.getSuperclass()) != null) { 3542 if (cl == ctor.getDeclaringClass()) { 3543 return true; 3544 } 3545 } 3546 return false; 3547 } 3548 3549 /** 3550 * Produces a method handle giving read access to a reflected field. 3551 * The type of the method handle will have a return type of the field's 3552 * value type. 3553 * If the field is {@code static}, the method handle will take no arguments. 3554 * Otherwise, its single argument will be the instance containing 3555 * the field. 3556 * If the {@code Field} object's {@code accessible} flag is not set, 3557 * access checking is performed immediately on behalf of the lookup class. 3558 * <p> 3559 * If the field is static, and 3560 * if the returned method handle is invoked, the field's class will 3561 * be initialized, if it has not already been initialized. 3562 * @param f the reflected field 3563 * @return a method handle which can load values from the reflected field 3564 * @throws IllegalAccessException if access checking fails 3565 * @throws NullPointerException if the argument is null 3566 */ 3567 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3568 return unreflectField(f, false); 3569 } 3570 3571 /** 3572 * Produces a method handle giving write access to a reflected field. 3573 * The type of the method handle will have a void return type. 3574 * If the field is {@code static}, the method handle will take a single 3575 * argument, of the field's value type, the value to be stored. 3576 * Otherwise, the two arguments will be the instance containing 3577 * the field, and the value to be stored. 3578 * If the {@code Field} object's {@code accessible} flag is not set, 3579 * access checking is performed immediately on behalf of the lookup class. 3580 * <p> 3581 * If the field is {@code final}, write access will not be 3582 * allowed and access checking will fail, except under certain 3583 * narrow circumstances documented for {@link Field#set Field.set}. 3584 * A method handle is returned only if a corresponding call to 3585 * the {@code Field} object's {@code set} method could return 3586 * normally. In particular, fields which are both {@code static} 3587 * and {@code final} may never be set. 3588 * <p> 3589 * If the field is {@code static}, and 3590 * if the returned method handle is invoked, the field's class will 3591 * be initialized, if it has not already been initialized. 3592 * @param f the reflected field 3593 * @return a method handle which can store values into the reflected field 3594 * @throws IllegalAccessException if access checking fails, 3595 * or if the field is {@code final} and write access 3596 * is not enabled on the {@code Field} object 3597 * @throws NullPointerException if the argument is null 3598 */ 3599 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3600 return unreflectField(f, true); 3601 } 3602 3603 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3604 MemberName field = new MemberName(f, isSetter); 3605 if (isSetter && field.isFinal()) { 3606 if (field.isTrustedFinalField()) { 3607 String msg = field.isStatic() ? "static final field has no write access" 3608 : "final field has no write access"; 3609 throw field.makeAccessException(msg, this); 3610 } 3611 } 3612 assert(isSetter 3613 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3614 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3615 @SuppressWarnings("deprecation") 3616 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3617 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3618 } 3619 3620 /** 3621 * Produces a VarHandle giving access to a reflected field {@code f} 3622 * of type {@code T} declared in a class of type {@code R}. 3623 * The VarHandle's variable type is {@code T}. 3624 * If the field is non-static the VarHandle has one coordinate type, 3625 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3626 * coordinate types. 3627 * <p> 3628 * Access checking is performed immediately on behalf of the lookup 3629 * class, regardless of the value of the field's {@code accessible} 3630 * flag. 3631 * <p> 3632 * If the field is static, and if the returned VarHandle is operated 3633 * on, the field's declaring class will be initialized, if it has not 3634 * already been initialized. 3635 * <p> 3636 * Certain access modes of the returned VarHandle are unsupported under 3637 * the following conditions: 3638 * <ul> 3639 * <li>if the field is declared {@code final}, then the write, atomic 3640 * update, numeric atomic update, and bitwise atomic update access 3641 * modes are unsupported. 3642 * <li>if the field type is anything other than {@code byte}, 3643 * {@code short}, {@code char}, {@code int}, {@code long}, 3644 * {@code float}, or {@code double} then numeric atomic update 3645 * access modes are unsupported. 3646 * <li>if the field type is anything other than {@code boolean}, 3647 * {@code byte}, {@code short}, {@code char}, {@code int} or 3648 * {@code long} then bitwise atomic update access modes are 3649 * unsupported. 3650 * </ul> 3651 * <p> 3652 * If the field is declared {@code volatile} then the returned VarHandle 3653 * will override access to the field (effectively ignore the 3654 * {@code volatile} declaration) in accordance to its specified 3655 * access modes. 3656 * <p> 3657 * If the field type is {@code float} or {@code double} then numeric 3658 * and atomic update access modes compare values using their bitwise 3659 * representation (see {@link Float#floatToRawIntBits} and 3660 * {@link Double#doubleToRawLongBits}, respectively). 3661 * @apiNote 3662 * Bitwise comparison of {@code float} values or {@code double} values, 3663 * as performed by the numeric and atomic update access modes, differ 3664 * from the primitive {@code ==} operator and the {@link Float#equals} 3665 * and {@link Double#equals} methods, specifically with respect to 3666 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3667 * Care should be taken when performing a compare and set or a compare 3668 * and exchange operation with such values since the operation may 3669 * unexpectedly fail. 3670 * There are many possible NaN values that are considered to be 3671 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3672 * provided by Java can distinguish between them. Operation failure can 3673 * occur if the expected or witness value is a NaN value and it is 3674 * transformed (perhaps in a platform specific manner) into another NaN 3675 * value, and thus has a different bitwise representation (see 3676 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3677 * details). 3678 * The values {@code -0.0} and {@code +0.0} have different bitwise 3679 * representations but are considered equal when using the primitive 3680 * {@code ==} operator. Operation failure can occur if, for example, a 3681 * numeric algorithm computes an expected value to be say {@code -0.0} 3682 * and previously computed the witness value to be say {@code +0.0}. 3683 * @param f the reflected field, with a field of type {@code T}, and 3684 * a declaring class of type {@code R} 3685 * @return a VarHandle giving access to non-static fields or a static 3686 * field 3687 * @throws IllegalAccessException if access checking fails 3688 * @throws NullPointerException if the argument is null 3689 * @since 9 3690 */ 3691 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3692 MemberName getField = new MemberName(f, false); 3693 MemberName putField = new MemberName(f, true); 3694 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3695 f.getDeclaringClass(), getField, putField); 3696 } 3697 3698 /** 3699 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3700 * created by this lookup object or a similar one. 3701 * Security and access checks are performed to ensure that this lookup object 3702 * is capable of reproducing the target method handle. 3703 * This means that the cracking may fail if target is a direct method handle 3704 * but was created by an unrelated lookup object. 3705 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3706 * and was created by a lookup object for a different class. 3707 * @param target a direct method handle to crack into symbolic reference components 3708 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3709 * @throws SecurityException if a security manager is present and it 3710 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3711 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3712 * @throws NullPointerException if the target is {@code null} 3713 * @see MethodHandleInfo 3714 * @since 1.8 3715 */ 3716 public MethodHandleInfo revealDirect(MethodHandle target) { 3717 if (!target.isCrackable()) { 3718 throw newIllegalArgumentException("not a direct method handle"); 3719 } 3720 MemberName member = target.internalMemberName(); 3721 Class<?> defc = member.getDeclaringClass(); 3722 byte refKind = member.getReferenceKind(); 3723 assert(MethodHandleNatives.refKindIsValid(refKind)); 3724 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3725 // Devirtualized method invocation is usually formally virtual. 3726 // To avoid creating extra MemberName objects for this common case, 3727 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3728 refKind = REF_invokeVirtual; 3729 if (refKind == REF_invokeVirtual && defc.isInterface()) 3730 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3731 refKind = REF_invokeInterface; 3732 // Check SM permissions and member access before cracking. 3733 try { 3734 checkAccess(refKind, defc, member); 3735 checkSecurityManager(defc, member); 3736 } catch (IllegalAccessException ex) { 3737 throw new IllegalArgumentException(ex); 3738 } 3739 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3740 Class<?> callerClass = target.internalCallerClass(); 3741 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3742 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3743 } 3744 // Produce the handle to the results. 3745 return new InfoFromMemberName(this, member, refKind); 3746 } 3747 3748 /// Helper methods, all package-private. 3749 3750 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3751 checkSymbolicClass(refc); // do this before attempting to resolve 3752 Objects.requireNonNull(name); 3753 Objects.requireNonNull(type); 3754 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3755 NoSuchFieldException.class); 3756 } 3757 3758 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3759 checkSymbolicClass(refc); // do this before attempting to resolve 3760 Objects.requireNonNull(type); 3761 checkMethodName(refKind, name); // implicit null-check of name 3762 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3763 NoSuchMethodException.class); 3764 } 3765 3766 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3767 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3768 Objects.requireNonNull(member.getName()); 3769 Objects.requireNonNull(member.getType()); 3770 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3771 ReflectiveOperationException.class); 3772 } 3773 3774 MemberName resolveOrNull(byte refKind, MemberName member) { 3775 // do this before attempting to resolve 3776 if (!isClassAccessible(member.getDeclaringClass())) { 3777 return null; 3778 } 3779 Objects.requireNonNull(member.getName()); 3780 Objects.requireNonNull(member.getType()); 3781 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3782 } 3783 3784 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3785 // do this before attempting to resolve 3786 if (!isClassAccessible(refc)) { 3787 return null; 3788 } 3789 Objects.requireNonNull(type); 3790 // implicit null-check of name 3791 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3792 return null; 3793 } 3794 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3795 } 3796 3797 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3798 if (!isClassAccessible(refc)) { 3799 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3800 } 3801 } 3802 3803 boolean isClassAccessible(Class<?> refc) { 3804 Objects.requireNonNull(refc); 3805 Class<?> caller = lookupClassOrNull(); 3806 Class<?> type = refc; 3807 while (type.isArray()) { 3808 type = type.getComponentType(); 3809 } 3810 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3811 } 3812 3813 /** Check name for an illegal leading "<" character. */ 3814 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3815 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3816 throw new NoSuchMethodException("illegal method name: "+name); 3817 } 3818 3819 /** 3820 * Find my trustable caller class if m is a caller sensitive method. 3821 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3822 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3823 */ 3824 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3825 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3826 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3827 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3828 } 3829 return this; 3830 } 3831 3832 /** 3833 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3834 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3835 * 3836 * @deprecated This method was originally designed to test {@code PRIVATE} access 3837 * that implies full privilege access but {@code MODULE} access has since become 3838 * independent of {@code PRIVATE} access. It is recommended to call 3839 * {@link #hasFullPrivilegeAccess()} instead. 3840 * @since 9 3841 */ 3842 @Deprecated(since="14") 3843 public boolean hasPrivateAccess() { 3844 return hasFullPrivilegeAccess(); 3845 } 3846 3847 /** 3848 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3849 * i.e. {@code PRIVATE} and {@code MODULE} access. 3850 * A {@code Lookup} object must have full privilege access in order to 3851 * access all members that are allowed to the 3852 * {@linkplain #lookupClass() lookup class}. 3853 * 3854 * @return {@code true} if this lookup has full privilege access. 3855 * @since 14 3856 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3857 */ 3858 public boolean hasFullPrivilegeAccess() { 3859 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3860 } 3861 3862 /** 3863 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3864 * for ensureInitialized, findClass or accessClass. 3865 */ 3866 void checkSecurityManager(Class<?> refc) { 3867 if (allowedModes == TRUSTED) return; 3868 3869 @SuppressWarnings("removal") 3870 SecurityManager smgr = System.getSecurityManager(); 3871 if (smgr == null) return; 3872 3873 // Step 1: 3874 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3875 if (!fullPrivilegeLookup || 3876 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3877 ReflectUtil.checkPackageAccess(refc); 3878 } 3879 3880 // Step 2b: 3881 if (!fullPrivilegeLookup) { 3882 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3883 } 3884 } 3885 3886 /** 3887 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3888 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3889 * If this lookup object has full privilege access except original access, 3890 * then the caller class is the lookupClass. 3891 * 3892 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3893 * from the same module skips the security permission check. 3894 */ 3895 void checkSecurityManager(Class<?> refc, MemberName m) { 3896 Objects.requireNonNull(refc); 3897 Objects.requireNonNull(m); 3898 3899 if (allowedModes == TRUSTED) return; 3900 3901 @SuppressWarnings("removal") 3902 SecurityManager smgr = System.getSecurityManager(); 3903 if (smgr == null) return; 3904 3905 // Step 1: 3906 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3907 if (!fullPrivilegeLookup || 3908 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3909 ReflectUtil.checkPackageAccess(refc); 3910 } 3911 3912 // Step 2a: 3913 if (m.isPublic()) return; 3914 if (!fullPrivilegeLookup) { 3915 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3916 } 3917 3918 // Step 3: 3919 Class<?> defc = m.getDeclaringClass(); 3920 if (!fullPrivilegeLookup && defc != refc) { 3921 ReflectUtil.checkPackageAccess(defc); 3922 } 3923 } 3924 3925 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3926 boolean wantStatic = (refKind == REF_invokeStatic); 3927 String message; 3928 if (m.isConstructor()) 3929 message = "expected a method, not a constructor"; 3930 else if (!m.isMethod()) 3931 message = "expected a method"; 3932 else if (wantStatic != m.isStatic()) 3933 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3934 else 3935 { checkAccess(refKind, refc, m); return; } 3936 throw m.makeAccessException(message, this); 3937 } 3938 3939 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3940 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3941 String message; 3942 if (wantStatic != m.isStatic()) 3943 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3944 else 3945 { checkAccess(refKind, refc, m); return; } 3946 throw m.makeAccessException(message, this); 3947 } 3948 3949 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3950 return Modifier.isProtected(m.getModifiers()) && 3951 refKind == REF_invokeVirtual && 3952 m.getDeclaringClass() == Object.class && 3953 m.getName().equals("clone") && 3954 refc.isArray(); 3955 } 3956 3957 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3958 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3959 assert(m.referenceKindIsConsistentWith(refKind) && 3960 MethodHandleNatives.refKindIsValid(refKind) && 3961 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3962 int allowedModes = this.allowedModes; 3963 if (allowedModes == TRUSTED) return; 3964 int mods = m.getModifiers(); 3965 if (isArrayClone(refKind, refc, m)) { 3966 // The JVM does this hack also. 3967 // (See ClassVerifier::verify_invoke_instructions 3968 // and LinkResolver::check_method_accessability.) 3969 // Because the JVM does not allow separate methods on array types, 3970 // there is no separate method for int[].clone. 3971 // All arrays simply inherit Object.clone. 3972 // But for access checking logic, we make Object.clone 3973 // (normally protected) appear to be public. 3974 // Later on, when the DirectMethodHandle is created, 3975 // its leading argument will be restricted to the 3976 // requested array type. 3977 // N.B. The return type is not adjusted, because 3978 // that is *not* the bytecode behavior. 3979 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3980 } 3981 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3982 // cannot "new" a protected ctor in a different package 3983 mods ^= Modifier.PROTECTED; 3984 } 3985 if (Modifier.isFinal(mods) && 3986 MethodHandleNatives.refKindIsSetter(refKind)) 3987 throw m.makeAccessException("unexpected set of a final field", this); 3988 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3989 if ((requestedModes & allowedModes) != 0) { 3990 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3991 mods, lookupClass(), previousLookupClass(), allowedModes)) 3992 return; 3993 } else { 3994 // Protected members can also be checked as if they were package-private. 3995 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3996 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3997 return; 3998 } 3999 throw m.makeAccessException(accessFailedMessage(refc, m), this); 4000 } 4001 4002 String accessFailedMessage(Class<?> refc, MemberName m) { 4003 Class<?> defc = m.getDeclaringClass(); 4004 int mods = m.getModifiers(); 4005 // check the class first: 4006 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 4007 (defc == refc || 4008 Modifier.isPublic(refc.getModifiers()))); 4009 if (!classOK && (allowedModes & PACKAGE) != 0) { 4010 // ignore previous lookup class to check if default package access 4011 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 4012 (defc == refc || 4013 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 4014 } 4015 if (!classOK) 4016 return "class is not public"; 4017 if (Modifier.isPublic(mods)) 4018 return "access to public member failed"; // (how?, module not readable?) 4019 if (Modifier.isPrivate(mods)) 4020 return "member is private"; 4021 if (Modifier.isProtected(mods)) 4022 return "member is protected"; 4023 return "member is private to package"; 4024 } 4025 4026 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 4027 int allowedModes = this.allowedModes; 4028 if (allowedModes == TRUSTED) return; 4029 if ((lookupModes() & PRIVATE) == 0 4030 || (specialCaller != lookupClass() 4031 // ensure non-abstract methods in superinterfaces can be special-invoked 4032 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 4033 throw new MemberName(specialCaller). 4034 makeAccessException("no private access for invokespecial", this); 4035 } 4036 4037 private boolean restrictProtectedReceiver(MemberName method) { 4038 // The accessing class only has the right to use a protected member 4039 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 4040 if (!method.isProtected() || method.isStatic() 4041 || allowedModes == TRUSTED 4042 || method.getDeclaringClass() == lookupClass() 4043 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 4044 return false; 4045 return true; 4046 } 4047 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 4048 assert(!method.isStatic()); 4049 // receiver type of mh is too wide; narrow to caller 4050 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 4051 throw method.makeAccessException("caller class must be a subclass below the method", caller); 4052 } 4053 MethodType rawType = mh.type(); 4054 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 4055 MethodType narrowType = rawType.changeParameterType(0, caller); 4056 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 4057 assert(mh.viewAsTypeChecks(narrowType, true)); 4058 return mh.copyWith(narrowType, mh.form); 4059 } 4060 4061 /** Check access and get the requested method. */ 4062 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4063 final boolean doRestrict = true; 4064 final boolean checkSecurity = true; 4065 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4066 } 4067 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 4068 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4069 final boolean doRestrict = false; 4070 final boolean checkSecurity = true; 4071 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 4072 } 4073 /** Check access and get the requested method, eliding security manager checks. */ 4074 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4075 final boolean doRestrict = true; 4076 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4077 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4078 } 4079 /** Common code for all methods; do not call directly except from immediately above. */ 4080 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 4081 boolean checkSecurity, 4082 boolean doRestrict, 4083 Lookup boundCaller) throws IllegalAccessException { 4084 checkMethod(refKind, refc, method); 4085 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4086 if (checkSecurity) 4087 checkSecurityManager(refc, method); 4088 assert(!method.isMethodHandleInvoke()); 4089 4090 if (refKind == REF_invokeSpecial && 4091 refc != lookupClass() && 4092 !refc.isInterface() && !lookupClass().isInterface() && 4093 refc != lookupClass().getSuperclass() && 4094 refc.isAssignableFrom(lookupClass())) { 4095 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 4096 4097 // Per JVMS 6.5, desc. of invokespecial instruction: 4098 // If the method is in a superclass of the LC, 4099 // and if our original search was above LC.super, 4100 // repeat the search (symbolic lookup) from LC.super 4101 // and continue with the direct superclass of that class, 4102 // and so forth, until a match is found or no further superclasses exist. 4103 // FIXME: MemberName.resolve should handle this instead. 4104 Class<?> refcAsSuper = lookupClass(); 4105 MemberName m2; 4106 do { 4107 refcAsSuper = refcAsSuper.getSuperclass(); 4108 m2 = new MemberName(refcAsSuper, 4109 method.getName(), 4110 method.getMethodType(), 4111 REF_invokeSpecial); 4112 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4113 } while (m2 == null && // no method is found yet 4114 refc != refcAsSuper); // search up to refc 4115 if (m2 == null) throw new InternalError(method.toString()); 4116 method = m2; 4117 refc = refcAsSuper; 4118 // redo basic checks 4119 checkMethod(refKind, refc, method); 4120 } 4121 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4122 MethodHandle mh = dmh; 4123 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4124 if ((doRestrict && refKind == REF_invokeSpecial) || 4125 (MethodHandleNatives.refKindHasReceiver(refKind) && 4126 restrictProtectedReceiver(method) && 4127 // All arrays simply inherit the protected Object.clone method. 4128 // The leading argument is already restricted to the requested 4129 // array type (not the lookup class). 4130 !isArrayClone(refKind, refc, method))) { 4131 mh = restrictReceiver(method, dmh, lookupClass()); 4132 } 4133 mh = maybeBindCaller(method, mh, boundCaller); 4134 mh = mh.setVarargs(method); 4135 return mh; 4136 } 4137 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4138 throws IllegalAccessException { 4139 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4140 return mh; 4141 4142 // boundCaller must have full privilege access. 4143 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4144 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4145 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4146 4147 assert boundCaller.hasFullPrivilegeAccess(); 4148 4149 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4150 // Note: caller will apply varargs after this step happens. 4151 return cbmh; 4152 } 4153 4154 /** Check access and get the requested field. */ 4155 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4156 final boolean checkSecurity = true; 4157 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4158 } 4159 /** Check access and get the requested field, eliding security manager checks. */ 4160 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4161 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4162 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4163 } 4164 /** Common code for all fields; do not call directly except from immediately above. */ 4165 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4166 boolean checkSecurity) throws IllegalAccessException { 4167 checkField(refKind, refc, field); 4168 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4169 if (checkSecurity) 4170 checkSecurityManager(refc, field); 4171 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4172 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4173 restrictProtectedReceiver(field)); 4174 if (doRestrict) 4175 return restrictReceiver(field, dmh, lookupClass()); 4176 return dmh; 4177 } 4178 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4179 Class<?> refc, MemberName getField, MemberName putField) 4180 throws IllegalAccessException { 4181 final boolean checkSecurity = true; 4182 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4183 } 4184 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4185 Class<?> refc, MemberName getField, MemberName putField) 4186 throws IllegalAccessException { 4187 final boolean checkSecurity = false; 4188 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4189 } 4190 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4191 Class<?> refc, MemberName getField, MemberName putField, 4192 boolean checkSecurity) throws IllegalAccessException { 4193 assert getField.isStatic() == putField.isStatic(); 4194 assert getField.isGetter() && putField.isSetter(); 4195 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4196 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4197 4198 checkField(getRefKind, refc, getField); 4199 if (checkSecurity) 4200 checkSecurityManager(refc, getField); 4201 4202 if (!putField.isFinal()) { 4203 // A VarHandle does not support updates to final fields, any 4204 // such VarHandle to a final field will be read-only and 4205 // therefore the following write-based accessibility checks are 4206 // only required for non-final fields 4207 checkField(putRefKind, refc, putField); 4208 if (checkSecurity) 4209 checkSecurityManager(refc, putField); 4210 } 4211 4212 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4213 restrictProtectedReceiver(getField)); 4214 if (doRestrict) { 4215 assert !getField.isStatic(); 4216 // receiver type of VarHandle is too wide; narrow to caller 4217 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4218 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4219 } 4220 refc = lookupClass(); 4221 } 4222 return VarHandles.makeFieldHandle(getField, refc, 4223 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4224 } 4225 /** Check access and get the requested constructor. */ 4226 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4227 final boolean checkSecurity = true; 4228 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4229 } 4230 /** Check access and get the requested constructor, eliding security manager checks. */ 4231 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4232 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4233 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4234 } 4235 /** Common code for all constructors; do not call directly except from immediately above. */ 4236 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4237 boolean checkSecurity) throws IllegalAccessException { 4238 assert(ctor.isConstructor()); 4239 checkAccess(REF_newInvokeSpecial, refc, ctor); 4240 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4241 if (checkSecurity) 4242 checkSecurityManager(refc, ctor); 4243 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4244 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4245 } 4246 4247 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4248 */ 4249 /*non-public*/ 4250 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4251 throws ReflectiveOperationException { 4252 if (!(type instanceof Class || type instanceof MethodType)) 4253 throw new InternalError("unresolved MemberName"); 4254 MemberName member = new MemberName(refKind, defc, name, type); 4255 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4256 if (mh != null) { 4257 checkSymbolicClass(defc); 4258 return mh; 4259 } 4260 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4261 // Treat MethodHandle.invoke and invokeExact specially. 4262 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4263 if (mh != null) { 4264 return mh; 4265 } 4266 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4267 // Treat signature-polymorphic methods on VarHandle specially. 4268 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4269 if (mh != null) { 4270 return mh; 4271 } 4272 } 4273 MemberName resolved = resolveOrFail(refKind, member); 4274 mh = getDirectMethodForConstant(refKind, defc, resolved); 4275 if (mh instanceof DirectMethodHandle dmh 4276 && canBeCached(refKind, defc, resolved)) { 4277 MemberName key = mh.internalMemberName(); 4278 if (key != null) { 4279 key = key.asNormalOriginal(); 4280 } 4281 if (member.equals(key)) { // better safe than sorry 4282 LOOKASIDE_TABLE.put(key, dmh); 4283 } 4284 } 4285 return mh; 4286 } 4287 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4288 if (refKind == REF_invokeSpecial) { 4289 return false; 4290 } 4291 if (!Modifier.isPublic(defc.getModifiers()) || 4292 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4293 !member.isPublic() || 4294 member.isCallerSensitive()) { 4295 return false; 4296 } 4297 ClassLoader loader = defc.getClassLoader(); 4298 if (loader != null) { 4299 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4300 boolean found = false; 4301 while (sysl != null) { 4302 if (loader == sysl) { found = true; break; } 4303 sysl = sysl.getParent(); 4304 } 4305 if (!found) { 4306 return false; 4307 } 4308 } 4309 try { 4310 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4311 new MemberName(refKind, defc, member.getName(), member.getType())); 4312 if (resolved2 == null) { 4313 return false; 4314 } 4315 checkSecurityManager(defc, resolved2); 4316 } catch (SecurityException ex) { 4317 return false; 4318 } 4319 return true; 4320 } 4321 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4322 throws ReflectiveOperationException { 4323 if (MethodHandleNatives.refKindIsField(refKind)) { 4324 return getDirectFieldNoSecurityManager(refKind, defc, member); 4325 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4326 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4327 } else if (refKind == REF_newInvokeSpecial) { 4328 return getDirectConstructorNoSecurityManager(defc, member); 4329 } 4330 // oops 4331 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4332 } 4333 4334 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4335 } 4336 4337 /** 4338 * Produces a method handle constructing arrays of a desired type, 4339 * as if by the {@code anewarray} bytecode. 4340 * The return type of the method handle will be the array type. 4341 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4342 * 4343 * <p> If the returned method handle is invoked with a negative 4344 * array size, a {@code NegativeArraySizeException} will be thrown. 4345 * 4346 * @param arrayClass an array type 4347 * @return a method handle which can create arrays of the given type 4348 * @throws NullPointerException if the argument is {@code null} 4349 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4350 * @see java.lang.reflect.Array#newInstance(Class, int) 4351 * @jvms 6.5 {@code anewarray} Instruction 4352 * @since 9 4353 */ 4354 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4355 if (!arrayClass.isArray()) { 4356 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4357 } 4358 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4359 bindTo(arrayClass.getComponentType()); 4360 return ani.asType(ani.type().changeReturnType(arrayClass)); 4361 } 4362 4363 /** 4364 * Produces a method handle returning the length of an array, 4365 * as if by the {@code arraylength} bytecode. 4366 * The type of the method handle will have {@code int} as return type, 4367 * and its sole argument will be the array type. 4368 * 4369 * <p> If the returned method handle is invoked with a {@code null} 4370 * array reference, a {@code NullPointerException} will be thrown. 4371 * 4372 * @param arrayClass an array type 4373 * @return a method handle which can retrieve the length of an array of the given array type 4374 * @throws NullPointerException if the argument is {@code null} 4375 * @throws IllegalArgumentException if arrayClass is not an array type 4376 * @jvms 6.5 {@code arraylength} Instruction 4377 * @since 9 4378 */ 4379 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4380 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4381 } 4382 4383 /** 4384 * Produces a method handle giving read access to elements of an array, 4385 * as if by the {@code aaload} bytecode. 4386 * The type of the method handle will have a return type of the array's 4387 * element type. Its first argument will be the array type, 4388 * and the second will be {@code int}. 4389 * 4390 * <p> When the returned method handle is invoked, 4391 * the array reference and array index are checked. 4392 * A {@code NullPointerException} will be thrown if the array reference 4393 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4394 * thrown if the index is negative or if it is greater than or equal to 4395 * the length of the array. 4396 * 4397 * @param arrayClass an array type 4398 * @return a method handle which can load values from the given array type 4399 * @throws NullPointerException if the argument is null 4400 * @throws IllegalArgumentException if arrayClass is not an array type 4401 * @jvms 6.5 {@code aaload} Instruction 4402 */ 4403 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4404 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4405 } 4406 4407 /** 4408 * Produces a method handle giving write access to elements of an array, 4409 * as if by the {@code astore} bytecode. 4410 * The type of the method handle will have a void return type. 4411 * Its last argument will be the array's element type. 4412 * The first and second arguments will be the array type and int. 4413 * 4414 * <p> When the returned method handle is invoked, 4415 * the array reference and array index are checked. 4416 * A {@code NullPointerException} will be thrown if the array reference 4417 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4418 * thrown if the index is negative or if it is greater than or equal to 4419 * the length of the array. 4420 * 4421 * @param arrayClass the class of an array 4422 * @return a method handle which can store values into the array type 4423 * @throws NullPointerException if the argument is null 4424 * @throws IllegalArgumentException if arrayClass is not an array type 4425 * @jvms 6.5 {@code aastore} Instruction 4426 */ 4427 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4428 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4429 } 4430 4431 /** 4432 * Produces a VarHandle giving access to elements of an array of type 4433 * {@code arrayClass}. The VarHandle's variable type is the component type 4434 * of {@code arrayClass} and the list of coordinate types is 4435 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4436 * corresponds to an argument that is an index into an array. 4437 * <p> 4438 * Certain access modes of the returned VarHandle are unsupported under 4439 * the following conditions: 4440 * <ul> 4441 * <li>if the component type is anything other than {@code byte}, 4442 * {@code short}, {@code char}, {@code int}, {@code long}, 4443 * {@code float}, or {@code double} then numeric atomic update access 4444 * modes are unsupported. 4445 * <li>if the component type is anything other than {@code boolean}, 4446 * {@code byte}, {@code short}, {@code char}, {@code int} or 4447 * {@code long} then bitwise atomic update access modes are 4448 * unsupported. 4449 * </ul> 4450 * <p> 4451 * If the component type is {@code float} or {@code double} then numeric 4452 * and atomic update access modes compare values using their bitwise 4453 * representation (see {@link Float#floatToRawIntBits} and 4454 * {@link Double#doubleToRawLongBits}, respectively). 4455 * 4456 * <p> When the returned {@code VarHandle} is invoked, 4457 * the array reference and array index are checked. 4458 * A {@code NullPointerException} will be thrown if the array reference 4459 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4460 * thrown if the index is negative or if it is greater than or equal to 4461 * the length of the array. 4462 * 4463 * @apiNote 4464 * Bitwise comparison of {@code float} values or {@code double} values, 4465 * as performed by the numeric and atomic update access modes, differ 4466 * from the primitive {@code ==} operator and the {@link Float#equals} 4467 * and {@link Double#equals} methods, specifically with respect to 4468 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4469 * Care should be taken when performing a compare and set or a compare 4470 * and exchange operation with such values since the operation may 4471 * unexpectedly fail. 4472 * There are many possible NaN values that are considered to be 4473 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4474 * provided by Java can distinguish between them. Operation failure can 4475 * occur if the expected or witness value is a NaN value and it is 4476 * transformed (perhaps in a platform specific manner) into another NaN 4477 * value, and thus has a different bitwise representation (see 4478 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4479 * details). 4480 * The values {@code -0.0} and {@code +0.0} have different bitwise 4481 * representations but are considered equal when using the primitive 4482 * {@code ==} operator. Operation failure can occur if, for example, a 4483 * numeric algorithm computes an expected value to be say {@code -0.0} 4484 * and previously computed the witness value to be say {@code +0.0}. 4485 * @param arrayClass the class of an array, of type {@code T[]} 4486 * @return a VarHandle giving access to elements of an array 4487 * @throws NullPointerException if the arrayClass is null 4488 * @throws IllegalArgumentException if arrayClass is not an array type 4489 * @since 9 4490 */ 4491 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4492 return VarHandles.makeArrayElementHandle(arrayClass); 4493 } 4494 4495 /** 4496 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4497 * viewed as if it were a different primitive array type, such as 4498 * {@code int[]} or {@code long[]}. 4499 * The VarHandle's variable type is the component type of 4500 * {@code viewArrayClass} and the list of coordinate types is 4501 * {@code (byte[], int)}, where the {@code int} coordinate type 4502 * corresponds to an argument that is an index into a {@code byte[]} array. 4503 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4504 * array, composing bytes to or from a value of the component type of 4505 * {@code viewArrayClass} according to the given endianness. 4506 * <p> 4507 * The supported component types (variables types) are {@code short}, 4508 * {@code char}, {@code int}, {@code long}, {@code float} and 4509 * {@code double}. 4510 * <p> 4511 * Access of bytes at a given index will result in an 4512 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4513 * or greater than the {@code byte[]} array length minus the size (in bytes) 4514 * of {@code T}. 4515 * <p> 4516 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4517 * access modes are supported by the returned var handle. For all other access modes, an 4518 * {@link UnsupportedOperationException} will be thrown. 4519 * 4520 * @apiNote if access modes other than plain access are required, clients should 4521 * consider using off-heap memory through 4522 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4523 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4524 * or memory segments backed by a 4525 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4526 * for which stronger alignment guarantees can be made. 4527 * 4528 * @param viewArrayClass the view array class, with a component type of 4529 * type {@code T} 4530 * @param byteOrder the endianness of the view array elements, as 4531 * stored in the underlying {@code byte} array 4532 * @return a VarHandle giving access to elements of a {@code byte[]} array 4533 * viewed as if elements corresponding to the components type of the view 4534 * array class 4535 * @throws NullPointerException if viewArrayClass or byteOrder is null 4536 * @throws IllegalArgumentException if viewArrayClass is not an array type 4537 * @throws UnsupportedOperationException if the component type of 4538 * viewArrayClass is not supported as a variable type 4539 * @since 9 4540 */ 4541 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4542 ByteOrder byteOrder) throws IllegalArgumentException { 4543 Objects.requireNonNull(byteOrder); 4544 return VarHandles.byteArrayViewHandle(viewArrayClass, 4545 byteOrder == ByteOrder.BIG_ENDIAN); 4546 } 4547 4548 /** 4549 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4550 * viewed as if it were an array of elements of a different primitive 4551 * component type to that of {@code byte}, such as {@code int[]} or 4552 * {@code long[]}. 4553 * The VarHandle's variable type is the component type of 4554 * {@code viewArrayClass} and the list of coordinate types is 4555 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4556 * corresponds to an argument that is an index into a {@code byte[]} array. 4557 * The returned VarHandle accesses bytes at an index in a 4558 * {@code ByteBuffer}, composing bytes to or from a value of the component 4559 * type of {@code viewArrayClass} according to the given endianness. 4560 * <p> 4561 * The supported component types (variables types) are {@code short}, 4562 * {@code char}, {@code int}, {@code long}, {@code float} and 4563 * {@code double}. 4564 * <p> 4565 * Access will result in a {@code ReadOnlyBufferException} for anything 4566 * other than the read access modes if the {@code ByteBuffer} is read-only. 4567 * <p> 4568 * Access of bytes at a given index will result in an 4569 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4570 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4571 * {@code T}. 4572 * <p> 4573 * For heap byte buffers, access is always unaligned. As a result, only the plain 4574 * {@linkplain VarHandle.AccessMode#GET get} 4575 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4576 * returned var handle. For all other access modes, an {@link IllegalStateException} 4577 * will be thrown. 4578 * <p> 4579 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4580 * with respect to the underlying memory address, {@code A} say, associated 4581 * with the {@code ByteBuffer} and index. 4582 * If access is misaligned then access for anything other than the 4583 * {@code get} and {@code set} access modes will result in an 4584 * {@code IllegalStateException}. In such cases atomic access is only 4585 * guaranteed with respect to the largest power of two that divides the GCD 4586 * of {@code A} and the size (in bytes) of {@code T}. 4587 * If access is aligned then following access modes are supported and are 4588 * guaranteed to support atomic access: 4589 * <ul> 4590 * <li>read write access modes for all {@code T}, with the exception of 4591 * access modes {@code get} and {@code set} for {@code long} and 4592 * {@code double} on 32-bit platforms. 4593 * <li>atomic update access modes for {@code int}, {@code long}, 4594 * {@code float} or {@code double}. 4595 * (Future major platform releases of the JDK may support additional 4596 * types for certain currently unsupported access modes.) 4597 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4598 * (Future major platform releases of the JDK may support additional 4599 * numeric types for certain currently unsupported access modes.) 4600 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4601 * (Future major platform releases of the JDK may support additional 4602 * numeric types for certain currently unsupported access modes.) 4603 * </ul> 4604 * <p> 4605 * Misaligned access, and therefore atomicity guarantees, may be determined 4606 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4607 * {@code index}, {@code T} and its corresponding boxed type, 4608 * {@code T_BOX}, as follows: 4609 * <pre>{@code 4610 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4611 * ByteBuffer bb = ... 4612 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4613 * boolean isMisaligned = misalignedAtIndex != 0; 4614 * }</pre> 4615 * <p> 4616 * If the variable type is {@code float} or {@code double} then atomic 4617 * update access modes compare values using their bitwise representation 4618 * (see {@link Float#floatToRawIntBits} and 4619 * {@link Double#doubleToRawLongBits}, respectively). 4620 * @param viewArrayClass the view array class, with a component type of 4621 * type {@code T} 4622 * @param byteOrder the endianness of the view array elements, as 4623 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4624 * endianness of a {@code ByteBuffer}) 4625 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4626 * viewed as if elements corresponding to the components type of the view 4627 * array class 4628 * @throws NullPointerException if viewArrayClass or byteOrder is null 4629 * @throws IllegalArgumentException if viewArrayClass is not an array type 4630 * @throws UnsupportedOperationException if the component type of 4631 * viewArrayClass is not supported as a variable type 4632 * @since 9 4633 */ 4634 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4635 ByteOrder byteOrder) throws IllegalArgumentException { 4636 Objects.requireNonNull(byteOrder); 4637 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4638 byteOrder == ByteOrder.BIG_ENDIAN); 4639 } 4640 4641 4642 /// method handle invocation (reflective style) 4643 4644 /** 4645 * Produces a method handle which will invoke any method handle of the 4646 * given {@code type}, with a given number of trailing arguments replaced by 4647 * a single trailing {@code Object[]} array. 4648 * The resulting invoker will be a method handle with the following 4649 * arguments: 4650 * <ul> 4651 * <li>a single {@code MethodHandle} target 4652 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4653 * <li>an {@code Object[]} array containing trailing arguments 4654 * </ul> 4655 * <p> 4656 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4657 * the indicated {@code type}. 4658 * That is, if the target is exactly of the given {@code type}, it will behave 4659 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4660 * is used to convert the target to the required {@code type}. 4661 * <p> 4662 * The type of the returned invoker will not be the given {@code type}, but rather 4663 * will have all parameters except the first {@code leadingArgCount} 4664 * replaced by a single array of type {@code Object[]}, which will be 4665 * the final parameter. 4666 * <p> 4667 * Before invoking its target, the invoker will spread the final array, apply 4668 * reference casts as necessary, and unbox and widen primitive arguments. 4669 * If, when the invoker is called, the supplied array argument does 4670 * not have the correct number of elements, the invoker will throw 4671 * an {@link IllegalArgumentException} instead of invoking the target. 4672 * <p> 4673 * This method is equivalent to the following code (though it may be more efficient): 4674 * {@snippet lang="java" : 4675 MethodHandle invoker = MethodHandles.invoker(type); 4676 int spreadArgCount = type.parameterCount() - leadingArgCount; 4677 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4678 return invoker; 4679 * } 4680 * This method throws no reflective or security exceptions. 4681 * @param type the desired target type 4682 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4683 * @return a method handle suitable for invoking any method handle of the given type 4684 * @throws NullPointerException if {@code type} is null 4685 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4686 * the range from 0 to {@code type.parameterCount()} inclusive, 4687 * or if the resulting method handle's type would have 4688 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4689 */ 4690 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4691 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4692 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4693 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4694 return type.invokers().spreadInvoker(leadingArgCount); 4695 } 4696 4697 /** 4698 * Produces a special <em>invoker method handle</em> which can be used to 4699 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4700 * The resulting invoker will have a type which is 4701 * exactly equal to the desired type, except that it will accept 4702 * an additional leading argument of type {@code MethodHandle}. 4703 * <p> 4704 * This method is equivalent to the following code (though it may be more efficient): 4705 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4706 * 4707 * <p style="font-size:smaller;"> 4708 * <em>Discussion:</em> 4709 * Invoker method handles can be useful when working with variable method handles 4710 * of unknown types. 4711 * For example, to emulate an {@code invokeExact} call to a variable method 4712 * handle {@code M}, extract its type {@code T}, 4713 * look up the invoker method {@code X} for {@code T}, 4714 * and call the invoker method, as {@code X.invoke(T, A...)}. 4715 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4716 * is unknown.) 4717 * If spreading, collecting, or other argument transformations are required, 4718 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4719 * method handle values, as long as they are compatible with the type of {@code X}. 4720 * <p style="font-size:smaller;"> 4721 * <em>(Note: The invoker method is not available via the Core Reflection API. 4722 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4723 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4724 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4725 * <p> 4726 * This method throws no reflective or security exceptions. 4727 * @param type the desired target type 4728 * @return a method handle suitable for invoking any method handle of the given type 4729 * @throws IllegalArgumentException if the resulting method handle's type would have 4730 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4731 */ 4732 public static MethodHandle exactInvoker(MethodType type) { 4733 return type.invokers().exactInvoker(); 4734 } 4735 4736 /** 4737 * Produces a special <em>invoker method handle</em> which can be used to 4738 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4739 * The resulting invoker will have a type which is 4740 * exactly equal to the desired type, except that it will accept 4741 * an additional leading argument of type {@code MethodHandle}. 4742 * <p> 4743 * Before invoking its target, if the target differs from the expected type, 4744 * the invoker will apply reference casts as 4745 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4746 * Similarly, the return value will be converted as necessary. 4747 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4748 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4749 * <p> 4750 * This method is equivalent to the following code (though it may be more efficient): 4751 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4752 * <p style="font-size:smaller;"> 4753 * <em>Discussion:</em> 4754 * A {@linkplain MethodType#genericMethodType general method type} is one which 4755 * mentions only {@code Object} arguments and return values. 4756 * An invoker for such a type is capable of calling any method handle 4757 * of the same arity as the general type. 4758 * <p style="font-size:smaller;"> 4759 * <em>(Note: The invoker method is not available via the Core Reflection API. 4760 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4761 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4762 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4763 * <p> 4764 * This method throws no reflective or security exceptions. 4765 * @param type the desired target type 4766 * @return a method handle suitable for invoking any method handle convertible to the given type 4767 * @throws IllegalArgumentException if the resulting method handle's type would have 4768 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4769 */ 4770 public static MethodHandle invoker(MethodType type) { 4771 return type.invokers().genericInvoker(); 4772 } 4773 4774 /** 4775 * Produces a special <em>invoker method handle</em> which can be used to 4776 * invoke a signature-polymorphic access mode method on any VarHandle whose 4777 * associated access mode type is compatible with the given type. 4778 * The resulting invoker will have a type which is exactly equal to the 4779 * desired given type, except that it will accept an additional leading 4780 * argument of type {@code VarHandle}. 4781 * 4782 * @param accessMode the VarHandle access mode 4783 * @param type the desired target type 4784 * @return a method handle suitable for invoking an access mode method of 4785 * any VarHandle whose access mode type is of the given type. 4786 * @since 9 4787 */ 4788 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4789 return type.invokers().varHandleMethodExactInvoker(accessMode); 4790 } 4791 4792 /** 4793 * Produces a special <em>invoker method handle</em> which can be used to 4794 * invoke a signature-polymorphic access mode method on any VarHandle whose 4795 * associated access mode type is compatible with the given type. 4796 * The resulting invoker will have a type which is exactly equal to the 4797 * desired given type, except that it will accept an additional leading 4798 * argument of type {@code VarHandle}. 4799 * <p> 4800 * Before invoking its target, if the access mode type differs from the 4801 * desired given type, the invoker will apply reference casts as necessary 4802 * and box, unbox, or widen primitive values, as if by 4803 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4804 * converted as necessary. 4805 * <p> 4806 * This method is equivalent to the following code (though it may be more 4807 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4808 * 4809 * @param accessMode the VarHandle access mode 4810 * @param type the desired target type 4811 * @return a method handle suitable for invoking an access mode method of 4812 * any VarHandle whose access mode type is convertible to the given 4813 * type. 4814 * @since 9 4815 */ 4816 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4817 return type.invokers().varHandleMethodInvoker(accessMode); 4818 } 4819 4820 /*non-public*/ 4821 static MethodHandle basicInvoker(MethodType type) { 4822 return type.invokers().basicInvoker(); 4823 } 4824 4825 /// method handle modification (creation from other method handles) 4826 4827 /** 4828 * Produces a method handle which adapts the type of the 4829 * given method handle to a new type by pairwise argument and return type conversion. 4830 * The original type and new type must have the same number of arguments. 4831 * The resulting method handle is guaranteed to report a type 4832 * which is equal to the desired new type. 4833 * <p> 4834 * If the original type and new type are equal, returns target. 4835 * <p> 4836 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4837 * and some additional conversions are also applied if those conversions fail. 4838 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4839 * if possible, before or instead of any conversions done by {@code asType}: 4840 * <ul> 4841 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4842 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4843 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4844 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4845 * the boolean is converted to a byte value, 1 for true, 0 for false. 4846 * (This treatment follows the usage of the bytecode verifier.) 4847 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4848 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4849 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4850 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4851 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4852 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4853 * widening and/or narrowing.) 4854 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4855 * conversion will be applied at runtime, possibly followed 4856 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4857 * possibly followed by a conversion from byte to boolean by testing 4858 * the low-order bit. 4859 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4860 * and if the reference is null at runtime, a zero value is introduced. 4861 * </ul> 4862 * @param target the method handle to invoke after arguments are retyped 4863 * @param newType the expected type of the new method handle 4864 * @return a method handle which delegates to the target after performing 4865 * any necessary argument conversions, and arranges for any 4866 * necessary return value conversions 4867 * @throws NullPointerException if either argument is null 4868 * @throws WrongMethodTypeException if the conversion cannot be made 4869 * @see MethodHandle#asType 4870 */ 4871 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4872 explicitCastArgumentsChecks(target, newType); 4873 // use the asTypeCache when possible: 4874 MethodType oldType = target.type(); 4875 if (oldType == newType) return target; 4876 if (oldType.explicitCastEquivalentToAsType(newType)) { 4877 return target.asFixedArity().asType(newType); 4878 } 4879 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4880 } 4881 4882 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4883 if (target.type().parameterCount() != newType.parameterCount()) { 4884 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4885 } 4886 } 4887 4888 /** 4889 * Produces a method handle which adapts the calling sequence of the 4890 * given method handle to a new type, by reordering the arguments. 4891 * The resulting method handle is guaranteed to report a type 4892 * which is equal to the desired new type. 4893 * <p> 4894 * The given array controls the reordering. 4895 * Call {@code #I} the number of incoming parameters (the value 4896 * {@code newType.parameterCount()}, and call {@code #O} the number 4897 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4898 * Then the length of the reordering array must be {@code #O}, 4899 * and each element must be a non-negative number less than {@code #I}. 4900 * For every {@code N} less than {@code #O}, the {@code N}-th 4901 * outgoing argument will be taken from the {@code I}-th incoming 4902 * argument, where {@code I} is {@code reorder[N]}. 4903 * <p> 4904 * No argument or return value conversions are applied. 4905 * The type of each incoming argument, as determined by {@code newType}, 4906 * must be identical to the type of the corresponding outgoing parameter 4907 * or parameters in the target method handle. 4908 * The return type of {@code newType} must be identical to the return 4909 * type of the original target. 4910 * <p> 4911 * The reordering array need not specify an actual permutation. 4912 * An incoming argument will be duplicated if its index appears 4913 * more than once in the array, and an incoming argument will be dropped 4914 * if its index does not appear in the array. 4915 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4916 * incoming arguments which are not mentioned in the reordering array 4917 * may be of any type, as determined only by {@code newType}. 4918 * {@snippet lang="java" : 4919 import static java.lang.invoke.MethodHandles.*; 4920 import static java.lang.invoke.MethodType.*; 4921 ... 4922 MethodType intfn1 = methodType(int.class, int.class); 4923 MethodType intfn2 = methodType(int.class, int.class, int.class); 4924 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4925 assert(sub.type().equals(intfn2)); 4926 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4927 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4928 assert((int)rsub.invokeExact(1, 100) == 99); 4929 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4930 assert(add.type().equals(intfn2)); 4931 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4932 assert(twice.type().equals(intfn1)); 4933 assert((int)twice.invokeExact(21) == 42); 4934 * } 4935 * <p> 4936 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4937 * variable-arity method handle}, even if the original target method handle was. 4938 * @param target the method handle to invoke after arguments are reordered 4939 * @param newType the expected type of the new method handle 4940 * @param reorder an index array which controls the reordering 4941 * @return a method handle which delegates to the target after it 4942 * drops unused arguments and moves and/or duplicates the other arguments 4943 * @throws NullPointerException if any argument is null 4944 * @throws IllegalArgumentException if the index array length is not equal to 4945 * the arity of the target, or if any index array element 4946 * not a valid index for a parameter of {@code newType}, 4947 * or if two corresponding parameter types in 4948 * {@code target.type()} and {@code newType} are not identical, 4949 */ 4950 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4951 reorder = reorder.clone(); // get a private copy 4952 MethodType oldType = target.type(); 4953 permuteArgumentChecks(reorder, newType, oldType); 4954 // first detect dropped arguments and handle them separately 4955 int[] originalReorder = reorder; 4956 BoundMethodHandle result = target.rebind(); 4957 LambdaForm form = result.form; 4958 int newArity = newType.parameterCount(); 4959 // Normalize the reordering into a real permutation, 4960 // by removing duplicates and adding dropped elements. 4961 // This somewhat improves lambda form caching, as well 4962 // as simplifying the transform by breaking it up into steps. 4963 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4964 if (ddIdx > 0) { 4965 // We found a duplicated entry at reorder[ddIdx]. 4966 // Example: (x,y,z)->asList(x,y,z) 4967 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4968 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4969 // The starred element corresponds to the argument 4970 // deleted by the dupArgumentForm transform. 4971 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4972 boolean killFirst = false; 4973 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4974 // Set killFirst if the dup is larger than an intervening position. 4975 // This will remove at least one inversion from the permutation. 4976 if (dupVal > val) killFirst = true; 4977 } 4978 if (!killFirst) { 4979 srcPos = dstPos; 4980 dstPos = ddIdx; 4981 } 4982 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4983 assert (reorder[srcPos] == reorder[dstPos]); 4984 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4985 // contract the reordering by removing the element at dstPos 4986 int tailPos = dstPos + 1; 4987 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4988 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4989 } else { 4990 int dropVal = ~ddIdx, insPos = 0; 4991 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4992 // Find first element of reorder larger than dropVal. 4993 // This is where we will insert the dropVal. 4994 insPos += 1; 4995 } 4996 Class<?> ptype = newType.parameterType(dropVal); 4997 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4998 oldType = oldType.insertParameterTypes(insPos, ptype); 4999 // expand the reordering by inserting an element at insPos 5000 int tailPos = insPos + 1; 5001 reorder = Arrays.copyOf(reorder, reorder.length + 1); 5002 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 5003 reorder[insPos] = dropVal; 5004 } 5005 assert (permuteArgumentChecks(reorder, newType, oldType)); 5006 } 5007 assert (reorder.length == newArity); // a perfect permutation 5008 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 5009 form = form.editor().permuteArgumentsForm(1, reorder); 5010 if (newType == result.type() && form == result.internalForm()) 5011 return result; 5012 return result.copyWith(newType, form); 5013 } 5014 5015 /** 5016 * Return an indication of any duplicate or omission in reorder. 5017 * If the reorder contains a duplicate entry, return the index of the second occurrence. 5018 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 5019 * Otherwise, return zero. 5020 * If an element not in [0..newArity-1] is encountered, return reorder.length. 5021 */ 5022 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 5023 final int BIT_LIMIT = 63; // max number of bits in bit mask 5024 if (newArity < BIT_LIMIT) { 5025 long mask = 0; 5026 for (int i = 0; i < reorder.length; i++) { 5027 int arg = reorder[i]; 5028 if (arg >= newArity) { 5029 return reorder.length; 5030 } 5031 long bit = 1L << arg; 5032 if ((mask & bit) != 0) { 5033 return i; // >0 indicates a dup 5034 } 5035 mask |= bit; 5036 } 5037 if (mask == (1L << newArity) - 1) { 5038 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 5039 return 0; 5040 } 5041 // find first zero 5042 long zeroBit = Long.lowestOneBit(~mask); 5043 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 5044 assert(zeroPos <= newArity); 5045 if (zeroPos == newArity) { 5046 return 0; 5047 } 5048 return ~zeroPos; 5049 } else { 5050 // same algorithm, different bit set 5051 BitSet mask = new BitSet(newArity); 5052 for (int i = 0; i < reorder.length; i++) { 5053 int arg = reorder[i]; 5054 if (arg >= newArity) { 5055 return reorder.length; 5056 } 5057 if (mask.get(arg)) { 5058 return i; // >0 indicates a dup 5059 } 5060 mask.set(arg); 5061 } 5062 int zeroPos = mask.nextClearBit(0); 5063 assert(zeroPos <= newArity); 5064 if (zeroPos == newArity) { 5065 return 0; 5066 } 5067 return ~zeroPos; 5068 } 5069 } 5070 5071 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 5072 if (newType.returnType() != oldType.returnType()) 5073 throw newIllegalArgumentException("return types do not match", 5074 oldType, newType); 5075 if (reorder.length != oldType.parameterCount()) 5076 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 5077 oldType, Arrays.toString(reorder)); 5078 5079 int limit = newType.parameterCount(); 5080 for (int j = 0; j < reorder.length; j++) { 5081 int i = reorder[j]; 5082 if (i < 0 || i >= limit) { 5083 throw newIllegalArgumentException("index is out of bounds for new type", 5084 i, newType); 5085 } 5086 Class<?> src = newType.parameterType(i); 5087 Class<?> dst = oldType.parameterType(j); 5088 if (src != dst) 5089 throw newIllegalArgumentException("parameter types do not match after reorder", 5090 oldType, newType); 5091 } 5092 return true; 5093 } 5094 5095 /** 5096 * Produces a method handle of the requested return type which returns the given 5097 * constant value every time it is invoked. 5098 * <p> 5099 * Before the method handle is returned, the passed-in value is converted to the requested type. 5100 * If the requested type is primitive, widening primitive conversions are attempted, 5101 * else reference conversions are attempted. 5102 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5103 * @param type the return type of the desired method handle 5104 * @param value the value to return 5105 * @return a method handle of the given return type and no arguments, which always returns the given value 5106 * @throws NullPointerException if the {@code type} argument is null 5107 * @throws ClassCastException if the value cannot be converted to the required return type 5108 * @throws IllegalArgumentException if the given type is {@code void.class} 5109 */ 5110 public static MethodHandle constant(Class<?> type, Object value) { 5111 if (type.isPrimitive()) { 5112 if (type == void.class) 5113 throw newIllegalArgumentException("void type"); 5114 Wrapper w = Wrapper.forPrimitiveType(type); 5115 value = w.convert(value, type); 5116 if (w.zero().equals(value)) 5117 return zero(w, type); 5118 return insertArguments(identity(type), 0, value); 5119 } else { 5120 if (value == null) 5121 return zero(Wrapper.OBJECT, type); 5122 return identity(type).bindTo(value); 5123 } 5124 } 5125 5126 /** 5127 * Produces a method handle which returns its sole argument when invoked. 5128 * @param type the type of the sole parameter and return value of the desired method handle 5129 * @return a unary method handle which accepts and returns the given type 5130 * @throws NullPointerException if the argument is null 5131 * @throws IllegalArgumentException if the given type is {@code void.class} 5132 */ 5133 public static MethodHandle identity(Class<?> type) { 5134 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5135 int pos = btw.ordinal(); 5136 MethodHandle ident = IDENTITY_MHS[pos]; 5137 if (ident == null) { 5138 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5139 } 5140 if (ident.type().returnType() == type) 5141 return ident; 5142 // something like identity(Foo.class); do not bother to intern these 5143 assert (btw == Wrapper.OBJECT); 5144 return makeIdentity(type); 5145 } 5146 5147 /** 5148 * Produces a constant method handle of the requested return type which 5149 * returns the default value for that type every time it is invoked. 5150 * The resulting constant method handle will have no side effects. 5151 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5152 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5153 * since {@code explicitCastArguments} converts {@code null} to default values. 5154 * @param type the expected return type of the desired method handle 5155 * @return a constant method handle that takes no arguments 5156 * and returns the default value of the given type (or void, if the type is void) 5157 * @throws NullPointerException if the argument is null 5158 * @see MethodHandles#constant 5159 * @see MethodHandles#empty 5160 * @see MethodHandles#explicitCastArguments 5161 * @since 9 5162 */ 5163 public static MethodHandle zero(Class<?> type) { 5164 Objects.requireNonNull(type); 5165 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5166 } 5167 5168 private static MethodHandle identityOrVoid(Class<?> type) { 5169 return type == void.class ? zero(type) : identity(type); 5170 } 5171 5172 /** 5173 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5174 * and returns a suitable default depending on the return type. 5175 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5176 * <p>The returned method handle is equivalent to 5177 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5178 * 5179 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5180 * {@code guardWithTest(pred, target, empty(target.type())}. 5181 * @param type the type of the desired method handle 5182 * @return a constant method handle of the given type, which returns a default value of the given return type 5183 * @throws NullPointerException if the argument is null 5184 * @see MethodHandles#zero 5185 * @see MethodHandles#constant 5186 * @since 9 5187 */ 5188 public static MethodHandle empty(MethodType type) { 5189 Objects.requireNonNull(type); 5190 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5191 } 5192 5193 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5194 private static MethodHandle makeIdentity(Class<?> ptype) { 5195 MethodType mtype = methodType(ptype, ptype); 5196 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5197 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5198 } 5199 5200 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5201 int pos = btw.ordinal(); 5202 MethodHandle zero = ZERO_MHS[pos]; 5203 if (zero == null) { 5204 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5205 } 5206 if (zero.type().returnType() == rtype) 5207 return zero; 5208 assert(btw == Wrapper.OBJECT); 5209 return makeZero(rtype); 5210 } 5211 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5212 private static MethodHandle makeZero(Class<?> rtype) { 5213 MethodType mtype = methodType(rtype); 5214 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5215 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5216 } 5217 5218 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5219 // Simulate a CAS, to avoid racy duplication of results. 5220 MethodHandle prev = cache[pos]; 5221 if (prev != null) return prev; 5222 return cache[pos] = value; 5223 } 5224 5225 /** 5226 * Provides a target method handle with one or more <em>bound arguments</em> 5227 * in advance of the method handle's invocation. 5228 * The formal parameters to the target corresponding to the bound 5229 * arguments are called <em>bound parameters</em>. 5230 * Returns a new method handle which saves away the bound arguments. 5231 * When it is invoked, it receives arguments for any non-bound parameters, 5232 * binds the saved arguments to their corresponding parameters, 5233 * and calls the original target. 5234 * <p> 5235 * The type of the new method handle will drop the types for the bound 5236 * parameters from the original target type, since the new method handle 5237 * will no longer require those arguments to be supplied by its callers. 5238 * <p> 5239 * Each given argument object must match the corresponding bound parameter type. 5240 * If a bound parameter type is a primitive, the argument object 5241 * must be a wrapper, and will be unboxed to produce the primitive value. 5242 * <p> 5243 * The {@code pos} argument selects which parameters are to be bound. 5244 * It may range between zero and <i>N-L</i> (inclusively), 5245 * where <i>N</i> is the arity of the target method handle 5246 * and <i>L</i> is the length of the values array. 5247 * <p> 5248 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5249 * variable-arity method handle}, even if the original target method handle was. 5250 * @param target the method handle to invoke after the argument is inserted 5251 * @param pos where to insert the argument (zero for the first) 5252 * @param values the series of arguments to insert 5253 * @return a method handle which inserts an additional argument, 5254 * before calling the original method handle 5255 * @throws NullPointerException if the target or the {@code values} array is null 5256 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 5257 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5258 * is the length of the values array. 5259 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5260 * type. 5261 * @see MethodHandle#bindTo 5262 */ 5263 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5264 int insCount = values.length; 5265 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5266 if (insCount == 0) return target; 5267 BoundMethodHandle result = target.rebind(); 5268 for (int i = 0; i < insCount; i++) { 5269 Object value = values[i]; 5270 Class<?> ptype = ptypes[pos+i]; 5271 if (ptype.isPrimitive()) { 5272 result = insertArgumentPrimitive(result, pos, ptype, value); 5273 } else { 5274 value = ptype.cast(value); // throw CCE if needed 5275 result = result.bindArgumentL(pos, value); 5276 } 5277 } 5278 return result; 5279 } 5280 5281 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5282 Class<?> ptype, Object value) { 5283 Wrapper w = Wrapper.forPrimitiveType(ptype); 5284 // perform unboxing and/or primitive conversion 5285 value = w.convert(value, ptype); 5286 return switch (w) { 5287 case INT -> result.bindArgumentI(pos, (int) value); 5288 case LONG -> result.bindArgumentJ(pos, (long) value); 5289 case FLOAT -> result.bindArgumentF(pos, (float) value); 5290 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5291 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5292 }; 5293 } 5294 5295 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5296 MethodType oldType = target.type(); 5297 int outargs = oldType.parameterCount(); 5298 int inargs = outargs - insCount; 5299 if (inargs < 0) 5300 throw newIllegalArgumentException("too many values to insert"); 5301 if (pos < 0 || pos > inargs) 5302 throw newIllegalArgumentException("no argument type to append"); 5303 return oldType.ptypes(); 5304 } 5305 5306 /** 5307 * Produces a method handle which will discard some dummy arguments 5308 * before calling some other specified <i>target</i> method handle. 5309 * The type of the new method handle will be the same as the target's type, 5310 * except it will also include the dummy argument types, 5311 * at some given position. 5312 * <p> 5313 * The {@code pos} argument may range between zero and <i>N</i>, 5314 * where <i>N</i> is the arity of the target. 5315 * If {@code pos} is zero, the dummy arguments will precede 5316 * the target's real arguments; if {@code pos} is <i>N</i> 5317 * they will come after. 5318 * <p> 5319 * <b>Example:</b> 5320 * {@snippet lang="java" : 5321 import static java.lang.invoke.MethodHandles.*; 5322 import static java.lang.invoke.MethodType.*; 5323 ... 5324 MethodHandle cat = lookup().findVirtual(String.class, 5325 "concat", methodType(String.class, String.class)); 5326 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5327 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5328 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5329 assertEquals(bigType, d0.type()); 5330 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5331 * } 5332 * <p> 5333 * This method is also equivalent to the following code: 5334 * <blockquote><pre> 5335 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5336 * </pre></blockquote> 5337 * @param target the method handle to invoke after the arguments are dropped 5338 * @param pos position of first argument to drop (zero for the leftmost) 5339 * @param valueTypes the type(s) of the argument(s) to drop 5340 * @return a method handle which drops arguments of the given types, 5341 * before calling the original method handle 5342 * @throws NullPointerException if the target is null, 5343 * or if the {@code valueTypes} list or any of its elements is null 5344 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5345 * or if {@code pos} is negative or greater than the arity of the target, 5346 * or if the new method handle's type would have too many parameters 5347 */ 5348 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5349 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5350 } 5351 5352 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5353 MethodType oldType = target.type(); // get NPE 5354 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5355 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5356 if (dropped == 0) return target; 5357 BoundMethodHandle result = target.rebind(); 5358 LambdaForm lform = result.form; 5359 int insertFormArg = 1 + pos; 5360 for (Class<?> ptype : valueTypes) { 5361 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5362 } 5363 result = result.copyWith(newType, lform); 5364 return result; 5365 } 5366 5367 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5368 int dropped = valueTypes.length; 5369 MethodType.checkSlotCount(dropped); 5370 int outargs = oldType.parameterCount(); 5371 int inargs = outargs + dropped; 5372 if (pos < 0 || pos > outargs) 5373 throw newIllegalArgumentException("no argument type to remove" 5374 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5375 ); 5376 return dropped; 5377 } 5378 5379 /** 5380 * Produces a method handle which will discard some dummy arguments 5381 * before calling some other specified <i>target</i> method handle. 5382 * The type of the new method handle will be the same as the target's type, 5383 * except it will also include the dummy argument types, 5384 * at some given position. 5385 * <p> 5386 * The {@code pos} argument may range between zero and <i>N</i>, 5387 * where <i>N</i> is the arity of the target. 5388 * If {@code pos} is zero, the dummy arguments will precede 5389 * the target's real arguments; if {@code pos} is <i>N</i> 5390 * they will come after. 5391 * @apiNote 5392 * {@snippet lang="java" : 5393 import static java.lang.invoke.MethodHandles.*; 5394 import static java.lang.invoke.MethodType.*; 5395 ... 5396 MethodHandle cat = lookup().findVirtual(String.class, 5397 "concat", methodType(String.class, String.class)); 5398 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5399 MethodHandle d0 = dropArguments(cat, 0, String.class); 5400 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5401 MethodHandle d1 = dropArguments(cat, 1, String.class); 5402 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5403 MethodHandle d2 = dropArguments(cat, 2, String.class); 5404 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5405 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5406 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5407 * } 5408 * <p> 5409 * This method is also equivalent to the following code: 5410 * <blockquote><pre> 5411 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5412 * </pre></blockquote> 5413 * @param target the method handle to invoke after the arguments are dropped 5414 * @param pos position of first argument to drop (zero for the leftmost) 5415 * @param valueTypes the type(s) of the argument(s) to drop 5416 * @return a method handle which drops arguments of the given types, 5417 * before calling the original method handle 5418 * @throws NullPointerException if the target is null, 5419 * or if the {@code valueTypes} array or any of its elements is null 5420 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5421 * or if {@code pos} is negative or greater than the arity of the target, 5422 * or if the new method handle's type would have 5423 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5424 */ 5425 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5426 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5427 } 5428 5429 /* Convenience overloads for trusting internal low-arity call-sites */ 5430 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5431 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5432 } 5433 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5434 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5435 } 5436 5437 // private version which allows caller some freedom with error handling 5438 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5439 boolean nullOnFailure) { 5440 Class<?>[] oldTypes = target.type().ptypes(); 5441 int match = oldTypes.length; 5442 if (skip != 0) { 5443 if (skip < 0 || skip > match) { 5444 throw newIllegalArgumentException("illegal skip", skip, target); 5445 } 5446 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5447 match -= skip; 5448 } 5449 Class<?>[] addTypes = newTypes; 5450 int add = addTypes.length; 5451 if (pos != 0) { 5452 if (pos < 0 || pos > add) { 5453 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5454 } 5455 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5456 add -= pos; 5457 assert(addTypes.length == add); 5458 } 5459 // Do not add types which already match the existing arguments. 5460 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5461 if (nullOnFailure) { 5462 return null; 5463 } 5464 throw newIllegalArgumentException("argument lists do not match", 5465 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5466 } 5467 addTypes = Arrays.copyOfRange(addTypes, match, add); 5468 add -= match; 5469 assert(addTypes.length == add); 5470 // newTypes: ( P*[pos], M*[match], A*[add] ) 5471 // target: ( S*[skip], M*[match] ) 5472 MethodHandle adapter = target; 5473 if (add > 0) { 5474 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5475 } 5476 // adapter: (S*[skip], M*[match], A*[add] ) 5477 if (pos > 0) { 5478 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5479 } 5480 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5481 return adapter; 5482 } 5483 5484 /** 5485 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5486 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5487 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5488 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5489 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5490 * {@link #dropArguments(MethodHandle, int, Class[])}. 5491 * <p> 5492 * The resulting handle will have the same return type as the target handle. 5493 * <p> 5494 * In more formal terms, assume these two type lists:<ul> 5495 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5496 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5497 * {@code newTypes}. 5498 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5499 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5500 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5501 * sub-list. 5502 * </ul> 5503 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5504 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5505 * {@link #dropArguments(MethodHandle, int, Class[])}. 5506 * 5507 * @apiNote 5508 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5509 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5510 * {@snippet lang="java" : 5511 import static java.lang.invoke.MethodHandles.*; 5512 import static java.lang.invoke.MethodType.*; 5513 ... 5514 ... 5515 MethodHandle h0 = constant(boolean.class, true); 5516 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5517 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5518 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5519 if (h1.type().parameterCount() < h2.type().parameterCount()) 5520 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5521 else 5522 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5523 MethodHandle h3 = guardWithTest(h0, h1, h2); 5524 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5525 * } 5526 * @param target the method handle to adapt 5527 * @param skip number of targets parameters to disregard (they will be unchanged) 5528 * @param newTypes the list of types to match {@code target}'s parameter type list to 5529 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5530 * @return a possibly adapted method handle 5531 * @throws NullPointerException if either argument is null 5532 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5533 * or if {@code skip} is negative or greater than the arity of the target, 5534 * or if {@code pos} is negative or greater than the newTypes list size, 5535 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5536 * {@code pos}. 5537 * @since 9 5538 */ 5539 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5540 Objects.requireNonNull(target); 5541 Objects.requireNonNull(newTypes); 5542 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5543 } 5544 5545 /** 5546 * Drop the return value of the target handle (if any). 5547 * The returned method handle will have a {@code void} return type. 5548 * 5549 * @param target the method handle to adapt 5550 * @return a possibly adapted method handle 5551 * @throws NullPointerException if {@code target} is null 5552 * @since 16 5553 */ 5554 public static MethodHandle dropReturn(MethodHandle target) { 5555 Objects.requireNonNull(target); 5556 MethodType oldType = target.type(); 5557 Class<?> oldReturnType = oldType.returnType(); 5558 if (oldReturnType == void.class) 5559 return target; 5560 MethodType newType = oldType.changeReturnType(void.class); 5561 BoundMethodHandle result = target.rebind(); 5562 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5563 result = result.copyWith(newType, lform); 5564 return result; 5565 } 5566 5567 /** 5568 * Adapts a target method handle by pre-processing 5569 * one or more of its arguments, each with its own unary filter function, 5570 * and then calling the target with each pre-processed argument 5571 * replaced by the result of its corresponding filter function. 5572 * <p> 5573 * The pre-processing is performed by one or more method handles, 5574 * specified in the elements of the {@code filters} array. 5575 * The first element of the filter array corresponds to the {@code pos} 5576 * argument of the target, and so on in sequence. 5577 * The filter functions are invoked in left to right order. 5578 * <p> 5579 * Null arguments in the array are treated as identity functions, 5580 * and the corresponding arguments left unchanged. 5581 * (If there are no non-null elements in the array, the original target is returned.) 5582 * Each filter is applied to the corresponding argument of the adapter. 5583 * <p> 5584 * If a filter {@code F} applies to the {@code N}th argument of 5585 * the target, then {@code F} must be a method handle which 5586 * takes exactly one argument. The type of {@code F}'s sole argument 5587 * replaces the corresponding argument type of the target 5588 * in the resulting adapted method handle. 5589 * The return type of {@code F} must be identical to the corresponding 5590 * parameter type of the target. 5591 * <p> 5592 * It is an error if there are elements of {@code filters} 5593 * (null or not) 5594 * which do not correspond to argument positions in the target. 5595 * <p><b>Example:</b> 5596 * {@snippet lang="java" : 5597 import static java.lang.invoke.MethodHandles.*; 5598 import static java.lang.invoke.MethodType.*; 5599 ... 5600 MethodHandle cat = lookup().findVirtual(String.class, 5601 "concat", methodType(String.class, String.class)); 5602 MethodHandle upcase = lookup().findVirtual(String.class, 5603 "toUpperCase", methodType(String.class)); 5604 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5605 MethodHandle f0 = filterArguments(cat, 0, upcase); 5606 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5607 MethodHandle f1 = filterArguments(cat, 1, upcase); 5608 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5609 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5610 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5611 * } 5612 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5613 * denotes the return type of both the {@code target} and resulting adapter. 5614 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5615 * of the parameters and arguments that precede and follow the filter position 5616 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5617 * values of the filtered parameters and arguments; they also represent the 5618 * return types of the {@code filter[i]} handles. The latter accept arguments 5619 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5620 * the resulting adapter. 5621 * {@snippet lang="java" : 5622 * T target(P... p, A[i]... a[i], B... b); 5623 * A[i] filter[i](V[i]); 5624 * T adapter(P... p, V[i]... v[i], B... b) { 5625 * return target(p..., filter[i](v[i])..., b...); 5626 * } 5627 * } 5628 * <p> 5629 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5630 * variable-arity method handle}, even if the original target method handle was. 5631 * 5632 * @param target the method handle to invoke after arguments are filtered 5633 * @param pos the position of the first argument to filter 5634 * @param filters method handles to call initially on filtered arguments 5635 * @return method handle which incorporates the specified argument filtering logic 5636 * @throws NullPointerException if the target is null 5637 * or if the {@code filters} array is null 5638 * @throws IllegalArgumentException if a non-null element of {@code filters} 5639 * does not match a corresponding argument type of target as described above, 5640 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5641 * or if the resulting method handle's type would have 5642 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5643 */ 5644 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5645 // In method types arguments start at index 0, while the LF 5646 // editor have the MH receiver at position 0 - adjust appropriately. 5647 final int MH_RECEIVER_OFFSET = 1; 5648 filterArgumentsCheckArity(target, pos, filters); 5649 MethodHandle adapter = target; 5650 5651 // keep track of currently matched filters, as to optimize repeated filters 5652 int index = 0; 5653 int[] positions = new int[filters.length]; 5654 MethodHandle filter = null; 5655 5656 // process filters in reverse order so that the invocation of 5657 // the resulting adapter will invoke the filters in left-to-right order 5658 for (int i = filters.length - 1; i >= 0; --i) { 5659 MethodHandle newFilter = filters[i]; 5660 if (newFilter == null) continue; // ignore null elements of filters 5661 5662 // flush changes on update 5663 if (filter != newFilter) { 5664 if (filter != null) { 5665 if (index > 1) { 5666 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5667 } else { 5668 adapter = filterArgument(adapter, positions[0] - 1, filter); 5669 } 5670 } 5671 filter = newFilter; 5672 index = 0; 5673 } 5674 5675 filterArgumentChecks(target, pos + i, newFilter); 5676 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5677 } 5678 if (index > 1) { 5679 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5680 } else if (index == 1) { 5681 adapter = filterArgument(adapter, positions[0] - 1, filter); 5682 } 5683 return adapter; 5684 } 5685 5686 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5687 MethodType targetType = adapter.type(); 5688 MethodType filterType = filter.type(); 5689 BoundMethodHandle result = adapter.rebind(); 5690 Class<?> newParamType = filterType.parameterType(0); 5691 5692 Class<?>[] ptypes = targetType.ptypes().clone(); 5693 for (int pos : positions) { 5694 ptypes[pos - 1] = newParamType; 5695 } 5696 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5697 5698 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5699 return result.copyWithExtendL(newType, lform, filter); 5700 } 5701 5702 /*non-public*/ 5703 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5704 filterArgumentChecks(target, pos, filter); 5705 MethodType targetType = target.type(); 5706 MethodType filterType = filter.type(); 5707 BoundMethodHandle result = target.rebind(); 5708 Class<?> newParamType = filterType.parameterType(0); 5709 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5710 MethodType newType = targetType.changeParameterType(pos, newParamType); 5711 result = result.copyWithExtendL(newType, lform, filter); 5712 return result; 5713 } 5714 5715 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5716 MethodType targetType = target.type(); 5717 int maxPos = targetType.parameterCount(); 5718 if (pos + filters.length > maxPos) 5719 throw newIllegalArgumentException("too many filters"); 5720 } 5721 5722 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5723 MethodType targetType = target.type(); 5724 MethodType filterType = filter.type(); 5725 if (filterType.parameterCount() != 1 5726 || filterType.returnType() != targetType.parameterType(pos)) 5727 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5728 } 5729 5730 /** 5731 * Adapts a target method handle by pre-processing 5732 * a sub-sequence of its arguments with a filter (another method handle). 5733 * The pre-processed arguments are replaced by the result (if any) of the 5734 * filter function. 5735 * The target is then called on the modified (usually shortened) argument list. 5736 * <p> 5737 * If the filter returns a value, the target must accept that value as 5738 * its argument in position {@code pos}, preceded and/or followed by 5739 * any arguments not passed to the filter. 5740 * If the filter returns void, the target must accept all arguments 5741 * not passed to the filter. 5742 * No arguments are reordered, and a result returned from the filter 5743 * replaces (in order) the whole subsequence of arguments originally 5744 * passed to the adapter. 5745 * <p> 5746 * The argument types (if any) of the filter 5747 * replace zero or one argument types of the target, at position {@code pos}, 5748 * in the resulting adapted method handle. 5749 * The return type of the filter (if any) must be identical to the 5750 * argument type of the target at position {@code pos}, and that target argument 5751 * is supplied by the return value of the filter. 5752 * <p> 5753 * In all cases, {@code pos} must be greater than or equal to zero, and 5754 * {@code pos} must also be less than or equal to the target's arity. 5755 * <p><b>Example:</b> 5756 * {@snippet lang="java" : 5757 import static java.lang.invoke.MethodHandles.*; 5758 import static java.lang.invoke.MethodType.*; 5759 ... 5760 MethodHandle deepToString = publicLookup() 5761 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5762 5763 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5764 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5765 5766 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5767 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5768 5769 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5770 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5771 assertEquals("[top, [up, down], strange]", 5772 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5773 5774 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5775 assertEquals("[top, [up, down], [strange]]", 5776 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5777 5778 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5779 assertEquals("[top, [[up, down, strange], charm], bottom]", 5780 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5781 * } 5782 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5783 * represents the return type of the {@code target} and resulting adapter. 5784 * {@code V}/{@code v} stand for the return type and value of the 5785 * {@code filter}, which are also found in the signature and arguments of 5786 * the {@code target}, respectively, unless {@code V} is {@code void}. 5787 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5788 * and values preceding and following the collection position, {@code pos}, 5789 * in the {@code target}'s signature. They also turn up in the resulting 5790 * adapter's signature and arguments, where they surround 5791 * {@code B}/{@code b}, which represent the parameter types and arguments 5792 * to the {@code filter} (if any). 5793 * {@snippet lang="java" : 5794 * T target(A...,V,C...); 5795 * V filter(B...); 5796 * T adapter(A... a,B... b,C... c) { 5797 * V v = filter(b...); 5798 * return target(a...,v,c...); 5799 * } 5800 * // and if the filter has no arguments: 5801 * T target2(A...,V,C...); 5802 * V filter2(); 5803 * T adapter2(A... a,C... c) { 5804 * V v = filter2(); 5805 * return target2(a...,v,c...); 5806 * } 5807 * // and if the filter has a void return: 5808 * T target3(A...,C...); 5809 * void filter3(B...); 5810 * T adapter3(A... a,B... b,C... c) { 5811 * filter3(b...); 5812 * return target3(a...,c...); 5813 * } 5814 * } 5815 * <p> 5816 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5817 * one which first "folds" the affected arguments, and then drops them, in separate 5818 * steps as follows: 5819 * {@snippet lang="java" : 5820 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5821 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5822 * } 5823 * If the target method handle consumes no arguments besides than the result 5824 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5825 * is equivalent to {@code filterReturnValue(coll, mh)}. 5826 * If the filter method handle {@code coll} consumes one argument and produces 5827 * a non-void result, then {@code collectArguments(mh, N, coll)} 5828 * is equivalent to {@code filterArguments(mh, N, coll)}. 5829 * Other equivalences are possible but would require argument permutation. 5830 * <p> 5831 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5832 * variable-arity method handle}, even if the original target method handle was. 5833 * 5834 * @param target the method handle to invoke after filtering the subsequence of arguments 5835 * @param pos the position of the first adapter argument to pass to the filter, 5836 * and/or the target argument which receives the result of the filter 5837 * @param filter method handle to call on the subsequence of arguments 5838 * @return method handle which incorporates the specified argument subsequence filtering logic 5839 * @throws NullPointerException if either argument is null 5840 * @throws IllegalArgumentException if the return type of {@code filter} 5841 * is non-void and is not the same as the {@code pos} argument of the target, 5842 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5843 * or if the resulting method handle's type would have 5844 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5845 * @see MethodHandles#foldArguments 5846 * @see MethodHandles#filterArguments 5847 * @see MethodHandles#filterReturnValue 5848 */ 5849 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5850 MethodType newType = collectArgumentsChecks(target, pos, filter); 5851 MethodType collectorType = filter.type(); 5852 BoundMethodHandle result = target.rebind(); 5853 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5854 return result.copyWithExtendL(newType, lform, filter); 5855 } 5856 5857 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5858 MethodType targetType = target.type(); 5859 MethodType filterType = filter.type(); 5860 Class<?> rtype = filterType.returnType(); 5861 Class<?>[] filterArgs = filterType.ptypes(); 5862 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5863 (rtype != void.class && pos >= targetType.parameterCount())) { 5864 throw newIllegalArgumentException("position is out of range for target", target, pos); 5865 } 5866 if (rtype == void.class) { 5867 return targetType.insertParameterTypes(pos, filterArgs); 5868 } 5869 if (rtype != targetType.parameterType(pos)) { 5870 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5871 } 5872 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5873 } 5874 5875 /** 5876 * Adapts a target method handle by post-processing 5877 * its return value (if any) with a filter (another method handle). 5878 * The result of the filter is returned from the adapter. 5879 * <p> 5880 * If the target returns a value, the filter must accept that value as 5881 * its only argument. 5882 * If the target returns void, the filter must accept no arguments. 5883 * <p> 5884 * The return type of the filter 5885 * replaces the return type of the target 5886 * in the resulting adapted method handle. 5887 * The argument type of the filter (if any) must be identical to the 5888 * return type of the target. 5889 * <p><b>Example:</b> 5890 * {@snippet lang="java" : 5891 import static java.lang.invoke.MethodHandles.*; 5892 import static java.lang.invoke.MethodType.*; 5893 ... 5894 MethodHandle cat = lookup().findVirtual(String.class, 5895 "concat", methodType(String.class, String.class)); 5896 MethodHandle length = lookup().findVirtual(String.class, 5897 "length", methodType(int.class)); 5898 System.out.println((String) cat.invokeExact("x", "y")); // xy 5899 MethodHandle f0 = filterReturnValue(cat, length); 5900 System.out.println((int) f0.invokeExact("x", "y")); // 2 5901 * } 5902 * <p>Here is pseudocode for the resulting adapter. In the code, 5903 * {@code T}/{@code t} represent the result type and value of the 5904 * {@code target}; {@code V}, the result type of the {@code filter}; and 5905 * {@code A}/{@code a}, the types and values of the parameters and arguments 5906 * of the {@code target} as well as the resulting adapter. 5907 * {@snippet lang="java" : 5908 * T target(A...); 5909 * V filter(T); 5910 * V adapter(A... a) { 5911 * T t = target(a...); 5912 * return filter(t); 5913 * } 5914 * // and if the target has a void return: 5915 * void target2(A...); 5916 * V filter2(); 5917 * V adapter2(A... a) { 5918 * target2(a...); 5919 * return filter2(); 5920 * } 5921 * // and if the filter has a void return: 5922 * T target3(A...); 5923 * void filter3(V); 5924 * void adapter3(A... a) { 5925 * T t = target3(a...); 5926 * filter3(t); 5927 * } 5928 * } 5929 * <p> 5930 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5931 * variable-arity method handle}, even if the original target method handle was. 5932 * @param target the method handle to invoke before filtering the return value 5933 * @param filter method handle to call on the return value 5934 * @return method handle which incorporates the specified return value filtering logic 5935 * @throws NullPointerException if either argument is null 5936 * @throws IllegalArgumentException if the argument list of {@code filter} 5937 * does not match the return type of target as described above 5938 */ 5939 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5940 MethodType targetType = target.type(); 5941 MethodType filterType = filter.type(); 5942 filterReturnValueChecks(targetType, filterType); 5943 BoundMethodHandle result = target.rebind(); 5944 BasicType rtype = BasicType.basicType(filterType.returnType()); 5945 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5946 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5947 result = result.copyWithExtendL(newType, lform, filter); 5948 return result; 5949 } 5950 5951 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5952 Class<?> rtype = targetType.returnType(); 5953 int filterValues = filterType.parameterCount(); 5954 if (filterValues == 0 5955 ? (rtype != void.class) 5956 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5957 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5958 } 5959 5960 /** 5961 * Filter the return value of a target method handle with a filter function. The filter function is 5962 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5963 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5964 * as follows: 5965 * {@snippet lang="java" : 5966 * T target(A...) 5967 * V filter(B... , T) 5968 * V adapter(A... a, B... b) { 5969 * T t = target(a...); 5970 * return filter(b..., t); 5971 * } 5972 * } 5973 * <p> 5974 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5975 * 5976 * @param target the target method handle 5977 * @param filter the filter method handle 5978 * @return the adapter method handle 5979 */ 5980 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5981 MethodType targetType = target.type(); 5982 MethodType filterType = filter.type(); 5983 BoundMethodHandle result = target.rebind(); 5984 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5985 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5986 if (filterType.parameterCount() > 1) { 5987 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5988 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5989 } 5990 } 5991 result = result.copyWithExtendL(newType, lform, filter); 5992 return result; 5993 } 5994 5995 /** 5996 * Adapts a target method handle by pre-processing 5997 * some of its arguments, and then calling the target with 5998 * the result of the pre-processing, inserted into the original 5999 * sequence of arguments. 6000 * <p> 6001 * The pre-processing is performed by {@code combiner}, a second method handle. 6002 * Of the arguments passed to the adapter, the first {@code N} arguments 6003 * are copied to the combiner, which is then called. 6004 * (Here, {@code N} is defined as the parameter count of the combiner.) 6005 * After this, control passes to the target, with any result 6006 * from the combiner inserted before the original {@code N} incoming 6007 * arguments. 6008 * <p> 6009 * If the combiner returns a value, the first parameter type of the target 6010 * must be identical with the return type of the combiner, and the next 6011 * {@code N} parameter types of the target must exactly match the parameters 6012 * of the combiner. 6013 * <p> 6014 * If the combiner has a void return, no result will be inserted, 6015 * and the first {@code N} parameter types of the target 6016 * must exactly match the parameters of the combiner. 6017 * <p> 6018 * The resulting adapter is the same type as the target, except that the 6019 * first parameter type is dropped, 6020 * if it corresponds to the result of the combiner. 6021 * <p> 6022 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 6023 * that either the combiner or the target does not wish to receive. 6024 * If some of the incoming arguments are destined only for the combiner, 6025 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 6026 * arguments will not need to be live on the stack on entry to the 6027 * target.) 6028 * <p><b>Example:</b> 6029 * {@snippet lang="java" : 6030 import static java.lang.invoke.MethodHandles.*; 6031 import static java.lang.invoke.MethodType.*; 6032 ... 6033 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6034 "println", methodType(void.class, String.class)) 6035 .bindTo(System.out); 6036 MethodHandle cat = lookup().findVirtual(String.class, 6037 "concat", methodType(String.class, String.class)); 6038 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6039 MethodHandle catTrace = foldArguments(cat, trace); 6040 // also prints "boo": 6041 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6042 * } 6043 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6044 * represents the result type of the {@code target} and resulting adapter. 6045 * {@code V}/{@code v} represent the type and value of the parameter and argument 6046 * of {@code target} that precedes the folding position; {@code V} also is 6047 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6048 * types and values of the {@code N} parameters and arguments at the folding 6049 * position. {@code B}/{@code b} represent the types and values of the 6050 * {@code target} parameters and arguments that follow the folded parameters 6051 * and arguments. 6052 * {@snippet lang="java" : 6053 * // there are N arguments in A... 6054 * T target(V, A[N]..., B...); 6055 * V combiner(A...); 6056 * T adapter(A... a, B... b) { 6057 * V v = combiner(a...); 6058 * return target(v, a..., b...); 6059 * } 6060 * // and if the combiner has a void return: 6061 * T target2(A[N]..., B...); 6062 * void combiner2(A...); 6063 * T adapter2(A... a, B... b) { 6064 * combiner2(a...); 6065 * return target2(a..., b...); 6066 * } 6067 * } 6068 * <p> 6069 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6070 * variable-arity method handle}, even if the original target method handle was. 6071 * @param target the method handle to invoke after arguments are combined 6072 * @param combiner method handle to call initially on the incoming arguments 6073 * @return method handle which incorporates the specified argument folding logic 6074 * @throws NullPointerException if either argument is null 6075 * @throws IllegalArgumentException if {@code combiner}'s return type 6076 * is non-void and not the same as the first argument type of 6077 * the target, or if the initial {@code N} argument types 6078 * of the target 6079 * (skipping one matching the {@code combiner}'s return type) 6080 * are not identical with the argument types of {@code combiner} 6081 */ 6082 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 6083 return foldArguments(target, 0, combiner); 6084 } 6085 6086 /** 6087 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6088 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6089 * before the folded arguments. 6090 * <p> 6091 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6092 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6093 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6094 * 0. 6095 * 6096 * @apiNote Example: 6097 * {@snippet lang="java" : 6098 import static java.lang.invoke.MethodHandles.*; 6099 import static java.lang.invoke.MethodType.*; 6100 ... 6101 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6102 "println", methodType(void.class, String.class)) 6103 .bindTo(System.out); 6104 MethodHandle cat = lookup().findVirtual(String.class, 6105 "concat", methodType(String.class, String.class)); 6106 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6107 MethodHandle catTrace = foldArguments(cat, 1, trace); 6108 // also prints "jum": 6109 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6110 * } 6111 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6112 * represents the result type of the {@code target} and resulting adapter. 6113 * {@code V}/{@code v} represent the type and value of the parameter and argument 6114 * of {@code target} that precedes the folding position; {@code V} also is 6115 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6116 * types and values of the {@code N} parameters and arguments at the folding 6117 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6118 * and values of the {@code target} parameters and arguments that precede and 6119 * follow the folded parameters and arguments starting at {@code pos}, 6120 * respectively. 6121 * {@snippet lang="java" : 6122 * // there are N arguments in A... 6123 * T target(Z..., V, A[N]..., B...); 6124 * V combiner(A...); 6125 * T adapter(Z... z, A... a, B... b) { 6126 * V v = combiner(a...); 6127 * return target(z..., v, a..., b...); 6128 * } 6129 * // and if the combiner has a void return: 6130 * T target2(Z..., A[N]..., B...); 6131 * void combiner2(A...); 6132 * T adapter2(Z... z, A... a, B... b) { 6133 * combiner2(a...); 6134 * return target2(z..., a..., b...); 6135 * } 6136 * } 6137 * <p> 6138 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6139 * variable-arity method handle}, even if the original target method handle was. 6140 * 6141 * @param target the method handle to invoke after arguments are combined 6142 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6143 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6144 * @param combiner method handle to call initially on the incoming arguments 6145 * @return method handle which incorporates the specified argument folding logic 6146 * @throws NullPointerException if either argument is null 6147 * @throws IllegalArgumentException if either of the following two conditions holds: 6148 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6149 * {@code pos} of the target signature; 6150 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6151 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6152 * 6153 * @see #foldArguments(MethodHandle, MethodHandle) 6154 * @since 9 6155 */ 6156 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6157 MethodType targetType = target.type(); 6158 MethodType combinerType = combiner.type(); 6159 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6160 BoundMethodHandle result = target.rebind(); 6161 boolean dropResult = rtype == void.class; 6162 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6163 MethodType newType = targetType; 6164 if (!dropResult) { 6165 newType = newType.dropParameterTypes(pos, pos + 1); 6166 } 6167 result = result.copyWithExtendL(newType, lform, combiner); 6168 return result; 6169 } 6170 6171 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6172 int foldArgs = combinerType.parameterCount(); 6173 Class<?> rtype = combinerType.returnType(); 6174 int foldVals = rtype == void.class ? 0 : 1; 6175 int afterInsertPos = foldPos + foldVals; 6176 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6177 if (ok) { 6178 for (int i = 0; i < foldArgs; i++) { 6179 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6180 ok = false; 6181 break; 6182 } 6183 } 6184 } 6185 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6186 ok = false; 6187 if (!ok) 6188 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6189 return rtype; 6190 } 6191 6192 /** 6193 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6194 * of the pre-processing replacing the argument at the given position. 6195 * 6196 * @param target the method handle to invoke after arguments are combined 6197 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6198 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6199 * @param combiner method handle to call initially on the incoming arguments 6200 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6201 * @return method handle which incorporates the specified argument folding logic 6202 * @throws NullPointerException if either argument is null 6203 * @throws IllegalArgumentException if either of the following two conditions holds: 6204 * (1) {@code combiner}'s return type is not the same as the argument type at position 6205 * {@code pos} of the target signature; 6206 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6207 * not identical with the argument types of {@code combiner}. 6208 */ 6209 /*non-public*/ 6210 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6211 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6212 } 6213 6214 /** 6215 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6216 * the pre-processing inserted into the original sequence of arguments at the given position. 6217 * 6218 * @param target the method handle to invoke after arguments are combined 6219 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6220 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6221 * @param combiner method handle to call initially on the incoming arguments 6222 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6223 * @return method handle which incorporates the specified argument folding logic 6224 * @throws NullPointerException if either argument is null 6225 * @throws IllegalArgumentException if either of the following two conditions holds: 6226 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6227 * {@code pos} of the target signature; 6228 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6229 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6230 * with the argument types of {@code combiner}. 6231 */ 6232 /*non-public*/ 6233 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6234 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6235 } 6236 6237 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6238 MethodType targetType = target.type(); 6239 MethodType combinerType = combiner.type(); 6240 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6241 BoundMethodHandle result = target.rebind(); 6242 6243 MethodType newType = targetType; 6244 LambdaForm lform; 6245 if (filter) { 6246 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6247 } else { 6248 boolean dropResult = rtype == void.class; 6249 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6250 if (!dropResult) { 6251 newType = newType.dropParameterTypes(position, position + 1); 6252 } 6253 } 6254 result = result.copyWithExtendL(newType, lform, combiner); 6255 return result; 6256 } 6257 6258 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6259 int combinerArgs = combinerType.parameterCount(); 6260 if (argPos.length != combinerArgs) { 6261 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6262 } 6263 Class<?> rtype = combinerType.returnType(); 6264 6265 for (int i = 0; i < combinerArgs; i++) { 6266 int arg = argPos[i]; 6267 if (arg < 0 || arg > targetType.parameterCount()) { 6268 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6269 } 6270 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6271 throw newIllegalArgumentException("target argument type at position " + arg 6272 + " must match combiner argument type at index " + i + ": " + targetType 6273 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6274 } 6275 } 6276 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6277 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6278 } 6279 return rtype; 6280 } 6281 6282 /** 6283 * Makes a method handle which adapts a target method handle, 6284 * by guarding it with a test, a boolean-valued method handle. 6285 * If the guard fails, a fallback handle is called instead. 6286 * All three method handles must have the same corresponding 6287 * argument and return types, except that the return type 6288 * of the test must be boolean, and the test is allowed 6289 * to have fewer arguments than the other two method handles. 6290 * <p> 6291 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6292 * represents the uniform result type of the three involved handles; 6293 * {@code A}/{@code a}, the types and values of the {@code target} 6294 * parameters and arguments that are consumed by the {@code test}; and 6295 * {@code B}/{@code b}, those types and values of the {@code target} 6296 * parameters and arguments that are not consumed by the {@code test}. 6297 * {@snippet lang="java" : 6298 * boolean test(A...); 6299 * T target(A...,B...); 6300 * T fallback(A...,B...); 6301 * T adapter(A... a,B... b) { 6302 * if (test(a...)) 6303 * return target(a..., b...); 6304 * else 6305 * return fallback(a..., b...); 6306 * } 6307 * } 6308 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6309 * be modified by execution of the test, and so are passed unchanged 6310 * from the caller to the target or fallback as appropriate. 6311 * @param test method handle used for test, must return boolean 6312 * @param target method handle to call if test passes 6313 * @param fallback method handle to call if test fails 6314 * @return method handle which incorporates the specified if/then/else logic 6315 * @throws NullPointerException if any argument is null 6316 * @throws IllegalArgumentException if {@code test} does not return boolean, 6317 * or if all three method types do not match (with the return 6318 * type of {@code test} changed to match that of the target). 6319 */ 6320 public static MethodHandle guardWithTest(MethodHandle test, 6321 MethodHandle target, 6322 MethodHandle fallback) { 6323 MethodType gtype = test.type(); 6324 MethodType ttype = target.type(); 6325 MethodType ftype = fallback.type(); 6326 if (!ttype.equals(ftype)) 6327 throw misMatchedTypes("target and fallback types", ttype, ftype); 6328 if (gtype.returnType() != boolean.class) 6329 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6330 6331 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6332 if (test == null) { 6333 throw misMatchedTypes("target and test types", ttype, gtype); 6334 } 6335 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6336 } 6337 6338 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6339 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6340 } 6341 6342 /** 6343 * Makes a method handle which adapts a target method handle, 6344 * by running it inside an exception handler. 6345 * If the target returns normally, the adapter returns that value. 6346 * If an exception matching the specified type is thrown, the fallback 6347 * handle is called instead on the exception, plus the original arguments. 6348 * <p> 6349 * The target and handler must have the same corresponding 6350 * argument and return types, except that handler may omit trailing arguments 6351 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6352 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6353 * <p> 6354 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6355 * represents the return type of the {@code target} and {@code handler}, 6356 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6357 * the types and values of arguments to the resulting handle consumed by 6358 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6359 * resulting handle discarded by {@code handler}. 6360 * {@snippet lang="java" : 6361 * T target(A..., B...); 6362 * T handler(ExType, A...); 6363 * T adapter(A... a, B... b) { 6364 * try { 6365 * return target(a..., b...); 6366 * } catch (ExType ex) { 6367 * return handler(ex, a...); 6368 * } 6369 * } 6370 * } 6371 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6372 * be modified by execution of the target, and so are passed unchanged 6373 * from the caller to the handler, if the handler is invoked. 6374 * <p> 6375 * The target and handler must return the same type, even if the handler 6376 * always throws. (This might happen, for instance, because the handler 6377 * is simulating a {@code finally} clause). 6378 * To create such a throwing handler, compose the handler creation logic 6379 * with {@link #throwException throwException}, 6380 * in order to create a method handle of the correct return type. 6381 * @param target method handle to call 6382 * @param exType the type of exception which the handler will catch 6383 * @param handler method handle to call if a matching exception is thrown 6384 * @return method handle which incorporates the specified try/catch logic 6385 * @throws NullPointerException if any argument is null 6386 * @throws IllegalArgumentException if {@code handler} does not accept 6387 * the given exception type, or if the method handle types do 6388 * not match in their return types and their 6389 * corresponding parameters 6390 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6391 */ 6392 public static MethodHandle catchException(MethodHandle target, 6393 Class<? extends Throwable> exType, 6394 MethodHandle handler) { 6395 MethodType ttype = target.type(); 6396 MethodType htype = handler.type(); 6397 if (!Throwable.class.isAssignableFrom(exType)) 6398 throw new ClassCastException(exType.getName()); 6399 if (htype.parameterCount() < 1 || 6400 !htype.parameterType(0).isAssignableFrom(exType)) 6401 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6402 if (htype.returnType() != ttype.returnType()) 6403 throw misMatchedTypes("target and handler return types", ttype, htype); 6404 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6405 if (handler == null) { 6406 throw misMatchedTypes("target and handler types", ttype, htype); 6407 } 6408 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6409 } 6410 6411 /** 6412 * Produces a method handle which will throw exceptions of the given {@code exType}. 6413 * The method handle will accept a single argument of {@code exType}, 6414 * and immediately throw it as an exception. 6415 * The method type will nominally specify a return of {@code returnType}. 6416 * The return type may be anything convenient: It doesn't matter to the 6417 * method handle's behavior, since it will never return normally. 6418 * @param returnType the return type of the desired method handle 6419 * @param exType the parameter type of the desired method handle 6420 * @return method handle which can throw the given exceptions 6421 * @throws NullPointerException if either argument is null 6422 */ 6423 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6424 if (!Throwable.class.isAssignableFrom(exType)) 6425 throw new ClassCastException(exType.getName()); 6426 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6427 } 6428 6429 /** 6430 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6431 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6432 * delivers the loop's result, which is the return value of the resulting handle. 6433 * <p> 6434 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6435 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6436 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6437 * terms of method handles, each clause will specify up to four independent actions:<ul> 6438 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6439 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6440 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6441 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6442 * </ul> 6443 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6444 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6445 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6446 * <p> 6447 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6448 * this case. See below for a detailed description. 6449 * <p> 6450 * <em>Parameters optional everywhere:</em> 6451 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6452 * As an exception, the init functions cannot take any {@code v} parameters, 6453 * because those values are not yet computed when the init functions are executed. 6454 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6455 * In fact, any clause function may take no arguments at all. 6456 * <p> 6457 * <em>Loop parameters:</em> 6458 * A clause function may take all the iteration variable values it is entitled to, in which case 6459 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6460 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6461 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6462 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6463 * init function is automatically a loop parameter {@code a}.) 6464 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6465 * These loop parameters act as loop-invariant values visible across the whole loop. 6466 * <p> 6467 * <em>Parameters visible everywhere:</em> 6468 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6469 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6470 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6471 * Most clause functions will not need all of this information, but they will be formally connected to it 6472 * as if by {@link #dropArguments}. 6473 * <a id="astar"></a> 6474 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6475 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6476 * In that notation, the general form of an init function parameter list 6477 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6478 * <p> 6479 * <em>Checking clause structure:</em> 6480 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6481 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6482 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6483 * met by the inputs to the loop combinator. 6484 * <p> 6485 * <em>Effectively identical sequences:</em> 6486 * <a id="effid"></a> 6487 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6488 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6489 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6490 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6491 * that longest list. 6492 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6493 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6494 * <p> 6495 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6496 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6497 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6498 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6499 * four. Padding takes place by appending elements to the array. 6500 * <li>Clauses with all {@code null}s are disregarded. 6501 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6502 * </ol> 6503 * <p> 6504 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6505 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6506 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6507 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6508 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6509 * iteration variable type. 6510 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6511 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6512 * </ol> 6513 * <p> 6514 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6515 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6516 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6517 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6518 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6519 * (These types will be checked in step 2, along with all the clause function types.) 6520 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6521 * <li>All of the collected parameter lists must be effectively identical. 6522 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6523 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6524 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6525 * the "internal parameter list". 6526 * </ul> 6527 * <p> 6528 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6529 * <li>Examine fini function return types, disregarding omitted fini functions. 6530 * <li>If there are no fini functions, the loop return type is {@code void}. 6531 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6532 * type. 6533 * </ol> 6534 * <p> 6535 * <em>Step 1D: Check other types.</em><ol type="a"> 6536 * <li>There must be at least one non-omitted pred function. 6537 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6538 * </ol> 6539 * <p> 6540 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6541 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6542 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6543 * (Note that their parameter lists are already effectively identical to this list.) 6544 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6545 * effectively identical to the internal parameter list {@code (V... A...)}. 6546 * </ol> 6547 * <p> 6548 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6549 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6550 * type. 6551 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6552 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6553 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6554 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6555 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6556 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6557 * loop return type. 6558 * </ol> 6559 * <p> 6560 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6561 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6562 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6563 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6564 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6565 * pad out the end of the list. 6566 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6567 * </ol> 6568 * <p> 6569 * <em>Final observations.</em><ol type="a"> 6570 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6571 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6572 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6573 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6574 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6575 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6576 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6577 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6578 * </ol> 6579 * <p> 6580 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6581 * <ul> 6582 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6583 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6584 * (Only one {@code Pn} has to be non-{@code null}.) 6585 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6586 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6587 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6588 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6589 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6590 * the resulting loop handle's parameter types {@code (A...)}. 6591 * </ul> 6592 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6593 * which is natural if most of the loop computation happens in the steps. For some loops, 6594 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6595 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6596 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6597 * where the init functions will need the extra parameters. For such reasons, the rules for 6598 * determining these parameters are as symmetric as possible, across all clause parts. 6599 * In general, the loop parameters function as common invariant values across the whole 6600 * loop, while the iteration variables function as common variant values, or (if there is 6601 * no step function) as internal loop invariant temporaries. 6602 * <p> 6603 * <em>Loop execution.</em><ol type="a"> 6604 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6605 * every clause function. These locals are loop invariant. 6606 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6607 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6608 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6609 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6610 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6611 * (in argument order). 6612 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6613 * returns {@code false}. 6614 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6615 * sequence {@code (v...)} of loop variables. 6616 * The updated value is immediately visible to all subsequent function calls. 6617 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6618 * (of type {@code R}) is returned from the loop as a whole. 6619 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6620 * except by throwing an exception. 6621 * </ol> 6622 * <p> 6623 * <em>Usage tips.</em> 6624 * <ul> 6625 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6626 * sometimes a step function only needs to observe the current value of its own variable. 6627 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6628 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6629 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6630 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6631 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6632 * <li>If some of the clause functions are virtual methods on an instance, the instance 6633 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6634 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6635 * will be the first iteration variable value, and it will be easy to use virtual 6636 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6637 * </ul> 6638 * <p> 6639 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6640 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6641 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6642 * {@snippet lang="java" : 6643 * V... init...(A...); 6644 * boolean pred...(V..., A...); 6645 * V... step...(V..., A...); 6646 * R fini...(V..., A...); 6647 * R loop(A... a) { 6648 * V... v... = init...(a...); 6649 * for (;;) { 6650 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6651 * v = s(v..., a...); 6652 * if (!p(v..., a...)) { 6653 * return f(v..., a...); 6654 * } 6655 * } 6656 * } 6657 * } 6658 * } 6659 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6660 * to their full length, even though individual clause functions may neglect to take them all. 6661 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6662 * 6663 * @apiNote Example: 6664 * {@snippet lang="java" : 6665 * // iterative implementation of the factorial function as a loop handle 6666 * static int one(int k) { return 1; } 6667 * static int inc(int i, int acc, int k) { return i + 1; } 6668 * static int mult(int i, int acc, int k) { return i * acc; } 6669 * static boolean pred(int i, int acc, int k) { return i < k; } 6670 * static int fin(int i, int acc, int k) { return acc; } 6671 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6672 * // null initializer for counter, should initialize to 0 6673 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6674 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6675 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6676 * assertEquals(120, loop.invoke(5)); 6677 * } 6678 * The same example, dropping arguments and using combinators: 6679 * {@snippet lang="java" : 6680 * // simplified implementation of the factorial function as a loop handle 6681 * static int inc(int i) { return i + 1; } // drop acc, k 6682 * static int mult(int i, int acc) { return i * acc; } //drop k 6683 * static boolean cmp(int i, int k) { return i < k; } 6684 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6685 * // null initializer for counter, should initialize to 0 6686 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6687 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6688 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6689 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6690 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6691 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6692 * assertEquals(720, loop.invoke(6)); 6693 * } 6694 * A similar example, using a helper object to hold a loop parameter: 6695 * {@snippet lang="java" : 6696 * // instance-based implementation of the factorial function as a loop handle 6697 * static class FacLoop { 6698 * final int k; 6699 * FacLoop(int k) { this.k = k; } 6700 * int inc(int i) { return i + 1; } 6701 * int mult(int i, int acc) { return i * acc; } 6702 * boolean pred(int i) { return i < k; } 6703 * int fin(int i, int acc) { return acc; } 6704 * } 6705 * // assume MH_FacLoop is a handle to the constructor 6706 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6707 * // null initializer for counter, should initialize to 0 6708 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6709 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6710 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6711 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6712 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6713 * assertEquals(5040, loop.invoke(7)); 6714 * } 6715 * 6716 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6717 * 6718 * @return a method handle embodying the looping behavior as defined by the arguments. 6719 * 6720 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6721 * 6722 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6723 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6724 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6725 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6726 * @since 9 6727 */ 6728 public static MethodHandle loop(MethodHandle[]... clauses) { 6729 // Step 0: determine clause structure. 6730 loopChecks0(clauses); 6731 6732 List<MethodHandle> init = new ArrayList<>(); 6733 List<MethodHandle> step = new ArrayList<>(); 6734 List<MethodHandle> pred = new ArrayList<>(); 6735 List<MethodHandle> fini = new ArrayList<>(); 6736 6737 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6738 init.add(clause[0]); // all clauses have at least length 1 6739 step.add(clause.length <= 1 ? null : clause[1]); 6740 pred.add(clause.length <= 2 ? null : clause[2]); 6741 fini.add(clause.length <= 3 ? null : clause[3]); 6742 }); 6743 6744 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6745 final int nclauses = init.size(); 6746 6747 // Step 1A: determine iteration variables (V...). 6748 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6749 for (int i = 0; i < nclauses; ++i) { 6750 MethodHandle in = init.get(i); 6751 MethodHandle st = step.get(i); 6752 if (in == null && st == null) { 6753 iterationVariableTypes.add(void.class); 6754 } else if (in != null && st != null) { 6755 loopChecks1a(i, in, st); 6756 iterationVariableTypes.add(in.type().returnType()); 6757 } else { 6758 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6759 } 6760 } 6761 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6762 6763 // Step 1B: determine loop parameters (A...). 6764 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6765 loopChecks1b(init, commonSuffix); 6766 6767 // Step 1C: determine loop return type. 6768 // Step 1D: check other types. 6769 // local variable required here; see JDK-8223553 6770 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6771 .map(MethodType::returnType); 6772 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6773 loopChecks1cd(pred, fini, loopReturnType); 6774 6775 // Step 2: determine parameter lists. 6776 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6777 commonParameterSequence.addAll(commonSuffix); 6778 loopChecks2(step, pred, fini, commonParameterSequence); 6779 // Step 3: fill in omitted functions. 6780 for (int i = 0; i < nclauses; ++i) { 6781 Class<?> t = iterationVariableTypes.get(i); 6782 if (init.get(i) == null) { 6783 init.set(i, empty(methodType(t, commonSuffix))); 6784 } 6785 if (step.get(i) == null) { 6786 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6787 } 6788 if (pred.get(i) == null) { 6789 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6790 } 6791 if (fini.get(i) == null) { 6792 fini.set(i, empty(methodType(t, commonParameterSequence))); 6793 } 6794 } 6795 6796 // Step 4: fill in missing parameter types. 6797 // Also convert all handles to fixed-arity handles. 6798 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6799 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6800 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6801 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6802 6803 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6804 allMatch(pl -> pl.equals(commonSuffix)); 6805 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6806 allMatch(pl -> pl.equals(commonParameterSequence)); 6807 6808 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6809 } 6810 6811 private static void loopChecks0(MethodHandle[][] clauses) { 6812 if (clauses == null || clauses.length == 0) { 6813 throw newIllegalArgumentException("null or no clauses passed"); 6814 } 6815 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6816 throw newIllegalArgumentException("null clauses are not allowed"); 6817 } 6818 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6819 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6820 } 6821 } 6822 6823 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6824 if (in.type().returnType() != st.type().returnType()) { 6825 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6826 st.type().returnType()); 6827 } 6828 } 6829 6830 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6831 return mhs.filter(Objects::nonNull) 6832 // take only those that can contribute to a common suffix because they are longer than the prefix 6833 .map(MethodHandle::type) 6834 .filter(t -> t.parameterCount() > skipSize) 6835 .max(Comparator.comparingInt(MethodType::parameterCount)) 6836 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6837 .orElse(List.of()); 6838 } 6839 6840 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6841 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6842 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6843 return longest1.size() >= longest2.size() ? longest1 : longest2; 6844 } 6845 6846 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6847 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6848 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6849 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6850 " (common suffix: " + commonSuffix + ")"); 6851 } 6852 } 6853 6854 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6855 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6856 anyMatch(t -> t != loopReturnType)) { 6857 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6858 loopReturnType + ")"); 6859 } 6860 6861 if (pred.stream().noneMatch(Objects::nonNull)) { 6862 throw newIllegalArgumentException("no predicate found", pred); 6863 } 6864 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6865 anyMatch(t -> t != boolean.class)) { 6866 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6867 } 6868 } 6869 6870 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6871 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6872 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6873 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6874 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6875 } 6876 } 6877 6878 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6879 return hs.stream().map(h -> { 6880 int pc = h.type().parameterCount(); 6881 int tpsize = targetParams.size(); 6882 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6883 }).toList(); 6884 } 6885 6886 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6887 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6888 } 6889 6890 /** 6891 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6892 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6893 * <p> 6894 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6895 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6896 * evaluates to {@code true}). 6897 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6898 * <p> 6899 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6900 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6901 * and updated with the value returned from its invocation. The result of loop execution will be 6902 * the final value of the additional loop-local variable (if present). 6903 * <p> 6904 * The following rules hold for these argument handles:<ul> 6905 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6906 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6907 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6908 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6909 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6910 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6911 * It will constrain the parameter lists of the other loop parts. 6912 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6913 * list {@code (A...)} is called the <em>external parameter list</em>. 6914 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6915 * additional state variable of the loop. 6916 * The body must both accept and return a value of this type {@code V}. 6917 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6918 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6919 * <a href="MethodHandles.html#effid">effectively identical</a> 6920 * to the external parameter list {@code (A...)}. 6921 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6922 * {@linkplain #empty default value}. 6923 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6924 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6925 * effectively identical to the internal parameter list. 6926 * </ul> 6927 * <p> 6928 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6929 * <li>The loop handle's result type is the result type {@code V} of the body. 6930 * <li>The loop handle's parameter types are the types {@code (A...)}, 6931 * from the external parameter list. 6932 * </ul> 6933 * <p> 6934 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6935 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6936 * passed to the loop. 6937 * {@snippet lang="java" : 6938 * V init(A...); 6939 * boolean pred(V, A...); 6940 * V body(V, A...); 6941 * V whileLoop(A... a...) { 6942 * V v = init(a...); 6943 * while (pred(v, a...)) { 6944 * v = body(v, a...); 6945 * } 6946 * return v; 6947 * } 6948 * } 6949 * 6950 * @apiNote Example: 6951 * {@snippet lang="java" : 6952 * // implement the zip function for lists as a loop handle 6953 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6954 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6955 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6956 * zip.add(a.next()); 6957 * zip.add(b.next()); 6958 * return zip; 6959 * } 6960 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6961 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6962 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6963 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6964 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6965 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6966 * } 6967 * 6968 * 6969 * @apiNote The implementation of this method can be expressed as follows: 6970 * {@snippet lang="java" : 6971 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6972 * MethodHandle fini = (body.type().returnType() == void.class 6973 * ? null : identity(body.type().returnType())); 6974 * MethodHandle[] 6975 * checkExit = { null, null, pred, fini }, 6976 * varBody = { init, body }; 6977 * return loop(checkExit, varBody); 6978 * } 6979 * } 6980 * 6981 * @param init optional initializer, providing the initial value of the loop variable. 6982 * May be {@code null}, implying a default initial value. See above for other constraints. 6983 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6984 * above for other constraints. 6985 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6986 * See above for other constraints. 6987 * 6988 * @return a method handle implementing the {@code while} loop as described by the arguments. 6989 * @throws IllegalArgumentException if the rules for the arguments are violated. 6990 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6991 * 6992 * @see #loop(MethodHandle[][]) 6993 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6994 * @since 9 6995 */ 6996 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6997 whileLoopChecks(init, pred, body); 6998 MethodHandle fini = identityOrVoid(body.type().returnType()); 6999 MethodHandle[] checkExit = { null, null, pred, fini }; 7000 MethodHandle[] varBody = { init, body }; 7001 return loop(checkExit, varBody); 7002 } 7003 7004 /** 7005 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 7006 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7007 * <p> 7008 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 7009 * method will, in each iteration, first execute its body and then evaluate the predicate. 7010 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 7011 * <p> 7012 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 7013 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 7014 * and updated with the value returned from its invocation. The result of loop execution will be 7015 * the final value of the additional loop-local variable (if present). 7016 * <p> 7017 * The following rules hold for these argument handles:<ul> 7018 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7019 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 7020 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7021 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 7022 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 7023 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 7024 * It will constrain the parameter lists of the other loop parts. 7025 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 7026 * list {@code (A...)} is called the <em>external parameter list</em>. 7027 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7028 * additional state variable of the loop. 7029 * The body must both accept and return a value of this type {@code V}. 7030 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7031 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7032 * <a href="MethodHandles.html#effid">effectively identical</a> 7033 * to the external parameter list {@code (A...)}. 7034 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7035 * {@linkplain #empty default value}. 7036 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 7037 * Its parameter list (either empty or of the form {@code (V A*)}) must be 7038 * effectively identical to the internal parameter list. 7039 * </ul> 7040 * <p> 7041 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7042 * <li>The loop handle's result type is the result type {@code V} of the body. 7043 * <li>The loop handle's parameter types are the types {@code (A...)}, 7044 * from the external parameter list. 7045 * </ul> 7046 * <p> 7047 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7048 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 7049 * passed to the loop. 7050 * {@snippet lang="java" : 7051 * V init(A...); 7052 * boolean pred(V, A...); 7053 * V body(V, A...); 7054 * V doWhileLoop(A... a...) { 7055 * V v = init(a...); 7056 * do { 7057 * v = body(v, a...); 7058 * } while (pred(v, a...)); 7059 * return v; 7060 * } 7061 * } 7062 * 7063 * @apiNote Example: 7064 * {@snippet lang="java" : 7065 * // int i = 0; while (i < limit) { ++i; } return i; => limit 7066 * static int zero(int limit) { return 0; } 7067 * static int step(int i, int limit) { return i + 1; } 7068 * static boolean pred(int i, int limit) { return i < limit; } 7069 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 7070 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 7071 * assertEquals(23, loop.invoke(23)); 7072 * } 7073 * 7074 * 7075 * @apiNote The implementation of this method can be expressed as follows: 7076 * {@snippet lang="java" : 7077 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7078 * MethodHandle fini = (body.type().returnType() == void.class 7079 * ? null : identity(body.type().returnType())); 7080 * MethodHandle[] clause = { init, body, pred, fini }; 7081 * return loop(clause); 7082 * } 7083 * } 7084 * 7085 * @param init optional initializer, providing the initial value of the loop variable. 7086 * May be {@code null}, implying a default initial value. See above for other constraints. 7087 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7088 * See above for other constraints. 7089 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7090 * above for other constraints. 7091 * 7092 * @return a method handle implementing the {@code while} loop as described by the arguments. 7093 * @throws IllegalArgumentException if the rules for the arguments are violated. 7094 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7095 * 7096 * @see #loop(MethodHandle[][]) 7097 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7098 * @since 9 7099 */ 7100 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7101 whileLoopChecks(init, pred, body); 7102 MethodHandle fini = identityOrVoid(body.type().returnType()); 7103 MethodHandle[] clause = {init, body, pred, fini }; 7104 return loop(clause); 7105 } 7106 7107 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7108 Objects.requireNonNull(pred); 7109 Objects.requireNonNull(body); 7110 MethodType bodyType = body.type(); 7111 Class<?> returnType = bodyType.returnType(); 7112 List<Class<?>> innerList = bodyType.parameterList(); 7113 List<Class<?>> outerList = innerList; 7114 if (returnType == void.class) { 7115 // OK 7116 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7117 // leading V argument missing => error 7118 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7119 throw misMatchedTypes("body function", bodyType, expected); 7120 } else { 7121 outerList = innerList.subList(1, innerList.size()); 7122 } 7123 MethodType predType = pred.type(); 7124 if (predType.returnType() != boolean.class || 7125 !predType.effectivelyIdenticalParameters(0, innerList)) { 7126 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7127 } 7128 if (init != null) { 7129 MethodType initType = init.type(); 7130 if (initType.returnType() != returnType || 7131 !initType.effectivelyIdenticalParameters(0, outerList)) { 7132 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7133 } 7134 } 7135 } 7136 7137 /** 7138 * Constructs a loop that runs a given number of iterations. 7139 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7140 * <p> 7141 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7142 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7143 * It will be initialized to 0 and incremented by 1 in each iteration. 7144 * <p> 7145 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7146 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7147 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7148 * <p> 7149 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7150 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7151 * iteration variable. 7152 * The result of the loop handle execution will be the final {@code V} value of that variable 7153 * (or {@code void} if there is no {@code V} variable). 7154 * <p> 7155 * The following rules hold for the argument handles:<ul> 7156 * <li>The {@code iterations} handle must not be {@code null}, and must return 7157 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7158 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7159 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7160 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7161 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7162 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7163 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7164 * of types called the <em>internal parameter list</em>. 7165 * It will constrain the parameter lists of the other loop parts. 7166 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7167 * with no additional {@code A} types, then the internal parameter list is extended by 7168 * the argument types {@code A...} of the {@code iterations} handle. 7169 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7170 * list {@code (A...)} is called the <em>external parameter list</em>. 7171 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7172 * additional state variable of the loop. 7173 * The body must both accept a leading parameter and return a value of this type {@code V}. 7174 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7175 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7176 * <a href="MethodHandles.html#effid">effectively identical</a> 7177 * to the external parameter list {@code (A...)}. 7178 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7179 * {@linkplain #empty default value}. 7180 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7181 * effectively identical to the external parameter list {@code (A...)}. 7182 * </ul> 7183 * <p> 7184 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7185 * <li>The loop handle's result type is the result type {@code V} of the body. 7186 * <li>The loop handle's parameter types are the types {@code (A...)}, 7187 * from the external parameter list. 7188 * </ul> 7189 * <p> 7190 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7191 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7192 * arguments passed to the loop. 7193 * {@snippet lang="java" : 7194 * int iterations(A...); 7195 * V init(A...); 7196 * V body(V, int, A...); 7197 * V countedLoop(A... a...) { 7198 * int end = iterations(a...); 7199 * V v = init(a...); 7200 * for (int i = 0; i < end; ++i) { 7201 * v = body(v, i, a...); 7202 * } 7203 * return v; 7204 * } 7205 * } 7206 * 7207 * @apiNote Example with a fully conformant body method: 7208 * {@snippet lang="java" : 7209 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7210 * // => a variation on a well known theme 7211 * static String step(String v, int counter, String init) { return "na " + v; } 7212 * // assume MH_step is a handle to the method above 7213 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7214 * MethodHandle start = MethodHandles.identity(String.class); 7215 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7216 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7217 * } 7218 * 7219 * @apiNote Example with the simplest possible body method type, 7220 * and passing the number of iterations to the loop invocation: 7221 * {@snippet lang="java" : 7222 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7223 * // => a variation on a well known theme 7224 * static String step(String v, int counter ) { return "na " + v; } 7225 * // assume MH_step is a handle to the method above 7226 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7227 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7228 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7229 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7230 * } 7231 * 7232 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7233 * as loop parameters: 7234 * {@snippet lang="java" : 7235 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7236 * // => a variation on a well known theme 7237 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 7238 * // assume MH_step is a handle to the method above 7239 * MethodHandle count = MethodHandles.identity(int.class); 7240 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7241 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7242 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7243 * } 7244 * 7245 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7246 * to enforce a loop type: 7247 * {@snippet lang="java" : 7248 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7249 * // => a variation on a well known theme 7250 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7251 * // assume MH_step is a handle to the method above 7252 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7253 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7254 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7255 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7256 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7257 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7258 * } 7259 * 7260 * @apiNote The implementation of this method can be expressed as follows: 7261 * {@snippet lang="java" : 7262 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7263 * return countedLoop(empty(iterations.type()), iterations, init, body); 7264 * } 7265 * } 7266 * 7267 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7268 * result type must be {@code int}. See above for other constraints. 7269 * @param init optional initializer, providing the initial value of the loop variable. 7270 * May be {@code null}, implying a default initial value. See above for other constraints. 7271 * @param body body of the loop, which may not be {@code null}. 7272 * It controls the loop parameters and result type in the standard case (see above for details). 7273 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7274 * and may accept any number of additional types. 7275 * See above for other constraints. 7276 * 7277 * @return a method handle representing the loop. 7278 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7279 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7280 * 7281 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7282 * @since 9 7283 */ 7284 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7285 return countedLoop(empty(iterations.type()), iterations, init, body); 7286 } 7287 7288 /** 7289 * Constructs a loop that counts over a range of numbers. 7290 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7291 * <p> 7292 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7293 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7294 * values of the loop counter. 7295 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7296 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7297 * <p> 7298 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7299 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7300 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7301 * <p> 7302 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7303 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7304 * iteration variable. 7305 * The result of the loop handle execution will be the final {@code V} value of that variable 7306 * (or {@code void} if there is no {@code V} variable). 7307 * <p> 7308 * The following rules hold for the argument handles:<ul> 7309 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7310 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7311 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7312 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7313 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7314 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7315 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7316 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7317 * of types called the <em>internal parameter list</em>. 7318 * It will constrain the parameter lists of the other loop parts. 7319 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7320 * with no additional {@code A} types, then the internal parameter list is extended by 7321 * the argument types {@code A...} of the {@code end} handle. 7322 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7323 * list {@code (A...)} is called the <em>external parameter list</em>. 7324 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7325 * additional state variable of the loop. 7326 * The body must both accept a leading parameter and return a value of this type {@code V}. 7327 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7328 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7329 * <a href="MethodHandles.html#effid">effectively identical</a> 7330 * to the external parameter list {@code (A...)}. 7331 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7332 * {@linkplain #empty default value}. 7333 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7334 * effectively identical to the external parameter list {@code (A...)}. 7335 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7336 * to the external parameter list. 7337 * </ul> 7338 * <p> 7339 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7340 * <li>The loop handle's result type is the result type {@code V} of the body. 7341 * <li>The loop handle's parameter types are the types {@code (A...)}, 7342 * from the external parameter list. 7343 * </ul> 7344 * <p> 7345 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7346 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7347 * arguments passed to the loop. 7348 * {@snippet lang="java" : 7349 * int start(A...); 7350 * int end(A...); 7351 * V init(A...); 7352 * V body(V, int, A...); 7353 * V countedLoop(A... a...) { 7354 * int e = end(a...); 7355 * int s = start(a...); 7356 * V v = init(a...); 7357 * for (int i = s; i < e; ++i) { 7358 * v = body(v, i, a...); 7359 * } 7360 * return v; 7361 * } 7362 * } 7363 * 7364 * @apiNote The implementation of this method can be expressed as follows: 7365 * {@snippet lang="java" : 7366 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7367 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7368 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7369 * // the following semantics: 7370 * // MH_increment: (int limit, int counter) -> counter + 1 7371 * // MH_predicate: (int limit, int counter) -> counter < limit 7372 * Class<?> counterType = start.type().returnType(); // int 7373 * Class<?> returnType = body.type().returnType(); 7374 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7375 * if (returnType != void.class) { // ignore the V variable 7376 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7377 * pred = dropArguments(pred, 1, returnType); // ditto 7378 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7379 * } 7380 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7381 * MethodHandle[] 7382 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7383 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7384 * indexVar = { start, incr }; // i = start(); i = i + 1 7385 * return loop(loopLimit, bodyClause, indexVar); 7386 * } 7387 * } 7388 * 7389 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7390 * See above for other constraints. 7391 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7392 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7393 * @param init optional initializer, providing the initial value of the loop variable. 7394 * May be {@code null}, implying a default initial value. See above for other constraints. 7395 * @param body body of the loop, which may not be {@code null}. 7396 * It controls the loop parameters and result type in the standard case (see above for details). 7397 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7398 * and may accept any number of additional types. 7399 * See above for other constraints. 7400 * 7401 * @return a method handle representing the loop. 7402 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7403 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7404 * 7405 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7406 * @since 9 7407 */ 7408 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7409 countedLoopChecks(start, end, init, body); 7410 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7411 Class<?> limitType = end.type().returnType(); // yes, int again 7412 Class<?> returnType = body.type().returnType(); 7413 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7414 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7415 MethodHandle retv = null; 7416 if (returnType != void.class) { 7417 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7418 pred = dropArguments(pred, 1, returnType); // ditto 7419 retv = dropArguments(identity(returnType), 0, counterType); 7420 } 7421 body = dropArguments(body, 0, counterType); // ignore the limit variable 7422 MethodHandle[] 7423 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7424 bodyClause = { init, body }, // v = init(); v = body(v, i) 7425 indexVar = { start, incr }; // i = start(); i = i + 1 7426 return loop(loopLimit, bodyClause, indexVar); 7427 } 7428 7429 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7430 Objects.requireNonNull(start); 7431 Objects.requireNonNull(end); 7432 Objects.requireNonNull(body); 7433 Class<?> counterType = start.type().returnType(); 7434 if (counterType != int.class) { 7435 MethodType expected = start.type().changeReturnType(int.class); 7436 throw misMatchedTypes("start function", start.type(), expected); 7437 } else if (end.type().returnType() != counterType) { 7438 MethodType expected = end.type().changeReturnType(counterType); 7439 throw misMatchedTypes("end function", end.type(), expected); 7440 } 7441 MethodType bodyType = body.type(); 7442 Class<?> returnType = bodyType.returnType(); 7443 List<Class<?>> innerList = bodyType.parameterList(); 7444 // strip leading V value if present 7445 int vsize = (returnType == void.class ? 0 : 1); 7446 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7447 // argument list has no "V" => error 7448 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7449 throw misMatchedTypes("body function", bodyType, expected); 7450 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7451 // missing I type => error 7452 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7453 throw misMatchedTypes("body function", bodyType, expected); 7454 } 7455 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7456 if (outerList.isEmpty()) { 7457 // special case; take lists from end handle 7458 outerList = end.type().parameterList(); 7459 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7460 } 7461 MethodType expected = methodType(counterType, outerList); 7462 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7463 throw misMatchedTypes("start parameter types", start.type(), expected); 7464 } 7465 if (end.type() != start.type() && 7466 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7467 throw misMatchedTypes("end parameter types", end.type(), expected); 7468 } 7469 if (init != null) { 7470 MethodType initType = init.type(); 7471 if (initType.returnType() != returnType || 7472 !initType.effectivelyIdenticalParameters(0, outerList)) { 7473 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7474 } 7475 } 7476 } 7477 7478 /** 7479 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7480 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7481 * <p> 7482 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7483 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7484 * <p> 7485 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7486 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7487 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7488 * <p> 7489 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7490 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7491 * iteration variable. 7492 * The result of the loop handle execution will be the final {@code V} value of that variable 7493 * (or {@code void} if there is no {@code V} variable). 7494 * <p> 7495 * The following rules hold for the argument handles:<ul> 7496 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7497 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7498 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7499 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7500 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7501 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7502 * of types called the <em>internal parameter list</em>. 7503 * It will constrain the parameter lists of the other loop parts. 7504 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7505 * with no additional {@code A} types, then the internal parameter list is extended by 7506 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7507 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7508 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7509 * list {@code (A...)} is called the <em>external parameter list</em>. 7510 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7511 * additional state variable of the loop. 7512 * The body must both accept a leading parameter and return a value of this type {@code V}. 7513 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7514 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7515 * <a href="MethodHandles.html#effid">effectively identical</a> 7516 * to the external parameter list {@code (A...)}. 7517 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7518 * {@linkplain #empty default value}. 7519 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7520 * type {@code java.util.Iterator} or a subtype thereof. 7521 * The iterator it produces when the loop is executed will be assumed 7522 * to yield values which can be converted to type {@code T}. 7523 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7524 * effectively identical to the external parameter list {@code (A...)}. 7525 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7526 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7527 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7528 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7529 * the {@link MethodHandle#asType asType} conversion method. 7530 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7531 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7532 * </ul> 7533 * <p> 7534 * The type {@code T} may be either a primitive or reference. 7535 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7536 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7537 * as if by the {@link MethodHandle#asType asType} conversion method. 7538 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7539 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7540 * <p> 7541 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7542 * <li>The loop handle's result type is the result type {@code V} of the body. 7543 * <li>The loop handle's parameter types are the types {@code (A...)}, 7544 * from the external parameter list. 7545 * </ul> 7546 * <p> 7547 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7548 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7549 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7550 * {@snippet lang="java" : 7551 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7552 * V init(A...); 7553 * V body(V,T,A...); 7554 * V iteratedLoop(A... a...) { 7555 * Iterator<T> it = iterator(a...); 7556 * V v = init(a...); 7557 * while (it.hasNext()) { 7558 * T t = it.next(); 7559 * v = body(v, t, a...); 7560 * } 7561 * return v; 7562 * } 7563 * } 7564 * 7565 * @apiNote Example: 7566 * {@snippet lang="java" : 7567 * // get an iterator from a list 7568 * static List<String> reverseStep(List<String> r, String e) { 7569 * r.add(0, e); 7570 * return r; 7571 * } 7572 * static List<String> newArrayList() { return new ArrayList<>(); } 7573 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7574 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7575 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7576 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7577 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7578 * } 7579 * 7580 * @apiNote The implementation of this method can be expressed approximately as follows: 7581 * {@snippet lang="java" : 7582 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7583 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7584 * Class<?> returnType = body.type().returnType(); 7585 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7586 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7587 * MethodHandle retv = null, step = body, startIter = iterator; 7588 * if (returnType != void.class) { 7589 * // the simple thing first: in (I V A...), drop the I to get V 7590 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7591 * // body type signature (V T A...), internal loop types (I V A...) 7592 * step = swapArguments(body, 0, 1); // swap V <-> T 7593 * } 7594 * if (startIter == null) startIter = MH_getIter; 7595 * MethodHandle[] 7596 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7597 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7598 * return loop(iterVar, bodyClause); 7599 * } 7600 * } 7601 * 7602 * @param iterator an optional handle to return the iterator to start the loop. 7603 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7604 * See above for other constraints. 7605 * @param init optional initializer, providing the initial value of the loop variable. 7606 * May be {@code null}, implying a default initial value. See above for other constraints. 7607 * @param body body of the loop, which may not be {@code null}. 7608 * It controls the loop parameters and result type in the standard case (see above for details). 7609 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7610 * and may accept any number of additional types. 7611 * See above for other constraints. 7612 * 7613 * @return a method handle embodying the iteration loop functionality. 7614 * @throws NullPointerException if the {@code body} handle is {@code null}. 7615 * @throws IllegalArgumentException if any argument violates the above requirements. 7616 * 7617 * @since 9 7618 */ 7619 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7620 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7621 Class<?> returnType = body.type().returnType(); 7622 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7623 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7624 MethodHandle startIter; 7625 MethodHandle nextVal; 7626 { 7627 MethodType iteratorType; 7628 if (iterator == null) { 7629 // derive argument type from body, if available, else use Iterable 7630 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7631 iteratorType = startIter.type().changeParameterType(0, iterableType); 7632 } else { 7633 // force return type to the internal iterator class 7634 iteratorType = iterator.type().changeReturnType(Iterator.class); 7635 startIter = iterator; 7636 } 7637 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7638 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7639 7640 // perform the asType transforms under an exception transformer, as per spec.: 7641 try { 7642 startIter = startIter.asType(iteratorType); 7643 nextVal = nextRaw.asType(nextValType); 7644 } catch (WrongMethodTypeException ex) { 7645 throw new IllegalArgumentException(ex); 7646 } 7647 } 7648 7649 MethodHandle retv = null, step = body; 7650 if (returnType != void.class) { 7651 // the simple thing first: in (I V A...), drop the I to get V 7652 retv = dropArguments(identity(returnType), 0, Iterator.class); 7653 // body type signature (V T A...), internal loop types (I V A...) 7654 step = swapArguments(body, 0, 1); // swap V <-> T 7655 } 7656 7657 MethodHandle[] 7658 iterVar = { startIter, null, hasNext, retv }, 7659 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7660 return loop(iterVar, bodyClause); 7661 } 7662 7663 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7664 Objects.requireNonNull(body); 7665 MethodType bodyType = body.type(); 7666 Class<?> returnType = bodyType.returnType(); 7667 List<Class<?>> internalParamList = bodyType.parameterList(); 7668 // strip leading V value if present 7669 int vsize = (returnType == void.class ? 0 : 1); 7670 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7671 // argument list has no "V" => error 7672 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7673 throw misMatchedTypes("body function", bodyType, expected); 7674 } else if (internalParamList.size() <= vsize) { 7675 // missing T type => error 7676 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7677 throw misMatchedTypes("body function", bodyType, expected); 7678 } 7679 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7680 Class<?> iterableType = null; 7681 if (iterator != null) { 7682 // special case; if the body handle only declares V and T then 7683 // the external parameter list is obtained from iterator handle 7684 if (externalParamList.isEmpty()) { 7685 externalParamList = iterator.type().parameterList(); 7686 } 7687 MethodType itype = iterator.type(); 7688 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7689 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7690 } 7691 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7692 MethodType expected = methodType(itype.returnType(), externalParamList); 7693 throw misMatchedTypes("iterator parameters", itype, expected); 7694 } 7695 } else { 7696 if (externalParamList.isEmpty()) { 7697 // special case; if the iterator handle is null and the body handle 7698 // only declares V and T then the external parameter list consists 7699 // of Iterable 7700 externalParamList = List.of(Iterable.class); 7701 iterableType = Iterable.class; 7702 } else { 7703 // special case; if the iterator handle is null and the external 7704 // parameter list is not empty then the first parameter must be 7705 // assignable to Iterable 7706 iterableType = externalParamList.get(0); 7707 if (!Iterable.class.isAssignableFrom(iterableType)) { 7708 throw newIllegalArgumentException( 7709 "inferred first loop argument must inherit from Iterable: " + iterableType); 7710 } 7711 } 7712 } 7713 if (init != null) { 7714 MethodType initType = init.type(); 7715 if (initType.returnType() != returnType || 7716 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7717 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7718 } 7719 } 7720 return iterableType; // help the caller a bit 7721 } 7722 7723 /*non-public*/ 7724 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7725 // there should be a better way to uncross my wires 7726 int arity = mh.type().parameterCount(); 7727 int[] order = new int[arity]; 7728 for (int k = 0; k < arity; k++) order[k] = k; 7729 order[i] = j; order[j] = i; 7730 Class<?>[] types = mh.type().parameterArray(); 7731 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7732 MethodType swapType = methodType(mh.type().returnType(), types); 7733 return permuteArguments(mh, swapType, order); 7734 } 7735 7736 /** 7737 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7738 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7739 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7740 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7741 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7742 * {@code try-finally} handle. 7743 * <p> 7744 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7745 * The first is the exception thrown during the 7746 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7747 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7748 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7749 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7750 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7751 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7752 * <p> 7753 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7754 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7755 * two extra leading parameters:<ul> 7756 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7757 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7758 * the result from the execution of the {@code target} handle. 7759 * This parameter is not present if the {@code target} returns {@code void}. 7760 * </ul> 7761 * <p> 7762 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7763 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7764 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7765 * the cleanup. 7766 * {@snippet lang="java" : 7767 * V target(A..., B...); 7768 * V cleanup(Throwable, V, A...); 7769 * V adapter(A... a, B... b) { 7770 * V result = (zero value for V); 7771 * Throwable throwable = null; 7772 * try { 7773 * result = target(a..., b...); 7774 * } catch (Throwable t) { 7775 * throwable = t; 7776 * throw t; 7777 * } finally { 7778 * result = cleanup(throwable, result, a...); 7779 * } 7780 * return result; 7781 * } 7782 * } 7783 * <p> 7784 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7785 * be modified by execution of the target, and so are passed unchanged 7786 * from the caller to the cleanup, if it is invoked. 7787 * <p> 7788 * The target and cleanup must return the same type, even if the cleanup 7789 * always throws. 7790 * To create such a throwing cleanup, compose the cleanup logic 7791 * with {@link #throwException throwException}, 7792 * in order to create a method handle of the correct return type. 7793 * <p> 7794 * Note that {@code tryFinally} never converts exceptions into normal returns. 7795 * In rare cases where exceptions must be converted in that way, first wrap 7796 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7797 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7798 * <p> 7799 * It is recommended that the first parameter type of {@code cleanup} be 7800 * declared {@code Throwable} rather than a narrower subtype. This ensures 7801 * {@code cleanup} will always be invoked with whatever exception that 7802 * {@code target} throws. Declaring a narrower type may result in a 7803 * {@code ClassCastException} being thrown by the {@code try-finally} 7804 * handle if the type of the exception thrown by {@code target} is not 7805 * assignable to the first parameter type of {@code cleanup}. Note that 7806 * various exception types of {@code VirtualMachineError}, 7807 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7808 * thrown by almost any kind of Java code, and a finally clause that 7809 * catches (say) only {@code IOException} would mask any of the others 7810 * behind a {@code ClassCastException}. 7811 * 7812 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7813 * @param cleanup the handle that is invoked in the finally block. 7814 * 7815 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7816 * @throws NullPointerException if any argument is null 7817 * @throws IllegalArgumentException if {@code cleanup} does not accept 7818 * the required leading arguments, or if the method handle types do 7819 * not match in their return types and their 7820 * corresponding trailing parameters 7821 * 7822 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7823 * @since 9 7824 */ 7825 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7826 Class<?>[] targetParamTypes = target.type().ptypes(); 7827 Class<?> rtype = target.type().returnType(); 7828 7829 tryFinallyChecks(target, cleanup); 7830 7831 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7832 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7833 // target parameter list. 7834 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7835 7836 // Ensure that the intrinsic type checks the instance thrown by the 7837 // target against the first parameter of cleanup 7838 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7839 7840 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7841 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7842 } 7843 7844 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7845 Class<?> rtype = target.type().returnType(); 7846 if (rtype != cleanup.type().returnType()) { 7847 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7848 } 7849 MethodType cleanupType = cleanup.type(); 7850 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7851 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7852 } 7853 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7854 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7855 } 7856 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7857 // target parameter list. 7858 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7859 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7860 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7861 cleanup.type(), target.type()); 7862 } 7863 } 7864 7865 /** 7866 * Creates a table switch method handle, which can be used to switch over a set of target 7867 * method handles, based on a given target index, called selector. 7868 * <p> 7869 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7870 * and where {@code N} is the number of target method handles, the table switch method 7871 * handle will invoke the n-th target method handle from the list of target method handles. 7872 * <p> 7873 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7874 * method handle will invoke the given fallback method handle. 7875 * <p> 7876 * All method handles passed to this method must have the same type, with the additional 7877 * requirement that the leading parameter be of type {@code int}. The leading parameter 7878 * represents the selector. 7879 * <p> 7880 * Any trailing parameters present in the type will appear on the returned table switch 7881 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7882 * together with the selector value, to the selected method handle when invoking it. 7883 * 7884 * @apiNote Example: 7885 * The cases each drop the {@code selector} value they are given, and take an additional 7886 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7887 * to a specific constant label string for each case: 7888 * {@snippet lang="java" : 7889 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7890 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7891 * MethodType.methodType(String.class, String.class)); 7892 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7893 * 7894 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7895 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7896 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7897 * 7898 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7899 * caseDefault, 7900 * case0, 7901 * case1 7902 * ); 7903 * 7904 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7905 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7906 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7907 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7908 * } 7909 * 7910 * @param fallback the fallback method handle that is called when the selector is not 7911 * within the range {@code [0, N)}. 7912 * @param targets array of target method handles. 7913 * @return the table switch method handle. 7914 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7915 * any of the elements of the {@code targets} array are 7916 * {@code null}. 7917 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7918 * parameter of the fallback handle or any of the target 7919 * handles is not {@code int}, or if the types of 7920 * the fallback handle and all of target handles are 7921 * not the same. 7922 */ 7923 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7924 Objects.requireNonNull(fallback); 7925 Objects.requireNonNull(targets); 7926 targets = targets.clone(); 7927 MethodType type = tableSwitchChecks(fallback, targets); 7928 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7929 } 7930 7931 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7932 if (caseActions.length == 0) 7933 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7934 7935 MethodType expectedType = defaultCase.type(); 7936 7937 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7938 throw new IllegalArgumentException( 7939 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7940 7941 for (MethodHandle mh : caseActions) { 7942 Objects.requireNonNull(mh); 7943 if (mh.type() != expectedType) 7944 throw new IllegalArgumentException( 7945 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7946 } 7947 7948 return expectedType; 7949 } 7950 7951 /** 7952 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7953 * <p> 7954 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7955 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7956 * to the target var handle. 7957 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7958 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7959 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7960 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7961 * <p> 7962 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7963 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7964 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7965 * will be appended to the coordinates of the target var handle). 7966 * <p> 7967 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7968 * throw an {@link IllegalStateException}. 7969 * <p> 7970 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7971 * atomic access guarantees as those featured by the target var handle. 7972 * 7973 * @param target the target var handle 7974 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7975 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7976 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7977 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7978 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7979 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7980 * @throws NullPointerException if any of the arguments is {@code null}. 7981 * @since 22 7982 */ 7983 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7984 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7985 } 7986 7987 /** 7988 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7989 * <p> 7990 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7991 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7992 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7993 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7994 * by the adaptation) to the target var handle. 7995 * <p> 7996 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7997 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7998 * <p> 7999 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8000 * throw an {@link IllegalStateException}. 8001 * <p> 8002 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8003 * atomic access guarantees as those featured by the target var handle. 8004 * 8005 * @param target the target var handle 8006 * @param pos the position of the first coordinate to be transformed 8007 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 8008 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 8009 * to the new coordinate values. 8010 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 8011 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 8012 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8013 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 8014 * or if it's determined that any of the filters throws any checked exceptions. 8015 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 8016 * @since 22 8017 */ 8018 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8019 return VarHandles.filterCoordinates(target, pos, filters); 8020 } 8021 8022 /** 8023 * Provides a target var handle with one or more <em>bound coordinates</em> 8024 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8025 * coordinate types than the target var handle. 8026 * <p> 8027 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8028 * are joined with bound coordinate values, and then passed to the target var handle. 8029 * <p> 8030 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8031 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8032 * <p> 8033 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8034 * atomic access guarantees as those featured by the target var handle. 8035 * 8036 * @param target the var handle to invoke after the bound coordinates are inserted 8037 * @param pos the position of the first coordinate to be inserted 8038 * @param values the series of bound coordinates to insert 8039 * @return an adapter var handle which inserts additional coordinates, 8040 * before calling the target var handle 8041 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8042 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8043 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8044 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8045 * of the target var handle. 8046 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8047 * @since 22 8048 */ 8049 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8050 return VarHandles.insertCoordinates(target, pos, values); 8051 } 8052 8053 /** 8054 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8055 * so that the new coordinates match the provided ones. 8056 * <p> 8057 * The given array controls the reordering. 8058 * Call {@code #I} the number of incoming coordinates (the value 8059 * {@code newCoordinates.size()}), and call {@code #O} the number 8060 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8061 * Then the length of the reordering array must be {@code #O}, 8062 * and each element must be a non-negative number less than {@code #I}. 8063 * For every {@code N} less than {@code #O}, the {@code N}-th 8064 * outgoing coordinate will be taken from the {@code I}-th incoming 8065 * coordinate, where {@code I} is {@code reorder[N]}. 8066 * <p> 8067 * No coordinate value conversions are applied. 8068 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8069 * must be identical to the type of the corresponding outgoing coordinate 8070 * in the target var handle. 8071 * <p> 8072 * The reordering array need not specify an actual permutation. 8073 * An incoming coordinate will be duplicated if its index appears 8074 * more than once in the array, and an incoming coordinate will be dropped 8075 * if its index does not appear in the array. 8076 * <p> 8077 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8078 * atomic access guarantees as those featured by the target var handle. 8079 * @param target the var handle to invoke after the coordinates have been reordered 8080 * @param newCoordinates the new coordinate types 8081 * @param reorder an index array which controls the reordering 8082 * @return an adapter var handle which re-arranges the incoming coordinate values, 8083 * before calling the target var handle 8084 * @throws IllegalArgumentException if the index array length is not equal to 8085 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8086 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8087 * the target var handle and in {@code newCoordinates} are not identical. 8088 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8089 * @since 22 8090 */ 8091 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8092 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8093 } 8094 8095 /** 8096 * Adapts a target var handle by pre-processing 8097 * a sub-sequence of its coordinate values with a filter (a method handle). 8098 * The pre-processed coordinates are replaced by the result (if any) of the 8099 * filter function and the target var handle is then called on the modified (usually shortened) 8100 * coordinate list. 8101 * <p> 8102 * If {@code R} is the return type of the filter, then: 8103 * <ul> 8104 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 8105 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 8106 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 8107 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 8108 * target var handle.</li> 8109 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 8110 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 8111 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 8112 * downstream invocation of the target var handle.</li> 8113 * </ul> 8114 * <p> 8115 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8116 * throw an {@link IllegalStateException}. 8117 * <p> 8118 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8119 * atomic access guarantees as those featured by the target var handle. 8120 * 8121 * @param target the var handle to invoke after the coordinates have been filtered 8122 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 8123 * @param filter the filter method handle 8124 * @return an adapter var handle which filters the incoming coordinate values, 8125 * before calling the target var handle 8126 * @throws IllegalArgumentException if the return type of {@code filter} 8127 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 8128 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8129 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8130 * or if it's determined that {@code filter} throws any checked exceptions. 8131 * @throws NullPointerException if any of the arguments is {@code null}. 8132 * @since 22 8133 */ 8134 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8135 return VarHandles.collectCoordinates(target, pos, filter); 8136 } 8137 8138 /** 8139 * Returns a var handle which will discard some dummy coordinates before delegating to the 8140 * target var handle. As a consequence, the resulting var handle will feature more 8141 * coordinate types than the target var handle. 8142 * <p> 8143 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8144 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8145 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8146 * <p> 8147 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8148 * atomic access guarantees as those featured by the target var handle. 8149 * 8150 * @param target the var handle to invoke after the dummy coordinates are dropped 8151 * @param pos position of the first coordinate to drop (zero for the leftmost) 8152 * @param valueTypes the type(s) of the coordinate(s) to drop 8153 * @return an adapter var handle which drops some dummy coordinates, 8154 * before calling the target var handle 8155 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8156 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8157 * @since 22 8158 */ 8159 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8160 return VarHandles.dropCoordinates(target, pos, valueTypes); 8161 } 8162 }