1 /* 2 * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.access.SharedSecrets; 29 import jdk.internal.misc.Unsafe; 30 import jdk.internal.misc.VM; 31 import jdk.internal.reflect.CallerSensitive; 32 import jdk.internal.reflect.CallerSensitiveAdapter; 33 import jdk.internal.reflect.Reflection; 34 import jdk.internal.util.ClassFileDumper; 35 import jdk.internal.vm.annotation.ForceInline; 36 import sun.invoke.util.ValueConversions; 37 import sun.invoke.util.VerifyAccess; 38 import sun.invoke.util.Wrapper; 39 import sun.reflect.misc.ReflectUtil; 40 import sun.security.util.SecurityConstants; 41 42 import java.lang.classfile.ClassModel; 43 import java.lang.constant.ConstantDescs; 44 import java.lang.invoke.LambdaForm.BasicType; 45 import java.lang.invoke.MethodHandleImpl.Intrinsic; 46 import java.lang.reflect.Constructor; 47 import java.lang.reflect.Field; 48 import java.lang.reflect.Member; 49 import java.lang.reflect.Method; 50 import java.lang.reflect.Modifier; 51 import java.nio.ByteOrder; 52 import java.security.ProtectionDomain; 53 import java.util.ArrayList; 54 import java.util.Arrays; 55 import java.util.BitSet; 56 import java.util.Comparator; 57 import java.util.Iterator; 58 import java.util.List; 59 import java.util.Objects; 60 import java.util.Set; 61 import java.util.concurrent.ConcurrentHashMap; 62 import java.util.stream.Stream; 63 64 import static java.lang.classfile.ClassFile.*; 65 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 66 import static java.lang.invoke.MethodHandleNatives.Constants.*; 67 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 68 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 69 import static java.lang.invoke.MethodHandleStatics.newInternalError; 70 import static java.lang.invoke.MethodType.methodType; 71 72 /** 73 * This class consists exclusively of static methods that operate on or return 74 * method handles. They fall into several categories: 75 * <ul> 76 * <li>Lookup methods which help create method handles for methods and fields. 77 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 78 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 79 * </ul> 80 * A lookup, combinator, or factory method will fail and throw an 81 * {@code IllegalArgumentException} if the created method handle's type 82 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 83 * 84 * @author John Rose, JSR 292 EG 85 * @since 1.7 86 */ 87 public class MethodHandles { 88 89 private MethodHandles() { } // do not instantiate 90 91 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 92 93 // See IMPL_LOOKUP below. 94 95 //--- Method handle creation from ordinary methods. 96 97 /** 98 * Returns a {@link Lookup lookup object} with 99 * full capabilities to emulate all supported bytecode behaviors of the caller. 100 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 101 * Factory methods on the lookup object can create 102 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 103 * for any member that the caller has access to via bytecodes, 104 * including protected and private fields and methods. 105 * This lookup object is created by the original lookup class 106 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 107 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 108 * Do not store it in place where untrusted code can access it. 109 * <p> 110 * This method is caller sensitive, which means that it may return different 111 * values to different callers. 112 * In cases where {@code MethodHandles.lookup} is called from a context where 113 * there is no caller frame on the stack (e.g. when called directly 114 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 115 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 116 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 117 * to obtain a low-privileged lookup instead. 118 * @return a lookup object for the caller of this method, with 119 * {@linkplain Lookup#ORIGINAL original} and 120 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 121 * @throws IllegalCallerException if there is no caller frame on the stack. 122 */ 123 @CallerSensitive 124 @ForceInline // to ensure Reflection.getCallerClass optimization 125 public static Lookup lookup() { 126 final Class<?> c = Reflection.getCallerClass(); 127 if (c == null) { 128 throw new IllegalCallerException("no caller frame"); 129 } 130 return new Lookup(c); 131 } 132 133 /** 134 * This lookup method is the alternate implementation of 135 * the lookup method with a leading caller class argument which is 136 * non-caller-sensitive. This method is only invoked by reflection 137 * and method handle. 138 */ 139 @CallerSensitiveAdapter 140 private static Lookup lookup(Class<?> caller) { 141 if (caller.getClassLoader() == null) { 142 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 143 } 144 return new Lookup(caller); 145 } 146 147 /** 148 * Returns a {@link Lookup lookup object} which is trusted minimally. 149 * The lookup has the {@code UNCONDITIONAL} mode. 150 * It can only be used to create method handles to public members of 151 * public classes in packages that are exported unconditionally. 152 * <p> 153 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 154 * of this lookup object will be {@link java.lang.Object}. 155 * 156 * @apiNote The use of Object is conventional, and because the lookup modes are 157 * limited, there is no special access provided to the internals of Object, its package 158 * or its module. This public lookup object or other lookup object with 159 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 160 * is not used to determine the lookup context. 161 * 162 * <p style="font-size:smaller;"> 163 * <em>Discussion:</em> 164 * The lookup class can be changed to any other class {@code C} using an expression of the form 165 * {@link Lookup#in publicLookup().in(C.class)}. 166 * A public lookup object is always subject to 167 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 168 * Also, it cannot access 169 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 170 * @return a lookup object which is trusted minimally 171 */ 172 public static Lookup publicLookup() { 173 return Lookup.PUBLIC_LOOKUP; 174 } 175 176 /** 177 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 178 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 179 * The returned lookup object can provide access to classes in modules and packages, 180 * and members of those classes, outside the normal rules of Java access control, 181 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 182 * <p> 183 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 184 * allowed to do deep reflection on module {@code M2} and package of the target class 185 * if and only if all of the following conditions are {@code true}: 186 * <ul> 187 * <li>If there is a security manager, its {@code checkPermission} method is 188 * called to check {@code ReflectPermission("suppressAccessChecks")} and 189 * that must return normally. 190 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 191 * full privilege access}. Specifically: 192 * <ul> 193 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 194 * (This is because otherwise there would be no way to ensure the original lookup 195 * creator was a member of any particular module, and so any subsequent checks 196 * for readability and qualified exports would become ineffective.) 197 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 198 * (This is because an application intending to share intra-module access 199 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 200 * deep reflection to its own module.) 201 * </ul> 202 * <li>The target class must be a proper class, not a primitive or array class. 203 * (Thus, {@code M2} is well-defined.) 204 * <li>If the caller module {@code M1} differs from 205 * the target module {@code M2} then both of the following must be true: 206 * <ul> 207 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 208 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 209 * containing the target class to at least {@code M1}.</li> 210 * </ul> 211 * </ul> 212 * <p> 213 * If any of the above checks is violated, this method fails with an 214 * exception. 215 * <p> 216 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 217 * returns a {@code Lookup} on {@code targetClass} with 218 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 219 * with {@code null} previous lookup class. 220 * <p> 221 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 222 * returns a {@code Lookup} on {@code targetClass} that records 223 * the lookup class of the caller as the new previous lookup class with 224 * {@code PRIVATE} access but no {@code MODULE} access. 225 * <p> 226 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 227 * 228 * @apiNote The {@code Lookup} object returned by this method is allowed to 229 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 230 * of {@code targetClass}. Extreme caution should be taken when opening a package 231 * to another module as such defined classes have the same full privilege 232 * access as other members in {@code targetClass}'s module. 233 * 234 * @param targetClass the target class 235 * @param caller the caller lookup object 236 * @return a lookup object for the target class, with private access 237 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 238 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 239 * @throws SecurityException if denied by the security manager 240 * @throws IllegalAccessException if any of the other access checks specified above fails 241 * @since 9 242 * @see Lookup#dropLookupMode 243 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 244 */ 245 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 246 if (caller.allowedModes == Lookup.TRUSTED) { 247 return new Lookup(targetClass); 248 } 249 250 @SuppressWarnings("removal") 251 SecurityManager sm = System.getSecurityManager(); 252 if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION); 253 if (targetClass.isPrimitive()) 254 throw new IllegalArgumentException(targetClass + " is a primitive class"); 255 if (targetClass.isArray()) 256 throw new IllegalArgumentException(targetClass + " is an array class"); 257 // Ensure that we can reason accurately about private and module access. 258 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 259 if ((caller.lookupModes() & requireAccess) != requireAccess) 260 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 261 262 // previous lookup class is never set if it has MODULE access 263 assert caller.previousLookupClass() == null; 264 265 Class<?> callerClass = caller.lookupClass(); 266 Module callerModule = callerClass.getModule(); // M1 267 Module targetModule = targetClass.getModule(); // M2 268 Class<?> newPreviousClass = null; 269 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 270 271 if (targetModule != callerModule) { 272 if (!callerModule.canRead(targetModule)) 273 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 274 if (targetModule.isNamed()) { 275 String pn = targetClass.getPackageName(); 276 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 277 if (!targetModule.isOpen(pn, callerModule)) 278 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 279 } 280 281 // M2 != M1, set previous lookup class to M1 and drop MODULE access 282 newPreviousClass = callerClass; 283 newModes &= ~Lookup.MODULE; 284 } 285 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 286 } 287 288 /** 289 * Returns the <em>class data</em> associated with the lookup class 290 * of the given {@code caller} lookup object, or {@code null}. 291 * 292 * <p> A hidden class with class data can be created by calling 293 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 294 * Lookup::defineHiddenClassWithClassData}. 295 * This method will cause the static class initializer of the lookup 296 * class of the given {@code caller} lookup object be executed if 297 * it has not been initialized. 298 * 299 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 300 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 301 * {@code null} is returned if this method is called on the lookup object 302 * on these classes. 303 * 304 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 305 * must have {@linkplain Lookup#ORIGINAL original access} 306 * in order to retrieve the class data. 307 * 308 * @apiNote 309 * This method can be called as a bootstrap method for a dynamically computed 310 * constant. A framework can create a hidden class with class data, for 311 * example that can be {@code Class} or {@code MethodHandle} object. 312 * The class data is accessible only to the lookup object 313 * created by the original caller but inaccessible to other members 314 * in the same nest. If a framework passes security sensitive objects 315 * to a hidden class via class data, it is recommended to load the value 316 * of class data as a dynamically computed constant instead of storing 317 * the class data in private static field(s) which are accessible to 318 * other nestmates. 319 * 320 * @param <T> the type to cast the class data object to 321 * @param caller the lookup context describing the class performing the 322 * operation (normally stacked by the JVM) 323 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 324 * ({@code "_"}) 325 * @param type the type of the class data 326 * @return the value of the class data if present in the lookup class; 327 * otherwise {@code null} 328 * @throws IllegalArgumentException if name is not {@code "_"} 329 * @throws IllegalAccessException if the lookup context does not have 330 * {@linkplain Lookup#ORIGINAL original} access 331 * @throws ClassCastException if the class data cannot be converted to 332 * the given {@code type} 333 * @throws NullPointerException if {@code caller} or {@code type} argument 334 * is {@code null} 335 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 336 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 337 * @since 16 338 * @jvms 5.5 Initialization 339 */ 340 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 341 Objects.requireNonNull(caller); 342 Objects.requireNonNull(type); 343 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 344 throw new IllegalArgumentException("name must be \"_\": " + name); 345 } 346 347 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 348 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 349 } 350 351 Object classdata = classData(caller.lookupClass()); 352 if (classdata == null) return null; 353 354 try { 355 return BootstrapMethodInvoker.widenAndCast(classdata, type); 356 } catch (RuntimeException|Error e) { 357 throw e; // let CCE and other runtime exceptions through 358 } catch (Throwable e) { 359 throw new InternalError(e); 360 } 361 } 362 363 /* 364 * Returns the class data set by the VM in the Class::classData field. 365 * 366 * This is also invoked by LambdaForms as it cannot use condy via 367 * MethodHandles::classData due to bootstrapping issue. 368 */ 369 static Object classData(Class<?> c) { 370 UNSAFE.ensureClassInitialized(c); 371 return SharedSecrets.getJavaLangAccess().classData(c); 372 } 373 374 /** 375 * Returns the element at the specified index in the 376 * {@linkplain #classData(Lookup, String, Class) class data}, 377 * if the class data associated with the lookup class 378 * of the given {@code caller} lookup object is a {@code List}. 379 * If the class data is not present in this lookup class, this method 380 * returns {@code null}. 381 * 382 * <p> A hidden class with class data can be created by calling 383 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 384 * Lookup::defineHiddenClassWithClassData}. 385 * This method will cause the static class initializer of the lookup 386 * class of the given {@code caller} lookup object be executed if 387 * it has not been initialized. 388 * 389 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 390 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 391 * {@code null} is returned if this method is called on the lookup object 392 * on these classes. 393 * 394 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 395 * must have {@linkplain Lookup#ORIGINAL original access} 396 * in order to retrieve the class data. 397 * 398 * @apiNote 399 * This method can be called as a bootstrap method for a dynamically computed 400 * constant. A framework can create a hidden class with class data, for 401 * example that can be {@code List.of(o1, o2, o3....)} containing more than 402 * one object and use this method to load one element at a specific index. 403 * The class data is accessible only to the lookup object 404 * created by the original caller but inaccessible to other members 405 * in the same nest. If a framework passes security sensitive objects 406 * to a hidden class via class data, it is recommended to load the value 407 * of class data as a dynamically computed constant instead of storing 408 * the class data in private static field(s) which are accessible to other 409 * nestmates. 410 * 411 * @param <T> the type to cast the result object to 412 * @param caller the lookup context describing the class performing the 413 * operation (normally stacked by the JVM) 414 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 415 * ({@code "_"}) 416 * @param type the type of the element at the given index in the class data 417 * @param index index of the element in the class data 418 * @return the element at the given index in the class data 419 * if the class data is present; otherwise {@code null} 420 * @throws IllegalArgumentException if name is not {@code "_"} 421 * @throws IllegalAccessException if the lookup context does not have 422 * {@linkplain Lookup#ORIGINAL original} access 423 * @throws ClassCastException if the class data cannot be converted to {@code List} 424 * or the element at the specified index cannot be converted to the given type 425 * @throws IndexOutOfBoundsException if the index is out of range 426 * @throws NullPointerException if {@code caller} or {@code type} argument is 427 * {@code null}; or if unboxing operation fails because 428 * the element at the given index is {@code null} 429 * 430 * @since 16 431 * @see #classData(Lookup, String, Class) 432 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 433 */ 434 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 435 throws IllegalAccessException 436 { 437 @SuppressWarnings("unchecked") 438 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 439 if (classdata == null) return null; 440 441 try { 442 Object element = classdata.get(index); 443 return BootstrapMethodInvoker.widenAndCast(element, type); 444 } catch (RuntimeException|Error e) { 445 throw e; // let specified exceptions and other runtime exceptions/errors through 446 } catch (Throwable e) { 447 throw new InternalError(e); 448 } 449 } 450 451 /** 452 * Performs an unchecked "crack" of a 453 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 454 * The result is as if the user had obtained a lookup object capable enough 455 * to crack the target method handle, called 456 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 457 * on the target to obtain its symbolic reference, and then called 458 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 459 * to resolve the symbolic reference to a member. 460 * <p> 461 * If there is a security manager, its {@code checkPermission} method 462 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 463 * @param <T> the desired type of the result, either {@link Member} or a subtype 464 * @param target a direct method handle to crack into symbolic reference components 465 * @param expected a class object representing the desired result type {@code T} 466 * @return a reference to the method, constructor, or field object 467 * @throws SecurityException if the caller is not privileged to call {@code setAccessible} 468 * @throws NullPointerException if either argument is {@code null} 469 * @throws IllegalArgumentException if the target is not a direct method handle 470 * @throws ClassCastException if the member is not of the expected type 471 * @since 1.8 472 */ 473 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 474 @SuppressWarnings("removal") 475 SecurityManager smgr = System.getSecurityManager(); 476 if (smgr != null) smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION); 477 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 478 return lookup.revealDirect(target).reflectAs(expected, lookup); 479 } 480 481 /** 482 * A <em>lookup object</em> is a factory for creating method handles, 483 * when the creation requires access checking. 484 * Method handles do not perform 485 * access checks when they are called, but rather when they are created. 486 * Therefore, method handle access 487 * restrictions must be enforced when a method handle is created. 488 * The caller class against which those restrictions are enforced 489 * is known as the {@linkplain #lookupClass() lookup class}. 490 * <p> 491 * A lookup class which needs to create method handles will call 492 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 493 * When the {@code Lookup} factory object is created, the identity of the lookup class is 494 * determined, and securely stored in the {@code Lookup} object. 495 * The lookup class (or its delegates) may then use factory methods 496 * on the {@code Lookup} object to create method handles for access-checked members. 497 * This includes all methods, constructors, and fields which are allowed to the lookup class, 498 * even private ones. 499 * 500 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 501 * The factory methods on a {@code Lookup} object correspond to all major 502 * use cases for methods, constructors, and fields. 503 * Each method handle created by a factory method is the functional 504 * equivalent of a particular <em>bytecode behavior</em>. 505 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 506 * the Java Virtual Machine Specification.) 507 * Here is a summary of the correspondence between these factory methods and 508 * the behavior of the resulting method handles: 509 * <table class="striped"> 510 * <caption style="display:none">lookup method behaviors</caption> 511 * <thead> 512 * <tr> 513 * <th scope="col"><a id="equiv"></a>lookup expression</th> 514 * <th scope="col">member</th> 515 * <th scope="col">bytecode behavior</th> 516 * </tr> 517 * </thead> 518 * <tbody> 519 * <tr> 520 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 521 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 522 * </tr> 523 * <tr> 524 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 525 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 526 * </tr> 527 * <tr> 528 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 529 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 530 * </tr> 531 * <tr> 532 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 533 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 534 * </tr> 535 * <tr> 536 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 537 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 538 * </tr> 539 * <tr> 540 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 541 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 542 * </tr> 543 * <tr> 544 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 545 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 546 * </tr> 547 * <tr> 548 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 549 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 550 * </tr> 551 * <tr> 552 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 553 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 554 * </tr> 555 * <tr> 556 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 557 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 558 * </tr> 559 * <tr> 560 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 561 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 562 * </tr> 563 * <tr> 564 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 565 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 566 * </tr> 567 * <tr> 568 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 569 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 570 * </tr> 571 * <tr> 572 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 573 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 574 * </tr> 575 * </tbody> 576 * </table> 577 * 578 * Here, the type {@code C} is the class or interface being searched for a member, 579 * documented as a parameter named {@code refc} in the lookup methods. 580 * The method type {@code MT} is composed from the return type {@code T} 581 * and the sequence of argument types {@code A*}. 582 * The constructor also has a sequence of argument types {@code A*} and 583 * is deemed to return the newly-created object of type {@code C}. 584 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 585 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 586 * if it is present, it is always the leading argument to the method handle invocation. 587 * (In the case of some {@code protected} members, {@code this} may be 588 * restricted in type to the lookup class; see below.) 589 * The name {@code arg} stands for all the other method handle arguments. 590 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 591 * stands for a null reference if the accessed method or field is static, 592 * and {@code this} otherwise. 593 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 594 * for reflective objects corresponding to the given members declared in type {@code C}. 595 * <p> 596 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 597 * as if by {@code ldc CONSTANT_Class}. 598 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 599 * <p> 600 * In cases where the given member is of variable arity (i.e., a method or constructor) 601 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 602 * In all other cases, the returned method handle will be of fixed arity. 603 * <p style="font-size:smaller;"> 604 * <em>Discussion:</em> 605 * The equivalence between looked-up method handles and underlying 606 * class members and bytecode behaviors 607 * can break down in a few ways: 608 * <ul style="font-size:smaller;"> 609 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 610 * the lookup can still succeed, even when there is no equivalent 611 * Java expression or bytecoded constant. 612 * <li>Likewise, if {@code T} or {@code MT} 613 * is not symbolically accessible from the lookup class's loader, 614 * the lookup can still succeed. 615 * For example, lookups for {@code MethodHandle.invokeExact} and 616 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 617 * <li>If there is a security manager installed, it can forbid the lookup 618 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 619 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 620 * constant is not subject to security manager checks. 621 * <li>If the looked-up method has a 622 * <a href="MethodHandle.html#maxarity">very large arity</a>, 623 * the method handle creation may fail with an 624 * {@code IllegalArgumentException}, due to the method handle type having 625 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 626 * </ul> 627 * 628 * <h2><a id="access"></a>Access checking</h2> 629 * Access checks are applied in the factory methods of {@code Lookup}, 630 * when a method handle is created. 631 * This is a key difference from the Core Reflection API, since 632 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 633 * performs access checking against every caller, on every call. 634 * <p> 635 * All access checks start from a {@code Lookup} object, which 636 * compares its recorded lookup class against all requests to 637 * create method handles. 638 * A single {@code Lookup} object can be used to create any number 639 * of access-checked method handles, all checked against a single 640 * lookup class. 641 * <p> 642 * A {@code Lookup} object can be shared with other trusted code, 643 * such as a metaobject protocol. 644 * A shared {@code Lookup} object delegates the capability 645 * to create method handles on private members of the lookup class. 646 * Even if privileged code uses the {@code Lookup} object, 647 * the access checking is confined to the privileges of the 648 * original lookup class. 649 * <p> 650 * A lookup can fail, because 651 * the containing class is not accessible to the lookup class, or 652 * because the desired class member is missing, or because the 653 * desired class member is not accessible to the lookup class, or 654 * because the lookup object is not trusted enough to access the member. 655 * In the case of a field setter function on a {@code final} field, 656 * finality enforcement is treated as a kind of access control, 657 * and the lookup will fail, except in special cases of 658 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 659 * In any of these cases, a {@code ReflectiveOperationException} will be 660 * thrown from the attempted lookup. The exact class will be one of 661 * the following: 662 * <ul> 663 * <li>NoSuchMethodException — if a method is requested but does not exist 664 * <li>NoSuchFieldException — if a field is requested but does not exist 665 * <li>IllegalAccessException — if the member exists but an access check fails 666 * </ul> 667 * <p> 668 * In general, the conditions under which a method handle may be 669 * looked up for a method {@code M} are no more restrictive than the conditions 670 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 671 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 672 * a method handle lookup will generally raise a corresponding 673 * checked exception, such as {@code NoSuchMethodException}. 674 * And the effect of invoking the method handle resulting from the lookup 675 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 676 * to executing the compiled, verified, and resolved call to {@code M}. 677 * The same point is true of fields and constructors. 678 * <p style="font-size:smaller;"> 679 * <em>Discussion:</em> 680 * Access checks only apply to named and reflected methods, 681 * constructors, and fields. 682 * Other method handle creation methods, such as 683 * {@link MethodHandle#asType MethodHandle.asType}, 684 * do not require any access checks, and are used 685 * independently of any {@code Lookup} object. 686 * <p> 687 * If the desired member is {@code protected}, the usual JVM rules apply, 688 * including the requirement that the lookup class must either be in the 689 * same package as the desired member, or must inherit that member. 690 * (See the Java Virtual Machine Specification, sections {@jvms 691 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 692 * In addition, if the desired member is a non-static field or method 693 * in a different package, the resulting method handle may only be applied 694 * to objects of the lookup class or one of its subclasses. 695 * This requirement is enforced by narrowing the type of the leading 696 * {@code this} parameter from {@code C} 697 * (which will necessarily be a superclass of the lookup class) 698 * to the lookup class itself. 699 * <p> 700 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 701 * that the receiver argument must match both the resolved method <em>and</em> 702 * the current class. Again, this requirement is enforced by narrowing the 703 * type of the leading parameter to the resulting method handle. 704 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 705 * <p> 706 * The JVM represents constructors and static initializer blocks as internal methods 707 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 708 * ConstantDescs#CLASS_INIT_NAME}). 709 * The internal syntax of invocation instructions allows them to refer to such internal 710 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 711 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 712 * <p> 713 * If the relationship between nested types is expressed directly through the 714 * {@code NestHost} and {@code NestMembers} attributes 715 * (see the Java Virtual Machine Specification, sections {@jvms 716 * 4.7.28} and {@jvms 4.7.29}), 717 * then the associated {@code Lookup} object provides direct access to 718 * the lookup class and all of its nestmates 719 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 720 * Otherwise, access between nested classes is obtained by the Java compiler creating 721 * a wrapper method to access a private method of another class in the same nest. 722 * For example, a nested class {@code C.D} 723 * can access private members within other related classes such as 724 * {@code C}, {@code C.D.E}, or {@code C.B}, 725 * but the Java compiler may need to generate wrapper methods in 726 * those related classes. In such cases, a {@code Lookup} object on 727 * {@code C.E} would be unable to access those private members. 728 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 729 * which can transform a lookup on {@code C.E} into one on any of those other 730 * classes, without special elevation of privilege. 731 * <p> 732 * The accesses permitted to a given lookup object may be limited, 733 * according to its set of {@link #lookupModes lookupModes}, 734 * to a subset of members normally accessible to the lookup class. 735 * For example, the {@link MethodHandles#publicLookup publicLookup} 736 * method produces a lookup object which is only allowed to access 737 * public members in public classes of exported packages. 738 * The caller sensitive method {@link MethodHandles#lookup lookup} 739 * produces a lookup object with full capabilities relative to 740 * its caller class, to emulate all supported bytecode behaviors. 741 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 742 * with fewer access modes than the original lookup object. 743 * 744 * <p style="font-size:smaller;"> 745 * <a id="privacc"></a> 746 * <em>Discussion of private and module access:</em> 747 * We say that a lookup has <em>private access</em> 748 * if its {@linkplain #lookupModes lookup modes} 749 * include the possibility of accessing {@code private} members 750 * (which includes the private members of nestmates). 751 * As documented in the relevant methods elsewhere, 752 * only lookups with private access possess the following capabilities: 753 * <ul style="font-size:smaller;"> 754 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 755 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 756 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 757 * for classes accessible to the lookup class 758 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 759 * within the same package member 760 * </ul> 761 * <p style="font-size:smaller;"> 762 * Similarly, a lookup with module access ensures that the original lookup creator was 763 * a member in the same module as the lookup class. 764 * <p style="font-size:smaller;"> 765 * Private and module access are independently determined modes; a lookup may have 766 * either or both or neither. A lookup which possesses both access modes is said to 767 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 768 * <p style="font-size:smaller;"> 769 * A lookup with <em>original access</em> ensures that this lookup is created by 770 * the original lookup class and the bootstrap method invoked by the VM. 771 * Such a lookup with original access also has private and module access 772 * which has the following additional capability: 773 * <ul style="font-size:smaller;"> 774 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 775 * such as {@code Class.forName} 776 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 777 * class data} associated with the lookup class</li> 778 * </ul> 779 * <p style="font-size:smaller;"> 780 * Each of these permissions is a consequence of the fact that a lookup object 781 * with private access can be securely traced back to an originating class, 782 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 783 * can be reliably determined and emulated by method handles. 784 * 785 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 786 * When a lookup class in one module {@code M1} accesses a class in another module 787 * {@code M2}, extra access checking is performed beyond the access mode bits. 788 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 789 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 790 * and when the type is in a package of {@code M2} that is exported to 791 * at least {@code M1}. 792 * <p> 793 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 794 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 795 * MethodHandles.privateLookupIn} methods. 796 * Teleporting across modules will always record the original lookup class as 797 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 798 * and drops {@link Lookup#MODULE MODULE} access. 799 * If the target class is in the same module as the lookup class {@code C}, 800 * then the target class becomes the new lookup class 801 * and there is no change to the previous lookup class. 802 * If the target class is in a different module from {@code M1} ({@code C}'s module), 803 * {@code C} becomes the new previous lookup class 804 * and the target class becomes the new lookup class. 805 * In that case, if there was already a previous lookup class in {@code M0}, 806 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 807 * drops all privileges. 808 * For example, 809 * {@snippet lang="java" : 810 * Lookup lookup = MethodHandles.lookup(); // in class C 811 * Lookup lookup2 = lookup.in(D.class); 812 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 813 * } 814 * <p> 815 * The {@link #lookup()} factory method produces a {@code Lookup} object 816 * with {@code null} previous lookup class. 817 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 818 * to class {@code D} without elevation of privileges. 819 * If {@code C} and {@code D} are in the same module, 820 * {@code lookup2} records {@code D} as the new lookup class and keeps the 821 * same previous lookup class as the original {@code lookup}, or 822 * {@code null} if not present. 823 * <p> 824 * When a {@code Lookup} teleports from a class 825 * in one nest to another nest, {@code PRIVATE} access is dropped. 826 * When a {@code Lookup} teleports from a class in one package to 827 * another package, {@code PACKAGE} access is dropped. 828 * When a {@code Lookup} teleports from a class in one module to another module, 829 * {@code MODULE} access is dropped. 830 * Teleporting across modules drops the ability to access non-exported classes 831 * in both the module of the new lookup class and the module of the old lookup class 832 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 833 * A {@code Lookup} can teleport back and forth to a class in the module of 834 * the lookup class and the module of the previous class lookup. 835 * Teleporting across modules can only decrease access but cannot increase it. 836 * Teleporting to some third module drops all accesses. 837 * <p> 838 * In the above example, if {@code C} and {@code D} are in different modules, 839 * {@code lookup2} records {@code D} as its lookup class and 840 * {@code C} as its previous lookup class and {@code lookup2} has only 841 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 842 * {@code C}'s module and {@code D}'s module. 843 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 844 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 845 * class {@code D} is recorded as its previous lookup class. 846 * <p> 847 * Teleporting across modules restricts access to the public types that 848 * both the lookup class and the previous lookup class can equally access 849 * (see below). 850 * <p> 851 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 852 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 853 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 854 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 855 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 856 * to call {@code privateLookupIn}. 857 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 858 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 859 * produces a new {@code Lookup} on {@code T} with full capabilities. 860 * A {@code lookup} on {@code C} is also allowed 861 * to do deep reflection on {@code T} in another module {@code M2} if 862 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 863 * the package containing {@code T} to at least {@code M1}. 864 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 865 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 866 * The resulting {@code Lookup} can be used to do member lookup or teleport 867 * to another lookup class by calling {@link #in Lookup::in}. But 868 * it cannot be used to obtain another private {@code Lookup} by calling 869 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 870 * because it has no {@code MODULE} access. 871 * <p> 872 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 873 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 874 * of {@code T}. Extreme caution should be taken when opening a package 875 * to another module as such defined classes have the same full privilege 876 * access as other members in {@code M2}. 877 * 878 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 879 * 880 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 881 * allows cross-module access. The access checking is performed with respect 882 * to both the lookup class and the previous lookup class if present. 883 * <p> 884 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 885 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 886 * exported unconditionally}. 887 * <p> 888 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 889 * the lookup with {@link #PUBLIC} mode can access all public types in modules 890 * that are readable to {@code M1} and the type is in a package that is exported 891 * at least to {@code M1}. 892 * <p> 893 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 894 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 895 * the intersection of all public types that are accessible to {@code M1} 896 * with all public types that are accessible to {@code M0}. {@code M0} 897 * reads {@code M1} and hence the set of accessible types includes: 898 * 899 * <ul> 900 * <li>unconditional-exported packages from {@code M1}</li> 901 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 902 * <li> 903 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 904 * and {@code M1} read {@code M2} 905 * </li> 906 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 907 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 908 * <li> 909 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 910 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 911 * </li> 912 * </ul> 913 * 914 * <h2><a id="access-modes"></a>Access modes</h2> 915 * 916 * The table below shows the access modes of a {@code Lookup} produced by 917 * any of the following factory or transformation methods: 918 * <ul> 919 * <li>{@link #lookup() MethodHandles::lookup}</li> 920 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 921 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 922 * <li>{@link Lookup#in Lookup::in}</li> 923 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 924 * </ul> 925 * 926 * <table class="striped"> 927 * <caption style="display:none"> 928 * Access mode summary 929 * </caption> 930 * <thead> 931 * <tr> 932 * <th scope="col">Lookup object</th> 933 * <th style="text-align:center">original</th> 934 * <th style="text-align:center">protected</th> 935 * <th style="text-align:center">private</th> 936 * <th style="text-align:center">package</th> 937 * <th style="text-align:center">module</th> 938 * <th style="text-align:center">public</th> 939 * </tr> 940 * </thead> 941 * <tbody> 942 * <tr> 943 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 944 * <td style="text-align:center">ORI</td> 945 * <td style="text-align:center">PRO</td> 946 * <td style="text-align:center">PRI</td> 947 * <td style="text-align:center">PAC</td> 948 * <td style="text-align:center">MOD</td> 949 * <td style="text-align:center">1R</td> 950 * </tr> 951 * <tr> 952 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 953 * <td></td> 954 * <td></td> 955 * <td></td> 956 * <td style="text-align:center">PAC</td> 957 * <td style="text-align:center">MOD</td> 958 * <td style="text-align:center">1R</td> 959 * </tr> 960 * <tr> 961 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 962 * <td></td> 963 * <td></td> 964 * <td></td> 965 * <td></td> 966 * <td style="text-align:center">MOD</td> 967 * <td style="text-align:center">1R</td> 968 * </tr> 969 * <tr> 970 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 971 * <td></td> 972 * <td></td> 973 * <td></td> 974 * <td></td> 975 * <td></td> 976 * <td style="text-align:center">2R</td> 977 * </tr> 978 * <tr> 979 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 980 * <td></td> 981 * <td></td> 982 * <td></td> 983 * <td></td> 984 * <td></td> 985 * <td style="text-align:center">2R</td> 986 * </tr> 987 * <tr> 988 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 989 * <td></td> 990 * <td style="text-align:center">PRO</td> 991 * <td style="text-align:center">PRI</td> 992 * <td style="text-align:center">PAC</td> 993 * <td style="text-align:center">MOD</td> 994 * <td style="text-align:center">1R</td> 995 * </tr> 996 * <tr> 997 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 998 * <td></td> 999 * <td style="text-align:center">PRO</td> 1000 * <td style="text-align:center">PRI</td> 1001 * <td style="text-align:center">PAC</td> 1002 * <td style="text-align:center">MOD</td> 1003 * <td style="text-align:center">1R</td> 1004 * </tr> 1005 * <tr> 1006 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 1007 * <td></td> 1008 * <td></td> 1009 * <td></td> 1010 * <td style="text-align:center">PAC</td> 1011 * <td style="text-align:center">MOD</td> 1012 * <td style="text-align:center">1R</td> 1013 * </tr> 1014 * <tr> 1015 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 1016 * <td></td> 1017 * <td></td> 1018 * <td></td> 1019 * <td></td> 1020 * <td style="text-align:center">MOD</td> 1021 * <td style="text-align:center">1R</td> 1022 * </tr> 1023 * <tr> 1024 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1025 * <td></td> 1026 * <td></td> 1027 * <td></td> 1028 * <td></td> 1029 * <td></td> 1030 * <td style="text-align:center">2R</td> 1031 * </tr> 1032 * <tr> 1033 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1034 * <td></td> 1035 * <td></td> 1036 * <td style="text-align:center">PRI</td> 1037 * <td style="text-align:center">PAC</td> 1038 * <td style="text-align:center">MOD</td> 1039 * <td style="text-align:center">1R</td> 1040 * </tr> 1041 * <tr> 1042 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1043 * <td></td> 1044 * <td></td> 1045 * <td></td> 1046 * <td style="text-align:center">PAC</td> 1047 * <td style="text-align:center">MOD</td> 1048 * <td style="text-align:center">1R</td> 1049 * </tr> 1050 * <tr> 1051 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1052 * <td></td> 1053 * <td></td> 1054 * <td></td> 1055 * <td></td> 1056 * <td style="text-align:center">MOD</td> 1057 * <td style="text-align:center">1R</td> 1058 * </tr> 1059 * <tr> 1060 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1061 * <td></td> 1062 * <td></td> 1063 * <td></td> 1064 * <td></td> 1065 * <td></td> 1066 * <td style="text-align:center">1R</td> 1067 * </tr> 1068 * <tr> 1069 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1070 * <td></td> 1071 * <td></td> 1072 * <td></td> 1073 * <td></td> 1074 * <td></td> 1075 * <td style="text-align:center">none</td> 1076 * <tr> 1077 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1078 * <td></td> 1079 * <td style="text-align:center">PRO</td> 1080 * <td style="text-align:center">PRI</td> 1081 * <td style="text-align:center">PAC</td> 1082 * <td></td> 1083 * <td style="text-align:center">2R</td> 1084 * </tr> 1085 * <tr> 1086 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1087 * <td></td> 1088 * <td style="text-align:center">PRO</td> 1089 * <td style="text-align:center">PRI</td> 1090 * <td style="text-align:center">PAC</td> 1091 * <td></td> 1092 * <td style="text-align:center">2R</td> 1093 * </tr> 1094 * <tr> 1095 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1096 * <td></td> 1097 * <td></td> 1098 * <td></td> 1099 * <td></td> 1100 * <td></td> 1101 * <td style="text-align:center">IAE</td> 1102 * </tr> 1103 * <tr> 1104 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1105 * <td></td> 1106 * <td></td> 1107 * <td></td> 1108 * <td style="text-align:center">PAC</td> 1109 * <td></td> 1110 * <td style="text-align:center">2R</td> 1111 * </tr> 1112 * <tr> 1113 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1114 * <td></td> 1115 * <td></td> 1116 * <td></td> 1117 * <td></td> 1118 * <td></td> 1119 * <td style="text-align:center">2R</td> 1120 * </tr> 1121 * <tr> 1122 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1123 * <td></td> 1124 * <td></td> 1125 * <td></td> 1126 * <td></td> 1127 * <td></td> 1128 * <td style="text-align:center">2R</td> 1129 * </tr> 1130 * <tr> 1131 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1132 * <td></td> 1133 * <td></td> 1134 * <td></td> 1135 * <td></td> 1136 * <td></td> 1137 * <td style="text-align:center">none</td> 1138 * </tr> 1139 * <tr> 1140 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1141 * <td></td> 1142 * <td></td> 1143 * <td style="text-align:center">PRI</td> 1144 * <td style="text-align:center">PAC</td> 1145 * <td></td> 1146 * <td style="text-align:center">2R</td> 1147 * </tr> 1148 * <tr> 1149 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1150 * <td></td> 1151 * <td></td> 1152 * <td></td> 1153 * <td style="text-align:center">PAC</td> 1154 * <td></td> 1155 * <td style="text-align:center">2R</td> 1156 * </tr> 1157 * <tr> 1158 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1159 * <td></td> 1160 * <td></td> 1161 * <td></td> 1162 * <td></td> 1163 * <td></td> 1164 * <td style="text-align:center">2R</td> 1165 * </tr> 1166 * <tr> 1167 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1168 * <td></td> 1169 * <td></td> 1170 * <td></td> 1171 * <td></td> 1172 * <td></td> 1173 * <td style="text-align:center">2R</td> 1174 * </tr> 1175 * <tr> 1176 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1177 * <td></td> 1178 * <td></td> 1179 * <td></td> 1180 * <td></td> 1181 * <td></td> 1182 * <td style="text-align:center">none</td> 1183 * </tr> 1184 * <tr> 1185 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1186 * <td></td> 1187 * <td></td> 1188 * <td style="text-align:center">PRI</td> 1189 * <td style="text-align:center">PAC</td> 1190 * <td style="text-align:center">MOD</td> 1191 * <td style="text-align:center">1R</td> 1192 * </tr> 1193 * <tr> 1194 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1195 * <td></td> 1196 * <td></td> 1197 * <td></td> 1198 * <td style="text-align:center">PAC</td> 1199 * <td style="text-align:center">MOD</td> 1200 * <td style="text-align:center">1R</td> 1201 * </tr> 1202 * <tr> 1203 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1204 * <td></td> 1205 * <td></td> 1206 * <td></td> 1207 * <td></td> 1208 * <td style="text-align:center">MOD</td> 1209 * <td style="text-align:center">1R</td> 1210 * </tr> 1211 * <tr> 1212 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1213 * <td></td> 1214 * <td></td> 1215 * <td></td> 1216 * <td></td> 1217 * <td></td> 1218 * <td style="text-align:center">1R</td> 1219 * </tr> 1220 * <tr> 1221 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1222 * <td></td> 1223 * <td></td> 1224 * <td></td> 1225 * <td></td> 1226 * <td></td> 1227 * <td style="text-align:center">none</td> 1228 * </tr> 1229 * <tr> 1230 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1231 * <td></td> 1232 * <td></td> 1233 * <td></td> 1234 * <td></td> 1235 * <td></td> 1236 * <td style="text-align:center">U</td> 1237 * </tr> 1238 * <tr> 1239 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1240 * <td></td> 1241 * <td></td> 1242 * <td></td> 1243 * <td></td> 1244 * <td></td> 1245 * <td style="text-align:center">U</td> 1246 * </tr> 1247 * <tr> 1248 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1249 * <td></td> 1250 * <td></td> 1251 * <td></td> 1252 * <td></td> 1253 * <td></td> 1254 * <td style="text-align:center">U</td> 1255 * </tr> 1256 * <tr> 1257 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1258 * <td></td> 1259 * <td></td> 1260 * <td></td> 1261 * <td></td> 1262 * <td></td> 1263 * <td style="text-align:center">none</td> 1264 * </tr> 1265 * <tr> 1266 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1267 * <td></td> 1268 * <td></td> 1269 * <td></td> 1270 * <td></td> 1271 * <td></td> 1272 * <td style="text-align:center">IAE</td> 1273 * </tr> 1274 * <tr> 1275 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1276 * <td></td> 1277 * <td></td> 1278 * <td></td> 1279 * <td></td> 1280 * <td></td> 1281 * <td style="text-align:center">none</td> 1282 * </tr> 1283 * </tbody> 1284 * </table> 1285 * 1286 * <p> 1287 * Notes: 1288 * <ul> 1289 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1290 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1291 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1292 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1293 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1294 * {@code PRO} indicates {@link #PROTECTED} bit set, 1295 * {@code PRI} indicates {@link #PRIVATE} bit set, 1296 * {@code PAC} indicates {@link #PACKAGE} bit set, 1297 * {@code MOD} indicates {@link #MODULE} bit set, 1298 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1299 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1300 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1301 * <li>Public access comes in three kinds: 1302 * <ul> 1303 * <li>unconditional ({@code U}): the lookup assumes readability. 1304 * The lookup has {@code null} previous lookup class. 1305 * <li>one-module-reads ({@code 1R}): the module access checking is 1306 * performed with respect to the lookup class. The lookup has {@code null} 1307 * previous lookup class. 1308 * <li>two-module-reads ({@code 2R}): the module access checking is 1309 * performed with respect to the lookup class and the previous lookup class. 1310 * The lookup has a non-null previous lookup class which is in a 1311 * different module from the current lookup class. 1312 * </ul> 1313 * <li>Any attempt to reach a third module loses all access.</li> 1314 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1315 * all access modes are dropped.</li> 1316 * </ul> 1317 * 1318 * <h2><a id="secmgr"></a>Security manager interactions</h2> 1319 * Although bytecode instructions can only refer to classes in 1320 * a related class loader, this API can search for methods in any 1321 * class, as long as a reference to its {@code Class} object is 1322 * available. Such cross-loader references are also possible with the 1323 * Core Reflection API, and are impossible to bytecode instructions 1324 * such as {@code invokestatic} or {@code getfield}. 1325 * There is a {@linkplain java.lang.SecurityManager security manager API} 1326 * to allow applications to check such cross-loader references. 1327 * These checks apply to both the {@code MethodHandles.Lookup} API 1328 * and the Core Reflection API 1329 * (as found on {@link java.lang.Class Class}). 1330 * <p> 1331 * If a security manager is present, member and class lookups are subject to 1332 * additional checks. 1333 * From one to three calls are made to the security manager. 1334 * Any of these calls can refuse access by throwing a 1335 * {@link java.lang.SecurityException SecurityException}. 1336 * Define {@code smgr} as the security manager, 1337 * {@code lookc} as the lookup class of the current lookup object, 1338 * {@code refc} as the containing class in which the member 1339 * is being sought, and {@code defc} as the class in which the 1340 * member is actually defined. 1341 * (If a class or other type is being accessed, 1342 * the {@code refc} and {@code defc} values are the class itself.) 1343 * The value {@code lookc} is defined as <em>not present</em> 1344 * if the current lookup object does not have 1345 * {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1346 * The calls are made according to the following rules: 1347 * <ul> 1348 * <li><b>Step 1:</b> 1349 * If {@code lookc} is not present, or if its class loader is not 1350 * the same as or an ancestor of the class loader of {@code refc}, 1351 * then {@link SecurityManager#checkPackageAccess 1352 * smgr.checkPackageAccess(refcPkg)} is called, 1353 * where {@code refcPkg} is the package of {@code refc}. 1354 * <li><b>Step 2a:</b> 1355 * If the retrieved member is not public and 1356 * {@code lookc} is not present, then 1357 * {@link SecurityManager#checkPermission smgr.checkPermission} 1358 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 1359 * <li><b>Step 2b:</b> 1360 * If the retrieved class has a {@code null} class loader, 1361 * and {@code lookc} is not present, then 1362 * {@link SecurityManager#checkPermission smgr.checkPermission} 1363 * with {@code RuntimePermission("getClassLoader")} is called. 1364 * <li><b>Step 3:</b> 1365 * If the retrieved member is not public, 1366 * and if {@code lookc} is not present, 1367 * and if {@code defc} and {@code refc} are different, 1368 * then {@link SecurityManager#checkPackageAccess 1369 * smgr.checkPackageAccess(defcPkg)} is called, 1370 * where {@code defcPkg} is the package of {@code defc}. 1371 * </ul> 1372 * Security checks are performed after other access checks have passed. 1373 * Therefore, the above rules presuppose a member or class that is public, 1374 * or else that is being accessed from a lookup class that has 1375 * rights to access the member or class. 1376 * <p> 1377 * If a security manager is present and the current lookup object does not have 1378 * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then 1379 * {@link #defineClass(byte[]) defineClass}, 1380 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass}, 1381 * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...) 1382 * defineHiddenClassWithClassData} 1383 * calls {@link SecurityManager#checkPermission smgr.checkPermission} 1384 * with {@code RuntimePermission("defineClass")}. 1385 * 1386 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1387 * A small number of Java methods have a special property called caller sensitivity. 1388 * A <em>caller-sensitive</em> method can behave differently depending on the 1389 * identity of its immediate caller. 1390 * <p> 1391 * If a method handle for a caller-sensitive method is requested, 1392 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1393 * but they take account of the lookup class in a special way. 1394 * The resulting method handle behaves as if it were called 1395 * from an instruction contained in the lookup class, 1396 * so that the caller-sensitive method detects the lookup class. 1397 * (By contrast, the invoker of the method handle is disregarded.) 1398 * Thus, in the case of caller-sensitive methods, 1399 * different lookup classes may give rise to 1400 * differently behaving method handles. 1401 * <p> 1402 * In cases where the lookup object is 1403 * {@link MethodHandles#publicLookup() publicLookup()}, 1404 * or some other lookup object without the 1405 * {@linkplain #ORIGINAL original access}, 1406 * the lookup class is disregarded. 1407 * In such cases, no caller-sensitive method handle can be created, 1408 * access is forbidden, and the lookup fails with an 1409 * {@code IllegalAccessException}. 1410 * <p style="font-size:smaller;"> 1411 * <em>Discussion:</em> 1412 * For example, the caller-sensitive method 1413 * {@link java.lang.Class#forName(String) Class.forName(x)} 1414 * can return varying classes or throw varying exceptions, 1415 * depending on the class loader of the class that calls it. 1416 * A public lookup of {@code Class.forName} will fail, because 1417 * there is no reasonable way to determine its bytecode behavior. 1418 * <p style="font-size:smaller;"> 1419 * If an application caches method handles for broad sharing, 1420 * it should use {@code publicLookup()} to create them. 1421 * If there is a lookup of {@code Class.forName}, it will fail, 1422 * and the application must take appropriate action in that case. 1423 * It may be that a later lookup, perhaps during the invocation of a 1424 * bootstrap method, can incorporate the specific identity 1425 * of the caller, making the method accessible. 1426 * <p style="font-size:smaller;"> 1427 * The function {@code MethodHandles.lookup} is caller sensitive 1428 * so that there can be a secure foundation for lookups. 1429 * Nearly all other methods in the JSR 292 API rely on lookup 1430 * objects to check access requests. 1431 */ 1432 public static final 1433 class Lookup { 1434 /** The class on behalf of whom the lookup is being performed. */ 1435 private final Class<?> lookupClass; 1436 1437 /** previous lookup class */ 1438 private final Class<?> prevLookupClass; 1439 1440 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1441 private final int allowedModes; 1442 1443 static { 1444 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1445 } 1446 1447 /** A single-bit mask representing {@code public} access, 1448 * which may contribute to the result of {@link #lookupModes lookupModes}. 1449 * The value, {@code 0x01}, happens to be the same as the value of the 1450 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1451 * <p> 1452 * A {@code Lookup} with this lookup mode performs cross-module access check 1453 * with respect to the {@linkplain #lookupClass() lookup class} and 1454 * {@linkplain #previousLookupClass() previous lookup class} if present. 1455 */ 1456 public static final int PUBLIC = Modifier.PUBLIC; 1457 1458 /** A single-bit mask representing {@code private} access, 1459 * which may contribute to the result of {@link #lookupModes lookupModes}. 1460 * The value, {@code 0x02}, happens to be the same as the value of the 1461 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1462 */ 1463 public static final int PRIVATE = Modifier.PRIVATE; 1464 1465 /** A single-bit mask representing {@code protected} access, 1466 * which may contribute to the result of {@link #lookupModes lookupModes}. 1467 * The value, {@code 0x04}, happens to be the same as the value of the 1468 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1469 */ 1470 public static final int PROTECTED = Modifier.PROTECTED; 1471 1472 /** A single-bit mask representing {@code package} access (default access), 1473 * which may contribute to the result of {@link #lookupModes lookupModes}. 1474 * The value is {@code 0x08}, which does not correspond meaningfully to 1475 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1476 */ 1477 public static final int PACKAGE = Modifier.STATIC; 1478 1479 /** A single-bit mask representing {@code module} access, 1480 * which may contribute to the result of {@link #lookupModes lookupModes}. 1481 * The value is {@code 0x10}, which does not correspond meaningfully to 1482 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1483 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1484 * with this lookup mode can access all public types in the module of the 1485 * lookup class and public types in packages exported by other modules 1486 * to the module of the lookup class. 1487 * <p> 1488 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1489 * previous lookup class} is always {@code null}. 1490 * 1491 * @since 9 1492 */ 1493 public static final int MODULE = PACKAGE << 1; 1494 1495 /** A single-bit mask representing {@code unconditional} access 1496 * which may contribute to the result of {@link #lookupModes lookupModes}. 1497 * The value is {@code 0x20}, which does not correspond meaningfully to 1498 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1499 * A {@code Lookup} with this lookup mode assumes {@linkplain 1500 * java.lang.Module#canRead(java.lang.Module) readability}. 1501 * This lookup mode can access all public members of public types 1502 * of all modules when the type is in a package that is {@link 1503 * java.lang.Module#isExported(String) exported unconditionally}. 1504 * 1505 * <p> 1506 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1507 * previous lookup class} is always {@code null}. 1508 * 1509 * @since 9 1510 * @see #publicLookup() 1511 */ 1512 public static final int UNCONDITIONAL = PACKAGE << 2; 1513 1514 /** A single-bit mask representing {@code original} access 1515 * which may contribute to the result of {@link #lookupModes lookupModes}. 1516 * The value is {@code 0x40}, which does not correspond meaningfully to 1517 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1518 * 1519 * <p> 1520 * If this lookup mode is set, the {@code Lookup} object must be 1521 * created by the original lookup class by calling 1522 * {@link MethodHandles#lookup()} method or by a bootstrap method 1523 * invoked by the VM. The {@code Lookup} object with this lookup 1524 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1525 * 1526 * @since 16 1527 */ 1528 public static final int ORIGINAL = PACKAGE << 3; 1529 1530 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1531 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1532 private static final int TRUSTED = -1; 1533 1534 /* 1535 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1536 * Adjust 0 => PACKAGE 1537 */ 1538 private static int fixmods(int mods) { 1539 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1540 if (Modifier.isPublic(mods)) 1541 mods |= UNCONDITIONAL; 1542 return (mods != 0) ? mods : PACKAGE; 1543 } 1544 1545 /** Tells which class is performing the lookup. It is this class against 1546 * which checks are performed for visibility and access permissions. 1547 * <p> 1548 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1549 * access checks are performed against both the lookup class and the previous lookup class. 1550 * <p> 1551 * The class implies a maximum level of access permission, 1552 * but the permissions may be additionally limited by the bitmask 1553 * {@link #lookupModes lookupModes}, which controls whether non-public members 1554 * can be accessed. 1555 * @return the lookup class, on behalf of which this lookup object finds members 1556 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1557 */ 1558 public Class<?> lookupClass() { 1559 return lookupClass; 1560 } 1561 1562 /** Reports a lookup class in another module that this lookup object 1563 * was previously teleported from, or {@code null}. 1564 * <p> 1565 * A {@code Lookup} object produced by the factory methods, such as the 1566 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1567 * has {@code null} previous lookup class. 1568 * A {@code Lookup} object has a non-null previous lookup class 1569 * when this lookup was teleported from an old lookup class 1570 * in one module to a new lookup class in another module. 1571 * 1572 * @return the lookup class in another module that this lookup object was 1573 * previously teleported from, or {@code null} 1574 * @since 14 1575 * @see #in(Class) 1576 * @see MethodHandles#privateLookupIn(Class, Lookup) 1577 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1578 */ 1579 public Class<?> previousLookupClass() { 1580 return prevLookupClass; 1581 } 1582 1583 // This is just for calling out to MethodHandleImpl. 1584 private Class<?> lookupClassOrNull() { 1585 return (allowedModes == TRUSTED) ? null : lookupClass; 1586 } 1587 1588 /** Tells which access-protection classes of members this lookup object can produce. 1589 * The result is a bit-mask of the bits 1590 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1591 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1592 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1593 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1594 * {@linkplain #MODULE MODULE (0x10)}, 1595 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1596 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1597 * <p> 1598 * A freshly-created lookup object 1599 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1600 * all possible bits set, except {@code UNCONDITIONAL}. 1601 * A lookup object on a new lookup class 1602 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1603 * may have some mode bits set to zero. 1604 * Mode bits can also be 1605 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1606 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1607 * The purpose of this is to restrict access via the new lookup object, 1608 * so that it can access only names which can be reached by the original 1609 * lookup object, and also by the new lookup class. 1610 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1611 * @see #in 1612 * @see #dropLookupMode 1613 */ 1614 public int lookupModes() { 1615 return allowedModes & ALL_MODES; 1616 } 1617 1618 /** Embody the current class (the lookupClass) as a lookup class 1619 * for method handle creation. 1620 * Must be called by from a method in this package, 1621 * which in turn is called by a method not in this package. 1622 */ 1623 Lookup(Class<?> lookupClass) { 1624 this(lookupClass, null, FULL_POWER_MODES); 1625 } 1626 1627 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1628 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1629 && prevLookupClass.getModule() != lookupClass.getModule()); 1630 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1631 this.lookupClass = lookupClass; 1632 this.prevLookupClass = prevLookupClass; 1633 this.allowedModes = allowedModes; 1634 } 1635 1636 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1637 // make sure we haven't accidentally picked up a privileged class: 1638 checkUnprivilegedlookupClass(lookupClass); 1639 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1640 } 1641 1642 /** 1643 * Creates a lookup on the specified new lookup class. 1644 * The resulting object will report the specified 1645 * class as its own {@link #lookupClass() lookupClass}. 1646 * 1647 * <p> 1648 * However, the resulting {@code Lookup} object is guaranteed 1649 * to have no more access capabilities than the original. 1650 * In particular, access capabilities can be lost as follows:<ul> 1651 * <li>If the new lookup class is different from the old lookup class, 1652 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1653 * <li>If the new lookup class is in a different module from the old one, 1654 * i.e. {@link #MODULE MODULE} access is lost. 1655 * <li>If the new lookup class is in a different package 1656 * than the old one, protected and default (package) members will not be accessible, 1657 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1658 * <li>If the new lookup class is not within the same package member 1659 * as the old one, private members will not be accessible, and protected members 1660 * will not be accessible by virtue of inheritance, 1661 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1662 * (Protected members may continue to be accessible because of package sharing.) 1663 * <li>If the new lookup class is not 1664 * {@linkplain #accessClass(Class) accessible} to this lookup, 1665 * then no members, not even public members, will be accessible 1666 * i.e. all access modes are lost. 1667 * <li>If the new lookup class, the old lookup class and the previous lookup class 1668 * are all in different modules i.e. teleporting to a third module, 1669 * all access modes are lost. 1670 * </ul> 1671 * <p> 1672 * The new previous lookup class is chosen as follows: 1673 * <ul> 1674 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1675 * the new previous lookup class is {@code null}. 1676 * <li>If the new lookup class is in the same module as the old lookup class, 1677 * the new previous lookup class is the old previous lookup class. 1678 * <li>If the new lookup class is in a different module from the old lookup class, 1679 * the new previous lookup class is the old lookup class. 1680 *</ul> 1681 * <p> 1682 * The resulting lookup's capabilities for loading classes 1683 * (used during {@link #findClass} invocations) 1684 * are determined by the lookup class' loader, 1685 * which may change due to this operation. 1686 * 1687 * @param requestedLookupClass the desired lookup class for the new lookup object 1688 * @return a lookup object which reports the desired lookup class, or the same object 1689 * if there is no change 1690 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1691 * @throws NullPointerException if the argument is null 1692 * 1693 * @see #accessClass(Class) 1694 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1695 */ 1696 public Lookup in(Class<?> requestedLookupClass) { 1697 Objects.requireNonNull(requestedLookupClass); 1698 if (requestedLookupClass.isPrimitive()) 1699 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1700 if (requestedLookupClass.isArray()) 1701 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1702 1703 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1704 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1705 if (requestedLookupClass == this.lookupClass) 1706 return this; // keep same capabilities 1707 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1708 Module fromModule = this.lookupClass.getModule(); 1709 Module targetModule = requestedLookupClass.getModule(); 1710 Class<?> plc = this.previousLookupClass(); 1711 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1712 assert plc == null; 1713 newModes = UNCONDITIONAL; 1714 } else if (fromModule != targetModule) { 1715 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1716 // allow hopping back and forth between fromModule and plc's module 1717 // but not the third module 1718 newModes = 0; 1719 } 1720 // drop MODULE access 1721 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1722 // teleport from this lookup class 1723 plc = this.lookupClass; 1724 } 1725 if ((newModes & PACKAGE) != 0 1726 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1727 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1728 } 1729 // Allow nestmate lookups to be created without special privilege: 1730 if ((newModes & PRIVATE) != 0 1731 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1732 newModes &= ~(PRIVATE|PROTECTED); 1733 } 1734 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1735 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1736 // The requested class it not accessible from the lookup class. 1737 // No permissions. 1738 newModes = 0; 1739 } 1740 return newLookup(requestedLookupClass, plc, newModes); 1741 } 1742 1743 /** 1744 * Creates a lookup on the same lookup class which this lookup object 1745 * finds members, but with a lookup mode that has lost the given lookup mode. 1746 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1747 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1748 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1749 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1750 * 1751 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1752 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1753 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1754 * lookup has no access. 1755 * 1756 * <p> If this lookup is not a public lookup, then the following applies 1757 * regardless of its {@linkplain #lookupModes() lookup modes}. 1758 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1759 * dropped and so the resulting lookup mode will never have these access 1760 * capabilities. When dropping {@code PACKAGE} 1761 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1762 * access. When dropping {@code MODULE} then the resulting lookup will not 1763 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1764 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1765 * 1766 * @apiNote 1767 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1768 * delegate non-public access within the package of the lookup class without 1769 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1770 * A lookup with {@code MODULE} but not 1771 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1772 * the module of the lookup class without conferring package access. 1773 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1774 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1775 * to public classes accessible to both the module of the lookup class 1776 * and the module of the previous lookup class. 1777 * 1778 * @param modeToDrop the lookup mode to drop 1779 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1780 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1781 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1782 * or {@code UNCONDITIONAL} 1783 * @see MethodHandles#privateLookupIn 1784 * @since 9 1785 */ 1786 public Lookup dropLookupMode(int modeToDrop) { 1787 int oldModes = lookupModes(); 1788 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1789 switch (modeToDrop) { 1790 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1791 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1792 case PACKAGE: newModes &= ~(PRIVATE); break; 1793 case PROTECTED: 1794 case PRIVATE: 1795 case ORIGINAL: 1796 case UNCONDITIONAL: break; 1797 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1798 } 1799 if (newModes == oldModes) return this; // return self if no change 1800 return newLookup(lookupClass(), previousLookupClass(), newModes); 1801 } 1802 1803 /** 1804 * Creates and links a class or interface from {@code bytes} 1805 * with the same class loader and in the same runtime package and 1806 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1807 * {@linkplain #lookupClass() lookup class} as if calling 1808 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1809 * ClassLoader::defineClass}. 1810 * 1811 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1812 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1813 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1814 * that the lookup object was created by a caller in the runtime package (or derived 1815 * from a lookup originally created by suitably privileged code to a target class in 1816 * the runtime package). </p> 1817 * 1818 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1819 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1820 * same package as the lookup class. </p> 1821 * 1822 * <p> This method does not run the class initializer. The class initializer may 1823 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1824 * Specification</em>. </p> 1825 * 1826 * <p> If there is a security manager and this lookup does not have {@linkplain 1827 * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method 1828 * is first called to check {@code RuntimePermission("defineClass")}. </p> 1829 * 1830 * @param bytes the class bytes 1831 * @return the {@code Class} object for the class 1832 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1833 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1834 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1835 * than the lookup class or {@code bytes} is not a class or interface 1836 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1837 * @throws VerifyError if the newly created class cannot be verified 1838 * @throws LinkageError if the newly created class cannot be linked for any other reason 1839 * @throws SecurityException if a security manager is present and it 1840 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1841 * @throws NullPointerException if {@code bytes} is {@code null} 1842 * @since 9 1843 * @see MethodHandles#privateLookupIn 1844 * @see Lookup#dropLookupMode 1845 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1846 */ 1847 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1848 ensureDefineClassPermission(); 1849 if ((lookupModes() & PACKAGE) == 0) 1850 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1851 return makeClassDefiner(bytes.clone()).defineClass(false); 1852 } 1853 1854 private void ensureDefineClassPermission() { 1855 if (allowedModes == TRUSTED) return; 1856 1857 if (!hasFullPrivilegeAccess()) { 1858 @SuppressWarnings("removal") 1859 SecurityManager sm = System.getSecurityManager(); 1860 if (sm != null) 1861 sm.checkPermission(new RuntimePermission("defineClass")); 1862 } 1863 } 1864 1865 /** 1866 * The set of class options that specify whether a hidden class created by 1867 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1868 * Lookup::defineHiddenClass} method is dynamically added as a new member 1869 * to the nest of a lookup class and/or whether a hidden class has 1870 * a strong relationship with the class loader marked as its defining loader. 1871 * 1872 * @since 15 1873 */ 1874 public enum ClassOption { 1875 /** 1876 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1877 * of a lookup class as a nestmate. 1878 * 1879 * <p> A hidden nestmate class has access to the private members of all 1880 * classes and interfaces in the same nest. 1881 * 1882 * @see Class#getNestHost() 1883 */ 1884 NESTMATE(NESTMATE_CLASS), 1885 1886 /** 1887 * Specifies that a hidden class has a <em>strong</em> 1888 * relationship with the class loader marked as its defining loader, 1889 * as a normal class or interface has with its own defining loader. 1890 * This means that the hidden class may be unloaded if and only if 1891 * its defining loader is not reachable and thus may be reclaimed 1892 * by a garbage collector (JLS {@jls 12.7}). 1893 * 1894 * <p> By default, a hidden class or interface may be unloaded 1895 * even if the class loader that is marked as its defining loader is 1896 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1897 1898 * 1899 * @jls 12.7 Unloading of Classes and Interfaces 1900 */ 1901 STRONG(STRONG_LOADER_LINK); 1902 1903 /* the flag value is used by VM at define class time */ 1904 private final int flag; 1905 ClassOption(int flag) { 1906 this.flag = flag; 1907 } 1908 1909 static int optionsToFlag(Set<ClassOption> options) { 1910 int flags = 0; 1911 for (ClassOption cp : options) { 1912 flags |= cp.flag; 1913 } 1914 return flags; 1915 } 1916 } 1917 1918 /** 1919 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1920 * returning a {@code Lookup} on the newly created class or interface. 1921 * 1922 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1923 * which either defines {@code C} directly or delegates to another class loader. 1924 * A class loader defines {@code C} directly by invoking 1925 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1926 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1927 * to derive {@code C} from a purported representation in {@code class} file format. 1928 * In situations where use of a class loader is undesirable, a class or interface 1929 * {@code C} can be created by this method instead. This method is capable of 1930 * defining {@code C}, and thereby creating it, without invoking 1931 * {@code ClassLoader::defineClass}. 1932 * Instead, this method defines {@code C} as if by arranging for 1933 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1934 * from a purported representation in {@code class} file format 1935 * using the following rules: 1936 * 1937 * <ol> 1938 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1939 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1940 * This level of access is needed to create {@code C} in the module 1941 * of the lookup class of this {@code Lookup}.</li> 1942 * 1943 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1944 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1945 * The major and minor version may differ from the {@code class} file version 1946 * of the lookup class of this {@code Lookup}.</li> 1947 * 1948 * <li> The value of {@code this_class} must be a valid index in the 1949 * {@code constant_pool} table, and the entry at that index must be a valid 1950 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1951 * encoded in internal form that is specified by this structure. {@code N} must 1952 * denote a class or interface in the same package as the lookup class.</li> 1953 * 1954 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1955 * where {@code <suffix>} is an unqualified name. 1956 * 1957 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1958 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1959 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1960 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1961 * refers to the new {@code CONSTANT_Utf8_info} structure. 1962 * 1963 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1964 * 1965 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1966 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1967 * with the following adjustments: 1968 * <ul> 1969 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1970 * that includes a single {@code "."} character, even though this is not a valid 1971 * binary class or interface name in internal form.</li> 1972 * 1973 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1974 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1975 * 1976 * <li> {@code C} is considered to have the same runtime 1977 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1978 * and {@linkplain java.security.ProtectionDomain protection domain} 1979 * as the lookup class of this {@code Lookup}. 1980 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1981 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1982 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1983 * <ul> 1984 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1985 * even though this is not a valid binary class or interface name.</li> 1986 * <li> {@link Class#descriptorString()} returns the string 1987 * {@code "L" + N + "." + <suffix> + ";"}, 1988 * even though this is not a valid type descriptor name.</li> 1989 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1990 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1991 * </ul> 1992 * </ul> 1993 * </li> 1994 * </ol> 1995 * 1996 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1997 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1998 * <ul> 1999 * <li> During verification, whenever it is necessary to load the class named 2000 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 2001 * made of any class loader.</li> 2002 * 2003 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 2004 * by {@code this_class}, the symbolic reference is considered to be resolved to 2005 * {@code C} and resolution always succeeds immediately.</li> 2006 * </ul> 2007 * 2008 * <p> If the {@code initialize} parameter is {@code true}, 2009 * then {@code C} is initialized by the Java Virtual Machine. 2010 * 2011 * <p> The newly created class or interface {@code C} serves as the 2012 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 2013 * returned by this method. {@code C} is <em>hidden</em> in the sense that 2014 * no other class or interface can refer to {@code C} via a constant pool entry. 2015 * That is, a hidden class or interface cannot be named as a supertype, a field type, 2016 * a method parameter type, or a method return type by any other class. 2017 * This is because a hidden class or interface does not have a binary name, so 2018 * there is no internal form available to record in any class's constant pool. 2019 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 2020 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 2021 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 2022 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 2023 * JVM Tool Interface</a>. 2024 * 2025 * <p> A class or interface created by 2026 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 2027 * a class loader} has a strong relationship with that class loader. 2028 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 2029 * that {@linkplain Class#getClassLoader() defined it}. 2030 * This means that a class created by a class loader may be unloaded if and 2031 * only if its defining loader is not reachable and thus may be reclaimed 2032 * by a garbage collector (JLS {@jls 12.7}). 2033 * 2034 * By default, however, a hidden class or interface may be unloaded even if 2035 * the class loader that is marked as its defining loader is 2036 * <a href="../ref/package-summary.html#reachability">reachable</a>. 2037 * This behavior is useful when a hidden class or interface serves multiple 2038 * classes defined by arbitrary class loaders. In other cases, a hidden 2039 * class or interface may be linked to a single class (or a small number of classes) 2040 * with the same defining loader as the hidden class or interface. 2041 * In such cases, where the hidden class or interface must be coterminous 2042 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 2043 * option may be passed in {@code options}. 2044 * This arranges for a hidden class to have the same strong relationship 2045 * with the class loader marked as its defining loader, 2046 * as a normal class or interface has with its own defining loader. 2047 * 2048 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 2049 * may still prevent a hidden class or interface from being 2050 * unloaded by ensuring that the {@code Class} object is reachable. 2051 * 2052 * <p> The unloading characteristics are set for each hidden class when it is 2053 * defined, and cannot be changed later. An advantage of allowing hidden classes 2054 * to be unloaded independently of the class loader marked as their defining loader 2055 * is that a very large number of hidden classes may be created by an application. 2056 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 2057 * just as if normal classes were created by class loaders. 2058 * 2059 * <p> Classes and interfaces in a nest are allowed to have mutual access to 2060 * their private members. The nest relationship is determined by 2061 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 2062 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 2063 * By default, a hidden class belongs to a nest consisting only of itself 2064 * because a hidden class has no binary name. 2065 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 2066 * to create a hidden class or interface {@code C} as a member of a nest. 2067 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 2068 * in the {@code ClassFile} structure from which {@code C} was derived. 2069 * Instead, the following rules determine the nest host of {@code C}: 2070 * <ul> 2071 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 2072 * been determined, then let {@code H} be the nest host of the lookup class. 2073 * Otherwise, the nest host of the lookup class is determined using the 2074 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 2075 * <li>The nest host of {@code C} is determined to be {@code H}, 2076 * the nest host of the lookup class.</li> 2077 * </ul> 2078 * 2079 * <p> A hidden class or interface may be serializable, but this requires a custom 2080 * serialization mechanism in order to ensure that instances are properly serialized 2081 * and deserialized. The default serialization mechanism supports only classes and 2082 * interfaces that are discoverable by their class name. 2083 * 2084 * @param bytes the bytes that make up the class data, 2085 * in the format of a valid {@code class} file as defined by 2086 * <cite>The Java Virtual Machine Specification</cite>. 2087 * @param initialize if {@code true} the class will be initialized. 2088 * @param options {@linkplain ClassOption class options} 2089 * @return the {@code Lookup} object on the hidden class, 2090 * with {@linkplain #ORIGINAL original} and 2091 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2092 * 2093 * @throws IllegalAccessException if this {@code Lookup} does not have 2094 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2095 * @throws SecurityException if a security manager is present and it 2096 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2097 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2098 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2099 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2100 * than the lookup class or {@code bytes} is not a class or interface 2101 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2102 * @throws IncompatibleClassChangeError if the class or interface named as 2103 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2104 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2105 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2106 * {@code C} is {@code C} itself 2107 * @throws VerifyError if the newly created class cannot be verified 2108 * @throws LinkageError if the newly created class cannot be linked for any other reason 2109 * @throws NullPointerException if any parameter is {@code null} 2110 * 2111 * @since 15 2112 * @see Class#isHidden() 2113 * @jvms 4.2.1 Binary Class and Interface Names 2114 * @jvms 4.2.2 Unqualified Names 2115 * @jvms 4.7.28 The {@code NestHost} Attribute 2116 * @jvms 4.7.29 The {@code NestMembers} Attribute 2117 * @jvms 5.4.3.1 Class and Interface Resolution 2118 * @jvms 5.4.4 Access Control 2119 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2120 * @jvms 5.4 Linking 2121 * @jvms 5.5 Initialization 2122 * @jls 12.7 Unloading of Classes and Interfaces 2123 */ 2124 @SuppressWarnings("doclint:reference") // cross-module links 2125 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2126 throws IllegalAccessException 2127 { 2128 Objects.requireNonNull(bytes); 2129 Objects.requireNonNull(options); 2130 2131 ensureDefineClassPermission(); 2132 if (!hasFullPrivilegeAccess()) { 2133 throw new IllegalAccessException(this + " does not have full privilege access"); 2134 } 2135 2136 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize); 2137 } 2138 2139 /** 2140 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2141 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2142 * returning a {@code Lookup} on the newly created class or interface. 2143 * 2144 * <p> This method is equivalent to calling 2145 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2146 * as if the hidden class is injected with a private static final <i>unnamed</i> 2147 * field which is initialized with the given {@code classData} at 2148 * the first instruction of the class initializer. 2149 * The newly created class is linked by the Java Virtual Machine. 2150 * 2151 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2152 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2153 * methods can be used to retrieve the {@code classData}. 2154 * 2155 * @apiNote 2156 * A framework can create a hidden class with class data with one or more 2157 * objects and load the class data as dynamically-computed constant(s) 2158 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2159 * Class data} is accessible only to the lookup object created by the newly 2160 * defined hidden class but inaccessible to other members in the same nest 2161 * (unlike private static fields that are accessible to nestmates). 2162 * Care should be taken w.r.t. mutability for example when passing 2163 * an array or other mutable structure through the class data. 2164 * Changing any value stored in the class data at runtime may lead to 2165 * unpredictable behavior. 2166 * If the class data is a {@code List}, it is good practice to make it 2167 * unmodifiable for example via {@link List#of List::of}. 2168 * 2169 * @param bytes the class bytes 2170 * @param classData pre-initialized class data 2171 * @param initialize if {@code true} the class will be initialized. 2172 * @param options {@linkplain ClassOption class options} 2173 * @return the {@code Lookup} object on the hidden class, 2174 * with {@linkplain #ORIGINAL original} and 2175 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2176 * 2177 * @throws IllegalAccessException if this {@code Lookup} does not have 2178 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2179 * @throws SecurityException if a security manager is present and it 2180 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2181 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2182 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2183 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2184 * than the lookup class or {@code bytes} is not a class or interface 2185 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2186 * @throws IncompatibleClassChangeError if the class or interface named as 2187 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2188 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2189 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2190 * {@code C} is {@code C} itself 2191 * @throws VerifyError if the newly created class cannot be verified 2192 * @throws LinkageError if the newly created class cannot be linked for any other reason 2193 * @throws NullPointerException if any parameter is {@code null} 2194 * 2195 * @since 16 2196 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2197 * @see Class#isHidden() 2198 * @see MethodHandles#classData(Lookup, String, Class) 2199 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2200 * @jvms 4.2.1 Binary Class and Interface Names 2201 * @jvms 4.2.2 Unqualified Names 2202 * @jvms 4.7.28 The {@code NestHost} Attribute 2203 * @jvms 4.7.29 The {@code NestMembers} Attribute 2204 * @jvms 5.4.3.1 Class and Interface Resolution 2205 * @jvms 5.4.4 Access Control 2206 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2207 * @jvms 5.4 Linking 2208 * @jvms 5.5 Initialization 2209 * @jls 12.7 Unloading of Classes and Interface 2210 */ 2211 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2212 throws IllegalAccessException 2213 { 2214 Objects.requireNonNull(bytes); 2215 Objects.requireNonNull(classData); 2216 Objects.requireNonNull(options); 2217 2218 ensureDefineClassPermission(); 2219 if (!hasFullPrivilegeAccess()) { 2220 throw new IllegalAccessException(this + " does not have full privilege access"); 2221 } 2222 2223 return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false) 2224 .defineClassAsLookup(initialize, classData); 2225 } 2226 2227 // A default dumper for writing class files passed to Lookup::defineClass 2228 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2229 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2230 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2231 // 2232 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2233 // and LambdaForms and method handle internals. They are dumped via 2234 // different ClassFileDumpers. 2235 private static ClassFileDumper defaultDumper() { 2236 return DEFAULT_DUMPER; 2237 } 2238 2239 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2240 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2241 2242 static class ClassFile { 2243 final String name; // internal name 2244 final int accessFlags; 2245 final byte[] bytes; 2246 ClassFile(String name, int accessFlags, byte[] bytes) { 2247 this.name = name; 2248 this.accessFlags = accessFlags; 2249 this.bytes = bytes; 2250 } 2251 2252 static ClassFile newInstanceNoCheck(String name, byte[] bytes) { 2253 return new ClassFile(name, 0, bytes); 2254 } 2255 2256 /** 2257 * This method checks the class file version and the structure of `this_class`. 2258 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2259 * that is in the named package. 2260 * 2261 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2262 * or the class is not in the given package name. 2263 */ 2264 static ClassFile newInstance(byte[] bytes, String pkgName) { 2265 var cf = readClassFile(bytes); 2266 2267 // check if it's in the named package 2268 int index = cf.name.lastIndexOf('/'); 2269 String pn = (index == -1) ? "" : cf.name.substring(0, index).replace('/', '.'); 2270 if (!pn.equals(pkgName)) { 2271 throw newIllegalArgumentException(cf.name + " not in same package as lookup class"); 2272 } 2273 return cf; 2274 } 2275 2276 private static ClassFile readClassFile(byte[] bytes) { 2277 int magic = readInt(bytes, 0); 2278 if (magic != 0xCAFEBABE) { 2279 throw new ClassFormatError("Incompatible magic value: " + magic); 2280 } 2281 int minor = readUnsignedShort(bytes, 4); 2282 int major = readUnsignedShort(bytes, 6); 2283 if (!VM.isSupportedClassFileVersion(major, minor)) { 2284 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2285 } 2286 2287 String name; 2288 int accessFlags; 2289 try { 2290 ClassModel cm = java.lang.classfile.ClassFile.of().parse(bytes); 2291 name = cm.thisClass().asInternalName(); 2292 accessFlags = cm.flags().flagsMask(); 2293 } catch (IllegalArgumentException e) { 2294 ClassFormatError cfe = new ClassFormatError(); 2295 cfe.initCause(e); 2296 throw cfe; 2297 } 2298 // must be a class or interface 2299 if ((accessFlags & ACC_MODULE) != 0) { 2300 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2301 } 2302 return new ClassFile(name, accessFlags, bytes); 2303 } 2304 2305 private static int readInt(byte[] bytes, int offset) { 2306 if ((offset+4) > bytes.length) { 2307 throw new ClassFormatError("Invalid ClassFile structure"); 2308 } 2309 return ((bytes[offset] & 0xFF) << 24) 2310 | ((bytes[offset + 1] & 0xFF) << 16) 2311 | ((bytes[offset + 2] & 0xFF) << 8) 2312 | (bytes[offset + 3] & 0xFF); 2313 } 2314 2315 private static int readUnsignedShort(byte[] bytes, int offset) { 2316 if ((offset+2) > bytes.length) { 2317 throw new ClassFormatError("Invalid ClassFile structure"); 2318 } 2319 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2320 } 2321 } 2322 2323 /* 2324 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2325 * from the given bytes. 2326 * 2327 * Caller should make a defensive copy of the arguments if needed 2328 * before calling this factory method. 2329 * 2330 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2331 * {@code bytes} denotes a class in a different package than the lookup class 2332 */ 2333 private ClassDefiner makeClassDefiner(byte[] bytes) { 2334 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2335 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, defaultDumper()); 2336 } 2337 2338 /** 2339 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2340 * from the given bytes. No package name check on the given bytes. 2341 * 2342 * @param name internal name 2343 * @param bytes class bytes 2344 * @param dumper dumper to write the given bytes to the dumper's output directory 2345 * @return ClassDefiner that defines a normal class of the given bytes. 2346 */ 2347 ClassDefiner makeClassDefiner(String name, byte[] bytes, ClassFileDumper dumper) { 2348 // skip package name validation 2349 ClassFile cf = ClassFile.newInstanceNoCheck(name, bytes); 2350 return new ClassDefiner(this, cf, STRONG_LOADER_LINK, dumper); 2351 } 2352 2353 /** 2354 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2355 * from the given bytes. The name must be in the same package as the lookup class. 2356 * 2357 * Caller should make a defensive copy of the arguments if needed 2358 * before calling this factory method. 2359 * 2360 * @param bytes class bytes 2361 * @param dumper dumper to write the given bytes to the dumper's output directory 2362 * @return ClassDefiner that defines a hidden class of the given bytes. 2363 * 2364 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2365 * {@code bytes} denotes a class in a different package than the lookup class 2366 */ 2367 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2368 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2369 return makeHiddenClassDefiner(cf, Set.of(), false, dumper); 2370 } 2371 2372 /** 2373 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2374 * from the given bytes and options. 2375 * The name must be in the same package as the lookup class. 2376 * 2377 * Caller should make a defensive copy of the arguments if needed 2378 * before calling this factory method. 2379 * 2380 * @param bytes class bytes 2381 * @param options class options 2382 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2383 * @return ClassDefiner that defines a hidden class of the given bytes and options 2384 * 2385 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2386 * {@code bytes} denotes a class in a different package than the lookup class 2387 */ 2388 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2389 Set<ClassOption> options, 2390 boolean accessVmAnnotations) { 2391 ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName()); 2392 return makeHiddenClassDefiner(cf, options, accessVmAnnotations, defaultDumper()); 2393 } 2394 2395 /** 2396 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2397 * from the given bytes and the given options. No package name check on the given bytes. 2398 * 2399 * @param name internal name that specifies the prefix of the hidden class 2400 * @param bytes class bytes 2401 * @param options class options 2402 * @param dumper dumper to write the given bytes to the dumper's output directory 2403 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2404 */ 2405 ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options, ClassFileDumper dumper) { 2406 Objects.requireNonNull(dumper); 2407 // skip name and access flags validation 2408 return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false, dumper); 2409 } 2410 2411 /** 2412 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2413 * from the given class file and options. 2414 * 2415 * @param cf ClassFile 2416 * @param options class options 2417 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2418 * @param dumper dumper to write the given bytes to the dumper's output directory 2419 */ 2420 private ClassDefiner makeHiddenClassDefiner(ClassFile cf, 2421 Set<ClassOption> options, 2422 boolean accessVmAnnotations, 2423 ClassFileDumper dumper) { 2424 int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options); 2425 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2426 // jdk.internal.vm.annotations are permitted for classes 2427 // defined to boot loader and platform loader 2428 flags |= ACCESS_VM_ANNOTATIONS; 2429 } 2430 2431 return new ClassDefiner(this, cf, flags, dumper); 2432 } 2433 2434 static class ClassDefiner { 2435 private final Lookup lookup; 2436 private final String name; // internal name 2437 private final byte[] bytes; 2438 private final int classFlags; 2439 private final ClassFileDumper dumper; 2440 2441 private ClassDefiner(Lookup lookup, ClassFile cf, int flags, ClassFileDumper dumper) { 2442 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2443 this.lookup = lookup; 2444 this.bytes = cf.bytes; 2445 this.name = cf.name; 2446 this.classFlags = flags; 2447 this.dumper = dumper; 2448 } 2449 2450 String internalName() { 2451 return name; 2452 } 2453 2454 Class<?> defineClass(boolean initialize) { 2455 return defineClass(initialize, null); 2456 } 2457 2458 Lookup defineClassAsLookup(boolean initialize) { 2459 Class<?> c = defineClass(initialize, null); 2460 return new Lookup(c, null, FULL_POWER_MODES); 2461 } 2462 2463 /** 2464 * Defines the class of the given bytes and the given classData. 2465 * If {@code initialize} parameter is true, then the class will be initialized. 2466 * 2467 * @param initialize true if the class to be initialized 2468 * @param classData classData or null 2469 * @return the class 2470 * 2471 * @throws LinkageError linkage error 2472 */ 2473 Class<?> defineClass(boolean initialize, Object classData) { 2474 Class<?> lookupClass = lookup.lookupClass(); 2475 ClassLoader loader = lookupClass.getClassLoader(); 2476 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2477 Class<?> c = null; 2478 try { 2479 c = SharedSecrets.getJavaLangAccess() 2480 .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData); 2481 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2482 return c; 2483 } finally { 2484 // dump the classfile for debugging 2485 if (dumper.isEnabled()) { 2486 String name = internalName(); 2487 if (c != null) { 2488 dumper.dumpClass(name, c, bytes); 2489 } else { 2490 dumper.dumpFailedClass(name, bytes); 2491 } 2492 } 2493 } 2494 } 2495 2496 /** 2497 * Defines the class of the given bytes and the given classData. 2498 * If {@code initialize} parameter is true, then the class will be initialized. 2499 * 2500 * @param initialize true if the class to be initialized 2501 * @param classData classData or null 2502 * @return a Lookup for the defined class 2503 * 2504 * @throws LinkageError linkage error 2505 */ 2506 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2507 Class<?> c = defineClass(initialize, classData); 2508 return new Lookup(c, null, FULL_POWER_MODES); 2509 } 2510 2511 private boolean isNestmate() { 2512 return (classFlags & NESTMATE_CLASS) != 0; 2513 } 2514 } 2515 2516 private ProtectionDomain lookupClassProtectionDomain() { 2517 ProtectionDomain pd = cachedProtectionDomain; 2518 if (pd == null) { 2519 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2520 } 2521 return pd; 2522 } 2523 2524 // cached protection domain 2525 private volatile ProtectionDomain cachedProtectionDomain; 2526 2527 // Make sure outer class is initialized first. 2528 static { IMPL_NAMES.getClass(); } 2529 2530 /** Package-private version of lookup which is trusted. */ 2531 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2532 2533 /** Version of lookup which is trusted minimally. 2534 * It can only be used to create method handles to publicly accessible 2535 * members in packages that are exported unconditionally. 2536 */ 2537 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2538 2539 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2540 String name = lookupClass.getName(); 2541 if (name.startsWith("java.lang.invoke.")) 2542 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2543 } 2544 2545 /** 2546 * Displays the name of the class from which lookups are to be made, 2547 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2548 * previous lookup class} if present. 2549 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2550 * If there are restrictions on the access permitted to this lookup, 2551 * this is indicated by adding a suffix to the class name, consisting 2552 * of a slash and a keyword. The keyword represents the strongest 2553 * allowed access, and is chosen as follows: 2554 * <ul> 2555 * <li>If no access is allowed, the suffix is "/noaccess". 2556 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2557 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2558 * <li>If only public and module access are allowed, the suffix is "/module". 2559 * <li>If public and package access are allowed, the suffix is "/package". 2560 * <li>If public, package, and private access are allowed, the suffix is "/private". 2561 * </ul> 2562 * If none of the above cases apply, it is the case that 2563 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2564 * (public, module, package, private, and protected) is allowed. 2565 * In this case, no suffix is added. 2566 * This is true only of an object obtained originally from 2567 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2568 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2569 * always have restricted access, and will display a suffix. 2570 * <p> 2571 * (It may seem strange that protected access should be 2572 * stronger than private access. Viewed independently from 2573 * package access, protected access is the first to be lost, 2574 * because it requires a direct subclass relationship between 2575 * caller and callee.) 2576 * @see #in 2577 */ 2578 @Override 2579 public String toString() { 2580 String cname = lookupClass.getName(); 2581 if (prevLookupClass != null) 2582 cname += "/" + prevLookupClass.getName(); 2583 switch (allowedModes) { 2584 case 0: // no privileges 2585 return cname + "/noaccess"; 2586 case UNCONDITIONAL: 2587 return cname + "/publicLookup"; 2588 case PUBLIC: 2589 return cname + "/public"; 2590 case PUBLIC|MODULE: 2591 return cname + "/module"; 2592 case PUBLIC|PACKAGE: 2593 case PUBLIC|MODULE|PACKAGE: 2594 return cname + "/package"; 2595 case PUBLIC|PACKAGE|PRIVATE: 2596 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2597 return cname + "/private"; 2598 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2599 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2600 case FULL_POWER_MODES: 2601 return cname; 2602 case TRUSTED: 2603 return "/trusted"; // internal only; not exported 2604 default: // Should not happen, but it's a bitfield... 2605 cname = cname + "/" + Integer.toHexString(allowedModes); 2606 assert(false) : cname; 2607 return cname; 2608 } 2609 } 2610 2611 /** 2612 * Produces a method handle for a static method. 2613 * The type of the method handle will be that of the method. 2614 * (Since static methods do not take receivers, there is no 2615 * additional receiver argument inserted into the method handle type, 2616 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2617 * The method and all its argument types must be accessible to the lookup object. 2618 * <p> 2619 * The returned method handle will have 2620 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2621 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2622 * <p> 2623 * If the returned method handle is invoked, the method's class will 2624 * be initialized, if it has not already been initialized. 2625 * <p><b>Example:</b> 2626 * {@snippet lang="java" : 2627 import static java.lang.invoke.MethodHandles.*; 2628 import static java.lang.invoke.MethodType.*; 2629 ... 2630 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2631 "asList", methodType(List.class, Object[].class)); 2632 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2633 * } 2634 * @param refc the class from which the method is accessed 2635 * @param name the name of the method 2636 * @param type the type of the method 2637 * @return the desired method handle 2638 * @throws NoSuchMethodException if the method does not exist 2639 * @throws IllegalAccessException if access checking fails, 2640 * or if the method is not {@code static}, 2641 * or if the method's variable arity modifier bit 2642 * is set and {@code asVarargsCollector} fails 2643 * @throws SecurityException if a security manager is present and it 2644 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2645 * @throws NullPointerException if any argument is null 2646 */ 2647 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2648 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2649 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2650 } 2651 2652 /** 2653 * Produces a method handle for a virtual method. 2654 * The type of the method handle will be that of the method, 2655 * with the receiver type (usually {@code refc}) prepended. 2656 * The method and all its argument types must be accessible to the lookup object. 2657 * <p> 2658 * When called, the handle will treat the first argument as a receiver 2659 * and, for non-private methods, dispatch on the receiver's type to determine which method 2660 * implementation to enter. 2661 * For private methods the named method in {@code refc} will be invoked on the receiver. 2662 * (The dispatching action is identical with that performed by an 2663 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2664 * <p> 2665 * The first argument will be of type {@code refc} if the lookup 2666 * class has full privileges to access the member. Otherwise 2667 * the member must be {@code protected} and the first argument 2668 * will be restricted in type to the lookup class. 2669 * <p> 2670 * The returned method handle will have 2671 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2672 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2673 * <p> 2674 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2675 * instructions and method handles produced by {@code findVirtual}, 2676 * if the class is {@code MethodHandle} and the name string is 2677 * {@code invokeExact} or {@code invoke}, the resulting 2678 * method handle is equivalent to one produced by 2679 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2680 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2681 * with the same {@code type} argument. 2682 * <p> 2683 * If the class is {@code VarHandle} and the name string corresponds to 2684 * the name of a signature-polymorphic access mode method, the resulting 2685 * method handle is equivalent to one produced by 2686 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2687 * the access mode corresponding to the name string and with the same 2688 * {@code type} arguments. 2689 * <p> 2690 * <b>Example:</b> 2691 * {@snippet lang="java" : 2692 import static java.lang.invoke.MethodHandles.*; 2693 import static java.lang.invoke.MethodType.*; 2694 ... 2695 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2696 "concat", methodType(String.class, String.class)); 2697 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2698 "hashCode", methodType(int.class)); 2699 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2700 "hashCode", methodType(int.class)); 2701 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2702 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2703 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2704 // interface method: 2705 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2706 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2707 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2708 // constructor "internal method" must be accessed differently: 2709 MethodType MT_newString = methodType(void.class); //()V for new String() 2710 try { assertEquals("impossible", lookup() 2711 .findVirtual(String.class, "<init>", MT_newString)); 2712 } catch (NoSuchMethodException ex) { } // OK 2713 MethodHandle MH_newString = publicLookup() 2714 .findConstructor(String.class, MT_newString); 2715 assertEquals("", (String) MH_newString.invokeExact()); 2716 * } 2717 * 2718 * @param refc the class or interface from which the method is accessed 2719 * @param name the name of the method 2720 * @param type the type of the method, with the receiver argument omitted 2721 * @return the desired method handle 2722 * @throws NoSuchMethodException if the method does not exist 2723 * @throws IllegalAccessException if access checking fails, 2724 * or if the method is {@code static}, 2725 * or if the method's variable arity modifier bit 2726 * is set and {@code asVarargsCollector} fails 2727 * @throws SecurityException if a security manager is present and it 2728 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2729 * @throws NullPointerException if any argument is null 2730 */ 2731 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2732 if (refc == MethodHandle.class) { 2733 MethodHandle mh = findVirtualForMH(name, type); 2734 if (mh != null) return mh; 2735 } else if (refc == VarHandle.class) { 2736 MethodHandle mh = findVirtualForVH(name, type); 2737 if (mh != null) return mh; 2738 } 2739 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2740 MemberName method = resolveOrFail(refKind, refc, name, type); 2741 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2742 } 2743 private MethodHandle findVirtualForMH(String name, MethodType type) { 2744 // these names require special lookups because of the implicit MethodType argument 2745 if ("invoke".equals(name)) 2746 return invoker(type); 2747 if ("invokeExact".equals(name)) 2748 return exactInvoker(type); 2749 assert(!MemberName.isMethodHandleInvokeName(name)); 2750 return null; 2751 } 2752 private MethodHandle findVirtualForVH(String name, MethodType type) { 2753 try { 2754 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2755 } catch (IllegalArgumentException e) { 2756 return null; 2757 } 2758 } 2759 2760 /** 2761 * Produces a method handle which creates an object and initializes it, using 2762 * the constructor of the specified type. 2763 * The parameter types of the method handle will be those of the constructor, 2764 * while the return type will be a reference to the constructor's class. 2765 * The constructor and all its argument types must be accessible to the lookup object. 2766 * <p> 2767 * The requested type must have a return type of {@code void}. 2768 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2769 * <p> 2770 * The returned method handle will have 2771 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2772 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2773 * <p> 2774 * If the returned method handle is invoked, the constructor's class will 2775 * be initialized, if it has not already been initialized. 2776 * <p><b>Example:</b> 2777 * {@snippet lang="java" : 2778 import static java.lang.invoke.MethodHandles.*; 2779 import static java.lang.invoke.MethodType.*; 2780 ... 2781 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2782 ArrayList.class, methodType(void.class, Collection.class)); 2783 Collection orig = Arrays.asList("x", "y"); 2784 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2785 assert(orig != copy); 2786 assertEquals(orig, copy); 2787 // a variable-arity constructor: 2788 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2789 ProcessBuilder.class, methodType(void.class, String[].class)); 2790 ProcessBuilder pb = (ProcessBuilder) 2791 MH_newProcessBuilder.invoke("x", "y", "z"); 2792 assertEquals("[x, y, z]", pb.command().toString()); 2793 * } 2794 * @param refc the class or interface from which the method is accessed 2795 * @param type the type of the method, with the receiver argument omitted, and a void return type 2796 * @return the desired method handle 2797 * @throws NoSuchMethodException if the constructor does not exist 2798 * @throws IllegalAccessException if access checking fails 2799 * or if the method's variable arity modifier bit 2800 * is set and {@code asVarargsCollector} fails 2801 * @throws SecurityException if a security manager is present and it 2802 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2803 * @throws NullPointerException if any argument is null 2804 */ 2805 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2806 if (refc.isArray()) { 2807 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2808 } 2809 String name = ConstantDescs.INIT_NAME; 2810 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2811 return getDirectConstructor(refc, ctor); 2812 } 2813 2814 /** 2815 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2816 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2817 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2818 * and then determines whether the class is accessible to this lookup object. 2819 * <p> 2820 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2821 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2822 * of {@code '['} and followed by the element type as encoded in the 2823 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2824 * <p> 2825 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2826 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2827 * 2828 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2829 * or the string representing an array class 2830 * @return the requested class. 2831 * @throws SecurityException if a security manager is present and it 2832 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2833 * @throws LinkageError if the linkage fails 2834 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2835 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2836 * modes. 2837 * @throws NullPointerException if {@code targetName} is null 2838 * @since 9 2839 * @jvms 5.4.3.1 Class and Interface Resolution 2840 */ 2841 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2842 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2843 return accessClass(targetClass); 2844 } 2845 2846 /** 2847 * Ensures that {@code targetClass} has been initialized. The class 2848 * to be initialized must be {@linkplain #accessClass accessible} 2849 * to this {@code Lookup} object. This method causes {@code targetClass} 2850 * to be initialized if it has not been already initialized, 2851 * as specified in JVMS {@jvms 5.5}. 2852 * 2853 * <p> 2854 * This method returns when {@code targetClass} is fully initialized, or 2855 * when {@code targetClass} is being initialized by the current thread. 2856 * 2857 * @param <T> the type of the class to be initialized 2858 * @param targetClass the class to be initialized 2859 * @return {@code targetClass} that has been initialized, or that is being 2860 * initialized by the current thread. 2861 * 2862 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2863 * or array class 2864 * @throws IllegalAccessException if {@code targetClass} is not 2865 * {@linkplain #accessClass accessible} to this lookup 2866 * @throws ExceptionInInitializerError if the class initialization provoked 2867 * by this method fails 2868 * @throws SecurityException if a security manager is present and it 2869 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2870 * @since 15 2871 * @jvms 5.5 Initialization 2872 */ 2873 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2874 if (targetClass.isPrimitive()) 2875 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2876 if (targetClass.isArray()) 2877 throw new IllegalArgumentException(targetClass + " is an array class"); 2878 2879 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2880 throw makeAccessException(targetClass); 2881 } 2882 checkSecurityManager(targetClass); 2883 2884 // ensure class initialization 2885 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2886 return targetClass; 2887 } 2888 2889 /* 2890 * Returns IllegalAccessException due to access violation to the given targetClass. 2891 * 2892 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2893 * which verifies access to a class rather a member. 2894 */ 2895 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2896 String message = "access violation: "+ targetClass; 2897 if (this == MethodHandles.publicLookup()) { 2898 message += ", from public Lookup"; 2899 } else { 2900 Module m = lookupClass().getModule(); 2901 message += ", from " + lookupClass() + " (" + m + ")"; 2902 if (prevLookupClass != null) { 2903 message += ", previous lookup " + 2904 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2905 } 2906 } 2907 return new IllegalAccessException(message); 2908 } 2909 2910 /** 2911 * Determines if a class can be accessed from the lookup context defined by 2912 * this {@code Lookup} object. The static initializer of the class is not run. 2913 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2914 * if the element type of the array class is accessible. Otherwise, 2915 * {@code targetClass} is determined as accessible as follows. 2916 * 2917 * <p> 2918 * If {@code targetClass} is in the same module as the lookup class, 2919 * the lookup class is {@code LC} in module {@code M1} and 2920 * the previous lookup class is in module {@code M0} or 2921 * {@code null} if not present, 2922 * {@code targetClass} is accessible if and only if one of the following is true: 2923 * <ul> 2924 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2925 * {@code LC} or other class in the same nest of {@code LC}.</li> 2926 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2927 * in the same runtime package of {@code LC}.</li> 2928 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2929 * a public type in {@code M1}.</li> 2930 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2931 * a public type in a package exported by {@code M1} to at least {@code M0} 2932 * if the previous lookup class is present; otherwise, {@code targetClass} 2933 * is a public type in a package exported by {@code M1} unconditionally.</li> 2934 * </ul> 2935 * 2936 * <p> 2937 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2938 * can access public types in all modules when the type is in a package 2939 * that is exported unconditionally. 2940 * <p> 2941 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2942 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2943 * is inaccessible. 2944 * <p> 2945 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2946 * {@code M1} is the module containing {@code lookupClass} and 2947 * {@code M2} is the module containing {@code targetClass}, 2948 * then {@code targetClass} is accessible if and only if 2949 * <ul> 2950 * <li>{@code M1} reads {@code M2}, and 2951 * <li>{@code targetClass} is public and in a package exported by 2952 * {@code M2} at least to {@code M1}. 2953 * </ul> 2954 * <p> 2955 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2956 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2957 * containing the previous lookup class, then {@code targetClass} is accessible 2958 * if and only if one of the following is true: 2959 * <ul> 2960 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2961 * {@linkplain Module#reads reads} {@code M0} and the type is 2962 * in a package that is exported to at least {@code M1}. 2963 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2964 * {@linkplain Module#reads reads} {@code M1} and the type is 2965 * in a package that is exported to at least {@code M0}. 2966 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2967 * and {@code M1} reads {@code M2} and the type is in a package 2968 * that is exported to at least both {@code M0} and {@code M2}. 2969 * </ul> 2970 * <p> 2971 * Otherwise, {@code targetClass} is not accessible. 2972 * 2973 * @param <T> the type of the class to be access-checked 2974 * @param targetClass the class to be access-checked 2975 * @return {@code targetClass} that has been access-checked 2976 * @throws IllegalAccessException if the class is not accessible from the lookup class 2977 * and previous lookup class, if present, using the allowed access modes. 2978 * @throws SecurityException if a security manager is present and it 2979 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 2980 * @throws NullPointerException if {@code targetClass} is {@code null} 2981 * @since 9 2982 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2983 */ 2984 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2985 if (!isClassAccessible(targetClass)) { 2986 throw makeAccessException(targetClass); 2987 } 2988 checkSecurityManager(targetClass); 2989 return targetClass; 2990 } 2991 2992 /** 2993 * Produces an early-bound method handle for a virtual method. 2994 * It will bypass checks for overriding methods on the receiver, 2995 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2996 * instruction from within the explicitly specified {@code specialCaller}. 2997 * The type of the method handle will be that of the method, 2998 * with a suitably restricted receiver type prepended. 2999 * (The receiver type will be {@code specialCaller} or a subtype.) 3000 * The method and all its argument types must be accessible 3001 * to the lookup object. 3002 * <p> 3003 * Before method resolution, 3004 * if the explicitly specified caller class is not identical with the 3005 * lookup class, or if this lookup object does not have 3006 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3007 * privileges, the access fails. 3008 * <p> 3009 * The returned method handle will have 3010 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3011 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3012 * <p style="font-size:smaller;"> 3013 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 3014 * are not visible to this API, 3015 * even though the {@code invokespecial} instruction can refer to them 3016 * in special circumstances. Use {@link #findConstructor findConstructor} 3017 * to access instance initialization methods in a safe manner.)</em> 3018 * <p><b>Example:</b> 3019 * {@snippet lang="java" : 3020 import static java.lang.invoke.MethodHandles.*; 3021 import static java.lang.invoke.MethodType.*; 3022 ... 3023 static class Listie extends ArrayList { 3024 public String toString() { return "[wee Listie]"; } 3025 static Lookup lookup() { return MethodHandles.lookup(); } 3026 } 3027 ... 3028 // no access to constructor via invokeSpecial: 3029 MethodHandle MH_newListie = Listie.lookup() 3030 .findConstructor(Listie.class, methodType(void.class)); 3031 Listie l = (Listie) MH_newListie.invokeExact(); 3032 try { assertEquals("impossible", Listie.lookup().findSpecial( 3033 Listie.class, "<init>", methodType(void.class), Listie.class)); 3034 } catch (NoSuchMethodException ex) { } // OK 3035 // access to super and self methods via invokeSpecial: 3036 MethodHandle MH_super = Listie.lookup().findSpecial( 3037 ArrayList.class, "toString" , methodType(String.class), Listie.class); 3038 MethodHandle MH_this = Listie.lookup().findSpecial( 3039 Listie.class, "toString" , methodType(String.class), Listie.class); 3040 MethodHandle MH_duper = Listie.lookup().findSpecial( 3041 Object.class, "toString" , methodType(String.class), Listie.class); 3042 assertEquals("[]", (String) MH_super.invokeExact(l)); 3043 assertEquals(""+l, (String) MH_this.invokeExact(l)); 3044 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 3045 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 3046 String.class, "toString", methodType(String.class), Listie.class)); 3047 } catch (IllegalAccessException ex) { } // OK 3048 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 3049 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 3050 * } 3051 * 3052 * @param refc the class or interface from which the method is accessed 3053 * @param name the name of the method (which must not be "<init>") 3054 * @param type the type of the method, with the receiver argument omitted 3055 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 3056 * @return the desired method handle 3057 * @throws NoSuchMethodException if the method does not exist 3058 * @throws IllegalAccessException if access checking fails, 3059 * or if the method is {@code static}, 3060 * or if the method's variable arity modifier bit 3061 * is set and {@code asVarargsCollector} fails 3062 * @throws SecurityException if a security manager is present and it 3063 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3064 * @throws NullPointerException if any argument is null 3065 */ 3066 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 3067 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 3068 checkSpecialCaller(specialCaller, refc); 3069 Lookup specialLookup = this.in(specialCaller); 3070 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 3071 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 3072 } 3073 3074 /** 3075 * Produces a method handle giving read access to a non-static field. 3076 * The type of the method handle will have a return type of the field's 3077 * value type. 3078 * The method handle's single argument will be the instance containing 3079 * the field. 3080 * Access checking is performed immediately on behalf of the lookup class. 3081 * @param refc the class or interface from which the method is accessed 3082 * @param name the field's name 3083 * @param type the field's type 3084 * @return a method handle which can load values from the field 3085 * @throws NoSuchFieldException if the field does not exist 3086 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3087 * @throws SecurityException if a security manager is present and it 3088 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3089 * @throws NullPointerException if any argument is null 3090 * @see #findVarHandle(Class, String, Class) 3091 */ 3092 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3093 MemberName field = resolveOrFail(REF_getField, refc, name, type); 3094 return getDirectField(REF_getField, refc, field); 3095 } 3096 3097 /** 3098 * Produces a method handle giving write access to a non-static field. 3099 * The type of the method handle will have a void return type. 3100 * The method handle will take two arguments, the instance containing 3101 * the field, and the value to be stored. 3102 * The second argument will be of the field's value type. 3103 * Access checking is performed immediately on behalf of the lookup class. 3104 * @param refc the class or interface from which the method is accessed 3105 * @param name the field's name 3106 * @param type the field's type 3107 * @return a method handle which can store values into the field 3108 * @throws NoSuchFieldException if the field does not exist 3109 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3110 * or {@code final} 3111 * @throws SecurityException if a security manager is present and it 3112 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3113 * @throws NullPointerException if any argument is null 3114 * @see #findVarHandle(Class, String, Class) 3115 */ 3116 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3117 MemberName field = resolveOrFail(REF_putField, refc, name, type); 3118 return getDirectField(REF_putField, refc, field); 3119 } 3120 3121 /** 3122 * Produces a VarHandle giving access to a non-static field {@code name} 3123 * of type {@code type} declared in a class of type {@code recv}. 3124 * The VarHandle's variable type is {@code type} and it has one 3125 * coordinate type, {@code recv}. 3126 * <p> 3127 * Access checking is performed immediately on behalf of the lookup 3128 * class. 3129 * <p> 3130 * Certain access modes of the returned VarHandle are unsupported under 3131 * the following conditions: 3132 * <ul> 3133 * <li>if the field is declared {@code final}, then the write, atomic 3134 * update, numeric atomic update, and bitwise atomic update access 3135 * modes are unsupported. 3136 * <li>if the field type is anything other than {@code byte}, 3137 * {@code short}, {@code char}, {@code int}, {@code long}, 3138 * {@code float}, or {@code double} then numeric atomic update 3139 * access modes are unsupported. 3140 * <li>if the field type is anything other than {@code boolean}, 3141 * {@code byte}, {@code short}, {@code char}, {@code int} or 3142 * {@code long} then bitwise atomic update access modes are 3143 * unsupported. 3144 * </ul> 3145 * <p> 3146 * If the field is declared {@code volatile} then the returned VarHandle 3147 * will override access to the field (effectively ignore the 3148 * {@code volatile} declaration) in accordance to its specified 3149 * access modes. 3150 * <p> 3151 * If the field type is {@code float} or {@code double} then numeric 3152 * and atomic update access modes compare values using their bitwise 3153 * representation (see {@link Float#floatToRawIntBits} and 3154 * {@link Double#doubleToRawLongBits}, respectively). 3155 * @apiNote 3156 * Bitwise comparison of {@code float} values or {@code double} values, 3157 * as performed by the numeric and atomic update access modes, differ 3158 * from the primitive {@code ==} operator and the {@link Float#equals} 3159 * and {@link Double#equals} methods, specifically with respect to 3160 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3161 * Care should be taken when performing a compare and set or a compare 3162 * and exchange operation with such values since the operation may 3163 * unexpectedly fail. 3164 * There are many possible NaN values that are considered to be 3165 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3166 * provided by Java can distinguish between them. Operation failure can 3167 * occur if the expected or witness value is a NaN value and it is 3168 * transformed (perhaps in a platform specific manner) into another NaN 3169 * value, and thus has a different bitwise representation (see 3170 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3171 * details). 3172 * The values {@code -0.0} and {@code +0.0} have different bitwise 3173 * representations but are considered equal when using the primitive 3174 * {@code ==} operator. Operation failure can occur if, for example, a 3175 * numeric algorithm computes an expected value to be say {@code -0.0} 3176 * and previously computed the witness value to be say {@code +0.0}. 3177 * @param recv the receiver class, of type {@code R}, that declares the 3178 * non-static field 3179 * @param name the field's name 3180 * @param type the field's type, of type {@code T} 3181 * @return a VarHandle giving access to non-static fields. 3182 * @throws NoSuchFieldException if the field does not exist 3183 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3184 * @throws SecurityException if a security manager is present and it 3185 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3186 * @throws NullPointerException if any argument is null 3187 * @since 9 3188 */ 3189 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3190 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3191 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3192 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3193 } 3194 3195 /** 3196 * Produces a method handle giving read access to a static field. 3197 * The type of the method handle will have a return type of the field's 3198 * value type. 3199 * The method handle will take no arguments. 3200 * Access checking is performed immediately on behalf of the lookup class. 3201 * <p> 3202 * If the returned method handle is invoked, the field's class will 3203 * be initialized, if it has not already been initialized. 3204 * @param refc the class or interface from which the method is accessed 3205 * @param name the field's name 3206 * @param type the field's type 3207 * @return a method handle which can load values from the field 3208 * @throws NoSuchFieldException if the field does not exist 3209 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3210 * @throws SecurityException if a security manager is present and it 3211 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3212 * @throws NullPointerException if any argument is null 3213 */ 3214 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3215 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3216 return getDirectField(REF_getStatic, refc, field); 3217 } 3218 3219 /** 3220 * Produces a method handle giving write access to a static field. 3221 * The type of the method handle will have a void return type. 3222 * The method handle will take a single 3223 * argument, of the field's value type, the value to be stored. 3224 * Access checking is performed immediately on behalf of the lookup class. 3225 * <p> 3226 * If the returned method handle is invoked, the field's class will 3227 * be initialized, if it has not already been initialized. 3228 * @param refc the class or interface from which the method is accessed 3229 * @param name the field's name 3230 * @param type the field's type 3231 * @return a method handle which can store values into the field 3232 * @throws NoSuchFieldException if the field does not exist 3233 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3234 * or is {@code final} 3235 * @throws SecurityException if a security manager is present and it 3236 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3237 * @throws NullPointerException if any argument is null 3238 */ 3239 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3240 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3241 return getDirectField(REF_putStatic, refc, field); 3242 } 3243 3244 /** 3245 * Produces a VarHandle giving access to a static field {@code name} of 3246 * type {@code type} declared in a class of type {@code decl}. 3247 * The VarHandle's variable type is {@code type} and it has no 3248 * coordinate types. 3249 * <p> 3250 * Access checking is performed immediately on behalf of the lookup 3251 * class. 3252 * <p> 3253 * If the returned VarHandle is operated on, the declaring class will be 3254 * initialized, if it has not already been initialized. 3255 * <p> 3256 * Certain access modes of the returned VarHandle are unsupported under 3257 * the following conditions: 3258 * <ul> 3259 * <li>if the field is declared {@code final}, then the write, atomic 3260 * update, numeric atomic update, and bitwise atomic update access 3261 * modes are unsupported. 3262 * <li>if the field type is anything other than {@code byte}, 3263 * {@code short}, {@code char}, {@code int}, {@code long}, 3264 * {@code float}, or {@code double}, then numeric atomic update 3265 * access modes are unsupported. 3266 * <li>if the field type is anything other than {@code boolean}, 3267 * {@code byte}, {@code short}, {@code char}, {@code int} or 3268 * {@code long} then bitwise atomic update access modes are 3269 * unsupported. 3270 * </ul> 3271 * <p> 3272 * If the field is declared {@code volatile} then the returned VarHandle 3273 * will override access to the field (effectively ignore the 3274 * {@code volatile} declaration) in accordance to its specified 3275 * access modes. 3276 * <p> 3277 * If the field type is {@code float} or {@code double} then numeric 3278 * and atomic update access modes compare values using their bitwise 3279 * representation (see {@link Float#floatToRawIntBits} and 3280 * {@link Double#doubleToRawLongBits}, respectively). 3281 * @apiNote 3282 * Bitwise comparison of {@code float} values or {@code double} values, 3283 * as performed by the numeric and atomic update access modes, differ 3284 * from the primitive {@code ==} operator and the {@link Float#equals} 3285 * and {@link Double#equals} methods, specifically with respect to 3286 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3287 * Care should be taken when performing a compare and set or a compare 3288 * and exchange operation with such values since the operation may 3289 * unexpectedly fail. 3290 * There are many possible NaN values that are considered to be 3291 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3292 * provided by Java can distinguish between them. Operation failure can 3293 * occur if the expected or witness value is a NaN value and it is 3294 * transformed (perhaps in a platform specific manner) into another NaN 3295 * value, and thus has a different bitwise representation (see 3296 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3297 * details). 3298 * The values {@code -0.0} and {@code +0.0} have different bitwise 3299 * representations but are considered equal when using the primitive 3300 * {@code ==} operator. Operation failure can occur if, for example, a 3301 * numeric algorithm computes an expected value to be say {@code -0.0} 3302 * and previously computed the witness value to be say {@code +0.0}. 3303 * @param decl the class that declares the static field 3304 * @param name the field's name 3305 * @param type the field's type, of type {@code T} 3306 * @return a VarHandle giving access to a static field 3307 * @throws NoSuchFieldException if the field does not exist 3308 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3309 * @throws SecurityException if a security manager is present and it 3310 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3311 * @throws NullPointerException if any argument is null 3312 * @since 9 3313 */ 3314 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3315 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3316 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3317 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3318 } 3319 3320 /** 3321 * Produces an early-bound method handle for a non-static method. 3322 * The receiver must have a supertype {@code defc} in which a method 3323 * of the given name and type is accessible to the lookup class. 3324 * The method and all its argument types must be accessible to the lookup object. 3325 * The type of the method handle will be that of the method, 3326 * without any insertion of an additional receiver parameter. 3327 * The given receiver will be bound into the method handle, 3328 * so that every call to the method handle will invoke the 3329 * requested method on the given receiver. 3330 * <p> 3331 * The returned method handle will have 3332 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3333 * the method's variable arity modifier bit ({@code 0x0080}) is set 3334 * <em>and</em> the trailing array argument is not the only argument. 3335 * (If the trailing array argument is the only argument, 3336 * the given receiver value will be bound to it.) 3337 * <p> 3338 * This is almost equivalent to the following code, with some differences noted below: 3339 * {@snippet lang="java" : 3340 import static java.lang.invoke.MethodHandles.*; 3341 import static java.lang.invoke.MethodType.*; 3342 ... 3343 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3344 MethodHandle mh1 = mh0.bindTo(receiver); 3345 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3346 return mh1; 3347 * } 3348 * where {@code defc} is either {@code receiver.getClass()} or a super 3349 * type of that class, in which the requested method is accessible 3350 * to the lookup class. 3351 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3352 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3353 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3354 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3355 * @param receiver the object from which the method is accessed 3356 * @param name the name of the method 3357 * @param type the type of the method, with the receiver argument omitted 3358 * @return the desired method handle 3359 * @throws NoSuchMethodException if the method does not exist 3360 * @throws IllegalAccessException if access checking fails 3361 * or if the method's variable arity modifier bit 3362 * is set and {@code asVarargsCollector} fails 3363 * @throws SecurityException if a security manager is present and it 3364 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3365 * @throws NullPointerException if any argument is null 3366 * @see MethodHandle#bindTo 3367 * @see #findVirtual 3368 */ 3369 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3370 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3371 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3372 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3373 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3374 throw new IllegalAccessException("The restricted defining class " + 3375 mh.type().leadingReferenceParameter().getName() + 3376 " is not assignable from receiver class " + 3377 receiver.getClass().getName()); 3378 } 3379 return mh.bindArgumentL(0, receiver).setVarargs(method); 3380 } 3381 3382 /** 3383 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3384 * to <i>m</i>, if the lookup class has permission. 3385 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3386 * If <i>m</i> is virtual, overriding is respected on every call. 3387 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3388 * The type of the method handle will be that of the method, 3389 * with the receiver type prepended (but only if it is non-static). 3390 * If the method's {@code accessible} flag is not set, 3391 * access checking is performed immediately on behalf of the lookup class. 3392 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3393 * <p> 3394 * The returned method handle will have 3395 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3396 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3397 * <p> 3398 * If <i>m</i> is static, and 3399 * if the returned method handle is invoked, the method's class will 3400 * be initialized, if it has not already been initialized. 3401 * @param m the reflected method 3402 * @return a method handle which can invoke the reflected method 3403 * @throws IllegalAccessException if access checking fails 3404 * or if the method's variable arity modifier bit 3405 * is set and {@code asVarargsCollector} fails 3406 * @throws NullPointerException if the argument is null 3407 */ 3408 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3409 if (m.getDeclaringClass() == MethodHandle.class) { 3410 MethodHandle mh = unreflectForMH(m); 3411 if (mh != null) return mh; 3412 } 3413 if (m.getDeclaringClass() == VarHandle.class) { 3414 MethodHandle mh = unreflectForVH(m); 3415 if (mh != null) return mh; 3416 } 3417 MemberName method = new MemberName(m); 3418 byte refKind = method.getReferenceKind(); 3419 if (refKind == REF_invokeSpecial) 3420 refKind = REF_invokeVirtual; 3421 assert(method.isMethod()); 3422 @SuppressWarnings("deprecation") 3423 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3424 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3425 } 3426 private MethodHandle unreflectForMH(Method m) { 3427 // these names require special lookups because they throw UnsupportedOperationException 3428 if (MemberName.isMethodHandleInvokeName(m.getName())) 3429 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3430 return null; 3431 } 3432 private MethodHandle unreflectForVH(Method m) { 3433 // these names require special lookups because they throw UnsupportedOperationException 3434 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3435 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3436 return null; 3437 } 3438 3439 /** 3440 * Produces a method handle for a reflected method. 3441 * It will bypass checks for overriding methods on the receiver, 3442 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3443 * instruction from within the explicitly specified {@code specialCaller}. 3444 * The type of the method handle will be that of the method, 3445 * with a suitably restricted receiver type prepended. 3446 * (The receiver type will be {@code specialCaller} or a subtype.) 3447 * If the method's {@code accessible} flag is not set, 3448 * access checking is performed immediately on behalf of the lookup class, 3449 * as if {@code invokespecial} instruction were being linked. 3450 * <p> 3451 * Before method resolution, 3452 * if the explicitly specified caller class is not identical with the 3453 * lookup class, or if this lookup object does not have 3454 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3455 * privileges, the access fails. 3456 * <p> 3457 * The returned method handle will have 3458 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3459 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3460 * @param m the reflected method 3461 * @param specialCaller the class nominally calling the method 3462 * @return a method handle which can invoke the reflected method 3463 * @throws IllegalAccessException if access checking fails, 3464 * or if the method is {@code static}, 3465 * or if the method's variable arity modifier bit 3466 * is set and {@code asVarargsCollector} fails 3467 * @throws NullPointerException if any argument is null 3468 */ 3469 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3470 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3471 Lookup specialLookup = this.in(specialCaller); 3472 MemberName method = new MemberName(m, true); 3473 assert(method.isMethod()); 3474 // ignore m.isAccessible: this is a new kind of access 3475 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3476 } 3477 3478 /** 3479 * Produces a method handle for a reflected constructor. 3480 * The type of the method handle will be that of the constructor, 3481 * with the return type changed to the declaring class. 3482 * The method handle will perform a {@code newInstance} operation, 3483 * creating a new instance of the constructor's class on the 3484 * arguments passed to the method handle. 3485 * <p> 3486 * If the constructor's {@code accessible} flag is not set, 3487 * access checking is performed immediately on behalf of the lookup class. 3488 * <p> 3489 * The returned method handle will have 3490 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3491 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3492 * <p> 3493 * If the returned method handle is invoked, the constructor's class will 3494 * be initialized, if it has not already been initialized. 3495 * @param c the reflected constructor 3496 * @return a method handle which can invoke the reflected constructor 3497 * @throws IllegalAccessException if access checking fails 3498 * or if the method's variable arity modifier bit 3499 * is set and {@code asVarargsCollector} fails 3500 * @throws NullPointerException if the argument is null 3501 */ 3502 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3503 MemberName ctor = new MemberName(c); 3504 assert(ctor.isConstructor()); 3505 @SuppressWarnings("deprecation") 3506 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3507 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 3508 } 3509 3510 /* 3511 * Produces a method handle that is capable of creating instances of the given class 3512 * and instantiated by the given constructor. No security manager check. 3513 * 3514 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3515 */ 3516 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3517 MemberName ctor = new MemberName(c); 3518 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3519 checkAccess(REF_newInvokeSpecial, decl, ctor); 3520 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3521 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3522 } 3523 3524 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3525 if (decl == ctor.getDeclaringClass()) 3526 return true; 3527 3528 Class<?> cl = decl; 3529 while ((cl = cl.getSuperclass()) != null) { 3530 if (cl == ctor.getDeclaringClass()) { 3531 return true; 3532 } 3533 } 3534 return false; 3535 } 3536 3537 /** 3538 * Produces a method handle giving read access to a reflected field. 3539 * The type of the method handle will have a return type of the field's 3540 * value type. 3541 * If the field is {@code static}, the method handle will take no arguments. 3542 * Otherwise, its single argument will be the instance containing 3543 * the field. 3544 * If the {@code Field} object's {@code accessible} flag is not set, 3545 * access checking is performed immediately on behalf of the lookup class. 3546 * <p> 3547 * If the field is static, and 3548 * if the returned method handle is invoked, the field's class will 3549 * be initialized, if it has not already been initialized. 3550 * @param f the reflected field 3551 * @return a method handle which can load values from the reflected field 3552 * @throws IllegalAccessException if access checking fails 3553 * @throws NullPointerException if the argument is null 3554 */ 3555 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3556 return unreflectField(f, false); 3557 } 3558 3559 /** 3560 * Produces a method handle giving write access to a reflected field. 3561 * The type of the method handle will have a void return type. 3562 * If the field is {@code static}, the method handle will take a single 3563 * argument, of the field's value type, the value to be stored. 3564 * Otherwise, the two arguments will be the instance containing 3565 * the field, and the value to be stored. 3566 * If the {@code Field} object's {@code accessible} flag is not set, 3567 * access checking is performed immediately on behalf of the lookup class. 3568 * <p> 3569 * If the field is {@code final}, write access will not be 3570 * allowed and access checking will fail, except under certain 3571 * narrow circumstances documented for {@link Field#set Field.set}. 3572 * A method handle is returned only if a corresponding call to 3573 * the {@code Field} object's {@code set} method could return 3574 * normally. In particular, fields which are both {@code static} 3575 * and {@code final} may never be set. 3576 * <p> 3577 * If the field is {@code static}, and 3578 * if the returned method handle is invoked, the field's class will 3579 * be initialized, if it has not already been initialized. 3580 * @param f the reflected field 3581 * @return a method handle which can store values into the reflected field 3582 * @throws IllegalAccessException if access checking fails, 3583 * or if the field is {@code final} and write access 3584 * is not enabled on the {@code Field} object 3585 * @throws NullPointerException if the argument is null 3586 */ 3587 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3588 return unreflectField(f, true); 3589 } 3590 3591 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3592 MemberName field = new MemberName(f, isSetter); 3593 if (isSetter && field.isFinal()) { 3594 if (field.isTrustedFinalField()) { 3595 String msg = field.isStatic() ? "static final field has no write access" 3596 : "final field has no write access"; 3597 throw field.makeAccessException(msg, this); 3598 } 3599 } 3600 assert(isSetter 3601 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3602 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3603 @SuppressWarnings("deprecation") 3604 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3605 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 3606 } 3607 3608 /** 3609 * Produces a VarHandle giving access to a reflected field {@code f} 3610 * of type {@code T} declared in a class of type {@code R}. 3611 * The VarHandle's variable type is {@code T}. 3612 * If the field is non-static the VarHandle has one coordinate type, 3613 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3614 * coordinate types. 3615 * <p> 3616 * Access checking is performed immediately on behalf of the lookup 3617 * class, regardless of the value of the field's {@code accessible} 3618 * flag. 3619 * <p> 3620 * If the field is static, and if the returned VarHandle is operated 3621 * on, the field's declaring class will be initialized, if it has not 3622 * already been initialized. 3623 * <p> 3624 * Certain access modes of the returned VarHandle are unsupported under 3625 * the following conditions: 3626 * <ul> 3627 * <li>if the field is declared {@code final}, then the write, atomic 3628 * update, numeric atomic update, and bitwise atomic update access 3629 * modes are unsupported. 3630 * <li>if the field type is anything other than {@code byte}, 3631 * {@code short}, {@code char}, {@code int}, {@code long}, 3632 * {@code float}, or {@code double} then numeric atomic update 3633 * access modes are unsupported. 3634 * <li>if the field type is anything other than {@code boolean}, 3635 * {@code byte}, {@code short}, {@code char}, {@code int} or 3636 * {@code long} then bitwise atomic update access modes are 3637 * unsupported. 3638 * </ul> 3639 * <p> 3640 * If the field is declared {@code volatile} then the returned VarHandle 3641 * will override access to the field (effectively ignore the 3642 * {@code volatile} declaration) in accordance to its specified 3643 * access modes. 3644 * <p> 3645 * If the field type is {@code float} or {@code double} then numeric 3646 * and atomic update access modes compare values using their bitwise 3647 * representation (see {@link Float#floatToRawIntBits} and 3648 * {@link Double#doubleToRawLongBits}, respectively). 3649 * @apiNote 3650 * Bitwise comparison of {@code float} values or {@code double} values, 3651 * as performed by the numeric and atomic update access modes, differ 3652 * from the primitive {@code ==} operator and the {@link Float#equals} 3653 * and {@link Double#equals} methods, specifically with respect to 3654 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3655 * Care should be taken when performing a compare and set or a compare 3656 * and exchange operation with such values since the operation may 3657 * unexpectedly fail. 3658 * There are many possible NaN values that are considered to be 3659 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3660 * provided by Java can distinguish between them. Operation failure can 3661 * occur if the expected or witness value is a NaN value and it is 3662 * transformed (perhaps in a platform specific manner) into another NaN 3663 * value, and thus has a different bitwise representation (see 3664 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3665 * details). 3666 * The values {@code -0.0} and {@code +0.0} have different bitwise 3667 * representations but are considered equal when using the primitive 3668 * {@code ==} operator. Operation failure can occur if, for example, a 3669 * numeric algorithm computes an expected value to be say {@code -0.0} 3670 * and previously computed the witness value to be say {@code +0.0}. 3671 * @param f the reflected field, with a field of type {@code T}, and 3672 * a declaring class of type {@code R} 3673 * @return a VarHandle giving access to non-static fields or a static 3674 * field 3675 * @throws IllegalAccessException if access checking fails 3676 * @throws NullPointerException if the argument is null 3677 * @since 9 3678 */ 3679 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3680 MemberName getField = new MemberName(f, false); 3681 MemberName putField = new MemberName(f, true); 3682 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 3683 f.getDeclaringClass(), getField, putField); 3684 } 3685 3686 /** 3687 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3688 * created by this lookup object or a similar one. 3689 * Security and access checks are performed to ensure that this lookup object 3690 * is capable of reproducing the target method handle. 3691 * This means that the cracking may fail if target is a direct method handle 3692 * but was created by an unrelated lookup object. 3693 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3694 * and was created by a lookup object for a different class. 3695 * @param target a direct method handle to crack into symbolic reference components 3696 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3697 * @throws SecurityException if a security manager is present and it 3698 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 3699 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3700 * @throws NullPointerException if the target is {@code null} 3701 * @see MethodHandleInfo 3702 * @since 1.8 3703 */ 3704 public MethodHandleInfo revealDirect(MethodHandle target) { 3705 if (!target.isCrackable()) { 3706 throw newIllegalArgumentException("not a direct method handle"); 3707 } 3708 MemberName member = target.internalMemberName(); 3709 Class<?> defc = member.getDeclaringClass(); 3710 byte refKind = member.getReferenceKind(); 3711 assert(MethodHandleNatives.refKindIsValid(refKind)); 3712 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3713 // Devirtualized method invocation is usually formally virtual. 3714 // To avoid creating extra MemberName objects for this common case, 3715 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3716 refKind = REF_invokeVirtual; 3717 if (refKind == REF_invokeVirtual && defc.isInterface()) 3718 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3719 refKind = REF_invokeInterface; 3720 // Check SM permissions and member access before cracking. 3721 try { 3722 checkAccess(refKind, defc, member); 3723 checkSecurityManager(defc, member); 3724 } catch (IllegalAccessException ex) { 3725 throw new IllegalArgumentException(ex); 3726 } 3727 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3728 Class<?> callerClass = target.internalCallerClass(); 3729 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3730 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3731 } 3732 // Produce the handle to the results. 3733 return new InfoFromMemberName(this, member, refKind); 3734 } 3735 3736 //--- Helper methods, all package-private. 3737 3738 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3739 checkSymbolicClass(refc); // do this before attempting to resolve 3740 Objects.requireNonNull(name); 3741 Objects.requireNonNull(type); 3742 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3743 NoSuchFieldException.class); 3744 } 3745 3746 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3747 checkSymbolicClass(refc); // do this before attempting to resolve 3748 Objects.requireNonNull(type); 3749 checkMethodName(refKind, name); // implicit null-check of name 3750 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3751 NoSuchMethodException.class); 3752 } 3753 3754 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3755 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3756 Objects.requireNonNull(member.getName()); 3757 Objects.requireNonNull(member.getType()); 3758 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3759 ReflectiveOperationException.class); 3760 } 3761 3762 MemberName resolveOrNull(byte refKind, MemberName member) { 3763 // do this before attempting to resolve 3764 if (!isClassAccessible(member.getDeclaringClass())) { 3765 return null; 3766 } 3767 Objects.requireNonNull(member.getName()); 3768 Objects.requireNonNull(member.getType()); 3769 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3770 } 3771 3772 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3773 // do this before attempting to resolve 3774 if (!isClassAccessible(refc)) { 3775 return null; 3776 } 3777 Objects.requireNonNull(type); 3778 // implicit null-check of name 3779 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3780 return null; 3781 } 3782 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3783 } 3784 3785 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3786 if (!isClassAccessible(refc)) { 3787 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3788 } 3789 } 3790 3791 boolean isClassAccessible(Class<?> refc) { 3792 Objects.requireNonNull(refc); 3793 Class<?> caller = lookupClassOrNull(); 3794 Class<?> type = refc; 3795 while (type.isArray()) { 3796 type = type.getComponentType(); 3797 } 3798 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3799 } 3800 3801 /** Check name for an illegal leading "<" character. */ 3802 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3803 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3804 throw new NoSuchMethodException("illegal method name: "+name); 3805 } 3806 3807 /** 3808 * Find my trustable caller class if m is a caller sensitive method. 3809 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3810 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3811 */ 3812 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3813 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3814 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3815 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3816 } 3817 return this; 3818 } 3819 3820 /** 3821 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3822 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3823 * 3824 * @deprecated This method was originally designed to test {@code PRIVATE} access 3825 * that implies full privilege access but {@code MODULE} access has since become 3826 * independent of {@code PRIVATE} access. It is recommended to call 3827 * {@link #hasFullPrivilegeAccess()} instead. 3828 * @since 9 3829 */ 3830 @Deprecated(since="14") 3831 public boolean hasPrivateAccess() { 3832 return hasFullPrivilegeAccess(); 3833 } 3834 3835 /** 3836 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3837 * i.e. {@code PRIVATE} and {@code MODULE} access. 3838 * A {@code Lookup} object must have full privilege access in order to 3839 * access all members that are allowed to the 3840 * {@linkplain #lookupClass() lookup class}. 3841 * 3842 * @return {@code true} if this lookup has full privilege access. 3843 * @since 14 3844 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3845 */ 3846 public boolean hasFullPrivilegeAccess() { 3847 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3848 } 3849 3850 /** 3851 * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a> 3852 * for ensureInitialized, findClass or accessClass. 3853 */ 3854 void checkSecurityManager(Class<?> refc) { 3855 if (allowedModes == TRUSTED) return; 3856 3857 @SuppressWarnings("removal") 3858 SecurityManager smgr = System.getSecurityManager(); 3859 if (smgr == null) return; 3860 3861 // Step 1: 3862 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3863 if (!fullPrivilegeLookup || 3864 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3865 ReflectUtil.checkPackageAccess(refc); 3866 } 3867 3868 // Step 2b: 3869 if (!fullPrivilegeLookup) { 3870 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 3871 } 3872 } 3873 3874 /** 3875 * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 3876 * Determines a trustable caller class to compare with refc, the symbolic reference class. 3877 * If this lookup object has full privilege access except original access, 3878 * then the caller class is the lookupClass. 3879 * 3880 * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)} 3881 * from the same module skips the security permission check. 3882 */ 3883 void checkSecurityManager(Class<?> refc, MemberName m) { 3884 Objects.requireNonNull(refc); 3885 Objects.requireNonNull(m); 3886 3887 if (allowedModes == TRUSTED) return; 3888 3889 @SuppressWarnings("removal") 3890 SecurityManager smgr = System.getSecurityManager(); 3891 if (smgr == null) return; 3892 3893 // Step 1: 3894 boolean fullPrivilegeLookup = hasFullPrivilegeAccess(); 3895 if (!fullPrivilegeLookup || 3896 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 3897 ReflectUtil.checkPackageAccess(refc); 3898 } 3899 3900 // Step 2a: 3901 if (m.isPublic()) return; 3902 if (!fullPrivilegeLookup) { 3903 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 3904 } 3905 3906 // Step 3: 3907 Class<?> defc = m.getDeclaringClass(); 3908 if (!fullPrivilegeLookup && defc != refc) { 3909 ReflectUtil.checkPackageAccess(defc); 3910 } 3911 } 3912 3913 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3914 boolean wantStatic = (refKind == REF_invokeStatic); 3915 String message; 3916 if (m.isConstructor()) 3917 message = "expected a method, not a constructor"; 3918 else if (!m.isMethod()) 3919 message = "expected a method"; 3920 else if (wantStatic != m.isStatic()) 3921 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3922 else 3923 { checkAccess(refKind, refc, m); return; } 3924 throw m.makeAccessException(message, this); 3925 } 3926 3927 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3928 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3929 String message; 3930 if (wantStatic != m.isStatic()) 3931 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3932 else 3933 { checkAccess(refKind, refc, m); return; } 3934 throw m.makeAccessException(message, this); 3935 } 3936 3937 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3938 return Modifier.isProtected(m.getModifiers()) && 3939 refKind == REF_invokeVirtual && 3940 m.getDeclaringClass() == Object.class && 3941 m.getName().equals("clone") && 3942 refc.isArray(); 3943 } 3944 3945 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3946 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3947 assert(m.referenceKindIsConsistentWith(refKind) && 3948 MethodHandleNatives.refKindIsValid(refKind) && 3949 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3950 int allowedModes = this.allowedModes; 3951 if (allowedModes == TRUSTED) return; 3952 int mods = m.getModifiers(); 3953 if (isArrayClone(refKind, refc, m)) { 3954 // The JVM does this hack also. 3955 // (See ClassVerifier::verify_invoke_instructions 3956 // and LinkResolver::check_method_accessability.) 3957 // Because the JVM does not allow separate methods on array types, 3958 // there is no separate method for int[].clone. 3959 // All arrays simply inherit Object.clone. 3960 // But for access checking logic, we make Object.clone 3961 // (normally protected) appear to be public. 3962 // Later on, when the DirectMethodHandle is created, 3963 // its leading argument will be restricted to the 3964 // requested array type. 3965 // N.B. The return type is not adjusted, because 3966 // that is *not* the bytecode behavior. 3967 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3968 } 3969 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3970 // cannot "new" a protected ctor in a different package 3971 mods ^= Modifier.PROTECTED; 3972 } 3973 if (Modifier.isFinal(mods) && 3974 MethodHandleNatives.refKindIsSetter(refKind)) 3975 throw m.makeAccessException("unexpected set of a final field", this); 3976 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3977 if ((requestedModes & allowedModes) != 0) { 3978 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3979 mods, lookupClass(), previousLookupClass(), allowedModes)) 3980 return; 3981 } else { 3982 // Protected members can also be checked as if they were package-private. 3983 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3984 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3985 return; 3986 } 3987 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3988 } 3989 3990 String accessFailedMessage(Class<?> refc, MemberName m) { 3991 Class<?> defc = m.getDeclaringClass(); 3992 int mods = m.getModifiers(); 3993 // check the class first: 3994 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3995 (defc == refc || 3996 Modifier.isPublic(refc.getModifiers()))); 3997 if (!classOK && (allowedModes & PACKAGE) != 0) { 3998 // ignore previous lookup class to check if default package access 3999 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 4000 (defc == refc || 4001 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 4002 } 4003 if (!classOK) 4004 return "class is not public"; 4005 if (Modifier.isPublic(mods)) 4006 return "access to public member failed"; // (how?, module not readable?) 4007 if (Modifier.isPrivate(mods)) 4008 return "member is private"; 4009 if (Modifier.isProtected(mods)) 4010 return "member is protected"; 4011 return "member is private to package"; 4012 } 4013 4014 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 4015 int allowedModes = this.allowedModes; 4016 if (allowedModes == TRUSTED) return; 4017 if ((lookupModes() & PRIVATE) == 0 4018 || (specialCaller != lookupClass() 4019 // ensure non-abstract methods in superinterfaces can be special-invoked 4020 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 4021 throw new MemberName(specialCaller). 4022 makeAccessException("no private access for invokespecial", this); 4023 } 4024 4025 private boolean restrictProtectedReceiver(MemberName method) { 4026 // The accessing class only has the right to use a protected member 4027 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 4028 if (!method.isProtected() || method.isStatic() 4029 || allowedModes == TRUSTED 4030 || method.getDeclaringClass() == lookupClass() 4031 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 4032 return false; 4033 return true; 4034 } 4035 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 4036 assert(!method.isStatic()); 4037 // receiver type of mh is too wide; narrow to caller 4038 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 4039 throw method.makeAccessException("caller class must be a subclass below the method", caller); 4040 } 4041 MethodType rawType = mh.type(); 4042 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 4043 MethodType narrowType = rawType.changeParameterType(0, caller); 4044 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 4045 assert(mh.viewAsTypeChecks(narrowType, true)); 4046 return mh.copyWith(narrowType, mh.form); 4047 } 4048 4049 /** Check access and get the requested method. */ 4050 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4051 final boolean doRestrict = true; 4052 final boolean checkSecurity = true; 4053 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4054 } 4055 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 4056 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4057 final boolean doRestrict = false; 4058 final boolean checkSecurity = true; 4059 return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup); 4060 } 4061 /** Check access and get the requested method, eliding security manager checks. */ 4062 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 4063 final boolean doRestrict = true; 4064 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4065 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup); 4066 } 4067 /** Common code for all methods; do not call directly except from immediately above. */ 4068 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 4069 boolean checkSecurity, 4070 boolean doRestrict, 4071 Lookup boundCaller) throws IllegalAccessException { 4072 checkMethod(refKind, refc, method); 4073 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4074 if (checkSecurity) 4075 checkSecurityManager(refc, method); 4076 assert(!method.isMethodHandleInvoke()); 4077 4078 if (refKind == REF_invokeSpecial && 4079 refc != lookupClass() && 4080 !refc.isInterface() && !lookupClass().isInterface() && 4081 refc != lookupClass().getSuperclass() && 4082 refc.isAssignableFrom(lookupClass())) { 4083 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 4084 4085 // Per JVMS 6.5, desc. of invokespecial instruction: 4086 // If the method is in a superclass of the LC, 4087 // and if our original search was above LC.super, 4088 // repeat the search (symbolic lookup) from LC.super 4089 // and continue with the direct superclass of that class, 4090 // and so forth, until a match is found or no further superclasses exist. 4091 // FIXME: MemberName.resolve should handle this instead. 4092 Class<?> refcAsSuper = lookupClass(); 4093 MemberName m2; 4094 do { 4095 refcAsSuper = refcAsSuper.getSuperclass(); 4096 m2 = new MemberName(refcAsSuper, 4097 method.getName(), 4098 method.getMethodType(), 4099 REF_invokeSpecial); 4100 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 4101 } while (m2 == null && // no method is found yet 4102 refc != refcAsSuper); // search up to refc 4103 if (m2 == null) throw new InternalError(method.toString()); 4104 method = m2; 4105 refc = refcAsSuper; 4106 // redo basic checks 4107 checkMethod(refKind, refc, method); 4108 } 4109 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 4110 MethodHandle mh = dmh; 4111 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 4112 if ((doRestrict && refKind == REF_invokeSpecial) || 4113 (MethodHandleNatives.refKindHasReceiver(refKind) && 4114 restrictProtectedReceiver(method) && 4115 // All arrays simply inherit the protected Object.clone method. 4116 // The leading argument is already restricted to the requested 4117 // array type (not the lookup class). 4118 !isArrayClone(refKind, refc, method))) { 4119 mh = restrictReceiver(method, dmh, lookupClass()); 4120 } 4121 mh = maybeBindCaller(method, mh, boundCaller); 4122 mh = mh.setVarargs(method); 4123 return mh; 4124 } 4125 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 4126 throws IllegalAccessException { 4127 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 4128 return mh; 4129 4130 // boundCaller must have full privilege access. 4131 // It should have been checked by findBoundCallerLookup. Safe to check this again. 4132 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 4133 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 4134 4135 assert boundCaller.hasFullPrivilegeAccess(); 4136 4137 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 4138 // Note: caller will apply varargs after this step happens. 4139 return cbmh; 4140 } 4141 4142 /** Check access and get the requested field. */ 4143 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4144 final boolean checkSecurity = true; 4145 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4146 } 4147 /** Check access and get the requested field, eliding security manager checks. */ 4148 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 4149 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4150 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 4151 } 4152 /** Common code for all fields; do not call directly except from immediately above. */ 4153 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 4154 boolean checkSecurity) throws IllegalAccessException { 4155 checkField(refKind, refc, field); 4156 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4157 if (checkSecurity) 4158 checkSecurityManager(refc, field); 4159 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 4160 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 4161 restrictProtectedReceiver(field)); 4162 if (doRestrict) 4163 return restrictReceiver(field, dmh, lookupClass()); 4164 return dmh; 4165 } 4166 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 4167 Class<?> refc, MemberName getField, MemberName putField) 4168 throws IllegalAccessException { 4169 final boolean checkSecurity = true; 4170 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4171 } 4172 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 4173 Class<?> refc, MemberName getField, MemberName putField) 4174 throws IllegalAccessException { 4175 final boolean checkSecurity = false; 4176 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 4177 } 4178 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 4179 Class<?> refc, MemberName getField, MemberName putField, 4180 boolean checkSecurity) throws IllegalAccessException { 4181 assert getField.isStatic() == putField.isStatic(); 4182 assert getField.isGetter() && putField.isSetter(); 4183 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 4184 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 4185 4186 checkField(getRefKind, refc, getField); 4187 if (checkSecurity) 4188 checkSecurityManager(refc, getField); 4189 4190 if (!putField.isFinal()) { 4191 // A VarHandle does not support updates to final fields, any 4192 // such VarHandle to a final field will be read-only and 4193 // therefore the following write-based accessibility checks are 4194 // only required for non-final fields 4195 checkField(putRefKind, refc, putField); 4196 if (checkSecurity) 4197 checkSecurityManager(refc, putField); 4198 } 4199 4200 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 4201 restrictProtectedReceiver(getField)); 4202 if (doRestrict) { 4203 assert !getField.isStatic(); 4204 // receiver type of VarHandle is too wide; narrow to caller 4205 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 4206 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 4207 } 4208 refc = lookupClass(); 4209 } 4210 return VarHandles.makeFieldHandle(getField, refc, 4211 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 4212 } 4213 /** Check access and get the requested constructor. */ 4214 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4215 final boolean checkSecurity = true; 4216 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4217 } 4218 /** Check access and get the requested constructor, eliding security manager checks. */ 4219 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 4220 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 4221 return getDirectConstructorCommon(refc, ctor, checkSecurity); 4222 } 4223 /** Common code for all constructors; do not call directly except from immediately above. */ 4224 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 4225 boolean checkSecurity) throws IllegalAccessException { 4226 assert(ctor.isConstructor()); 4227 checkAccess(REF_newInvokeSpecial, refc, ctor); 4228 // Optionally check with the security manager; this isn't needed for unreflect* calls. 4229 if (checkSecurity) 4230 checkSecurityManager(refc, ctor); 4231 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 4232 return DirectMethodHandle.make(ctor).setVarargs(ctor); 4233 } 4234 4235 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 4236 */ 4237 /*non-public*/ 4238 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 4239 throws ReflectiveOperationException { 4240 if (!(type instanceof Class || type instanceof MethodType)) 4241 throw new InternalError("unresolved MemberName"); 4242 MemberName member = new MemberName(refKind, defc, name, type); 4243 MethodHandle mh = LOOKASIDE_TABLE.get(member); 4244 if (mh != null) { 4245 checkSymbolicClass(defc); 4246 return mh; 4247 } 4248 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 4249 // Treat MethodHandle.invoke and invokeExact specially. 4250 mh = findVirtualForMH(member.getName(), member.getMethodType()); 4251 if (mh != null) { 4252 return mh; 4253 } 4254 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 4255 // Treat signature-polymorphic methods on VarHandle specially. 4256 mh = findVirtualForVH(member.getName(), member.getMethodType()); 4257 if (mh != null) { 4258 return mh; 4259 } 4260 } 4261 MemberName resolved = resolveOrFail(refKind, member); 4262 mh = getDirectMethodForConstant(refKind, defc, resolved); 4263 if (mh instanceof DirectMethodHandle dmh 4264 && canBeCached(refKind, defc, resolved)) { 4265 MemberName key = mh.internalMemberName(); 4266 if (key != null) { 4267 key = key.asNormalOriginal(); 4268 } 4269 if (member.equals(key)) { // better safe than sorry 4270 LOOKASIDE_TABLE.put(key, dmh); 4271 } 4272 } 4273 return mh; 4274 } 4275 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4276 if (refKind == REF_invokeSpecial) { 4277 return false; 4278 } 4279 if (!Modifier.isPublic(defc.getModifiers()) || 4280 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4281 !member.isPublic() || 4282 member.isCallerSensitive()) { 4283 return false; 4284 } 4285 ClassLoader loader = defc.getClassLoader(); 4286 if (loader != null) { 4287 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4288 boolean found = false; 4289 while (sysl != null) { 4290 if (loader == sysl) { found = true; break; } 4291 sysl = sysl.getParent(); 4292 } 4293 if (!found) { 4294 return false; 4295 } 4296 } 4297 try { 4298 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4299 new MemberName(refKind, defc, member.getName(), member.getType())); 4300 if (resolved2 == null) { 4301 return false; 4302 } 4303 checkSecurityManager(defc, resolved2); 4304 } catch (SecurityException ex) { 4305 return false; 4306 } 4307 return true; 4308 } 4309 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4310 throws ReflectiveOperationException { 4311 if (MethodHandleNatives.refKindIsField(refKind)) { 4312 return getDirectFieldNoSecurityManager(refKind, defc, member); 4313 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4314 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member)); 4315 } else if (refKind == REF_newInvokeSpecial) { 4316 return getDirectConstructorNoSecurityManager(defc, member); 4317 } 4318 // oops 4319 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4320 } 4321 4322 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4323 } 4324 4325 /** 4326 * Produces a method handle constructing arrays of a desired type, 4327 * as if by the {@code anewarray} bytecode. 4328 * The return type of the method handle will be the array type. 4329 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4330 * 4331 * <p> If the returned method handle is invoked with a negative 4332 * array size, a {@code NegativeArraySizeException} will be thrown. 4333 * 4334 * @param arrayClass an array type 4335 * @return a method handle which can create arrays of the given type 4336 * @throws NullPointerException if the argument is {@code null} 4337 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4338 * @see java.lang.reflect.Array#newInstance(Class, int) 4339 * @jvms 6.5 {@code anewarray} Instruction 4340 * @since 9 4341 */ 4342 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4343 if (!arrayClass.isArray()) { 4344 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4345 } 4346 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4347 bindTo(arrayClass.getComponentType()); 4348 return ani.asType(ani.type().changeReturnType(arrayClass)); 4349 } 4350 4351 /** 4352 * Produces a method handle returning the length of an array, 4353 * as if by the {@code arraylength} bytecode. 4354 * The type of the method handle will have {@code int} as return type, 4355 * and its sole argument will be the array type. 4356 * 4357 * <p> If the returned method handle is invoked with a {@code null} 4358 * array reference, a {@code NullPointerException} will be thrown. 4359 * 4360 * @param arrayClass an array type 4361 * @return a method handle which can retrieve the length of an array of the given array type 4362 * @throws NullPointerException if the argument is {@code null} 4363 * @throws IllegalArgumentException if arrayClass is not an array type 4364 * @jvms 6.5 {@code arraylength} Instruction 4365 * @since 9 4366 */ 4367 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4368 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4369 } 4370 4371 /** 4372 * Produces a method handle giving read access to elements of an array, 4373 * as if by the {@code aaload} bytecode. 4374 * The type of the method handle will have a return type of the array's 4375 * element type. Its first argument will be the array type, 4376 * and the second will be {@code int}. 4377 * 4378 * <p> When the returned method handle is invoked, 4379 * the array reference and array index are checked. 4380 * A {@code NullPointerException} will be thrown if the array reference 4381 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4382 * thrown if the index is negative or if it is greater than or equal to 4383 * the length of the array. 4384 * 4385 * @param arrayClass an array type 4386 * @return a method handle which can load values from the given array type 4387 * @throws NullPointerException if the argument is null 4388 * @throws IllegalArgumentException if arrayClass is not an array type 4389 * @jvms 6.5 {@code aaload} Instruction 4390 */ 4391 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4392 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4393 } 4394 4395 /** 4396 * Produces a method handle giving write access to elements of an array, 4397 * as if by the {@code astore} bytecode. 4398 * The type of the method handle will have a void return type. 4399 * Its last argument will be the array's element type. 4400 * The first and second arguments will be the array type and int. 4401 * 4402 * <p> When the returned method handle is invoked, 4403 * the array reference and array index are checked. 4404 * A {@code NullPointerException} will be thrown if the array reference 4405 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4406 * thrown if the index is negative or if it is greater than or equal to 4407 * the length of the array. 4408 * 4409 * @param arrayClass the class of an array 4410 * @return a method handle which can store values into the array type 4411 * @throws NullPointerException if the argument is null 4412 * @throws IllegalArgumentException if arrayClass is not an array type 4413 * @jvms 6.5 {@code aastore} Instruction 4414 */ 4415 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4416 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4417 } 4418 4419 /** 4420 * Produces a VarHandle giving access to elements of an array of type 4421 * {@code arrayClass}. The VarHandle's variable type is the component type 4422 * of {@code arrayClass} and the list of coordinate types is 4423 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4424 * corresponds to an argument that is an index into an array. 4425 * <p> 4426 * Certain access modes of the returned VarHandle are unsupported under 4427 * the following conditions: 4428 * <ul> 4429 * <li>if the component type is anything other than {@code byte}, 4430 * {@code short}, {@code char}, {@code int}, {@code long}, 4431 * {@code float}, or {@code double} then numeric atomic update access 4432 * modes are unsupported. 4433 * <li>if the component type is anything other than {@code boolean}, 4434 * {@code byte}, {@code short}, {@code char}, {@code int} or 4435 * {@code long} then bitwise atomic update access modes are 4436 * unsupported. 4437 * </ul> 4438 * <p> 4439 * If the component type is {@code float} or {@code double} then numeric 4440 * and atomic update access modes compare values using their bitwise 4441 * representation (see {@link Float#floatToRawIntBits} and 4442 * {@link Double#doubleToRawLongBits}, respectively). 4443 * 4444 * <p> When the returned {@code VarHandle} is invoked, 4445 * the array reference and array index are checked. 4446 * A {@code NullPointerException} will be thrown if the array reference 4447 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4448 * thrown if the index is negative or if it is greater than or equal to 4449 * the length of the array. 4450 * 4451 * @apiNote 4452 * Bitwise comparison of {@code float} values or {@code double} values, 4453 * as performed by the numeric and atomic update access modes, differ 4454 * from the primitive {@code ==} operator and the {@link Float#equals} 4455 * and {@link Double#equals} methods, specifically with respect to 4456 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4457 * Care should be taken when performing a compare and set or a compare 4458 * and exchange operation with such values since the operation may 4459 * unexpectedly fail. 4460 * There are many possible NaN values that are considered to be 4461 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4462 * provided by Java can distinguish between them. Operation failure can 4463 * occur if the expected or witness value is a NaN value and it is 4464 * transformed (perhaps in a platform specific manner) into another NaN 4465 * value, and thus has a different bitwise representation (see 4466 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4467 * details). 4468 * The values {@code -0.0} and {@code +0.0} have different bitwise 4469 * representations but are considered equal when using the primitive 4470 * {@code ==} operator. Operation failure can occur if, for example, a 4471 * numeric algorithm computes an expected value to be say {@code -0.0} 4472 * and previously computed the witness value to be say {@code +0.0}. 4473 * @param arrayClass the class of an array, of type {@code T[]} 4474 * @return a VarHandle giving access to elements of an array 4475 * @throws NullPointerException if the arrayClass is null 4476 * @throws IllegalArgumentException if arrayClass is not an array type 4477 * @since 9 4478 */ 4479 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4480 return VarHandles.makeArrayElementHandle(arrayClass); 4481 } 4482 4483 /** 4484 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4485 * viewed as if it were a different primitive array type, such as 4486 * {@code int[]} or {@code long[]}. 4487 * The VarHandle's variable type is the component type of 4488 * {@code viewArrayClass} and the list of coordinate types is 4489 * {@code (byte[], int)}, where the {@code int} coordinate type 4490 * corresponds to an argument that is an index into a {@code byte[]} array. 4491 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4492 * array, composing bytes to or from a value of the component type of 4493 * {@code viewArrayClass} according to the given endianness. 4494 * <p> 4495 * The supported component types (variables types) are {@code short}, 4496 * {@code char}, {@code int}, {@code long}, {@code float} and 4497 * {@code double}. 4498 * <p> 4499 * Access of bytes at a given index will result in an 4500 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4501 * or greater than the {@code byte[]} array length minus the size (in bytes) 4502 * of {@code T}. 4503 * <p> 4504 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4505 * access modes are supported by the returned var handle. For all other access modes, an 4506 * {@link UnsupportedOperationException} will be thrown. 4507 * 4508 * @apiNote if access modes other than plain access are required, clients should 4509 * consider using off-heap memory through 4510 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4511 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4512 * or memory segments backed by a 4513 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4514 * for which stronger alignment guarantees can be made. 4515 * 4516 * @param viewArrayClass the view array class, with a component type of 4517 * type {@code T} 4518 * @param byteOrder the endianness of the view array elements, as 4519 * stored in the underlying {@code byte} array 4520 * @return a VarHandle giving access to elements of a {@code byte[]} array 4521 * viewed as if elements corresponding to the components type of the view 4522 * array class 4523 * @throws NullPointerException if viewArrayClass or byteOrder is null 4524 * @throws IllegalArgumentException if viewArrayClass is not an array type 4525 * @throws UnsupportedOperationException if the component type of 4526 * viewArrayClass is not supported as a variable type 4527 * @since 9 4528 */ 4529 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4530 ByteOrder byteOrder) throws IllegalArgumentException { 4531 Objects.requireNonNull(byteOrder); 4532 return VarHandles.byteArrayViewHandle(viewArrayClass, 4533 byteOrder == ByteOrder.BIG_ENDIAN); 4534 } 4535 4536 /** 4537 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4538 * viewed as if it were an array of elements of a different primitive 4539 * component type to that of {@code byte}, such as {@code int[]} or 4540 * {@code long[]}. 4541 * The VarHandle's variable type is the component type of 4542 * {@code viewArrayClass} and the list of coordinate types is 4543 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4544 * corresponds to an argument that is an index into a {@code byte[]} array. 4545 * The returned VarHandle accesses bytes at an index in a 4546 * {@code ByteBuffer}, composing bytes to or from a value of the component 4547 * type of {@code viewArrayClass} according to the given endianness. 4548 * <p> 4549 * The supported component types (variables types) are {@code short}, 4550 * {@code char}, {@code int}, {@code long}, {@code float} and 4551 * {@code double}. 4552 * <p> 4553 * Access will result in a {@code ReadOnlyBufferException} for anything 4554 * other than the read access modes if the {@code ByteBuffer} is read-only. 4555 * <p> 4556 * Access of bytes at a given index will result in an 4557 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4558 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4559 * {@code T}. 4560 * <p> 4561 * For heap byte buffers, access is always unaligned. As a result, only the plain 4562 * {@linkplain VarHandle.AccessMode#GET get} 4563 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4564 * returned var handle. For all other access modes, an {@link IllegalStateException} 4565 * will be thrown. 4566 * <p> 4567 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4568 * with respect to the underlying memory address, {@code A} say, associated 4569 * with the {@code ByteBuffer} and index. 4570 * If access is misaligned then access for anything other than the 4571 * {@code get} and {@code set} access modes will result in an 4572 * {@code IllegalStateException}. In such cases atomic access is only 4573 * guaranteed with respect to the largest power of two that divides the GCD 4574 * of {@code A} and the size (in bytes) of {@code T}. 4575 * If access is aligned then following access modes are supported and are 4576 * guaranteed to support atomic access: 4577 * <ul> 4578 * <li>read write access modes for all {@code T}, with the exception of 4579 * access modes {@code get} and {@code set} for {@code long} and 4580 * {@code double} on 32-bit platforms. 4581 * <li>atomic update access modes for {@code int}, {@code long}, 4582 * {@code float} or {@code double}. 4583 * (Future major platform releases of the JDK may support additional 4584 * types for certain currently unsupported access modes.) 4585 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4586 * (Future major platform releases of the JDK may support additional 4587 * numeric types for certain currently unsupported access modes.) 4588 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4589 * (Future major platform releases of the JDK may support additional 4590 * numeric types for certain currently unsupported access modes.) 4591 * </ul> 4592 * <p> 4593 * Misaligned access, and therefore atomicity guarantees, may be determined 4594 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4595 * {@code index}, {@code T} and its corresponding boxed type, 4596 * {@code T_BOX}, as follows: 4597 * <pre>{@code 4598 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4599 * ByteBuffer bb = ... 4600 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4601 * boolean isMisaligned = misalignedAtIndex != 0; 4602 * }</pre> 4603 * <p> 4604 * If the variable type is {@code float} or {@code double} then atomic 4605 * update access modes compare values using their bitwise representation 4606 * (see {@link Float#floatToRawIntBits} and 4607 * {@link Double#doubleToRawLongBits}, respectively). 4608 * @param viewArrayClass the view array class, with a component type of 4609 * type {@code T} 4610 * @param byteOrder the endianness of the view array elements, as 4611 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4612 * endianness of a {@code ByteBuffer}) 4613 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4614 * viewed as if elements corresponding to the components type of the view 4615 * array class 4616 * @throws NullPointerException if viewArrayClass or byteOrder is null 4617 * @throws IllegalArgumentException if viewArrayClass is not an array type 4618 * @throws UnsupportedOperationException if the component type of 4619 * viewArrayClass is not supported as a variable type 4620 * @since 9 4621 */ 4622 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4623 ByteOrder byteOrder) throws IllegalArgumentException { 4624 Objects.requireNonNull(byteOrder); 4625 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4626 byteOrder == ByteOrder.BIG_ENDIAN); 4627 } 4628 4629 4630 //--- method handle invocation (reflective style) 4631 4632 /** 4633 * Produces a method handle which will invoke any method handle of the 4634 * given {@code type}, with a given number of trailing arguments replaced by 4635 * a single trailing {@code Object[]} array. 4636 * The resulting invoker will be a method handle with the following 4637 * arguments: 4638 * <ul> 4639 * <li>a single {@code MethodHandle} target 4640 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4641 * <li>an {@code Object[]} array containing trailing arguments 4642 * </ul> 4643 * <p> 4644 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4645 * the indicated {@code type}. 4646 * That is, if the target is exactly of the given {@code type}, it will behave 4647 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4648 * is used to convert the target to the required {@code type}. 4649 * <p> 4650 * The type of the returned invoker will not be the given {@code type}, but rather 4651 * will have all parameters except the first {@code leadingArgCount} 4652 * replaced by a single array of type {@code Object[]}, which will be 4653 * the final parameter. 4654 * <p> 4655 * Before invoking its target, the invoker will spread the final array, apply 4656 * reference casts as necessary, and unbox and widen primitive arguments. 4657 * If, when the invoker is called, the supplied array argument does 4658 * not have the correct number of elements, the invoker will throw 4659 * an {@link IllegalArgumentException} instead of invoking the target. 4660 * <p> 4661 * This method is equivalent to the following code (though it may be more efficient): 4662 * {@snippet lang="java" : 4663 MethodHandle invoker = MethodHandles.invoker(type); 4664 int spreadArgCount = type.parameterCount() - leadingArgCount; 4665 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4666 return invoker; 4667 * } 4668 * This method throws no reflective or security exceptions. 4669 * @param type the desired target type 4670 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4671 * @return a method handle suitable for invoking any method handle of the given type 4672 * @throws NullPointerException if {@code type} is null 4673 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4674 * the range from 0 to {@code type.parameterCount()} inclusive, 4675 * or if the resulting method handle's type would have 4676 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4677 */ 4678 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4679 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4680 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4681 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4682 return type.invokers().spreadInvoker(leadingArgCount); 4683 } 4684 4685 /** 4686 * Produces a special <em>invoker method handle</em> which can be used to 4687 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4688 * The resulting invoker will have a type which is 4689 * exactly equal to the desired type, except that it will accept 4690 * an additional leading argument of type {@code MethodHandle}. 4691 * <p> 4692 * This method is equivalent to the following code (though it may be more efficient): 4693 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4694 * 4695 * <p style="font-size:smaller;"> 4696 * <em>Discussion:</em> 4697 * Invoker method handles can be useful when working with variable method handles 4698 * of unknown types. 4699 * For example, to emulate an {@code invokeExact} call to a variable method 4700 * handle {@code M}, extract its type {@code T}, 4701 * look up the invoker method {@code X} for {@code T}, 4702 * and call the invoker method, as {@code X.invoke(T, A...)}. 4703 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4704 * is unknown.) 4705 * If spreading, collecting, or other argument transformations are required, 4706 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4707 * method handle values, as long as they are compatible with the type of {@code X}. 4708 * <p style="font-size:smaller;"> 4709 * <em>(Note: The invoker method is not available via the Core Reflection API. 4710 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4711 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4712 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4713 * <p> 4714 * This method throws no reflective or security exceptions. 4715 * @param type the desired target type 4716 * @return a method handle suitable for invoking any method handle of the given type 4717 * @throws IllegalArgumentException if the resulting method handle's type would have 4718 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4719 */ 4720 public static MethodHandle exactInvoker(MethodType type) { 4721 return type.invokers().exactInvoker(); 4722 } 4723 4724 /** 4725 * Produces a special <em>invoker method handle</em> which can be used to 4726 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4727 * The resulting invoker will have a type which is 4728 * exactly equal to the desired type, except that it will accept 4729 * an additional leading argument of type {@code MethodHandle}. 4730 * <p> 4731 * Before invoking its target, if the target differs from the expected type, 4732 * the invoker will apply reference casts as 4733 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4734 * Similarly, the return value will be converted as necessary. 4735 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4736 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4737 * <p> 4738 * This method is equivalent to the following code (though it may be more efficient): 4739 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4740 * <p style="font-size:smaller;"> 4741 * <em>Discussion:</em> 4742 * A {@linkplain MethodType#genericMethodType general method type} is one which 4743 * mentions only {@code Object} arguments and return values. 4744 * An invoker for such a type is capable of calling any method handle 4745 * of the same arity as the general type. 4746 * <p style="font-size:smaller;"> 4747 * <em>(Note: The invoker method is not available via the Core Reflection API. 4748 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4749 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4750 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4751 * <p> 4752 * This method throws no reflective or security exceptions. 4753 * @param type the desired target type 4754 * @return a method handle suitable for invoking any method handle convertible to the given type 4755 * @throws IllegalArgumentException if the resulting method handle's type would have 4756 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4757 */ 4758 public static MethodHandle invoker(MethodType type) { 4759 return type.invokers().genericInvoker(); 4760 } 4761 4762 /** 4763 * Produces a special <em>invoker method handle</em> which can be used to 4764 * invoke a signature-polymorphic access mode method on any VarHandle whose 4765 * associated access mode type is compatible with the given type. 4766 * The resulting invoker will have a type which is exactly equal to the 4767 * desired given type, except that it will accept an additional leading 4768 * argument of type {@code VarHandle}. 4769 * 4770 * @param accessMode the VarHandle access mode 4771 * @param type the desired target type 4772 * @return a method handle suitable for invoking an access mode method of 4773 * any VarHandle whose access mode type is of the given type. 4774 * @since 9 4775 */ 4776 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4777 return type.invokers().varHandleMethodExactInvoker(accessMode); 4778 } 4779 4780 /** 4781 * Produces a special <em>invoker method handle</em> which can be used to 4782 * invoke a signature-polymorphic access mode method on any VarHandle whose 4783 * associated access mode type is compatible with the given type. 4784 * The resulting invoker will have a type which is exactly equal to the 4785 * desired given type, except that it will accept an additional leading 4786 * argument of type {@code VarHandle}. 4787 * <p> 4788 * Before invoking its target, if the access mode type differs from the 4789 * desired given type, the invoker will apply reference casts as necessary 4790 * and box, unbox, or widen primitive values, as if by 4791 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4792 * converted as necessary. 4793 * <p> 4794 * This method is equivalent to the following code (though it may be more 4795 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4796 * 4797 * @param accessMode the VarHandle access mode 4798 * @param type the desired target type 4799 * @return a method handle suitable for invoking an access mode method of 4800 * any VarHandle whose access mode type is convertible to the given 4801 * type. 4802 * @since 9 4803 */ 4804 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4805 return type.invokers().varHandleMethodInvoker(accessMode); 4806 } 4807 4808 /*non-public*/ 4809 static MethodHandle basicInvoker(MethodType type) { 4810 return type.invokers().basicInvoker(); 4811 } 4812 4813 //--- method handle modification (creation from other method handles) 4814 4815 /** 4816 * Produces a method handle which adapts the type of the 4817 * given method handle to a new type by pairwise argument and return type conversion. 4818 * The original type and new type must have the same number of arguments. 4819 * The resulting method handle is guaranteed to report a type 4820 * which is equal to the desired new type. 4821 * <p> 4822 * If the original type and new type are equal, returns target. 4823 * <p> 4824 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4825 * and some additional conversions are also applied if those conversions fail. 4826 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4827 * if possible, before or instead of any conversions done by {@code asType}: 4828 * <ul> 4829 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4830 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4831 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4832 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4833 * the boolean is converted to a byte value, 1 for true, 0 for false. 4834 * (This treatment follows the usage of the bytecode verifier.) 4835 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4836 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4837 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4838 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4839 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4840 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4841 * widening and/or narrowing.) 4842 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4843 * conversion will be applied at runtime, possibly followed 4844 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4845 * possibly followed by a conversion from byte to boolean by testing 4846 * the low-order bit. 4847 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4848 * and if the reference is null at runtime, a zero value is introduced. 4849 * </ul> 4850 * @param target the method handle to invoke after arguments are retyped 4851 * @param newType the expected type of the new method handle 4852 * @return a method handle which delegates to the target after performing 4853 * any necessary argument conversions, and arranges for any 4854 * necessary return value conversions 4855 * @throws NullPointerException if either argument is null 4856 * @throws WrongMethodTypeException if the conversion cannot be made 4857 * @see MethodHandle#asType 4858 */ 4859 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4860 explicitCastArgumentsChecks(target, newType); 4861 // use the asTypeCache when possible: 4862 MethodType oldType = target.type(); 4863 if (oldType == newType) return target; 4864 if (oldType.explicitCastEquivalentToAsType(newType)) { 4865 return target.asFixedArity().asType(newType); 4866 } 4867 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4868 } 4869 4870 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4871 if (target.type().parameterCount() != newType.parameterCount()) { 4872 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4873 } 4874 } 4875 4876 /** 4877 * Produces a method handle which adapts the calling sequence of the 4878 * given method handle to a new type, by reordering the arguments. 4879 * The resulting method handle is guaranteed to report a type 4880 * which is equal to the desired new type. 4881 * <p> 4882 * The given array controls the reordering. 4883 * Call {@code #I} the number of incoming parameters (the value 4884 * {@code newType.parameterCount()}, and call {@code #O} the number 4885 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4886 * Then the length of the reordering array must be {@code #O}, 4887 * and each element must be a non-negative number less than {@code #I}. 4888 * For every {@code N} less than {@code #O}, the {@code N}-th 4889 * outgoing argument will be taken from the {@code I}-th incoming 4890 * argument, where {@code I} is {@code reorder[N]}. 4891 * <p> 4892 * No argument or return value conversions are applied. 4893 * The type of each incoming argument, as determined by {@code newType}, 4894 * must be identical to the type of the corresponding outgoing parameter 4895 * or parameters in the target method handle. 4896 * The return type of {@code newType} must be identical to the return 4897 * type of the original target. 4898 * <p> 4899 * The reordering array need not specify an actual permutation. 4900 * An incoming argument will be duplicated if its index appears 4901 * more than once in the array, and an incoming argument will be dropped 4902 * if its index does not appear in the array. 4903 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4904 * incoming arguments which are not mentioned in the reordering array 4905 * may be of any type, as determined only by {@code newType}. 4906 * {@snippet lang="java" : 4907 import static java.lang.invoke.MethodHandles.*; 4908 import static java.lang.invoke.MethodType.*; 4909 ... 4910 MethodType intfn1 = methodType(int.class, int.class); 4911 MethodType intfn2 = methodType(int.class, int.class, int.class); 4912 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4913 assert(sub.type().equals(intfn2)); 4914 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4915 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4916 assert((int)rsub.invokeExact(1, 100) == 99); 4917 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4918 assert(add.type().equals(intfn2)); 4919 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4920 assert(twice.type().equals(intfn1)); 4921 assert((int)twice.invokeExact(21) == 42); 4922 * } 4923 * <p> 4924 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4925 * variable-arity method handle}, even if the original target method handle was. 4926 * @param target the method handle to invoke after arguments are reordered 4927 * @param newType the expected type of the new method handle 4928 * @param reorder an index array which controls the reordering 4929 * @return a method handle which delegates to the target after it 4930 * drops unused arguments and moves and/or duplicates the other arguments 4931 * @throws NullPointerException if any argument is null 4932 * @throws IllegalArgumentException if the index array length is not equal to 4933 * the arity of the target, or if any index array element 4934 * not a valid index for a parameter of {@code newType}, 4935 * or if two corresponding parameter types in 4936 * {@code target.type()} and {@code newType} are not identical, 4937 */ 4938 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4939 reorder = reorder.clone(); // get a private copy 4940 MethodType oldType = target.type(); 4941 permuteArgumentChecks(reorder, newType, oldType); 4942 // first detect dropped arguments and handle them separately 4943 int[] originalReorder = reorder; 4944 BoundMethodHandle result = target.rebind(); 4945 LambdaForm form = result.form; 4946 int newArity = newType.parameterCount(); 4947 // Normalize the reordering into a real permutation, 4948 // by removing duplicates and adding dropped elements. 4949 // This somewhat improves lambda form caching, as well 4950 // as simplifying the transform by breaking it up into steps. 4951 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4952 if (ddIdx > 0) { 4953 // We found a duplicated entry at reorder[ddIdx]. 4954 // Example: (x,y,z)->asList(x,y,z) 4955 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4956 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4957 // The starred element corresponds to the argument 4958 // deleted by the dupArgumentForm transform. 4959 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4960 boolean killFirst = false; 4961 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4962 // Set killFirst if the dup is larger than an intervening position. 4963 // This will remove at least one inversion from the permutation. 4964 if (dupVal > val) killFirst = true; 4965 } 4966 if (!killFirst) { 4967 srcPos = dstPos; 4968 dstPos = ddIdx; 4969 } 4970 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4971 assert (reorder[srcPos] == reorder[dstPos]); 4972 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4973 // contract the reordering by removing the element at dstPos 4974 int tailPos = dstPos + 1; 4975 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4976 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4977 } else { 4978 int dropVal = ~ddIdx, insPos = 0; 4979 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4980 // Find first element of reorder larger than dropVal. 4981 // This is where we will insert the dropVal. 4982 insPos += 1; 4983 } 4984 Class<?> ptype = newType.parameterType(dropVal); 4985 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4986 oldType = oldType.insertParameterTypes(insPos, ptype); 4987 // expand the reordering by inserting an element at insPos 4988 int tailPos = insPos + 1; 4989 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4990 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4991 reorder[insPos] = dropVal; 4992 } 4993 assert (permuteArgumentChecks(reorder, newType, oldType)); 4994 } 4995 assert (reorder.length == newArity); // a perfect permutation 4996 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4997 form = form.editor().permuteArgumentsForm(1, reorder); 4998 if (newType == result.type() && form == result.internalForm()) 4999 return result; 5000 return result.copyWith(newType, form); 5001 } 5002 5003 /** 5004 * Return an indication of any duplicate or omission in reorder. 5005 * If the reorder contains a duplicate entry, return the index of the second occurrence. 5006 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 5007 * Otherwise, return zero. 5008 * If an element not in [0..newArity-1] is encountered, return reorder.length. 5009 */ 5010 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 5011 final int BIT_LIMIT = 63; // max number of bits in bit mask 5012 if (newArity < BIT_LIMIT) { 5013 long mask = 0; 5014 for (int i = 0; i < reorder.length; i++) { 5015 int arg = reorder[i]; 5016 if (arg >= newArity) { 5017 return reorder.length; 5018 } 5019 long bit = 1L << arg; 5020 if ((mask & bit) != 0) { 5021 return i; // >0 indicates a dup 5022 } 5023 mask |= bit; 5024 } 5025 if (mask == (1L << newArity) - 1) { 5026 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 5027 return 0; 5028 } 5029 // find first zero 5030 long zeroBit = Long.lowestOneBit(~mask); 5031 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 5032 assert(zeroPos <= newArity); 5033 if (zeroPos == newArity) { 5034 return 0; 5035 } 5036 return ~zeroPos; 5037 } else { 5038 // same algorithm, different bit set 5039 BitSet mask = new BitSet(newArity); 5040 for (int i = 0; i < reorder.length; i++) { 5041 int arg = reorder[i]; 5042 if (arg >= newArity) { 5043 return reorder.length; 5044 } 5045 if (mask.get(arg)) { 5046 return i; // >0 indicates a dup 5047 } 5048 mask.set(arg); 5049 } 5050 int zeroPos = mask.nextClearBit(0); 5051 assert(zeroPos <= newArity); 5052 if (zeroPos == newArity) { 5053 return 0; 5054 } 5055 return ~zeroPos; 5056 } 5057 } 5058 5059 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 5060 if (newType.returnType() != oldType.returnType()) 5061 throw newIllegalArgumentException("return types do not match", 5062 oldType, newType); 5063 if (reorder.length != oldType.parameterCount()) 5064 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 5065 oldType, Arrays.toString(reorder)); 5066 5067 int limit = newType.parameterCount(); 5068 for (int j = 0; j < reorder.length; j++) { 5069 int i = reorder[j]; 5070 if (i < 0 || i >= limit) { 5071 throw newIllegalArgumentException("index is out of bounds for new type", 5072 i, newType); 5073 } 5074 Class<?> src = newType.parameterType(i); 5075 Class<?> dst = oldType.parameterType(j); 5076 if (src != dst) 5077 throw newIllegalArgumentException("parameter types do not match after reorder", 5078 oldType, newType); 5079 } 5080 return true; 5081 } 5082 5083 /** 5084 * Produces a method handle of the requested return type which returns the given 5085 * constant value every time it is invoked. 5086 * <p> 5087 * Before the method handle is returned, the passed-in value is converted to the requested type. 5088 * If the requested type is primitive, widening primitive conversions are attempted, 5089 * else reference conversions are attempted. 5090 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 5091 * @param type the return type of the desired method handle 5092 * @param value the value to return 5093 * @return a method handle of the given return type and no arguments, which always returns the given value 5094 * @throws NullPointerException if the {@code type} argument is null 5095 * @throws ClassCastException if the value cannot be converted to the required return type 5096 * @throws IllegalArgumentException if the given type is {@code void.class} 5097 */ 5098 public static MethodHandle constant(Class<?> type, Object value) { 5099 if (type.isPrimitive()) { 5100 if (type == void.class) 5101 throw newIllegalArgumentException("void type"); 5102 Wrapper w = Wrapper.forPrimitiveType(type); 5103 value = w.convert(value, type); 5104 if (w.zero().equals(value)) 5105 return zero(w, type); 5106 return insertArguments(identity(type), 0, value); 5107 } else { 5108 if (value == null) 5109 return zero(Wrapper.OBJECT, type); 5110 return identity(type).bindTo(value); 5111 } 5112 } 5113 5114 /** 5115 * Produces a method handle which returns its sole argument when invoked. 5116 * @param type the type of the sole parameter and return value of the desired method handle 5117 * @return a unary method handle which accepts and returns the given type 5118 * @throws NullPointerException if the argument is null 5119 * @throws IllegalArgumentException if the given type is {@code void.class} 5120 */ 5121 public static MethodHandle identity(Class<?> type) { 5122 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 5123 int pos = btw.ordinal(); 5124 MethodHandle ident = IDENTITY_MHS[pos]; 5125 if (ident == null) { 5126 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 5127 } 5128 if (ident.type().returnType() == type) 5129 return ident; 5130 // something like identity(Foo.class); do not bother to intern these 5131 assert (btw == Wrapper.OBJECT); 5132 return makeIdentity(type); 5133 } 5134 5135 /** 5136 * Produces a constant method handle of the requested return type which 5137 * returns the default value for that type every time it is invoked. 5138 * The resulting constant method handle will have no side effects. 5139 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 5140 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 5141 * since {@code explicitCastArguments} converts {@code null} to default values. 5142 * @param type the expected return type of the desired method handle 5143 * @return a constant method handle that takes no arguments 5144 * and returns the default value of the given type (or void, if the type is void) 5145 * @throws NullPointerException if the argument is null 5146 * @see MethodHandles#constant 5147 * @see MethodHandles#empty 5148 * @see MethodHandles#explicitCastArguments 5149 * @since 9 5150 */ 5151 public static MethodHandle zero(Class<?> type) { 5152 Objects.requireNonNull(type); 5153 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 5154 } 5155 5156 private static MethodHandle identityOrVoid(Class<?> type) { 5157 return type == void.class ? zero(type) : identity(type); 5158 } 5159 5160 /** 5161 * Produces a method handle of the requested type which ignores any arguments, does nothing, 5162 * and returns a suitable default depending on the return type. 5163 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 5164 * <p>The returned method handle is equivalent to 5165 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 5166 * 5167 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 5168 * {@code guardWithTest(pred, target, empty(target.type())}. 5169 * @param type the type of the desired method handle 5170 * @return a constant method handle of the given type, which returns a default value of the given return type 5171 * @throws NullPointerException if the argument is null 5172 * @see MethodHandles#zero 5173 * @see MethodHandles#constant 5174 * @since 9 5175 */ 5176 public static MethodHandle empty(MethodType type) { 5177 Objects.requireNonNull(type); 5178 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 5179 } 5180 5181 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 5182 private static MethodHandle makeIdentity(Class<?> ptype) { 5183 MethodType mtype = methodType(ptype, ptype); 5184 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 5185 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 5186 } 5187 5188 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 5189 int pos = btw.ordinal(); 5190 MethodHandle zero = ZERO_MHS[pos]; 5191 if (zero == null) { 5192 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 5193 } 5194 if (zero.type().returnType() == rtype) 5195 return zero; 5196 assert(btw == Wrapper.OBJECT); 5197 return makeZero(rtype); 5198 } 5199 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 5200 private static MethodHandle makeZero(Class<?> rtype) { 5201 MethodType mtype = methodType(rtype); 5202 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 5203 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 5204 } 5205 5206 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 5207 // Simulate a CAS, to avoid racy duplication of results. 5208 MethodHandle prev = cache[pos]; 5209 if (prev != null) return prev; 5210 return cache[pos] = value; 5211 } 5212 5213 /** 5214 * Provides a target method handle with one or more <em>bound arguments</em> 5215 * in advance of the method handle's invocation. 5216 * The formal parameters to the target corresponding to the bound 5217 * arguments are called <em>bound parameters</em>. 5218 * Returns a new method handle which saves away the bound arguments. 5219 * When it is invoked, it receives arguments for any non-bound parameters, 5220 * binds the saved arguments to their corresponding parameters, 5221 * and calls the original target. 5222 * <p> 5223 * The type of the new method handle will drop the types for the bound 5224 * parameters from the original target type, since the new method handle 5225 * will no longer require those arguments to be supplied by its callers. 5226 * <p> 5227 * Each given argument object must match the corresponding bound parameter type. 5228 * If a bound parameter type is a primitive, the argument object 5229 * must be a wrapper, and will be unboxed to produce the primitive value. 5230 * <p> 5231 * The {@code pos} argument selects which parameters are to be bound. 5232 * It may range between zero and <i>N-L</i> (inclusively), 5233 * where <i>N</i> is the arity of the target method handle 5234 * and <i>L</i> is the length of the values array. 5235 * <p> 5236 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5237 * variable-arity method handle}, even if the original target method handle was. 5238 * @param target the method handle to invoke after the argument is inserted 5239 * @param pos where to insert the argument (zero for the first) 5240 * @param values the series of arguments to insert 5241 * @return a method handle which inserts an additional argument, 5242 * before calling the original method handle 5243 * @throws NullPointerException if the target or the {@code values} array is null 5244 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 5245 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 5246 * is the length of the values array. 5247 * @throws ClassCastException if an argument does not match the corresponding bound parameter 5248 * type. 5249 * @see MethodHandle#bindTo 5250 */ 5251 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 5252 int insCount = values.length; 5253 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 5254 if (insCount == 0) return target; 5255 BoundMethodHandle result = target.rebind(); 5256 for (int i = 0; i < insCount; i++) { 5257 Object value = values[i]; 5258 Class<?> ptype = ptypes[pos+i]; 5259 if (ptype.isPrimitive()) { 5260 result = insertArgumentPrimitive(result, pos, ptype, value); 5261 } else { 5262 value = ptype.cast(value); // throw CCE if needed 5263 result = result.bindArgumentL(pos, value); 5264 } 5265 } 5266 return result; 5267 } 5268 5269 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5270 Class<?> ptype, Object value) { 5271 Wrapper w = Wrapper.forPrimitiveType(ptype); 5272 // perform unboxing and/or primitive conversion 5273 value = w.convert(value, ptype); 5274 return switch (w) { 5275 case INT -> result.bindArgumentI(pos, (int) value); 5276 case LONG -> result.bindArgumentJ(pos, (long) value); 5277 case FLOAT -> result.bindArgumentF(pos, (float) value); 5278 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5279 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5280 }; 5281 } 5282 5283 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5284 MethodType oldType = target.type(); 5285 int outargs = oldType.parameterCount(); 5286 int inargs = outargs - insCount; 5287 if (inargs < 0) 5288 throw newIllegalArgumentException("too many values to insert"); 5289 if (pos < 0 || pos > inargs) 5290 throw newIllegalArgumentException("no argument type to append"); 5291 return oldType.ptypes(); 5292 } 5293 5294 /** 5295 * Produces a method handle which will discard some dummy arguments 5296 * before calling some other specified <i>target</i> method handle. 5297 * The type of the new method handle will be the same as the target's type, 5298 * except it will also include the dummy argument types, 5299 * at some given position. 5300 * <p> 5301 * The {@code pos} argument may range between zero and <i>N</i>, 5302 * where <i>N</i> is the arity of the target. 5303 * If {@code pos} is zero, the dummy arguments will precede 5304 * the target's real arguments; if {@code pos} is <i>N</i> 5305 * they will come after. 5306 * <p> 5307 * <b>Example:</b> 5308 * {@snippet lang="java" : 5309 import static java.lang.invoke.MethodHandles.*; 5310 import static java.lang.invoke.MethodType.*; 5311 ... 5312 MethodHandle cat = lookup().findVirtual(String.class, 5313 "concat", methodType(String.class, String.class)); 5314 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5315 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5316 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5317 assertEquals(bigType, d0.type()); 5318 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5319 * } 5320 * <p> 5321 * This method is also equivalent to the following code: 5322 * <blockquote><pre> 5323 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5324 * </pre></blockquote> 5325 * @param target the method handle to invoke after the arguments are dropped 5326 * @param pos position of first argument to drop (zero for the leftmost) 5327 * @param valueTypes the type(s) of the argument(s) to drop 5328 * @return a method handle which drops arguments of the given types, 5329 * before calling the original method handle 5330 * @throws NullPointerException if the target is null, 5331 * or if the {@code valueTypes} list or any of its elements is null 5332 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5333 * or if {@code pos} is negative or greater than the arity of the target, 5334 * or if the new method handle's type would have too many parameters 5335 */ 5336 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5337 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5338 } 5339 5340 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5341 MethodType oldType = target.type(); // get NPE 5342 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5343 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5344 if (dropped == 0) return target; 5345 BoundMethodHandle result = target.rebind(); 5346 LambdaForm lform = result.form; 5347 int insertFormArg = 1 + pos; 5348 for (Class<?> ptype : valueTypes) { 5349 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5350 } 5351 result = result.copyWith(newType, lform); 5352 return result; 5353 } 5354 5355 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5356 int dropped = valueTypes.length; 5357 MethodType.checkSlotCount(dropped); 5358 int outargs = oldType.parameterCount(); 5359 int inargs = outargs + dropped; 5360 if (pos < 0 || pos > outargs) 5361 throw newIllegalArgumentException("no argument type to remove" 5362 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5363 ); 5364 return dropped; 5365 } 5366 5367 /** 5368 * Produces a method handle which will discard some dummy arguments 5369 * before calling some other specified <i>target</i> method handle. 5370 * The type of the new method handle will be the same as the target's type, 5371 * except it will also include the dummy argument types, 5372 * at some given position. 5373 * <p> 5374 * The {@code pos} argument may range between zero and <i>N</i>, 5375 * where <i>N</i> is the arity of the target. 5376 * If {@code pos} is zero, the dummy arguments will precede 5377 * the target's real arguments; if {@code pos} is <i>N</i> 5378 * they will come after. 5379 * @apiNote 5380 * {@snippet lang="java" : 5381 import static java.lang.invoke.MethodHandles.*; 5382 import static java.lang.invoke.MethodType.*; 5383 ... 5384 MethodHandle cat = lookup().findVirtual(String.class, 5385 "concat", methodType(String.class, String.class)); 5386 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5387 MethodHandle d0 = dropArguments(cat, 0, String.class); 5388 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5389 MethodHandle d1 = dropArguments(cat, 1, String.class); 5390 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5391 MethodHandle d2 = dropArguments(cat, 2, String.class); 5392 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5393 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5394 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5395 * } 5396 * <p> 5397 * This method is also equivalent to the following code: 5398 * <blockquote><pre> 5399 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5400 * </pre></blockquote> 5401 * @param target the method handle to invoke after the arguments are dropped 5402 * @param pos position of first argument to drop (zero for the leftmost) 5403 * @param valueTypes the type(s) of the argument(s) to drop 5404 * @return a method handle which drops arguments of the given types, 5405 * before calling the original method handle 5406 * @throws NullPointerException if the target is null, 5407 * or if the {@code valueTypes} array or any of its elements is null 5408 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5409 * or if {@code pos} is negative or greater than the arity of the target, 5410 * or if the new method handle's type would have 5411 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5412 */ 5413 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5414 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5415 } 5416 5417 /* Convenience overloads for trusting internal low-arity call-sites */ 5418 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5419 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5420 } 5421 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5422 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5423 } 5424 5425 // private version which allows caller some freedom with error handling 5426 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5427 boolean nullOnFailure) { 5428 Class<?>[] oldTypes = target.type().ptypes(); 5429 int match = oldTypes.length; 5430 if (skip != 0) { 5431 if (skip < 0 || skip > match) { 5432 throw newIllegalArgumentException("illegal skip", skip, target); 5433 } 5434 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5435 match -= skip; 5436 } 5437 Class<?>[] addTypes = newTypes; 5438 int add = addTypes.length; 5439 if (pos != 0) { 5440 if (pos < 0 || pos > add) { 5441 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5442 } 5443 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5444 add -= pos; 5445 assert(addTypes.length == add); 5446 } 5447 // Do not add types which already match the existing arguments. 5448 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5449 if (nullOnFailure) { 5450 return null; 5451 } 5452 throw newIllegalArgumentException("argument lists do not match", 5453 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5454 } 5455 addTypes = Arrays.copyOfRange(addTypes, match, add); 5456 add -= match; 5457 assert(addTypes.length == add); 5458 // newTypes: ( P*[pos], M*[match], A*[add] ) 5459 // target: ( S*[skip], M*[match] ) 5460 MethodHandle adapter = target; 5461 if (add > 0) { 5462 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5463 } 5464 // adapter: (S*[skip], M*[match], A*[add] ) 5465 if (pos > 0) { 5466 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5467 } 5468 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5469 return adapter; 5470 } 5471 5472 /** 5473 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5474 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5475 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5476 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5477 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5478 * {@link #dropArguments(MethodHandle, int, Class[])}. 5479 * <p> 5480 * The resulting handle will have the same return type as the target handle. 5481 * <p> 5482 * In more formal terms, assume these two type lists:<ul> 5483 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5484 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5485 * {@code newTypes}. 5486 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5487 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5488 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5489 * sub-list. 5490 * </ul> 5491 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5492 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5493 * {@link #dropArguments(MethodHandle, int, Class[])}. 5494 * 5495 * @apiNote 5496 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5497 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5498 * {@snippet lang="java" : 5499 import static java.lang.invoke.MethodHandles.*; 5500 import static java.lang.invoke.MethodType.*; 5501 ... 5502 ... 5503 MethodHandle h0 = constant(boolean.class, true); 5504 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5505 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5506 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5507 if (h1.type().parameterCount() < h2.type().parameterCount()) 5508 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5509 else 5510 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5511 MethodHandle h3 = guardWithTest(h0, h1, h2); 5512 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5513 * } 5514 * @param target the method handle to adapt 5515 * @param skip number of targets parameters to disregard (they will be unchanged) 5516 * @param newTypes the list of types to match {@code target}'s parameter type list to 5517 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5518 * @return a possibly adapted method handle 5519 * @throws NullPointerException if either argument is null 5520 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5521 * or if {@code skip} is negative or greater than the arity of the target, 5522 * or if {@code pos} is negative or greater than the newTypes list size, 5523 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5524 * {@code pos}. 5525 * @since 9 5526 */ 5527 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5528 Objects.requireNonNull(target); 5529 Objects.requireNonNull(newTypes); 5530 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5531 } 5532 5533 /** 5534 * Drop the return value of the target handle (if any). 5535 * The returned method handle will have a {@code void} return type. 5536 * 5537 * @param target the method handle to adapt 5538 * @return a possibly adapted method handle 5539 * @throws NullPointerException if {@code target} is null 5540 * @since 16 5541 */ 5542 public static MethodHandle dropReturn(MethodHandle target) { 5543 Objects.requireNonNull(target); 5544 MethodType oldType = target.type(); 5545 Class<?> oldReturnType = oldType.returnType(); 5546 if (oldReturnType == void.class) 5547 return target; 5548 MethodType newType = oldType.changeReturnType(void.class); 5549 BoundMethodHandle result = target.rebind(); 5550 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5551 result = result.copyWith(newType, lform); 5552 return result; 5553 } 5554 5555 /** 5556 * Adapts a target method handle by pre-processing 5557 * one or more of its arguments, each with its own unary filter function, 5558 * and then calling the target with each pre-processed argument 5559 * replaced by the result of its corresponding filter function. 5560 * <p> 5561 * The pre-processing is performed by one or more method handles, 5562 * specified in the elements of the {@code filters} array. 5563 * The first element of the filter array corresponds to the {@code pos} 5564 * argument of the target, and so on in sequence. 5565 * The filter functions are invoked in left to right order. 5566 * <p> 5567 * Null arguments in the array are treated as identity functions, 5568 * and the corresponding arguments left unchanged. 5569 * (If there are no non-null elements in the array, the original target is returned.) 5570 * Each filter is applied to the corresponding argument of the adapter. 5571 * <p> 5572 * If a filter {@code F} applies to the {@code N}th argument of 5573 * the target, then {@code F} must be a method handle which 5574 * takes exactly one argument. The type of {@code F}'s sole argument 5575 * replaces the corresponding argument type of the target 5576 * in the resulting adapted method handle. 5577 * The return type of {@code F} must be identical to the corresponding 5578 * parameter type of the target. 5579 * <p> 5580 * It is an error if there are elements of {@code filters} 5581 * (null or not) 5582 * which do not correspond to argument positions in the target. 5583 * <p><b>Example:</b> 5584 * {@snippet lang="java" : 5585 import static java.lang.invoke.MethodHandles.*; 5586 import static java.lang.invoke.MethodType.*; 5587 ... 5588 MethodHandle cat = lookup().findVirtual(String.class, 5589 "concat", methodType(String.class, String.class)); 5590 MethodHandle upcase = lookup().findVirtual(String.class, 5591 "toUpperCase", methodType(String.class)); 5592 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5593 MethodHandle f0 = filterArguments(cat, 0, upcase); 5594 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5595 MethodHandle f1 = filterArguments(cat, 1, upcase); 5596 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5597 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5598 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5599 * } 5600 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5601 * denotes the return type of both the {@code target} and resulting adapter. 5602 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5603 * of the parameters and arguments that precede and follow the filter position 5604 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5605 * values of the filtered parameters and arguments; they also represent the 5606 * return types of the {@code filter[i]} handles. The latter accept arguments 5607 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5608 * the resulting adapter. 5609 * {@snippet lang="java" : 5610 * T target(P... p, A[i]... a[i], B... b); 5611 * A[i] filter[i](V[i]); 5612 * T adapter(P... p, V[i]... v[i], B... b) { 5613 * return target(p..., filter[i](v[i])..., b...); 5614 * } 5615 * } 5616 * <p> 5617 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5618 * variable-arity method handle}, even if the original target method handle was. 5619 * 5620 * @param target the method handle to invoke after arguments are filtered 5621 * @param pos the position of the first argument to filter 5622 * @param filters method handles to call initially on filtered arguments 5623 * @return method handle which incorporates the specified argument filtering logic 5624 * @throws NullPointerException if the target is null 5625 * or if the {@code filters} array is null 5626 * @throws IllegalArgumentException if a non-null element of {@code filters} 5627 * does not match a corresponding argument type of target as described above, 5628 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5629 * or if the resulting method handle's type would have 5630 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5631 */ 5632 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5633 // In method types arguments start at index 0, while the LF 5634 // editor have the MH receiver at position 0 - adjust appropriately. 5635 final int MH_RECEIVER_OFFSET = 1; 5636 filterArgumentsCheckArity(target, pos, filters); 5637 MethodHandle adapter = target; 5638 5639 // keep track of currently matched filters, as to optimize repeated filters 5640 int index = 0; 5641 int[] positions = new int[filters.length]; 5642 MethodHandle filter = null; 5643 5644 // process filters in reverse order so that the invocation of 5645 // the resulting adapter will invoke the filters in left-to-right order 5646 for (int i = filters.length - 1; i >= 0; --i) { 5647 MethodHandle newFilter = filters[i]; 5648 if (newFilter == null) continue; // ignore null elements of filters 5649 5650 // flush changes on update 5651 if (filter != newFilter) { 5652 if (filter != null) { 5653 if (index > 1) { 5654 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5655 } else { 5656 adapter = filterArgument(adapter, positions[0] - 1, filter); 5657 } 5658 } 5659 filter = newFilter; 5660 index = 0; 5661 } 5662 5663 filterArgumentChecks(target, pos + i, newFilter); 5664 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5665 } 5666 if (index > 1) { 5667 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5668 } else if (index == 1) { 5669 adapter = filterArgument(adapter, positions[0] - 1, filter); 5670 } 5671 return adapter; 5672 } 5673 5674 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5675 MethodType targetType = adapter.type(); 5676 MethodType filterType = filter.type(); 5677 BoundMethodHandle result = adapter.rebind(); 5678 Class<?> newParamType = filterType.parameterType(0); 5679 5680 Class<?>[] ptypes = targetType.ptypes().clone(); 5681 for (int pos : positions) { 5682 ptypes[pos - 1] = newParamType; 5683 } 5684 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5685 5686 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5687 return result.copyWithExtendL(newType, lform, filter); 5688 } 5689 5690 /*non-public*/ 5691 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5692 filterArgumentChecks(target, pos, filter); 5693 MethodType targetType = target.type(); 5694 MethodType filterType = filter.type(); 5695 BoundMethodHandle result = target.rebind(); 5696 Class<?> newParamType = filterType.parameterType(0); 5697 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5698 MethodType newType = targetType.changeParameterType(pos, newParamType); 5699 result = result.copyWithExtendL(newType, lform, filter); 5700 return result; 5701 } 5702 5703 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5704 MethodType targetType = target.type(); 5705 int maxPos = targetType.parameterCount(); 5706 if (pos + filters.length > maxPos) 5707 throw newIllegalArgumentException("too many filters"); 5708 } 5709 5710 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5711 MethodType targetType = target.type(); 5712 MethodType filterType = filter.type(); 5713 if (filterType.parameterCount() != 1 5714 || filterType.returnType() != targetType.parameterType(pos)) 5715 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5716 } 5717 5718 /** 5719 * Adapts a target method handle by pre-processing 5720 * a sub-sequence of its arguments with a filter (another method handle). 5721 * The pre-processed arguments are replaced by the result (if any) of the 5722 * filter function. 5723 * The target is then called on the modified (usually shortened) argument list. 5724 * <p> 5725 * If the filter returns a value, the target must accept that value as 5726 * its argument in position {@code pos}, preceded and/or followed by 5727 * any arguments not passed to the filter. 5728 * If the filter returns void, the target must accept all arguments 5729 * not passed to the filter. 5730 * No arguments are reordered, and a result returned from the filter 5731 * replaces (in order) the whole subsequence of arguments originally 5732 * passed to the adapter. 5733 * <p> 5734 * The argument types (if any) of the filter 5735 * replace zero or one argument types of the target, at position {@code pos}, 5736 * in the resulting adapted method handle. 5737 * The return type of the filter (if any) must be identical to the 5738 * argument type of the target at position {@code pos}, and that target argument 5739 * is supplied by the return value of the filter. 5740 * <p> 5741 * In all cases, {@code pos} must be greater than or equal to zero, and 5742 * {@code pos} must also be less than or equal to the target's arity. 5743 * <p><b>Example:</b> 5744 * {@snippet lang="java" : 5745 import static java.lang.invoke.MethodHandles.*; 5746 import static java.lang.invoke.MethodType.*; 5747 ... 5748 MethodHandle deepToString = publicLookup() 5749 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5750 5751 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5752 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5753 5754 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5755 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5756 5757 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5758 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5759 assertEquals("[top, [up, down], strange]", 5760 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5761 5762 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5763 assertEquals("[top, [up, down], [strange]]", 5764 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5765 5766 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5767 assertEquals("[top, [[up, down, strange], charm], bottom]", 5768 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5769 * } 5770 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5771 * represents the return type of the {@code target} and resulting adapter. 5772 * {@code V}/{@code v} stand for the return type and value of the 5773 * {@code filter}, which are also found in the signature and arguments of 5774 * the {@code target}, respectively, unless {@code V} is {@code void}. 5775 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5776 * and values preceding and following the collection position, {@code pos}, 5777 * in the {@code target}'s signature. They also turn up in the resulting 5778 * adapter's signature and arguments, where they surround 5779 * {@code B}/{@code b}, which represent the parameter types and arguments 5780 * to the {@code filter} (if any). 5781 * {@snippet lang="java" : 5782 * T target(A...,V,C...); 5783 * V filter(B...); 5784 * T adapter(A... a,B... b,C... c) { 5785 * V v = filter(b...); 5786 * return target(a...,v,c...); 5787 * } 5788 * // and if the filter has no arguments: 5789 * T target2(A...,V,C...); 5790 * V filter2(); 5791 * T adapter2(A... a,C... c) { 5792 * V v = filter2(); 5793 * return target2(a...,v,c...); 5794 * } 5795 * // and if the filter has a void return: 5796 * T target3(A...,C...); 5797 * void filter3(B...); 5798 * T adapter3(A... a,B... b,C... c) { 5799 * filter3(b...); 5800 * return target3(a...,c...); 5801 * } 5802 * } 5803 * <p> 5804 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5805 * one which first "folds" the affected arguments, and then drops them, in separate 5806 * steps as follows: 5807 * {@snippet lang="java" : 5808 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5809 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5810 * } 5811 * If the target method handle consumes no arguments besides than the result 5812 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5813 * is equivalent to {@code filterReturnValue(coll, mh)}. 5814 * If the filter method handle {@code coll} consumes one argument and produces 5815 * a non-void result, then {@code collectArguments(mh, N, coll)} 5816 * is equivalent to {@code filterArguments(mh, N, coll)}. 5817 * Other equivalences are possible but would require argument permutation. 5818 * <p> 5819 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5820 * variable-arity method handle}, even if the original target method handle was. 5821 * 5822 * @param target the method handle to invoke after filtering the subsequence of arguments 5823 * @param pos the position of the first adapter argument to pass to the filter, 5824 * and/or the target argument which receives the result of the filter 5825 * @param filter method handle to call on the subsequence of arguments 5826 * @return method handle which incorporates the specified argument subsequence filtering logic 5827 * @throws NullPointerException if either argument is null 5828 * @throws IllegalArgumentException if the return type of {@code filter} 5829 * is non-void and is not the same as the {@code pos} argument of the target, 5830 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5831 * or if the resulting method handle's type would have 5832 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5833 * @see MethodHandles#foldArguments 5834 * @see MethodHandles#filterArguments 5835 * @see MethodHandles#filterReturnValue 5836 */ 5837 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5838 MethodType newType = collectArgumentsChecks(target, pos, filter); 5839 MethodType collectorType = filter.type(); 5840 BoundMethodHandle result = target.rebind(); 5841 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5842 return result.copyWithExtendL(newType, lform, filter); 5843 } 5844 5845 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5846 MethodType targetType = target.type(); 5847 MethodType filterType = filter.type(); 5848 Class<?> rtype = filterType.returnType(); 5849 Class<?>[] filterArgs = filterType.ptypes(); 5850 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5851 (rtype != void.class && pos >= targetType.parameterCount())) { 5852 throw newIllegalArgumentException("position is out of range for target", target, pos); 5853 } 5854 if (rtype == void.class) { 5855 return targetType.insertParameterTypes(pos, filterArgs); 5856 } 5857 if (rtype != targetType.parameterType(pos)) { 5858 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5859 } 5860 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5861 } 5862 5863 /** 5864 * Adapts a target method handle by post-processing 5865 * its return value (if any) with a filter (another method handle). 5866 * The result of the filter is returned from the adapter. 5867 * <p> 5868 * If the target returns a value, the filter must accept that value as 5869 * its only argument. 5870 * If the target returns void, the filter must accept no arguments. 5871 * <p> 5872 * The return type of the filter 5873 * replaces the return type of the target 5874 * in the resulting adapted method handle. 5875 * The argument type of the filter (if any) must be identical to the 5876 * return type of the target. 5877 * <p><b>Example:</b> 5878 * {@snippet lang="java" : 5879 import static java.lang.invoke.MethodHandles.*; 5880 import static java.lang.invoke.MethodType.*; 5881 ... 5882 MethodHandle cat = lookup().findVirtual(String.class, 5883 "concat", methodType(String.class, String.class)); 5884 MethodHandle length = lookup().findVirtual(String.class, 5885 "length", methodType(int.class)); 5886 System.out.println((String) cat.invokeExact("x", "y")); // xy 5887 MethodHandle f0 = filterReturnValue(cat, length); 5888 System.out.println((int) f0.invokeExact("x", "y")); // 2 5889 * } 5890 * <p>Here is pseudocode for the resulting adapter. In the code, 5891 * {@code T}/{@code t} represent the result type and value of the 5892 * {@code target}; {@code V}, the result type of the {@code filter}; and 5893 * {@code A}/{@code a}, the types and values of the parameters and arguments 5894 * of the {@code target} as well as the resulting adapter. 5895 * {@snippet lang="java" : 5896 * T target(A...); 5897 * V filter(T); 5898 * V adapter(A... a) { 5899 * T t = target(a...); 5900 * return filter(t); 5901 * } 5902 * // and if the target has a void return: 5903 * void target2(A...); 5904 * V filter2(); 5905 * V adapter2(A... a) { 5906 * target2(a...); 5907 * return filter2(); 5908 * } 5909 * // and if the filter has a void return: 5910 * T target3(A...); 5911 * void filter3(V); 5912 * void adapter3(A... a) { 5913 * T t = target3(a...); 5914 * filter3(t); 5915 * } 5916 * } 5917 * <p> 5918 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5919 * variable-arity method handle}, even if the original target method handle was. 5920 * @param target the method handle to invoke before filtering the return value 5921 * @param filter method handle to call on the return value 5922 * @return method handle which incorporates the specified return value filtering logic 5923 * @throws NullPointerException if either argument is null 5924 * @throws IllegalArgumentException if the argument list of {@code filter} 5925 * does not match the return type of target as described above 5926 */ 5927 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5928 MethodType targetType = target.type(); 5929 MethodType filterType = filter.type(); 5930 filterReturnValueChecks(targetType, filterType); 5931 BoundMethodHandle result = target.rebind(); 5932 BasicType rtype = BasicType.basicType(filterType.returnType()); 5933 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5934 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5935 result = result.copyWithExtendL(newType, lform, filter); 5936 return result; 5937 } 5938 5939 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5940 Class<?> rtype = targetType.returnType(); 5941 int filterValues = filterType.parameterCount(); 5942 if (filterValues == 0 5943 ? (rtype != void.class) 5944 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5945 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5946 } 5947 5948 /** 5949 * Filter the return value of a target method handle with a filter function. The filter function is 5950 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5951 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5952 * as follows: 5953 * {@snippet lang="java" : 5954 * T target(A...) 5955 * V filter(B... , T) 5956 * V adapter(A... a, B... b) { 5957 * T t = target(a...); 5958 * return filter(b..., t); 5959 * } 5960 * } 5961 * <p> 5962 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5963 * 5964 * @param target the target method handle 5965 * @param filter the filter method handle 5966 * @return the adapter method handle 5967 */ 5968 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5969 MethodType targetType = target.type(); 5970 MethodType filterType = filter.type(); 5971 BoundMethodHandle result = target.rebind(); 5972 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5973 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5974 if (filterType.parameterCount() > 1) { 5975 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5976 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5977 } 5978 } 5979 result = result.copyWithExtendL(newType, lform, filter); 5980 return result; 5981 } 5982 5983 /** 5984 * Adapts a target method handle by pre-processing 5985 * some of its arguments, and then calling the target with 5986 * the result of the pre-processing, inserted into the original 5987 * sequence of arguments. 5988 * <p> 5989 * The pre-processing is performed by {@code combiner}, a second method handle. 5990 * Of the arguments passed to the adapter, the first {@code N} arguments 5991 * are copied to the combiner, which is then called. 5992 * (Here, {@code N} is defined as the parameter count of the combiner.) 5993 * After this, control passes to the target, with any result 5994 * from the combiner inserted before the original {@code N} incoming 5995 * arguments. 5996 * <p> 5997 * If the combiner returns a value, the first parameter type of the target 5998 * must be identical with the return type of the combiner, and the next 5999 * {@code N} parameter types of the target must exactly match the parameters 6000 * of the combiner. 6001 * <p> 6002 * If the combiner has a void return, no result will be inserted, 6003 * and the first {@code N} parameter types of the target 6004 * must exactly match the parameters of the combiner. 6005 * <p> 6006 * The resulting adapter is the same type as the target, except that the 6007 * first parameter type is dropped, 6008 * if it corresponds to the result of the combiner. 6009 * <p> 6010 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 6011 * that either the combiner or the target does not wish to receive. 6012 * If some of the incoming arguments are destined only for the combiner, 6013 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 6014 * arguments will not need to be live on the stack on entry to the 6015 * target.) 6016 * <p><b>Example:</b> 6017 * {@snippet lang="java" : 6018 import static java.lang.invoke.MethodHandles.*; 6019 import static java.lang.invoke.MethodType.*; 6020 ... 6021 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6022 "println", methodType(void.class, String.class)) 6023 .bindTo(System.out); 6024 MethodHandle cat = lookup().findVirtual(String.class, 6025 "concat", methodType(String.class, String.class)); 6026 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6027 MethodHandle catTrace = foldArguments(cat, trace); 6028 // also prints "boo": 6029 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6030 * } 6031 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6032 * represents the result type of the {@code target} and resulting adapter. 6033 * {@code V}/{@code v} represent the type and value of the parameter and argument 6034 * of {@code target} that precedes the folding position; {@code V} also is 6035 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6036 * types and values of the {@code N} parameters and arguments at the folding 6037 * position. {@code B}/{@code b} represent the types and values of the 6038 * {@code target} parameters and arguments that follow the folded parameters 6039 * and arguments. 6040 * {@snippet lang="java" : 6041 * // there are N arguments in A... 6042 * T target(V, A[N]..., B...); 6043 * V combiner(A...); 6044 * T adapter(A... a, B... b) { 6045 * V v = combiner(a...); 6046 * return target(v, a..., b...); 6047 * } 6048 * // and if the combiner has a void return: 6049 * T target2(A[N]..., B...); 6050 * void combiner2(A...); 6051 * T adapter2(A... a, B... b) { 6052 * combiner2(a...); 6053 * return target2(a..., b...); 6054 * } 6055 * } 6056 * <p> 6057 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6058 * variable-arity method handle}, even if the original target method handle was. 6059 * @param target the method handle to invoke after arguments are combined 6060 * @param combiner method handle to call initially on the incoming arguments 6061 * @return method handle which incorporates the specified argument folding logic 6062 * @throws NullPointerException if either argument is null 6063 * @throws IllegalArgumentException if {@code combiner}'s return type 6064 * is non-void and not the same as the first argument type of 6065 * the target, or if the initial {@code N} argument types 6066 * of the target 6067 * (skipping one matching the {@code combiner}'s return type) 6068 * are not identical with the argument types of {@code combiner} 6069 */ 6070 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 6071 return foldArguments(target, 0, combiner); 6072 } 6073 6074 /** 6075 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 6076 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 6077 * before the folded arguments. 6078 * <p> 6079 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 6080 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 6081 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 6082 * 0. 6083 * 6084 * @apiNote Example: 6085 * {@snippet lang="java" : 6086 import static java.lang.invoke.MethodHandles.*; 6087 import static java.lang.invoke.MethodType.*; 6088 ... 6089 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 6090 "println", methodType(void.class, String.class)) 6091 .bindTo(System.out); 6092 MethodHandle cat = lookup().findVirtual(String.class, 6093 "concat", methodType(String.class, String.class)); 6094 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 6095 MethodHandle catTrace = foldArguments(cat, 1, trace); 6096 // also prints "jum": 6097 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 6098 * } 6099 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 6100 * represents the result type of the {@code target} and resulting adapter. 6101 * {@code V}/{@code v} represent the type and value of the parameter and argument 6102 * of {@code target} that precedes the folding position; {@code V} also is 6103 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 6104 * types and values of the {@code N} parameters and arguments at the folding 6105 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 6106 * and values of the {@code target} parameters and arguments that precede and 6107 * follow the folded parameters and arguments starting at {@code pos}, 6108 * respectively. 6109 * {@snippet lang="java" : 6110 * // there are N arguments in A... 6111 * T target(Z..., V, A[N]..., B...); 6112 * V combiner(A...); 6113 * T adapter(Z... z, A... a, B... b) { 6114 * V v = combiner(a...); 6115 * return target(z..., v, a..., b...); 6116 * } 6117 * // and if the combiner has a void return: 6118 * T target2(Z..., A[N]..., B...); 6119 * void combiner2(A...); 6120 * T adapter2(Z... z, A... a, B... b) { 6121 * combiner2(a...); 6122 * return target2(z..., a..., b...); 6123 * } 6124 * } 6125 * <p> 6126 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 6127 * variable-arity method handle}, even if the original target method handle was. 6128 * 6129 * @param target the method handle to invoke after arguments are combined 6130 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 6131 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6132 * @param combiner method handle to call initially on the incoming arguments 6133 * @return method handle which incorporates the specified argument folding logic 6134 * @throws NullPointerException if either argument is null 6135 * @throws IllegalArgumentException if either of the following two conditions holds: 6136 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6137 * {@code pos} of the target signature; 6138 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 6139 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 6140 * 6141 * @see #foldArguments(MethodHandle, MethodHandle) 6142 * @since 9 6143 */ 6144 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 6145 MethodType targetType = target.type(); 6146 MethodType combinerType = combiner.type(); 6147 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 6148 BoundMethodHandle result = target.rebind(); 6149 boolean dropResult = rtype == void.class; 6150 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 6151 MethodType newType = targetType; 6152 if (!dropResult) { 6153 newType = newType.dropParameterTypes(pos, pos + 1); 6154 } 6155 result = result.copyWithExtendL(newType, lform, combiner); 6156 return result; 6157 } 6158 6159 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 6160 int foldArgs = combinerType.parameterCount(); 6161 Class<?> rtype = combinerType.returnType(); 6162 int foldVals = rtype == void.class ? 0 : 1; 6163 int afterInsertPos = foldPos + foldVals; 6164 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 6165 if (ok) { 6166 for (int i = 0; i < foldArgs; i++) { 6167 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 6168 ok = false; 6169 break; 6170 } 6171 } 6172 } 6173 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 6174 ok = false; 6175 if (!ok) 6176 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6177 return rtype; 6178 } 6179 6180 /** 6181 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 6182 * of the pre-processing replacing the argument at the given position. 6183 * 6184 * @param target the method handle to invoke after arguments are combined 6185 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6186 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6187 * @param combiner method handle to call initially on the incoming arguments 6188 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6189 * @return method handle which incorporates the specified argument folding logic 6190 * @throws NullPointerException if either argument is null 6191 * @throws IllegalArgumentException if either of the following two conditions holds: 6192 * (1) {@code combiner}'s return type is not the same as the argument type at position 6193 * {@code pos} of the target signature; 6194 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 6195 * not identical with the argument types of {@code combiner}. 6196 */ 6197 /*non-public*/ 6198 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6199 return argumentsWithCombiner(true, target, position, combiner, argPositions); 6200 } 6201 6202 /** 6203 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 6204 * the pre-processing inserted into the original sequence of arguments at the given position. 6205 * 6206 * @param target the method handle to invoke after arguments are combined 6207 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 6208 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 6209 * @param combiner method handle to call initially on the incoming arguments 6210 * @param argPositions indexes of the target to pick arguments sent to the combiner from 6211 * @return method handle which incorporates the specified argument folding logic 6212 * @throws NullPointerException if either argument is null 6213 * @throws IllegalArgumentException if either of the following two conditions holds: 6214 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 6215 * {@code pos} of the target signature; 6216 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 6217 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 6218 * with the argument types of {@code combiner}. 6219 */ 6220 /*non-public*/ 6221 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6222 return argumentsWithCombiner(false, target, position, combiner, argPositions); 6223 } 6224 6225 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 6226 MethodType targetType = target.type(); 6227 MethodType combinerType = combiner.type(); 6228 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 6229 BoundMethodHandle result = target.rebind(); 6230 6231 MethodType newType = targetType; 6232 LambdaForm lform; 6233 if (filter) { 6234 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 6235 } else { 6236 boolean dropResult = rtype == void.class; 6237 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 6238 if (!dropResult) { 6239 newType = newType.dropParameterTypes(position, position + 1); 6240 } 6241 } 6242 result = result.copyWithExtendL(newType, lform, combiner); 6243 return result; 6244 } 6245 6246 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 6247 int combinerArgs = combinerType.parameterCount(); 6248 if (argPos.length != combinerArgs) { 6249 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 6250 } 6251 Class<?> rtype = combinerType.returnType(); 6252 6253 for (int i = 0; i < combinerArgs; i++) { 6254 int arg = argPos[i]; 6255 if (arg < 0 || arg > targetType.parameterCount()) { 6256 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 6257 } 6258 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 6259 throw newIllegalArgumentException("target argument type at position " + arg 6260 + " must match combiner argument type at index " + i + ": " + targetType 6261 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 6262 } 6263 } 6264 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 6265 throw misMatchedTypes("target and combiner types", targetType, combinerType); 6266 } 6267 return rtype; 6268 } 6269 6270 /** 6271 * Makes a method handle which adapts a target method handle, 6272 * by guarding it with a test, a boolean-valued method handle. 6273 * If the guard fails, a fallback handle is called instead. 6274 * All three method handles must have the same corresponding 6275 * argument and return types, except that the return type 6276 * of the test must be boolean, and the test is allowed 6277 * to have fewer arguments than the other two method handles. 6278 * <p> 6279 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6280 * represents the uniform result type of the three involved handles; 6281 * {@code A}/{@code a}, the types and values of the {@code target} 6282 * parameters and arguments that are consumed by the {@code test}; and 6283 * {@code B}/{@code b}, those types and values of the {@code target} 6284 * parameters and arguments that are not consumed by the {@code test}. 6285 * {@snippet lang="java" : 6286 * boolean test(A...); 6287 * T target(A...,B...); 6288 * T fallback(A...,B...); 6289 * T adapter(A... a,B... b) { 6290 * if (test(a...)) 6291 * return target(a..., b...); 6292 * else 6293 * return fallback(a..., b...); 6294 * } 6295 * } 6296 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6297 * be modified by execution of the test, and so are passed unchanged 6298 * from the caller to the target or fallback as appropriate. 6299 * @param test method handle used for test, must return boolean 6300 * @param target method handle to call if test passes 6301 * @param fallback method handle to call if test fails 6302 * @return method handle which incorporates the specified if/then/else logic 6303 * @throws NullPointerException if any argument is null 6304 * @throws IllegalArgumentException if {@code test} does not return boolean, 6305 * or if all three method types do not match (with the return 6306 * type of {@code test} changed to match that of the target). 6307 */ 6308 public static MethodHandle guardWithTest(MethodHandle test, 6309 MethodHandle target, 6310 MethodHandle fallback) { 6311 MethodType gtype = test.type(); 6312 MethodType ttype = target.type(); 6313 MethodType ftype = fallback.type(); 6314 if (!ttype.equals(ftype)) 6315 throw misMatchedTypes("target and fallback types", ttype, ftype); 6316 if (gtype.returnType() != boolean.class) 6317 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6318 6319 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6320 if (test == null) { 6321 throw misMatchedTypes("target and test types", ttype, gtype); 6322 } 6323 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6324 } 6325 6326 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6327 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6328 } 6329 6330 /** 6331 * Makes a method handle which adapts a target method handle, 6332 * by running it inside an exception handler. 6333 * If the target returns normally, the adapter returns that value. 6334 * If an exception matching the specified type is thrown, the fallback 6335 * handle is called instead on the exception, plus the original arguments. 6336 * <p> 6337 * The target and handler must have the same corresponding 6338 * argument and return types, except that handler may omit trailing arguments 6339 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6340 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6341 * <p> 6342 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6343 * represents the return type of the {@code target} and {@code handler}, 6344 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6345 * the types and values of arguments to the resulting handle consumed by 6346 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6347 * resulting handle discarded by {@code handler}. 6348 * {@snippet lang="java" : 6349 * T target(A..., B...); 6350 * T handler(ExType, A...); 6351 * T adapter(A... a, B... b) { 6352 * try { 6353 * return target(a..., b...); 6354 * } catch (ExType ex) { 6355 * return handler(ex, a...); 6356 * } 6357 * } 6358 * } 6359 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6360 * be modified by execution of the target, and so are passed unchanged 6361 * from the caller to the handler, if the handler is invoked. 6362 * <p> 6363 * The target and handler must return the same type, even if the handler 6364 * always throws. (This might happen, for instance, because the handler 6365 * is simulating a {@code finally} clause). 6366 * To create such a throwing handler, compose the handler creation logic 6367 * with {@link #throwException throwException}, 6368 * in order to create a method handle of the correct return type. 6369 * @param target method handle to call 6370 * @param exType the type of exception which the handler will catch 6371 * @param handler method handle to call if a matching exception is thrown 6372 * @return method handle which incorporates the specified try/catch logic 6373 * @throws NullPointerException if any argument is null 6374 * @throws IllegalArgumentException if {@code handler} does not accept 6375 * the given exception type, or if the method handle types do 6376 * not match in their return types and their 6377 * corresponding parameters 6378 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6379 */ 6380 public static MethodHandle catchException(MethodHandle target, 6381 Class<? extends Throwable> exType, 6382 MethodHandle handler) { 6383 MethodType ttype = target.type(); 6384 MethodType htype = handler.type(); 6385 if (!Throwable.class.isAssignableFrom(exType)) 6386 throw new ClassCastException(exType.getName()); 6387 if (htype.parameterCount() < 1 || 6388 !htype.parameterType(0).isAssignableFrom(exType)) 6389 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6390 if (htype.returnType() != ttype.returnType()) 6391 throw misMatchedTypes("target and handler return types", ttype, htype); 6392 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6393 if (handler == null) { 6394 throw misMatchedTypes("target and handler types", ttype, htype); 6395 } 6396 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6397 } 6398 6399 /** 6400 * Produces a method handle which will throw exceptions of the given {@code exType}. 6401 * The method handle will accept a single argument of {@code exType}, 6402 * and immediately throw it as an exception. 6403 * The method type will nominally specify a return of {@code returnType}. 6404 * The return type may be anything convenient: It doesn't matter to the 6405 * method handle's behavior, since it will never return normally. 6406 * @param returnType the return type of the desired method handle 6407 * @param exType the parameter type of the desired method handle 6408 * @return method handle which can throw the given exceptions 6409 * @throws NullPointerException if either argument is null 6410 */ 6411 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6412 if (!Throwable.class.isAssignableFrom(exType)) 6413 throw new ClassCastException(exType.getName()); 6414 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6415 } 6416 6417 /** 6418 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6419 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6420 * delivers the loop's result, which is the return value of the resulting handle. 6421 * <p> 6422 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6423 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6424 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6425 * terms of method handles, each clause will specify up to four independent actions:<ul> 6426 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6427 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6428 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6429 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6430 * </ul> 6431 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6432 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6433 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6434 * <p> 6435 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6436 * this case. See below for a detailed description. 6437 * <p> 6438 * <em>Parameters optional everywhere:</em> 6439 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6440 * As an exception, the init functions cannot take any {@code v} parameters, 6441 * because those values are not yet computed when the init functions are executed. 6442 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6443 * In fact, any clause function may take no arguments at all. 6444 * <p> 6445 * <em>Loop parameters:</em> 6446 * A clause function may take all the iteration variable values it is entitled to, in which case 6447 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6448 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6449 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6450 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6451 * init function is automatically a loop parameter {@code a}.) 6452 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6453 * These loop parameters act as loop-invariant values visible across the whole loop. 6454 * <p> 6455 * <em>Parameters visible everywhere:</em> 6456 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6457 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6458 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6459 * Most clause functions will not need all of this information, but they will be formally connected to it 6460 * as if by {@link #dropArguments}. 6461 * <a id="astar"></a> 6462 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6463 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6464 * In that notation, the general form of an init function parameter list 6465 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6466 * <p> 6467 * <em>Checking clause structure:</em> 6468 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6469 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6470 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6471 * met by the inputs to the loop combinator. 6472 * <p> 6473 * <em>Effectively identical sequences:</em> 6474 * <a id="effid"></a> 6475 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6476 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6477 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6478 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6479 * that longest list. 6480 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6481 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6482 * <p> 6483 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6484 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6485 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6486 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6487 * four. Padding takes place by appending elements to the array. 6488 * <li>Clauses with all {@code null}s are disregarded. 6489 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6490 * </ol> 6491 * <p> 6492 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6493 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6494 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6495 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6496 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6497 * iteration variable type. 6498 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6499 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6500 * </ol> 6501 * <p> 6502 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6503 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6504 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6505 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6506 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6507 * (These types will be checked in step 2, along with all the clause function types.) 6508 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6509 * <li>All of the collected parameter lists must be effectively identical. 6510 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6511 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6512 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6513 * the "internal parameter list". 6514 * </ul> 6515 * <p> 6516 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6517 * <li>Examine fini function return types, disregarding omitted fini functions. 6518 * <li>If there are no fini functions, the loop return type is {@code void}. 6519 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6520 * type. 6521 * </ol> 6522 * <p> 6523 * <em>Step 1D: Check other types.</em><ol type="a"> 6524 * <li>There must be at least one non-omitted pred function. 6525 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6526 * </ol> 6527 * <p> 6528 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6529 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6530 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6531 * (Note that their parameter lists are already effectively identical to this list.) 6532 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6533 * effectively identical to the internal parameter list {@code (V... A...)}. 6534 * </ol> 6535 * <p> 6536 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6537 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6538 * type. 6539 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6540 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6541 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6542 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6543 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6544 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6545 * loop return type. 6546 * </ol> 6547 * <p> 6548 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6549 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6550 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6551 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6552 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6553 * pad out the end of the list. 6554 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6555 * </ol> 6556 * <p> 6557 * <em>Final observations.</em><ol type="a"> 6558 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6559 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6560 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6561 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6562 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6563 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6564 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6565 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6566 * </ol> 6567 * <p> 6568 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6569 * <ul> 6570 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6571 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6572 * (Only one {@code Pn} has to be non-{@code null}.) 6573 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6574 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6575 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6576 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6577 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6578 * the resulting loop handle's parameter types {@code (A...)}. 6579 * </ul> 6580 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6581 * which is natural if most of the loop computation happens in the steps. For some loops, 6582 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6583 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6584 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6585 * where the init functions will need the extra parameters. For such reasons, the rules for 6586 * determining these parameters are as symmetric as possible, across all clause parts. 6587 * In general, the loop parameters function as common invariant values across the whole 6588 * loop, while the iteration variables function as common variant values, or (if there is 6589 * no step function) as internal loop invariant temporaries. 6590 * <p> 6591 * <em>Loop execution.</em><ol type="a"> 6592 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6593 * every clause function. These locals are loop invariant. 6594 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6595 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6596 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6597 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6598 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6599 * (in argument order). 6600 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6601 * returns {@code false}. 6602 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6603 * sequence {@code (v...)} of loop variables. 6604 * The updated value is immediately visible to all subsequent function calls. 6605 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6606 * (of type {@code R}) is returned from the loop as a whole. 6607 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6608 * except by throwing an exception. 6609 * </ol> 6610 * <p> 6611 * <em>Usage tips.</em> 6612 * <ul> 6613 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6614 * sometimes a step function only needs to observe the current value of its own variable. 6615 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6616 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6617 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6618 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6619 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6620 * <li>If some of the clause functions are virtual methods on an instance, the instance 6621 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6622 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6623 * will be the first iteration variable value, and it will be easy to use virtual 6624 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6625 * </ul> 6626 * <p> 6627 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6628 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6629 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6630 * {@snippet lang="java" : 6631 * V... init...(A...); 6632 * boolean pred...(V..., A...); 6633 * V... step...(V..., A...); 6634 * R fini...(V..., A...); 6635 * R loop(A... a) { 6636 * V... v... = init...(a...); 6637 * for (;;) { 6638 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6639 * v = s(v..., a...); 6640 * if (!p(v..., a...)) { 6641 * return f(v..., a...); 6642 * } 6643 * } 6644 * } 6645 * } 6646 * } 6647 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6648 * to their full length, even though individual clause functions may neglect to take them all. 6649 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6650 * 6651 * @apiNote Example: 6652 * {@snippet lang="java" : 6653 * // iterative implementation of the factorial function as a loop handle 6654 * static int one(int k) { return 1; } 6655 * static int inc(int i, int acc, int k) { return i + 1; } 6656 * static int mult(int i, int acc, int k) { return i * acc; } 6657 * static boolean pred(int i, int acc, int k) { return i < k; } 6658 * static int fin(int i, int acc, int k) { return acc; } 6659 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6660 * // null initializer for counter, should initialize to 0 6661 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6662 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6663 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6664 * assertEquals(120, loop.invoke(5)); 6665 * } 6666 * The same example, dropping arguments and using combinators: 6667 * {@snippet lang="java" : 6668 * // simplified implementation of the factorial function as a loop handle 6669 * static int inc(int i) { return i + 1; } // drop acc, k 6670 * static int mult(int i, int acc) { return i * acc; } //drop k 6671 * static boolean cmp(int i, int k) { return i < k; } 6672 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6673 * // null initializer for counter, should initialize to 0 6674 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6675 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6676 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6677 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6678 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6679 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6680 * assertEquals(720, loop.invoke(6)); 6681 * } 6682 * A similar example, using a helper object to hold a loop parameter: 6683 * {@snippet lang="java" : 6684 * // instance-based implementation of the factorial function as a loop handle 6685 * static class FacLoop { 6686 * final int k; 6687 * FacLoop(int k) { this.k = k; } 6688 * int inc(int i) { return i + 1; } 6689 * int mult(int i, int acc) { return i * acc; } 6690 * boolean pred(int i) { return i < k; } 6691 * int fin(int i, int acc) { return acc; } 6692 * } 6693 * // assume MH_FacLoop is a handle to the constructor 6694 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6695 * // null initializer for counter, should initialize to 0 6696 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6697 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6698 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6699 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6700 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6701 * assertEquals(5040, loop.invoke(7)); 6702 * } 6703 * 6704 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6705 * 6706 * @return a method handle embodying the looping behavior as defined by the arguments. 6707 * 6708 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6709 * 6710 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6711 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6712 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6713 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6714 * @since 9 6715 */ 6716 public static MethodHandle loop(MethodHandle[]... clauses) { 6717 // Step 0: determine clause structure. 6718 loopChecks0(clauses); 6719 6720 List<MethodHandle> init = new ArrayList<>(); 6721 List<MethodHandle> step = new ArrayList<>(); 6722 List<MethodHandle> pred = new ArrayList<>(); 6723 List<MethodHandle> fini = new ArrayList<>(); 6724 6725 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6726 init.add(clause[0]); // all clauses have at least length 1 6727 step.add(clause.length <= 1 ? null : clause[1]); 6728 pred.add(clause.length <= 2 ? null : clause[2]); 6729 fini.add(clause.length <= 3 ? null : clause[3]); 6730 }); 6731 6732 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6733 final int nclauses = init.size(); 6734 6735 // Step 1A: determine iteration variables (V...). 6736 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6737 for (int i = 0; i < nclauses; ++i) { 6738 MethodHandle in = init.get(i); 6739 MethodHandle st = step.get(i); 6740 if (in == null && st == null) { 6741 iterationVariableTypes.add(void.class); 6742 } else if (in != null && st != null) { 6743 loopChecks1a(i, in, st); 6744 iterationVariableTypes.add(in.type().returnType()); 6745 } else { 6746 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6747 } 6748 } 6749 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6750 6751 // Step 1B: determine loop parameters (A...). 6752 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6753 loopChecks1b(init, commonSuffix); 6754 6755 // Step 1C: determine loop return type. 6756 // Step 1D: check other types. 6757 // local variable required here; see JDK-8223553 6758 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6759 .map(MethodType::returnType); 6760 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6761 loopChecks1cd(pred, fini, loopReturnType); 6762 6763 // Step 2: determine parameter lists. 6764 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6765 commonParameterSequence.addAll(commonSuffix); 6766 loopChecks2(step, pred, fini, commonParameterSequence); 6767 // Step 3: fill in omitted functions. 6768 for (int i = 0; i < nclauses; ++i) { 6769 Class<?> t = iterationVariableTypes.get(i); 6770 if (init.get(i) == null) { 6771 init.set(i, empty(methodType(t, commonSuffix))); 6772 } 6773 if (step.get(i) == null) { 6774 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6775 } 6776 if (pred.get(i) == null) { 6777 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6778 } 6779 if (fini.get(i) == null) { 6780 fini.set(i, empty(methodType(t, commonParameterSequence))); 6781 } 6782 } 6783 6784 // Step 4: fill in missing parameter types. 6785 // Also convert all handles to fixed-arity handles. 6786 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6787 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6788 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6789 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6790 6791 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6792 allMatch(pl -> pl.equals(commonSuffix)); 6793 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6794 allMatch(pl -> pl.equals(commonParameterSequence)); 6795 6796 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6797 } 6798 6799 private static void loopChecks0(MethodHandle[][] clauses) { 6800 if (clauses == null || clauses.length == 0) { 6801 throw newIllegalArgumentException("null or no clauses passed"); 6802 } 6803 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6804 throw newIllegalArgumentException("null clauses are not allowed"); 6805 } 6806 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6807 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6808 } 6809 } 6810 6811 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6812 if (in.type().returnType() != st.type().returnType()) { 6813 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6814 st.type().returnType()); 6815 } 6816 } 6817 6818 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6819 return mhs.filter(Objects::nonNull) 6820 // take only those that can contribute to a common suffix because they are longer than the prefix 6821 .map(MethodHandle::type) 6822 .filter(t -> t.parameterCount() > skipSize) 6823 .max(Comparator.comparingInt(MethodType::parameterCount)) 6824 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6825 .orElse(List.of()); 6826 } 6827 6828 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6829 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6830 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6831 return longest1.size() >= longest2.size() ? longest1 : longest2; 6832 } 6833 6834 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6835 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6836 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6837 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6838 " (common suffix: " + commonSuffix + ")"); 6839 } 6840 } 6841 6842 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6843 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6844 anyMatch(t -> t != loopReturnType)) { 6845 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6846 loopReturnType + ")"); 6847 } 6848 6849 if (pred.stream().noneMatch(Objects::nonNull)) { 6850 throw newIllegalArgumentException("no predicate found", pred); 6851 } 6852 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6853 anyMatch(t -> t != boolean.class)) { 6854 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6855 } 6856 } 6857 6858 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6859 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6860 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6861 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6862 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6863 } 6864 } 6865 6866 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6867 return hs.stream().map(h -> { 6868 int pc = h.type().parameterCount(); 6869 int tpsize = targetParams.size(); 6870 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6871 }).toList(); 6872 } 6873 6874 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6875 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6876 } 6877 6878 /** 6879 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6880 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6881 * <p> 6882 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6883 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6884 * evaluates to {@code true}). 6885 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6886 * <p> 6887 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6888 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6889 * and updated with the value returned from its invocation. The result of loop execution will be 6890 * the final value of the additional loop-local variable (if present). 6891 * <p> 6892 * The following rules hold for these argument handles:<ul> 6893 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6894 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6895 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6896 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6897 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6898 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6899 * It will constrain the parameter lists of the other loop parts. 6900 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6901 * list {@code (A...)} is called the <em>external parameter list</em>. 6902 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6903 * additional state variable of the loop. 6904 * The body must both accept and return a value of this type {@code V}. 6905 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6906 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6907 * <a href="MethodHandles.html#effid">effectively identical</a> 6908 * to the external parameter list {@code (A...)}. 6909 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6910 * {@linkplain #empty default value}. 6911 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6912 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6913 * effectively identical to the internal parameter list. 6914 * </ul> 6915 * <p> 6916 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6917 * <li>The loop handle's result type is the result type {@code V} of the body. 6918 * <li>The loop handle's parameter types are the types {@code (A...)}, 6919 * from the external parameter list. 6920 * </ul> 6921 * <p> 6922 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6923 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6924 * passed to the loop. 6925 * {@snippet lang="java" : 6926 * V init(A...); 6927 * boolean pred(V, A...); 6928 * V body(V, A...); 6929 * V whileLoop(A... a...) { 6930 * V v = init(a...); 6931 * while (pred(v, a...)) { 6932 * v = body(v, a...); 6933 * } 6934 * return v; 6935 * } 6936 * } 6937 * 6938 * @apiNote Example: 6939 * {@snippet lang="java" : 6940 * // implement the zip function for lists as a loop handle 6941 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6942 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6943 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6944 * zip.add(a.next()); 6945 * zip.add(b.next()); 6946 * return zip; 6947 * } 6948 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6949 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6950 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6951 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6952 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6953 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6954 * } 6955 * 6956 * 6957 * @apiNote The implementation of this method can be expressed as follows: 6958 * {@snippet lang="java" : 6959 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6960 * MethodHandle fini = (body.type().returnType() == void.class 6961 * ? null : identity(body.type().returnType())); 6962 * MethodHandle[] 6963 * checkExit = { null, null, pred, fini }, 6964 * varBody = { init, body }; 6965 * return loop(checkExit, varBody); 6966 * } 6967 * } 6968 * 6969 * @param init optional initializer, providing the initial value of the loop variable. 6970 * May be {@code null}, implying a default initial value. See above for other constraints. 6971 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6972 * above for other constraints. 6973 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6974 * See above for other constraints. 6975 * 6976 * @return a method handle implementing the {@code while} loop as described by the arguments. 6977 * @throws IllegalArgumentException if the rules for the arguments are violated. 6978 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6979 * 6980 * @see #loop(MethodHandle[][]) 6981 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6982 * @since 9 6983 */ 6984 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6985 whileLoopChecks(init, pred, body); 6986 MethodHandle fini = identityOrVoid(body.type().returnType()); 6987 MethodHandle[] checkExit = { null, null, pred, fini }; 6988 MethodHandle[] varBody = { init, body }; 6989 return loop(checkExit, varBody); 6990 } 6991 6992 /** 6993 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6994 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6995 * <p> 6996 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6997 * method will, in each iteration, first execute its body and then evaluate the predicate. 6998 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6999 * <p> 7000 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 7001 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 7002 * and updated with the value returned from its invocation. The result of loop execution will be 7003 * the final value of the additional loop-local variable (if present). 7004 * <p> 7005 * The following rules hold for these argument handles:<ul> 7006 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7007 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 7008 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7009 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 7010 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 7011 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 7012 * It will constrain the parameter lists of the other loop parts. 7013 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 7014 * list {@code (A...)} is called the <em>external parameter list</em>. 7015 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7016 * additional state variable of the loop. 7017 * The body must both accept and return a value of this type {@code V}. 7018 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7019 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7020 * <a href="MethodHandles.html#effid">effectively identical</a> 7021 * to the external parameter list {@code (A...)}. 7022 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7023 * {@linkplain #empty default value}. 7024 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 7025 * Its parameter list (either empty or of the form {@code (V A*)}) must be 7026 * effectively identical to the internal parameter list. 7027 * </ul> 7028 * <p> 7029 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7030 * <li>The loop handle's result type is the result type {@code V} of the body. 7031 * <li>The loop handle's parameter types are the types {@code (A...)}, 7032 * from the external parameter list. 7033 * </ul> 7034 * <p> 7035 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7036 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 7037 * passed to the loop. 7038 * {@snippet lang="java" : 7039 * V init(A...); 7040 * boolean pred(V, A...); 7041 * V body(V, A...); 7042 * V doWhileLoop(A... a...) { 7043 * V v = init(a...); 7044 * do { 7045 * v = body(v, a...); 7046 * } while (pred(v, a...)); 7047 * return v; 7048 * } 7049 * } 7050 * 7051 * @apiNote Example: 7052 * {@snippet lang="java" : 7053 * // int i = 0; while (i < limit) { ++i; } return i; => limit 7054 * static int zero(int limit) { return 0; } 7055 * static int step(int i, int limit) { return i + 1; } 7056 * static boolean pred(int i, int limit) { return i < limit; } 7057 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 7058 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 7059 * assertEquals(23, loop.invoke(23)); 7060 * } 7061 * 7062 * 7063 * @apiNote The implementation of this method can be expressed as follows: 7064 * {@snippet lang="java" : 7065 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7066 * MethodHandle fini = (body.type().returnType() == void.class 7067 * ? null : identity(body.type().returnType())); 7068 * MethodHandle[] clause = { init, body, pred, fini }; 7069 * return loop(clause); 7070 * } 7071 * } 7072 * 7073 * @param init optional initializer, providing the initial value of the loop variable. 7074 * May be {@code null}, implying a default initial value. See above for other constraints. 7075 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 7076 * See above for other constraints. 7077 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 7078 * above for other constraints. 7079 * 7080 * @return a method handle implementing the {@code while} loop as described by the arguments. 7081 * @throws IllegalArgumentException if the rules for the arguments are violated. 7082 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 7083 * 7084 * @see #loop(MethodHandle[][]) 7085 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 7086 * @since 9 7087 */ 7088 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 7089 whileLoopChecks(init, pred, body); 7090 MethodHandle fini = identityOrVoid(body.type().returnType()); 7091 MethodHandle[] clause = {init, body, pred, fini }; 7092 return loop(clause); 7093 } 7094 7095 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 7096 Objects.requireNonNull(pred); 7097 Objects.requireNonNull(body); 7098 MethodType bodyType = body.type(); 7099 Class<?> returnType = bodyType.returnType(); 7100 List<Class<?>> innerList = bodyType.parameterList(); 7101 List<Class<?>> outerList = innerList; 7102 if (returnType == void.class) { 7103 // OK 7104 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 7105 // leading V argument missing => error 7106 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7107 throw misMatchedTypes("body function", bodyType, expected); 7108 } else { 7109 outerList = innerList.subList(1, innerList.size()); 7110 } 7111 MethodType predType = pred.type(); 7112 if (predType.returnType() != boolean.class || 7113 !predType.effectivelyIdenticalParameters(0, innerList)) { 7114 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 7115 } 7116 if (init != null) { 7117 MethodType initType = init.type(); 7118 if (initType.returnType() != returnType || 7119 !initType.effectivelyIdenticalParameters(0, outerList)) { 7120 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7121 } 7122 } 7123 } 7124 7125 /** 7126 * Constructs a loop that runs a given number of iterations. 7127 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7128 * <p> 7129 * The number of iterations is determined by the {@code iterations} handle evaluation result. 7130 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 7131 * It will be initialized to 0 and incremented by 1 in each iteration. 7132 * <p> 7133 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7134 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7135 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7136 * <p> 7137 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7138 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7139 * iteration variable. 7140 * The result of the loop handle execution will be the final {@code V} value of that variable 7141 * (or {@code void} if there is no {@code V} variable). 7142 * <p> 7143 * The following rules hold for the argument handles:<ul> 7144 * <li>The {@code iterations} handle must not be {@code null}, and must return 7145 * the type {@code int}, referred to here as {@code I} in parameter type lists. 7146 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7147 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7148 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7149 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7150 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7151 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7152 * of types called the <em>internal parameter list</em>. 7153 * It will constrain the parameter lists of the other loop parts. 7154 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7155 * with no additional {@code A} types, then the internal parameter list is extended by 7156 * the argument types {@code A...} of the {@code iterations} handle. 7157 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7158 * list {@code (A...)} is called the <em>external parameter list</em>. 7159 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7160 * additional state variable of the loop. 7161 * The body must both accept a leading parameter and return a value of this type {@code V}. 7162 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7163 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7164 * <a href="MethodHandles.html#effid">effectively identical</a> 7165 * to the external parameter list {@code (A...)}. 7166 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7167 * {@linkplain #empty default value}. 7168 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 7169 * effectively identical to the external parameter list {@code (A...)}. 7170 * </ul> 7171 * <p> 7172 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7173 * <li>The loop handle's result type is the result type {@code V} of the body. 7174 * <li>The loop handle's parameter types are the types {@code (A...)}, 7175 * from the external parameter list. 7176 * </ul> 7177 * <p> 7178 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7179 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7180 * arguments passed to the loop. 7181 * {@snippet lang="java" : 7182 * int iterations(A...); 7183 * V init(A...); 7184 * V body(V, int, A...); 7185 * V countedLoop(A... a...) { 7186 * int end = iterations(a...); 7187 * V v = init(a...); 7188 * for (int i = 0; i < end; ++i) { 7189 * v = body(v, i, a...); 7190 * } 7191 * return v; 7192 * } 7193 * } 7194 * 7195 * @apiNote Example with a fully conformant body method: 7196 * {@snippet lang="java" : 7197 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7198 * // => a variation on a well known theme 7199 * static String step(String v, int counter, String init) { return "na " + v; } 7200 * // assume MH_step is a handle to the method above 7201 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 7202 * MethodHandle start = MethodHandles.identity(String.class); 7203 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 7204 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 7205 * } 7206 * 7207 * @apiNote Example with the simplest possible body method type, 7208 * and passing the number of iterations to the loop invocation: 7209 * {@snippet lang="java" : 7210 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 7211 * // => a variation on a well known theme 7212 * static String step(String v, int counter ) { return "na " + v; } 7213 * // assume MH_step is a handle to the method above 7214 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 7215 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 7216 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 7217 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 7218 * } 7219 * 7220 * @apiNote Example that treats the number of iterations, string to append to, and string to append 7221 * as loop parameters: 7222 * {@snippet lang="java" : 7223 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7224 * // => a variation on a well known theme 7225 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 7226 * // assume MH_step is a handle to the method above 7227 * MethodHandle count = MethodHandles.identity(int.class); 7228 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 7229 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 7230 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 7231 * } 7232 * 7233 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 7234 * to enforce a loop type: 7235 * {@snippet lang="java" : 7236 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 7237 * // => a variation on a well known theme 7238 * static String step(String v, int counter, String pre) { return pre + " " + v; } 7239 * // assume MH_step is a handle to the method above 7240 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 7241 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 7242 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 7243 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 7244 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 7245 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 7246 * } 7247 * 7248 * @apiNote The implementation of this method can be expressed as follows: 7249 * {@snippet lang="java" : 7250 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7251 * return countedLoop(empty(iterations.type()), iterations, init, body); 7252 * } 7253 * } 7254 * 7255 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 7256 * result type must be {@code int}. See above for other constraints. 7257 * @param init optional initializer, providing the initial value of the loop variable. 7258 * May be {@code null}, implying a default initial value. See above for other constraints. 7259 * @param body body of the loop, which may not be {@code null}. 7260 * It controls the loop parameters and result type in the standard case (see above for details). 7261 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7262 * and may accept any number of additional types. 7263 * See above for other constraints. 7264 * 7265 * @return a method handle representing the loop. 7266 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 7267 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7268 * 7269 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7270 * @since 9 7271 */ 7272 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7273 return countedLoop(empty(iterations.type()), iterations, init, body); 7274 } 7275 7276 /** 7277 * Constructs a loop that counts over a range of numbers. 7278 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7279 * <p> 7280 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7281 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7282 * values of the loop counter. 7283 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7284 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7285 * <p> 7286 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7287 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7288 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7289 * <p> 7290 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7291 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7292 * iteration variable. 7293 * The result of the loop handle execution will be the final {@code V} value of that variable 7294 * (or {@code void} if there is no {@code V} variable). 7295 * <p> 7296 * The following rules hold for the argument handles:<ul> 7297 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7298 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7299 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7300 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7301 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7302 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7303 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7304 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7305 * of types called the <em>internal parameter list</em>. 7306 * It will constrain the parameter lists of the other loop parts. 7307 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7308 * with no additional {@code A} types, then the internal parameter list is extended by 7309 * the argument types {@code A...} of the {@code end} handle. 7310 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7311 * list {@code (A...)} is called the <em>external parameter list</em>. 7312 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7313 * additional state variable of the loop. 7314 * The body must both accept a leading parameter and return a value of this type {@code V}. 7315 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7316 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7317 * <a href="MethodHandles.html#effid">effectively identical</a> 7318 * to the external parameter list {@code (A...)}. 7319 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7320 * {@linkplain #empty default value}. 7321 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7322 * effectively identical to the external parameter list {@code (A...)}. 7323 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7324 * to the external parameter list. 7325 * </ul> 7326 * <p> 7327 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7328 * <li>The loop handle's result type is the result type {@code V} of the body. 7329 * <li>The loop handle's parameter types are the types {@code (A...)}, 7330 * from the external parameter list. 7331 * </ul> 7332 * <p> 7333 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7334 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7335 * arguments passed to the loop. 7336 * {@snippet lang="java" : 7337 * int start(A...); 7338 * int end(A...); 7339 * V init(A...); 7340 * V body(V, int, A...); 7341 * V countedLoop(A... a...) { 7342 * int e = end(a...); 7343 * int s = start(a...); 7344 * V v = init(a...); 7345 * for (int i = s; i < e; ++i) { 7346 * v = body(v, i, a...); 7347 * } 7348 * return v; 7349 * } 7350 * } 7351 * 7352 * @apiNote The implementation of this method can be expressed as follows: 7353 * {@snippet lang="java" : 7354 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7355 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7356 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7357 * // the following semantics: 7358 * // MH_increment: (int limit, int counter) -> counter + 1 7359 * // MH_predicate: (int limit, int counter) -> counter < limit 7360 * Class<?> counterType = start.type().returnType(); // int 7361 * Class<?> returnType = body.type().returnType(); 7362 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7363 * if (returnType != void.class) { // ignore the V variable 7364 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7365 * pred = dropArguments(pred, 1, returnType); // ditto 7366 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7367 * } 7368 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7369 * MethodHandle[] 7370 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7371 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7372 * indexVar = { start, incr }; // i = start(); i = i + 1 7373 * return loop(loopLimit, bodyClause, indexVar); 7374 * } 7375 * } 7376 * 7377 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7378 * See above for other constraints. 7379 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7380 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7381 * @param init optional initializer, providing the initial value of the loop variable. 7382 * May be {@code null}, implying a default initial value. See above for other constraints. 7383 * @param body body of the loop, which may not be {@code null}. 7384 * It controls the loop parameters and result type in the standard case (see above for details). 7385 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7386 * and may accept any number of additional types. 7387 * See above for other constraints. 7388 * 7389 * @return a method handle representing the loop. 7390 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7391 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7392 * 7393 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7394 * @since 9 7395 */ 7396 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7397 countedLoopChecks(start, end, init, body); 7398 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7399 Class<?> limitType = end.type().returnType(); // yes, int again 7400 Class<?> returnType = body.type().returnType(); 7401 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7402 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7403 MethodHandle retv = null; 7404 if (returnType != void.class) { 7405 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7406 pred = dropArguments(pred, 1, returnType); // ditto 7407 retv = dropArguments(identity(returnType), 0, counterType); 7408 } 7409 body = dropArguments(body, 0, counterType); // ignore the limit variable 7410 MethodHandle[] 7411 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7412 bodyClause = { init, body }, // v = init(); v = body(v, i) 7413 indexVar = { start, incr }; // i = start(); i = i + 1 7414 return loop(loopLimit, bodyClause, indexVar); 7415 } 7416 7417 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7418 Objects.requireNonNull(start); 7419 Objects.requireNonNull(end); 7420 Objects.requireNonNull(body); 7421 Class<?> counterType = start.type().returnType(); 7422 if (counterType != int.class) { 7423 MethodType expected = start.type().changeReturnType(int.class); 7424 throw misMatchedTypes("start function", start.type(), expected); 7425 } else if (end.type().returnType() != counterType) { 7426 MethodType expected = end.type().changeReturnType(counterType); 7427 throw misMatchedTypes("end function", end.type(), expected); 7428 } 7429 MethodType bodyType = body.type(); 7430 Class<?> returnType = bodyType.returnType(); 7431 List<Class<?>> innerList = bodyType.parameterList(); 7432 // strip leading V value if present 7433 int vsize = (returnType == void.class ? 0 : 1); 7434 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7435 // argument list has no "V" => error 7436 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7437 throw misMatchedTypes("body function", bodyType, expected); 7438 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7439 // missing I type => error 7440 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7441 throw misMatchedTypes("body function", bodyType, expected); 7442 } 7443 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7444 if (outerList.isEmpty()) { 7445 // special case; take lists from end handle 7446 outerList = end.type().parameterList(); 7447 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7448 } 7449 MethodType expected = methodType(counterType, outerList); 7450 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7451 throw misMatchedTypes("start parameter types", start.type(), expected); 7452 } 7453 if (end.type() != start.type() && 7454 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7455 throw misMatchedTypes("end parameter types", end.type(), expected); 7456 } 7457 if (init != null) { 7458 MethodType initType = init.type(); 7459 if (initType.returnType() != returnType || 7460 !initType.effectivelyIdenticalParameters(0, outerList)) { 7461 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7462 } 7463 } 7464 } 7465 7466 /** 7467 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7468 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7469 * <p> 7470 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7471 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7472 * <p> 7473 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7474 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7475 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7476 * <p> 7477 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7478 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7479 * iteration variable. 7480 * The result of the loop handle execution will be the final {@code V} value of that variable 7481 * (or {@code void} if there is no {@code V} variable). 7482 * <p> 7483 * The following rules hold for the argument handles:<ul> 7484 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7485 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7486 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7487 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7488 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7489 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7490 * of types called the <em>internal parameter list</em>. 7491 * It will constrain the parameter lists of the other loop parts. 7492 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7493 * with no additional {@code A} types, then the internal parameter list is extended by 7494 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7495 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7496 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7497 * list {@code (A...)} is called the <em>external parameter list</em>. 7498 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7499 * additional state variable of the loop. 7500 * The body must both accept a leading parameter and return a value of this type {@code V}. 7501 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7502 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7503 * <a href="MethodHandles.html#effid">effectively identical</a> 7504 * to the external parameter list {@code (A...)}. 7505 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7506 * {@linkplain #empty default value}. 7507 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7508 * type {@code java.util.Iterator} or a subtype thereof. 7509 * The iterator it produces when the loop is executed will be assumed 7510 * to yield values which can be converted to type {@code T}. 7511 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7512 * effectively identical to the external parameter list {@code (A...)}. 7513 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7514 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7515 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7516 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7517 * the {@link MethodHandle#asType asType} conversion method. 7518 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7519 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7520 * </ul> 7521 * <p> 7522 * The type {@code T} may be either a primitive or reference. 7523 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7524 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7525 * as if by the {@link MethodHandle#asType asType} conversion method. 7526 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7527 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7528 * <p> 7529 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7530 * <li>The loop handle's result type is the result type {@code V} of the body. 7531 * <li>The loop handle's parameter types are the types {@code (A...)}, 7532 * from the external parameter list. 7533 * </ul> 7534 * <p> 7535 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7536 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7537 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7538 * {@snippet lang="java" : 7539 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7540 * V init(A...); 7541 * V body(V,T,A...); 7542 * V iteratedLoop(A... a...) { 7543 * Iterator<T> it = iterator(a...); 7544 * V v = init(a...); 7545 * while (it.hasNext()) { 7546 * T t = it.next(); 7547 * v = body(v, t, a...); 7548 * } 7549 * return v; 7550 * } 7551 * } 7552 * 7553 * @apiNote Example: 7554 * {@snippet lang="java" : 7555 * // get an iterator from a list 7556 * static List<String> reverseStep(List<String> r, String e) { 7557 * r.add(0, e); 7558 * return r; 7559 * } 7560 * static List<String> newArrayList() { return new ArrayList<>(); } 7561 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7562 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7563 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7564 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7565 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7566 * } 7567 * 7568 * @apiNote The implementation of this method can be expressed approximately as follows: 7569 * {@snippet lang="java" : 7570 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7571 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7572 * Class<?> returnType = body.type().returnType(); 7573 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7574 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7575 * MethodHandle retv = null, step = body, startIter = iterator; 7576 * if (returnType != void.class) { 7577 * // the simple thing first: in (I V A...), drop the I to get V 7578 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7579 * // body type signature (V T A...), internal loop types (I V A...) 7580 * step = swapArguments(body, 0, 1); // swap V <-> T 7581 * } 7582 * if (startIter == null) startIter = MH_getIter; 7583 * MethodHandle[] 7584 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7585 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7586 * return loop(iterVar, bodyClause); 7587 * } 7588 * } 7589 * 7590 * @param iterator an optional handle to return the iterator to start the loop. 7591 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7592 * See above for other constraints. 7593 * @param init optional initializer, providing the initial value of the loop variable. 7594 * May be {@code null}, implying a default initial value. See above for other constraints. 7595 * @param body body of the loop, which may not be {@code null}. 7596 * It controls the loop parameters and result type in the standard case (see above for details). 7597 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7598 * and may accept any number of additional types. 7599 * See above for other constraints. 7600 * 7601 * @return a method handle embodying the iteration loop functionality. 7602 * @throws NullPointerException if the {@code body} handle is {@code null}. 7603 * @throws IllegalArgumentException if any argument violates the above requirements. 7604 * 7605 * @since 9 7606 */ 7607 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7608 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7609 Class<?> returnType = body.type().returnType(); 7610 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7611 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7612 MethodHandle startIter; 7613 MethodHandle nextVal; 7614 { 7615 MethodType iteratorType; 7616 if (iterator == null) { 7617 // derive argument type from body, if available, else use Iterable 7618 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7619 iteratorType = startIter.type().changeParameterType(0, iterableType); 7620 } else { 7621 // force return type to the internal iterator class 7622 iteratorType = iterator.type().changeReturnType(Iterator.class); 7623 startIter = iterator; 7624 } 7625 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7626 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7627 7628 // perform the asType transforms under an exception transformer, as per spec.: 7629 try { 7630 startIter = startIter.asType(iteratorType); 7631 nextVal = nextRaw.asType(nextValType); 7632 } catch (WrongMethodTypeException ex) { 7633 throw new IllegalArgumentException(ex); 7634 } 7635 } 7636 7637 MethodHandle retv = null, step = body; 7638 if (returnType != void.class) { 7639 // the simple thing first: in (I V A...), drop the I to get V 7640 retv = dropArguments(identity(returnType), 0, Iterator.class); 7641 // body type signature (V T A...), internal loop types (I V A...) 7642 step = swapArguments(body, 0, 1); // swap V <-> T 7643 } 7644 7645 MethodHandle[] 7646 iterVar = { startIter, null, hasNext, retv }, 7647 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7648 return loop(iterVar, bodyClause); 7649 } 7650 7651 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7652 Objects.requireNonNull(body); 7653 MethodType bodyType = body.type(); 7654 Class<?> returnType = bodyType.returnType(); 7655 List<Class<?>> internalParamList = bodyType.parameterList(); 7656 // strip leading V value if present 7657 int vsize = (returnType == void.class ? 0 : 1); 7658 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7659 // argument list has no "V" => error 7660 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7661 throw misMatchedTypes("body function", bodyType, expected); 7662 } else if (internalParamList.size() <= vsize) { 7663 // missing T type => error 7664 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7665 throw misMatchedTypes("body function", bodyType, expected); 7666 } 7667 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7668 Class<?> iterableType = null; 7669 if (iterator != null) { 7670 // special case; if the body handle only declares V and T then 7671 // the external parameter list is obtained from iterator handle 7672 if (externalParamList.isEmpty()) { 7673 externalParamList = iterator.type().parameterList(); 7674 } 7675 MethodType itype = iterator.type(); 7676 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7677 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7678 } 7679 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7680 MethodType expected = methodType(itype.returnType(), externalParamList); 7681 throw misMatchedTypes("iterator parameters", itype, expected); 7682 } 7683 } else { 7684 if (externalParamList.isEmpty()) { 7685 // special case; if the iterator handle is null and the body handle 7686 // only declares V and T then the external parameter list consists 7687 // of Iterable 7688 externalParamList = List.of(Iterable.class); 7689 iterableType = Iterable.class; 7690 } else { 7691 // special case; if the iterator handle is null and the external 7692 // parameter list is not empty then the first parameter must be 7693 // assignable to Iterable 7694 iterableType = externalParamList.get(0); 7695 if (!Iterable.class.isAssignableFrom(iterableType)) { 7696 throw newIllegalArgumentException( 7697 "inferred first loop argument must inherit from Iterable: " + iterableType); 7698 } 7699 } 7700 } 7701 if (init != null) { 7702 MethodType initType = init.type(); 7703 if (initType.returnType() != returnType || 7704 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7705 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7706 } 7707 } 7708 return iterableType; // help the caller a bit 7709 } 7710 7711 /*non-public*/ 7712 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7713 // there should be a better way to uncross my wires 7714 int arity = mh.type().parameterCount(); 7715 int[] order = new int[arity]; 7716 for (int k = 0; k < arity; k++) order[k] = k; 7717 order[i] = j; order[j] = i; 7718 Class<?>[] types = mh.type().parameterArray(); 7719 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7720 MethodType swapType = methodType(mh.type().returnType(), types); 7721 return permuteArguments(mh, swapType, order); 7722 } 7723 7724 /** 7725 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7726 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7727 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7728 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7729 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7730 * {@code try-finally} handle. 7731 * <p> 7732 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7733 * The first is the exception thrown during the 7734 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7735 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7736 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7737 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7738 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7739 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7740 * <p> 7741 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7742 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7743 * two extra leading parameters:<ul> 7744 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7745 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7746 * the result from the execution of the {@code target} handle. 7747 * This parameter is not present if the {@code target} returns {@code void}. 7748 * </ul> 7749 * <p> 7750 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7751 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7752 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7753 * the cleanup. 7754 * {@snippet lang="java" : 7755 * V target(A..., B...); 7756 * V cleanup(Throwable, V, A...); 7757 * V adapter(A... a, B... b) { 7758 * V result = (zero value for V); 7759 * Throwable throwable = null; 7760 * try { 7761 * result = target(a..., b...); 7762 * } catch (Throwable t) { 7763 * throwable = t; 7764 * throw t; 7765 * } finally { 7766 * result = cleanup(throwable, result, a...); 7767 * } 7768 * return result; 7769 * } 7770 * } 7771 * <p> 7772 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7773 * be modified by execution of the target, and so are passed unchanged 7774 * from the caller to the cleanup, if it is invoked. 7775 * <p> 7776 * The target and cleanup must return the same type, even if the cleanup 7777 * always throws. 7778 * To create such a throwing cleanup, compose the cleanup logic 7779 * with {@link #throwException throwException}, 7780 * in order to create a method handle of the correct return type. 7781 * <p> 7782 * Note that {@code tryFinally} never converts exceptions into normal returns. 7783 * In rare cases where exceptions must be converted in that way, first wrap 7784 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7785 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7786 * <p> 7787 * It is recommended that the first parameter type of {@code cleanup} be 7788 * declared {@code Throwable} rather than a narrower subtype. This ensures 7789 * {@code cleanup} will always be invoked with whatever exception that 7790 * {@code target} throws. Declaring a narrower type may result in a 7791 * {@code ClassCastException} being thrown by the {@code try-finally} 7792 * handle if the type of the exception thrown by {@code target} is not 7793 * assignable to the first parameter type of {@code cleanup}. Note that 7794 * various exception types of {@code VirtualMachineError}, 7795 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7796 * thrown by almost any kind of Java code, and a finally clause that 7797 * catches (say) only {@code IOException} would mask any of the others 7798 * behind a {@code ClassCastException}. 7799 * 7800 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7801 * @param cleanup the handle that is invoked in the finally block. 7802 * 7803 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7804 * @throws NullPointerException if any argument is null 7805 * @throws IllegalArgumentException if {@code cleanup} does not accept 7806 * the required leading arguments, or if the method handle types do 7807 * not match in their return types and their 7808 * corresponding trailing parameters 7809 * 7810 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7811 * @since 9 7812 */ 7813 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7814 Class<?>[] targetParamTypes = target.type().ptypes(); 7815 Class<?> rtype = target.type().returnType(); 7816 7817 tryFinallyChecks(target, cleanup); 7818 7819 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7820 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7821 // target parameter list. 7822 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7823 7824 // Ensure that the intrinsic type checks the instance thrown by the 7825 // target against the first parameter of cleanup 7826 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7827 7828 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7829 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7830 } 7831 7832 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7833 Class<?> rtype = target.type().returnType(); 7834 if (rtype != cleanup.type().returnType()) { 7835 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7836 } 7837 MethodType cleanupType = cleanup.type(); 7838 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7839 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7840 } 7841 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7842 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7843 } 7844 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7845 // target parameter list. 7846 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7847 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7848 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7849 cleanup.type(), target.type()); 7850 } 7851 } 7852 7853 /** 7854 * Creates a table switch method handle, which can be used to switch over a set of target 7855 * method handles, based on a given target index, called selector. 7856 * <p> 7857 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7858 * and where {@code N} is the number of target method handles, the table switch method 7859 * handle will invoke the n-th target method handle from the list of target method handles. 7860 * <p> 7861 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7862 * method handle will invoke the given fallback method handle. 7863 * <p> 7864 * All method handles passed to this method must have the same type, with the additional 7865 * requirement that the leading parameter be of type {@code int}. The leading parameter 7866 * represents the selector. 7867 * <p> 7868 * Any trailing parameters present in the type will appear on the returned table switch 7869 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7870 * together with the selector value, to the selected method handle when invoking it. 7871 * 7872 * @apiNote Example: 7873 * The cases each drop the {@code selector} value they are given, and take an additional 7874 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7875 * to a specific constant label string for each case: 7876 * {@snippet lang="java" : 7877 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7878 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7879 * MethodType.methodType(String.class, String.class)); 7880 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7881 * 7882 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7883 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7884 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7885 * 7886 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7887 * caseDefault, 7888 * case0, 7889 * case1 7890 * ); 7891 * 7892 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7893 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7894 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7895 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7896 * } 7897 * 7898 * @param fallback the fallback method handle that is called when the selector is not 7899 * within the range {@code [0, N)}. 7900 * @param targets array of target method handles. 7901 * @return the table switch method handle. 7902 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7903 * any of the elements of the {@code targets} array are 7904 * {@code null}. 7905 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7906 * parameter of the fallback handle or any of the target 7907 * handles is not {@code int}, or if the types of 7908 * the fallback handle and all of target handles are 7909 * not the same. 7910 * 7911 * @since 17 7912 */ 7913 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7914 Objects.requireNonNull(fallback); 7915 Objects.requireNonNull(targets); 7916 targets = targets.clone(); 7917 MethodType type = tableSwitchChecks(fallback, targets); 7918 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7919 } 7920 7921 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7922 if (caseActions.length == 0) 7923 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7924 7925 MethodType expectedType = defaultCase.type(); 7926 7927 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7928 throw new IllegalArgumentException( 7929 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7930 7931 for (MethodHandle mh : caseActions) { 7932 Objects.requireNonNull(mh); 7933 if (mh.type() != expectedType) 7934 throw new IllegalArgumentException( 7935 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7936 } 7937 7938 return expectedType; 7939 } 7940 7941 /** 7942 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7943 * <p> 7944 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7945 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7946 * to the target var handle. 7947 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7948 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7949 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7950 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7951 * <p> 7952 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7953 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7954 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7955 * will be appended to the coordinates of the target var handle). 7956 * <p> 7957 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7958 * throw an {@link IllegalStateException}. 7959 * <p> 7960 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7961 * atomic access guarantees as those featured by the target var handle. 7962 * 7963 * @param target the target var handle 7964 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7965 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7966 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7967 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7968 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7969 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7970 * @throws NullPointerException if any of the arguments is {@code null}. 7971 * @since 22 7972 */ 7973 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7974 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7975 } 7976 7977 /** 7978 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7979 * <p> 7980 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7981 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7982 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7983 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7984 * by the adaptation) to the target var handle. 7985 * <p> 7986 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7987 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7988 * <p> 7989 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7990 * throw an {@link IllegalStateException}. 7991 * <p> 7992 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7993 * atomic access guarantees as those featured by the target var handle. 7994 * 7995 * @param target the target var handle 7996 * @param pos the position of the first coordinate to be transformed 7997 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7998 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7999 * to the new coordinate values. 8000 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 8001 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 8002 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8003 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 8004 * or if it's determined that any of the filters throws any checked exceptions. 8005 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 8006 * @since 22 8007 */ 8008 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 8009 return VarHandles.filterCoordinates(target, pos, filters); 8010 } 8011 8012 /** 8013 * Provides a target var handle with one or more <em>bound coordinates</em> 8014 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 8015 * coordinate types than the target var handle. 8016 * <p> 8017 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 8018 * are joined with bound coordinate values, and then passed to the target var handle. 8019 * <p> 8020 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 8021 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 8022 * <p> 8023 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8024 * atomic access guarantees as those featured by the target var handle. 8025 * 8026 * @param target the var handle to invoke after the bound coordinates are inserted 8027 * @param pos the position of the first coordinate to be inserted 8028 * @param values the series of bound coordinates to insert 8029 * @return an adapter var handle which inserts additional coordinates, 8030 * before calling the target var handle 8031 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8032 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 8033 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 8034 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 8035 * of the target var handle. 8036 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 8037 * @since 22 8038 */ 8039 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 8040 return VarHandles.insertCoordinates(target, pos, values); 8041 } 8042 8043 /** 8044 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 8045 * so that the new coordinates match the provided ones. 8046 * <p> 8047 * The given array controls the reordering. 8048 * Call {@code #I} the number of incoming coordinates (the value 8049 * {@code newCoordinates.size()}), and call {@code #O} the number 8050 * of outgoing coordinates (the number of coordinates associated with the target var handle). 8051 * Then the length of the reordering array must be {@code #O}, 8052 * and each element must be a non-negative number less than {@code #I}. 8053 * For every {@code N} less than {@code #O}, the {@code N}-th 8054 * outgoing coordinate will be taken from the {@code I}-th incoming 8055 * coordinate, where {@code I} is {@code reorder[N]}. 8056 * <p> 8057 * No coordinate value conversions are applied. 8058 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 8059 * must be identical to the type of the corresponding outgoing coordinate 8060 * in the target var handle. 8061 * <p> 8062 * The reordering array need not specify an actual permutation. 8063 * An incoming coordinate will be duplicated if its index appears 8064 * more than once in the array, and an incoming coordinate will be dropped 8065 * if its index does not appear in the array. 8066 * <p> 8067 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8068 * atomic access guarantees as those featured by the target var handle. 8069 * @param target the var handle to invoke after the coordinates have been reordered 8070 * @param newCoordinates the new coordinate types 8071 * @param reorder an index array which controls the reordering 8072 * @return an adapter var handle which re-arranges the incoming coordinate values, 8073 * before calling the target var handle 8074 * @throws IllegalArgumentException if the index array length is not equal to 8075 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 8076 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 8077 * the target var handle and in {@code newCoordinates} are not identical. 8078 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 8079 * @since 22 8080 */ 8081 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 8082 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 8083 } 8084 8085 /** 8086 * Adapts a target var handle by pre-processing 8087 * a sub-sequence of its coordinate values with a filter (a method handle). 8088 * The pre-processed coordinates are replaced by the result (if any) of the 8089 * filter function and the target var handle is then called on the modified (usually shortened) 8090 * coordinate list. 8091 * <p> 8092 * If {@code R} is the return type of the filter, then: 8093 * <ul> 8094 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 8095 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 8096 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 8097 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 8098 * target var handle.</li> 8099 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 8100 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 8101 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 8102 * downstream invocation of the target var handle.</li> 8103 * </ul> 8104 * <p> 8105 * If any of the filters throws a checked exception when invoked, the resulting var handle will 8106 * throw an {@link IllegalStateException}. 8107 * <p> 8108 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8109 * atomic access guarantees as those featured by the target var handle. 8110 * 8111 * @param target the var handle to invoke after the coordinates have been filtered 8112 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 8113 * @param filter the filter method handle 8114 * @return an adapter var handle which filters the incoming coordinate values, 8115 * before calling the target var handle 8116 * @throws IllegalArgumentException if the return type of {@code filter} 8117 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 8118 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 8119 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 8120 * or if it's determined that {@code filter} throws any checked exceptions. 8121 * @throws NullPointerException if any of the arguments is {@code null}. 8122 * @since 22 8123 */ 8124 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 8125 return VarHandles.collectCoordinates(target, pos, filter); 8126 } 8127 8128 /** 8129 * Returns a var handle which will discard some dummy coordinates before delegating to the 8130 * target var handle. As a consequence, the resulting var handle will feature more 8131 * coordinate types than the target var handle. 8132 * <p> 8133 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 8134 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 8135 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 8136 * <p> 8137 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 8138 * atomic access guarantees as those featured by the target var handle. 8139 * 8140 * @param target the var handle to invoke after the dummy coordinates are dropped 8141 * @param pos position of the first coordinate to drop (zero for the leftmost) 8142 * @param valueTypes the type(s) of the coordinate(s) to drop 8143 * @return an adapter var handle which drops some dummy coordinates, 8144 * before calling the target var handle 8145 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 8146 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 8147 * @since 22 8148 */ 8149 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 8150 return VarHandles.dropCoordinates(target, pos, valueTypes); 8151 } 8152 }