1 /* 2 * Copyright (c) 2008, 2025, 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.AOTSafeClassInitializer; 36 import jdk.internal.vm.annotation.ForceInline; 37 import jdk.internal.vm.annotation.Stable; 38 import sun.invoke.util.ValueConversions; 39 import sun.invoke.util.VerifyAccess; 40 import sun.invoke.util.Wrapper; 41 42 import java.lang.classfile.ClassFile; 43 import java.lang.classfile.ClassModel; 44 import java.lang.constant.ClassDesc; 45 import java.lang.constant.ConstantDescs; 46 import java.lang.invoke.LambdaForm.BasicType; 47 import java.lang.invoke.MethodHandleImpl.Intrinsic; 48 import java.lang.reflect.Constructor; 49 import java.lang.reflect.Field; 50 import java.lang.reflect.Member; 51 import java.lang.reflect.Method; 52 import java.lang.reflect.Modifier; 53 import java.nio.ByteOrder; 54 import java.security.ProtectionDomain; 55 import java.util.ArrayList; 56 import java.util.Arrays; 57 import java.util.BitSet; 58 import java.util.Comparator; 59 import java.util.Iterator; 60 import java.util.List; 61 import java.util.Objects; 62 import java.util.Set; 63 import java.util.concurrent.ConcurrentHashMap; 64 import java.util.stream.Stream; 65 66 import static java.lang.classfile.ClassFile.*; 67 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 68 import static java.lang.invoke.MethodHandleNatives.Constants.*; 69 import static java.lang.invoke.MethodHandleStatics.*; 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 @AOTSafeClassInitializer 88 public final class MethodHandles { 89 90 private MethodHandles() { } // do not instantiate 91 92 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 93 94 // See IMPL_LOOKUP below. 95 96 //--- Method handle creation from ordinary methods. 97 98 /** 99 * Returns a {@link Lookup lookup object} with 100 * full capabilities to emulate all supported bytecode behaviors of the caller. 101 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 102 * Factory methods on the lookup object can create 103 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 104 * for any member that the caller has access to via bytecodes, 105 * including protected and private fields and methods. 106 * This lookup object is created by the original lookup class 107 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 108 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 109 * Do not store it in place where untrusted code can access it. 110 * <p> 111 * This method is caller sensitive, which means that it may return different 112 * values to different callers. 113 * In cases where {@code MethodHandles.lookup} is called from a context where 114 * there is no caller frame on the stack (e.g. when called directly 115 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 116 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 117 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 118 * to obtain a low-privileged lookup instead. 119 * @return a lookup object for the caller of this method, with 120 * {@linkplain Lookup#ORIGINAL original} and 121 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 122 * @throws IllegalCallerException if there is no caller frame on the stack. 123 */ 124 @CallerSensitive 125 @ForceInline // to ensure Reflection.getCallerClass optimization 126 public static Lookup lookup() { 127 final Class<?> c = Reflection.getCallerClass(); 128 if (c == null) { 129 throw new IllegalCallerException("no caller frame"); 130 } 131 return new Lookup(c); 132 } 133 134 /** 135 * This lookup method is the alternate implementation of 136 * the lookup method with a leading caller class argument which is 137 * non-caller-sensitive. This method is only invoked by reflection 138 * and method handle. 139 */ 140 @CallerSensitiveAdapter 141 private static Lookup lookup(Class<?> caller) { 142 if (caller.getClassLoader() == null) { 143 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 144 } 145 return new Lookup(caller); 146 } 147 148 /** 149 * Returns a {@link Lookup lookup object} which is trusted minimally. 150 * The lookup has the {@code UNCONDITIONAL} mode. 151 * It can only be used to create method handles to public members of 152 * public classes in packages that are exported unconditionally. 153 * <p> 154 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 155 * of this lookup object will be {@link java.lang.Object}. 156 * 157 * @apiNote The use of Object is conventional, and because the lookup modes are 158 * limited, there is no special access provided to the internals of Object, its package 159 * or its module. This public lookup object or other lookup object with 160 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 161 * is not used to determine the lookup context. 162 * 163 * <p style="font-size:smaller;"> 164 * <em>Discussion:</em> 165 * The lookup class can be changed to any other class {@code C} using an expression of the form 166 * {@link Lookup#in publicLookup().in(C.class)}. 167 * Also, it cannot access 168 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 169 * @return a lookup object which is trusted minimally 170 */ 171 public static Lookup publicLookup() { 172 return Lookup.PUBLIC_LOOKUP; 173 } 174 175 /** 176 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 177 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 178 * The returned lookup object can provide access to classes in modules and packages, 179 * and members of those classes, outside the normal rules of Java access control, 180 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 181 * <p> 182 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 183 * allowed to do deep reflection on module {@code M2} and package of the target class 184 * if and only if all of the following conditions are {@code true}: 185 * <ul> 186 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 187 * full privilege access}. Specifically: 188 * <ul> 189 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 190 * (This is because otherwise there would be no way to ensure the original lookup 191 * creator was a member of any particular module, and so any subsequent checks 192 * for readability and qualified exports would become ineffective.) 193 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 194 * (This is because an application intending to share intra-module access 195 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 196 * deep reflection to its own module.) 197 * </ul> 198 * <li>The target class must be a proper class, not a primitive or array class. 199 * (Thus, {@code M2} is well-defined.) 200 * <li>If the caller module {@code M1} differs from 201 * the target module {@code M2} then both of the following must be true: 202 * <ul> 203 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 204 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 205 * containing the target class to at least {@code M1}.</li> 206 * </ul> 207 * </ul> 208 * <p> 209 * If any of the above checks is violated, this method fails with an 210 * exception. 211 * <p> 212 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 213 * returns a {@code Lookup} on {@code targetClass} with 214 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 215 * with {@code null} previous lookup class. 216 * <p> 217 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 218 * returns a {@code Lookup} on {@code targetClass} that records 219 * the lookup class of the caller as the new previous lookup class with 220 * {@code PRIVATE} access but no {@code MODULE} access. 221 * <p> 222 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 223 * 224 * @apiNote The {@code Lookup} object returned by this method is allowed to 225 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 226 * of {@code targetClass}. Extreme caution should be taken when opening a package 227 * to another module as such defined classes have the same full privilege 228 * access as other members in {@code targetClass}'s module. 229 * 230 * @param targetClass the target class 231 * @param caller the caller lookup object 232 * @return a lookup object for the target class, with private access 233 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 234 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 235 * @throws IllegalAccessException if any of the other access checks specified above fails 236 * @since 9 237 * @see Lookup#dropLookupMode 238 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 239 */ 240 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 241 if (caller.allowedModes == Lookup.TRUSTED) { 242 return new Lookup(targetClass); 243 } 244 245 if (targetClass.isPrimitive()) 246 throw new IllegalArgumentException(targetClass + " is a primitive class"); 247 if (targetClass.isArray()) 248 throw new IllegalArgumentException(targetClass + " is an array class"); 249 // Ensure that we can reason accurately about private and module access. 250 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 251 if ((caller.lookupModes() & requireAccess) != requireAccess) 252 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 253 254 // previous lookup class is never set if it has MODULE access 255 assert caller.previousLookupClass() == null; 256 257 Class<?> callerClass = caller.lookupClass(); 258 Module callerModule = callerClass.getModule(); // M1 259 Module targetModule = targetClass.getModule(); // M2 260 Class<?> newPreviousClass = null; 261 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 262 263 if (targetModule != callerModule) { 264 if (!callerModule.canRead(targetModule)) 265 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 266 if (targetModule.isNamed()) { 267 String pn = targetClass.getPackageName(); 268 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 269 if (!targetModule.isOpen(pn, callerModule)) 270 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 271 } 272 273 // M2 != M1, set previous lookup class to M1 and drop MODULE access 274 newPreviousClass = callerClass; 275 newModes &= ~Lookup.MODULE; 276 } 277 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 278 } 279 280 /** 281 * Returns the <em>class data</em> associated with the lookup class 282 * of the given {@code caller} lookup object, or {@code null}. 283 * 284 * <p> A hidden class with class data can be created by calling 285 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 286 * Lookup::defineHiddenClassWithClassData}. 287 * This method will cause the static class initializer of the lookup 288 * class of the given {@code caller} lookup object be executed if 289 * it has not been initialized. 290 * 291 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 292 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 293 * {@code null} is returned if this method is called on the lookup object 294 * on these classes. 295 * 296 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 297 * must have {@linkplain Lookup#ORIGINAL original access} 298 * in order to retrieve the class data. 299 * 300 * @apiNote 301 * This method can be called as a bootstrap method for a dynamically computed 302 * constant. A framework can create a hidden class with class data, for 303 * example that can be {@code Class} or {@code MethodHandle} object. 304 * The class data is accessible only to the lookup object 305 * created by the original caller but inaccessible to other members 306 * in the same nest. If a framework passes security sensitive objects 307 * to a hidden class via class data, it is recommended to load the value 308 * of class data as a dynamically computed constant instead of storing 309 * the class data in private static field(s) which are accessible to 310 * other nestmates. 311 * 312 * @param <T> the type to cast the class data object to 313 * @param caller the lookup context describing the class performing the 314 * operation (normally stacked by the JVM) 315 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 316 * ({@code "_"}) 317 * @param type the type of the class data 318 * @return the value of the class data if present in the lookup class; 319 * otherwise {@code null} 320 * @throws IllegalArgumentException if name is not {@code "_"} 321 * @throws IllegalAccessException if the lookup context does not have 322 * {@linkplain Lookup#ORIGINAL original} access 323 * @throws ClassCastException if the class data cannot be converted to 324 * the given {@code type} 325 * @throws NullPointerException if {@code caller} or {@code type} argument 326 * is {@code null} 327 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 328 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 329 * @since 16 330 * @jvms 5.5 Initialization 331 */ 332 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 333 Objects.requireNonNull(caller); 334 Objects.requireNonNull(type); 335 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 336 throw new IllegalArgumentException("name must be \"_\": " + name); 337 } 338 339 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 340 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 341 } 342 343 Object classdata = classData(caller.lookupClass()); 344 if (classdata == null) return null; 345 346 try { 347 return BootstrapMethodInvoker.widenAndCast(classdata, type); 348 } catch (RuntimeException|Error e) { 349 throw e; // let CCE and other runtime exceptions through 350 } catch (Throwable e) { 351 throw new InternalError(e); 352 } 353 } 354 355 /* 356 * Returns the class data set by the VM in the Class::classData field. 357 * 358 * This is also invoked by LambdaForms as it cannot use condy via 359 * MethodHandles::classData due to bootstrapping issue. 360 */ 361 static Object classData(Class<?> c) { 362 UNSAFE.ensureClassInitialized(c); 363 return SharedSecrets.getJavaLangAccess().classData(c); 364 } 365 366 /** 367 * Returns the element at the specified index in the 368 * {@linkplain #classData(Lookup, String, Class) class data}, 369 * if the class data associated with the lookup class 370 * of the given {@code caller} lookup object is a {@code List}. 371 * If the class data is not present in this lookup class, this method 372 * returns {@code null}. 373 * 374 * <p> A hidden class with class data can be created by calling 375 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 376 * Lookup::defineHiddenClassWithClassData}. 377 * This method will cause the static class initializer of the lookup 378 * class of the given {@code caller} lookup object be executed if 379 * it has not been initialized. 380 * 381 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 382 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 383 * {@code null} is returned if this method is called on the lookup object 384 * on these classes. 385 * 386 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 387 * must have {@linkplain Lookup#ORIGINAL original access} 388 * in order to retrieve the class data. 389 * 390 * @apiNote 391 * This method can be called as a bootstrap method for a dynamically computed 392 * constant. A framework can create a hidden class with class data, for 393 * example that can be {@code List.of(o1, o2, o3....)} containing more than 394 * one object and use this method to load one element at a specific index. 395 * The class data is accessible only to the lookup object 396 * created by the original caller but inaccessible to other members 397 * in the same nest. If a framework passes security sensitive objects 398 * to a hidden class via class data, it is recommended to load the value 399 * of class data as a dynamically computed constant instead of storing 400 * the class data in private static field(s) which are accessible to other 401 * nestmates. 402 * 403 * @param <T> the type to cast the result object to 404 * @param caller the lookup context describing the class performing the 405 * operation (normally stacked by the JVM) 406 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 407 * ({@code "_"}) 408 * @param type the type of the element at the given index in the class data 409 * @param index index of the element in the class data 410 * @return the element at the given index in the class data 411 * if the class data is present; otherwise {@code null} 412 * @throws IllegalArgumentException if name is not {@code "_"} 413 * @throws IllegalAccessException if the lookup context does not have 414 * {@linkplain Lookup#ORIGINAL original} access 415 * @throws ClassCastException if the class data cannot be converted to {@code List} 416 * or the element at the specified index cannot be converted to the given type 417 * @throws IndexOutOfBoundsException if the index is out of range 418 * @throws NullPointerException if {@code caller} or {@code type} argument is 419 * {@code null}; or if unboxing operation fails because 420 * the element at the given index is {@code null} 421 * 422 * @since 16 423 * @see #classData(Lookup, String, Class) 424 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 425 */ 426 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 427 throws IllegalAccessException 428 { 429 @SuppressWarnings("unchecked") 430 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 431 if (classdata == null) return null; 432 433 try { 434 Object element = classdata.get(index); 435 return BootstrapMethodInvoker.widenAndCast(element, type); 436 } catch (RuntimeException|Error e) { 437 throw e; // let specified exceptions and other runtime exceptions/errors through 438 } catch (Throwable e) { 439 throw new InternalError(e); 440 } 441 } 442 443 /** 444 * Performs an unchecked "crack" of a 445 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 446 * The result is as if the user had obtained a lookup object capable enough 447 * to crack the target method handle, called 448 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 449 * on the target to obtain its symbolic reference, and then called 450 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 451 * to resolve the symbolic reference to a member. 452 * @param <T> the desired type of the result, either {@link Member} or a subtype 453 * @param expected a class object representing the desired result type {@code T} 454 * @param target a direct method handle to crack into symbolic reference components 455 * @return a reference to the method, constructor, or field object 456 * @throws NullPointerException if either argument is {@code null} 457 * @throws IllegalArgumentException if the target is not a direct method handle 458 * @throws ClassCastException if the member is not of the expected type 459 * @since 1.8 460 */ 461 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 462 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 463 return lookup.revealDirect(target).reflectAs(expected, lookup); 464 } 465 466 /** 467 * A <em>lookup object</em> is a factory for creating method handles, 468 * when the creation requires access checking. 469 * Method handles do not perform 470 * access checks when they are called, but rather when they are created. 471 * Therefore, method handle access 472 * restrictions must be enforced when a method handle is created. 473 * The caller class against which those restrictions are enforced 474 * is known as the {@linkplain #lookupClass() lookup class}. 475 * <p> 476 * A lookup class which needs to create method handles will call 477 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 478 * When the {@code Lookup} factory object is created, the identity of the lookup class is 479 * determined, and securely stored in the {@code Lookup} object. 480 * The lookup class (or its delegates) may then use factory methods 481 * on the {@code Lookup} object to create method handles for access-checked members. 482 * This includes all methods, constructors, and fields which are allowed to the lookup class, 483 * even private ones. 484 * 485 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 486 * The factory methods on a {@code Lookup} object correspond to all major 487 * use cases for methods, constructors, and fields. 488 * Each method handle created by a factory method is the functional 489 * equivalent of a particular <em>bytecode behavior</em>. 490 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 491 * the Java Virtual Machine Specification.) 492 * Here is a summary of the correspondence between these factory methods and 493 * the behavior of the resulting method handles: 494 * <table class="striped"> 495 * <caption style="display:none">lookup method behaviors</caption> 496 * <thead> 497 * <tr> 498 * <th scope="col"><a id="equiv"></a>lookup expression</th> 499 * <th scope="col">member</th> 500 * <th scope="col">bytecode behavior</th> 501 * </tr> 502 * </thead> 503 * <tbody> 504 * <tr> 505 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 506 * <td>{@code FT f;}</td><td>{@code (FT) this.f;}</td> 507 * </tr> 508 * <tr> 509 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 510 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 511 * </tr> 512 * <tr> 513 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 514 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 515 * </tr> 516 * <tr> 517 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 518 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 519 * </tr> 520 * <tr> 521 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 522 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 523 * </tr> 524 * <tr> 525 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 526 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 527 * </tr> 528 * <tr> 529 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 530 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 531 * </tr> 532 * <tr> 533 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 534 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 535 * </tr> 536 * <tr> 537 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 538 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 539 * </tr> 540 * <tr> 541 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 542 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 543 * </tr> 544 * <tr> 545 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 546 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 547 * </tr> 548 * <tr> 549 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 550 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 551 * </tr> 552 * <tr> 553 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 554 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 555 * </tr> 556 * <tr> 557 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 558 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 559 * </tr> 560 * </tbody> 561 * </table> 562 * 563 * Here, the type {@code C} is the class or interface being searched for a member, 564 * documented as a parameter named {@code refc} in the lookup methods. 565 * The method type {@code MT} is composed from the return type {@code T} 566 * and the sequence of argument types {@code A*}. 567 * The constructor also has a sequence of argument types {@code A*} and 568 * is deemed to return the newly-created object of type {@code C}. 569 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 570 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 571 * if it is present, it is always the leading argument to the method handle invocation. 572 * (In the case of some {@code protected} members, {@code this} may be 573 * restricted in type to the lookup class; see below.) 574 * The name {@code arg} stands for all the other method handle arguments. 575 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 576 * stands for a null reference if the accessed method or field is static, 577 * and {@code this} otherwise. 578 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 579 * for reflective objects corresponding to the given members declared in type {@code C}. 580 * <p> 581 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 582 * as if by {@code ldc CONSTANT_Class}. 583 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 584 * <p> 585 * In cases where the given member is of variable arity (i.e., a method or constructor) 586 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 587 * In all other cases, the returned method handle will be of fixed arity. 588 * <p style="font-size:smaller;"> 589 * <em>Discussion:</em> 590 * The equivalence between looked-up method handles and underlying 591 * class members and bytecode behaviors 592 * can break down in a few ways: 593 * <ul style="font-size:smaller;"> 594 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 595 * the lookup can still succeed, even when there is no equivalent 596 * Java expression or bytecoded constant. 597 * <li>Likewise, if {@code T} or {@code MT} 598 * is not symbolically accessible from the lookup class's loader, 599 * the lookup can still succeed. 600 * For example, lookups for {@code MethodHandle.invokeExact} and 601 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 602 * <li>If the looked-up method has a 603 * <a href="MethodHandle.html#maxarity">very large arity</a>, 604 * the method handle creation may fail with an 605 * {@code IllegalArgumentException}, due to the method handle type having 606 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 607 * </ul> 608 * 609 * <h2><a id="access"></a>Access checking</h2> 610 * Access checks are applied in the factory methods of {@code Lookup}, 611 * when a method handle is created. 612 * This is a key difference from the Core Reflection API, since 613 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 614 * performs access checking against every caller, on every call. 615 * <p> 616 * All access checks start from a {@code Lookup} object, which 617 * compares its recorded lookup class against all requests to 618 * create method handles. 619 * A single {@code Lookup} object can be used to create any number 620 * of access-checked method handles, all checked against a single 621 * lookup class. 622 * <p> 623 * A {@code Lookup} object can be shared with other trusted code, 624 * such as a metaobject protocol. 625 * A shared {@code Lookup} object delegates the capability 626 * to create method handles on private members of the lookup class. 627 * Even if privileged code uses the {@code Lookup} object, 628 * the access checking is confined to the privileges of the 629 * original lookup class. 630 * <p> 631 * A lookup can fail, because 632 * the containing class is not accessible to the lookup class, or 633 * because the desired class member is missing, or because the 634 * desired class member is not accessible to the lookup class, or 635 * because the lookup object is not trusted enough to access the member. 636 * In the case of a field setter function on a {@code final} field, 637 * finality enforcement is treated as a kind of access control, 638 * and the lookup will fail, except in special cases of 639 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 640 * In any of these cases, a {@code ReflectiveOperationException} will be 641 * thrown from the attempted lookup. The exact class will be one of 642 * the following: 643 * <ul> 644 * <li>NoSuchMethodException — if a method is requested but does not exist 645 * <li>NoSuchFieldException — if a field is requested but does not exist 646 * <li>IllegalAccessException — if the member exists but an access check fails 647 * </ul> 648 * <p> 649 * In general, the conditions under which a method handle may be 650 * looked up for a method {@code M} are no more restrictive than the conditions 651 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 652 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 653 * a method handle lookup will generally raise a corresponding 654 * checked exception, such as {@code NoSuchMethodException}. 655 * And the effect of invoking the method handle resulting from the lookup 656 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 657 * to executing the compiled, verified, and resolved call to {@code M}. 658 * The same point is true of fields and constructors. 659 * <p style="font-size:smaller;"> 660 * <em>Discussion:</em> 661 * Access checks only apply to named and reflected methods, 662 * constructors, and fields. 663 * Other method handle creation methods, such as 664 * {@link MethodHandle#asType MethodHandle.asType}, 665 * do not require any access checks, and are used 666 * independently of any {@code Lookup} object. 667 * <p> 668 * If the desired member is {@code protected}, the usual JVM rules apply, 669 * including the requirement that the lookup class must either be in the 670 * same package as the desired member, or must inherit that member. 671 * (See the Java Virtual Machine Specification, sections {@jvms 672 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 673 * In addition, if the desired member is a non-static field or method 674 * in a different package, the resulting method handle may only be applied 675 * to objects of the lookup class or one of its subclasses. 676 * This requirement is enforced by narrowing the type of the leading 677 * {@code this} parameter from {@code C} 678 * (which will necessarily be a superclass of the lookup class) 679 * to the lookup class itself. 680 * <p> 681 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 682 * that the receiver argument must match both the resolved method <em>and</em> 683 * the current class. Again, this requirement is enforced by narrowing the 684 * type of the leading parameter to the resulting method handle. 685 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 686 * <p> 687 * The JVM represents constructors and static initializer blocks as internal methods 688 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 689 * ConstantDescs#CLASS_INIT_NAME}). 690 * The internal syntax of invocation instructions allows them to refer to such internal 691 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 692 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 693 * <p> 694 * If the relationship between nested types is expressed directly through the 695 * {@code NestHost} and {@code NestMembers} attributes 696 * (see the Java Virtual Machine Specification, sections {@jvms 697 * 4.7.28} and {@jvms 4.7.29}), 698 * then the associated {@code Lookup} object provides direct access to 699 * the lookup class and all of its nestmates 700 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 701 * Otherwise, access between nested classes is obtained by the Java compiler creating 702 * a wrapper method to access a private method of another class in the same nest. 703 * For example, a nested class {@code C.D} 704 * can access private members within other related classes such as 705 * {@code C}, {@code C.D.E}, or {@code C.B}, 706 * but the Java compiler may need to generate wrapper methods in 707 * those related classes. In such cases, a {@code Lookup} object on 708 * {@code C.E} would be unable to access those private members. 709 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 710 * which can transform a lookup on {@code C.E} into one on any of those other 711 * classes, without special elevation of privilege. 712 * <p> 713 * The accesses permitted to a given lookup object may be limited, 714 * according to its set of {@link #lookupModes lookupModes}, 715 * to a subset of members normally accessible to the lookup class. 716 * For example, the {@link MethodHandles#publicLookup publicLookup} 717 * method produces a lookup object which is only allowed to access 718 * public members in public classes of exported packages. 719 * The caller sensitive method {@link MethodHandles#lookup lookup} 720 * produces a lookup object with full capabilities relative to 721 * its caller class, to emulate all supported bytecode behaviors. 722 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 723 * with fewer access modes than the original lookup object. 724 * 725 * <p style="font-size:smaller;"> 726 * <a id="privacc"></a> 727 * <em>Discussion of private and module access:</em> 728 * We say that a lookup has <em>private access</em> 729 * if its {@linkplain #lookupModes lookup modes} 730 * include the possibility of accessing {@code private} members 731 * (which includes the private members of nestmates). 732 * As documented in the relevant methods elsewhere, 733 * only lookups with private access possess the following capabilities: 734 * <ul style="font-size:smaller;"> 735 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 736 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 737 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 738 * within the same package member 739 * </ul> 740 * <p style="font-size:smaller;"> 741 * Similarly, a lookup with module access ensures that the original lookup creator was 742 * a member in the same module as the lookup class. 743 * <p style="font-size:smaller;"> 744 * Private and module access are independently determined modes; a lookup may have 745 * either or both or neither. A lookup which possesses both access modes is said to 746 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 747 * <p style="font-size:smaller;"> 748 * A lookup with <em>original access</em> ensures that this lookup is created by 749 * the original lookup class and the bootstrap method invoked by the VM. 750 * Such a lookup with original access also has private and module access 751 * which has the following additional capability: 752 * <ul style="font-size:smaller;"> 753 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 754 * such as {@code Class.forName} 755 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 756 * class data} associated with the lookup class</li> 757 * </ul> 758 * <p style="font-size:smaller;"> 759 * Each of these permissions is a consequence of the fact that a lookup object 760 * with private access can be securely traced back to an originating class, 761 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 762 * can be reliably determined and emulated by method handles. 763 * 764 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 765 * When a lookup class in one module {@code M1} accesses a class in another module 766 * {@code M2}, extra access checking is performed beyond the access mode bits. 767 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 768 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 769 * and when the type is in a package of {@code M2} that is exported to 770 * at least {@code M1}. 771 * <p> 772 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 773 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 774 * MethodHandles.privateLookupIn} methods. 775 * Teleporting across modules will always record the original lookup class as 776 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 777 * and drops {@link Lookup#MODULE MODULE} access. 778 * If the target class is in the same module as the lookup class {@code C}, 779 * then the target class becomes the new lookup class 780 * and there is no change to the previous lookup class. 781 * If the target class is in a different module from {@code M1} ({@code C}'s module), 782 * {@code C} becomes the new previous lookup class 783 * and the target class becomes the new lookup class. 784 * In that case, if there was already a previous lookup class in {@code M0}, 785 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 786 * drops all privileges. 787 * For example, 788 * {@snippet lang="java" : 789 * Lookup lookup = MethodHandles.lookup(); // in class C 790 * Lookup lookup2 = lookup.in(D.class); 791 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 792 * } 793 * <p> 794 * The {@link #lookup()} factory method produces a {@code Lookup} object 795 * with {@code null} previous lookup class. 796 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 797 * to class {@code D} without elevation of privileges. 798 * If {@code C} and {@code D} are in the same module, 799 * {@code lookup2} records {@code D} as the new lookup class and keeps the 800 * same previous lookup class as the original {@code lookup}, or 801 * {@code null} if not present. 802 * <p> 803 * When a {@code Lookup} teleports from a class 804 * in one nest to another nest, {@code PRIVATE} access is dropped. 805 * When a {@code Lookup} teleports from a class in one package to 806 * another package, {@code PACKAGE} access is dropped. 807 * When a {@code Lookup} teleports from a class in one module to another module, 808 * {@code MODULE} access is dropped. 809 * Teleporting across modules drops the ability to access non-exported classes 810 * in both the module of the new lookup class and the module of the old lookup class 811 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 812 * A {@code Lookup} can teleport back and forth to a class in the module of 813 * the lookup class and the module of the previous class lookup. 814 * Teleporting across modules can only decrease access but cannot increase it. 815 * Teleporting to some third module drops all accesses. 816 * <p> 817 * In the above example, if {@code C} and {@code D} are in different modules, 818 * {@code lookup2} records {@code D} as its lookup class and 819 * {@code C} as its previous lookup class and {@code lookup2} has only 820 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 821 * {@code C}'s module and {@code D}'s module. 822 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 823 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 824 * class {@code D} is recorded as its previous lookup class. 825 * <p> 826 * Teleporting across modules restricts access to the public types that 827 * both the lookup class and the previous lookup class can equally access 828 * (see below). 829 * <p> 830 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 831 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 832 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 833 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 834 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 835 * to call {@code privateLookupIn}. 836 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 837 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 838 * produces a new {@code Lookup} on {@code T} with full capabilities. 839 * A {@code lookup} on {@code C} is also allowed 840 * to do deep reflection on {@code T} in another module {@code M2} if 841 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 842 * the package containing {@code T} to at least {@code M1}. 843 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 844 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 845 * The resulting {@code Lookup} can be used to do member lookup or teleport 846 * to another lookup class by calling {@link #in Lookup::in}. But 847 * it cannot be used to obtain another private {@code Lookup} by calling 848 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 849 * because it has no {@code MODULE} access. 850 * <p> 851 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 852 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 853 * of {@code T}. Extreme caution should be taken when opening a package 854 * to another module as such defined classes have the same full privilege 855 * access as other members in {@code M2}. 856 * 857 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 858 * 859 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 860 * allows cross-module access. The access checking is performed with respect 861 * to both the lookup class and the previous lookup class if present. 862 * <p> 863 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 864 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 865 * exported unconditionally}. 866 * <p> 867 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 868 * the lookup with {@link #PUBLIC} mode can access all public types in modules 869 * that are readable to {@code M1} and the type is in a package that is exported 870 * at least to {@code M1}. 871 * <p> 872 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 873 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 874 * the intersection of all public types that are accessible to {@code M1} 875 * with all public types that are accessible to {@code M0}. {@code M0} 876 * reads {@code M1} and hence the set of accessible types includes: 877 * 878 * <ul> 879 * <li>unconditional-exported packages from {@code M1}</li> 880 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 881 * <li> 882 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 883 * and {@code M1} read {@code M2} 884 * </li> 885 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 886 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 887 * <li> 888 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 889 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 890 * </li> 891 * </ul> 892 * 893 * <h2><a id="access-modes"></a>Access modes</h2> 894 * 895 * The table below shows the access modes of a {@code Lookup} produced by 896 * any of the following factory or transformation methods: 897 * <ul> 898 * <li>{@link #lookup() MethodHandles::lookup}</li> 899 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 900 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 901 * <li>{@link Lookup#in Lookup::in}</li> 902 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 903 * </ul> 904 * 905 * <table class="striped"> 906 * <caption style="display:none"> 907 * Access mode summary 908 * </caption> 909 * <thead> 910 * <tr> 911 * <th scope="col">Lookup object</th> 912 * <th style="text-align:center">original</th> 913 * <th style="text-align:center">protected</th> 914 * <th style="text-align:center">private</th> 915 * <th style="text-align:center">package</th> 916 * <th style="text-align:center">module</th> 917 * <th style="text-align:center">public</th> 918 * </tr> 919 * </thead> 920 * <tbody> 921 * <tr> 922 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 923 * <td style="text-align:center">ORI</td> 924 * <td style="text-align:center">PRO</td> 925 * <td style="text-align:center">PRI</td> 926 * <td style="text-align:center">PAC</td> 927 * <td style="text-align:center">MOD</td> 928 * <td style="text-align:center">1R</td> 929 * </tr> 930 * <tr> 931 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 932 * <td></td> 933 * <td></td> 934 * <td></td> 935 * <td style="text-align:center">PAC</td> 936 * <td style="text-align:center">MOD</td> 937 * <td style="text-align:center">1R</td> 938 * </tr> 939 * <tr> 940 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 941 * <td></td> 942 * <td></td> 943 * <td></td> 944 * <td></td> 945 * <td style="text-align:center">MOD</td> 946 * <td style="text-align:center">1R</td> 947 * </tr> 948 * <tr> 949 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 950 * <td></td> 951 * <td></td> 952 * <td></td> 953 * <td></td> 954 * <td></td> 955 * <td style="text-align:center">2R</td> 956 * </tr> 957 * <tr> 958 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 959 * <td></td> 960 * <td></td> 961 * <td></td> 962 * <td></td> 963 * <td></td> 964 * <td style="text-align:center">2R</td> 965 * </tr> 966 * <tr> 967 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 968 * <td></td> 969 * <td style="text-align:center">PRO</td> 970 * <td style="text-align:center">PRI</td> 971 * <td style="text-align:center">PAC</td> 972 * <td style="text-align:center">MOD</td> 973 * <td style="text-align:center">1R</td> 974 * </tr> 975 * <tr> 976 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 977 * <td></td> 978 * <td style="text-align:center">PRO</td> 979 * <td style="text-align:center">PRI</td> 980 * <td style="text-align:center">PAC</td> 981 * <td style="text-align:center">MOD</td> 982 * <td style="text-align:center">1R</td> 983 * </tr> 984 * <tr> 985 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 986 * <td></td> 987 * <td></td> 988 * <td></td> 989 * <td style="text-align:center">PAC</td> 990 * <td style="text-align:center">MOD</td> 991 * <td style="text-align:center">1R</td> 992 * </tr> 993 * <tr> 994 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 995 * <td></td> 996 * <td></td> 997 * <td></td> 998 * <td></td> 999 * <td style="text-align:center">MOD</td> 1000 * <td style="text-align:center">1R</td> 1001 * </tr> 1002 * <tr> 1003 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1004 * <td></td> 1005 * <td></td> 1006 * <td></td> 1007 * <td></td> 1008 * <td></td> 1009 * <td style="text-align:center">2R</td> 1010 * </tr> 1011 * <tr> 1012 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1013 * <td></td> 1014 * <td></td> 1015 * <td style="text-align:center">PRI</td> 1016 * <td style="text-align:center">PAC</td> 1017 * <td style="text-align:center">MOD</td> 1018 * <td style="text-align:center">1R</td> 1019 * </tr> 1020 * <tr> 1021 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1022 * <td></td> 1023 * <td></td> 1024 * <td></td> 1025 * <td style="text-align:center">PAC</td> 1026 * <td style="text-align:center">MOD</td> 1027 * <td style="text-align:center">1R</td> 1028 * </tr> 1029 * <tr> 1030 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1031 * <td></td> 1032 * <td></td> 1033 * <td></td> 1034 * <td></td> 1035 * <td style="text-align:center">MOD</td> 1036 * <td style="text-align:center">1R</td> 1037 * </tr> 1038 * <tr> 1039 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1040 * <td></td> 1041 * <td></td> 1042 * <td></td> 1043 * <td></td> 1044 * <td></td> 1045 * <td style="text-align:center">1R</td> 1046 * </tr> 1047 * <tr> 1048 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1049 * <td></td> 1050 * <td></td> 1051 * <td></td> 1052 * <td></td> 1053 * <td></td> 1054 * <td style="text-align:center">none</td> 1055 * <tr> 1056 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1057 * <td></td> 1058 * <td style="text-align:center">PRO</td> 1059 * <td style="text-align:center">PRI</td> 1060 * <td style="text-align:center">PAC</td> 1061 * <td></td> 1062 * <td style="text-align:center">2R</td> 1063 * </tr> 1064 * <tr> 1065 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1066 * <td></td> 1067 * <td style="text-align:center">PRO</td> 1068 * <td style="text-align:center">PRI</td> 1069 * <td style="text-align:center">PAC</td> 1070 * <td></td> 1071 * <td style="text-align:center">2R</td> 1072 * </tr> 1073 * <tr> 1074 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1075 * <td></td> 1076 * <td></td> 1077 * <td></td> 1078 * <td></td> 1079 * <td></td> 1080 * <td style="text-align:center">IAE</td> 1081 * </tr> 1082 * <tr> 1083 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1084 * <td></td> 1085 * <td></td> 1086 * <td></td> 1087 * <td style="text-align:center">PAC</td> 1088 * <td></td> 1089 * <td style="text-align:center">2R</td> 1090 * </tr> 1091 * <tr> 1092 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1093 * <td></td> 1094 * <td></td> 1095 * <td></td> 1096 * <td></td> 1097 * <td></td> 1098 * <td style="text-align:center">2R</td> 1099 * </tr> 1100 * <tr> 1101 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1102 * <td></td> 1103 * <td></td> 1104 * <td></td> 1105 * <td></td> 1106 * <td></td> 1107 * <td style="text-align:center">2R</td> 1108 * </tr> 1109 * <tr> 1110 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1111 * <td></td> 1112 * <td></td> 1113 * <td></td> 1114 * <td></td> 1115 * <td></td> 1116 * <td style="text-align:center">none</td> 1117 * </tr> 1118 * <tr> 1119 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1120 * <td></td> 1121 * <td></td> 1122 * <td style="text-align:center">PRI</td> 1123 * <td style="text-align:center">PAC</td> 1124 * <td></td> 1125 * <td style="text-align:center">2R</td> 1126 * </tr> 1127 * <tr> 1128 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1129 * <td></td> 1130 * <td></td> 1131 * <td></td> 1132 * <td style="text-align:center">PAC</td> 1133 * <td></td> 1134 * <td style="text-align:center">2R</td> 1135 * </tr> 1136 * <tr> 1137 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1138 * <td></td> 1139 * <td></td> 1140 * <td></td> 1141 * <td></td> 1142 * <td></td> 1143 * <td style="text-align:center">2R</td> 1144 * </tr> 1145 * <tr> 1146 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1147 * <td></td> 1148 * <td></td> 1149 * <td></td> 1150 * <td></td> 1151 * <td></td> 1152 * <td style="text-align:center">2R</td> 1153 * </tr> 1154 * <tr> 1155 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1156 * <td></td> 1157 * <td></td> 1158 * <td></td> 1159 * <td></td> 1160 * <td></td> 1161 * <td style="text-align:center">none</td> 1162 * </tr> 1163 * <tr> 1164 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1165 * <td></td> 1166 * <td></td> 1167 * <td style="text-align:center">PRI</td> 1168 * <td style="text-align:center">PAC</td> 1169 * <td style="text-align:center">MOD</td> 1170 * <td style="text-align:center">1R</td> 1171 * </tr> 1172 * <tr> 1173 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1174 * <td></td> 1175 * <td></td> 1176 * <td></td> 1177 * <td style="text-align:center">PAC</td> 1178 * <td style="text-align:center">MOD</td> 1179 * <td style="text-align:center">1R</td> 1180 * </tr> 1181 * <tr> 1182 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1183 * <td></td> 1184 * <td></td> 1185 * <td></td> 1186 * <td></td> 1187 * <td style="text-align:center">MOD</td> 1188 * <td style="text-align:center">1R</td> 1189 * </tr> 1190 * <tr> 1191 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1192 * <td></td> 1193 * <td></td> 1194 * <td></td> 1195 * <td></td> 1196 * <td></td> 1197 * <td style="text-align:center">1R</td> 1198 * </tr> 1199 * <tr> 1200 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1201 * <td></td> 1202 * <td></td> 1203 * <td></td> 1204 * <td></td> 1205 * <td></td> 1206 * <td style="text-align:center">none</td> 1207 * </tr> 1208 * <tr> 1209 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1210 * <td></td> 1211 * <td></td> 1212 * <td></td> 1213 * <td></td> 1214 * <td></td> 1215 * <td style="text-align:center">U</td> 1216 * </tr> 1217 * <tr> 1218 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1219 * <td></td> 1220 * <td></td> 1221 * <td></td> 1222 * <td></td> 1223 * <td></td> 1224 * <td style="text-align:center">U</td> 1225 * </tr> 1226 * <tr> 1227 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1228 * <td></td> 1229 * <td></td> 1230 * <td></td> 1231 * <td></td> 1232 * <td></td> 1233 * <td style="text-align:center">U</td> 1234 * </tr> 1235 * <tr> 1236 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1237 * <td></td> 1238 * <td></td> 1239 * <td></td> 1240 * <td></td> 1241 * <td></td> 1242 * <td style="text-align:center">none</td> 1243 * </tr> 1244 * <tr> 1245 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1246 * <td></td> 1247 * <td></td> 1248 * <td></td> 1249 * <td></td> 1250 * <td></td> 1251 * <td style="text-align:center">IAE</td> 1252 * </tr> 1253 * <tr> 1254 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1255 * <td></td> 1256 * <td></td> 1257 * <td></td> 1258 * <td></td> 1259 * <td></td> 1260 * <td style="text-align:center">none</td> 1261 * </tr> 1262 * </tbody> 1263 * </table> 1264 * 1265 * <p> 1266 * Notes: 1267 * <ul> 1268 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1269 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1270 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1271 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1272 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1273 * {@code PRO} indicates {@link #PROTECTED} bit set, 1274 * {@code PRI} indicates {@link #PRIVATE} bit set, 1275 * {@code PAC} indicates {@link #PACKAGE} bit set, 1276 * {@code MOD} indicates {@link #MODULE} bit set, 1277 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1278 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1279 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1280 * <li>Public access comes in three kinds: 1281 * <ul> 1282 * <li>unconditional ({@code U}): the lookup assumes readability. 1283 * The lookup has {@code null} previous lookup class. 1284 * <li>one-module-reads ({@code 1R}): the module access checking is 1285 * performed with respect to the lookup class. The lookup has {@code null} 1286 * previous lookup class. 1287 * <li>two-module-reads ({@code 2R}): the module access checking is 1288 * performed with respect to the lookup class and the previous lookup class. 1289 * The lookup has a non-null previous lookup class which is in a 1290 * different module from the current lookup class. 1291 * </ul> 1292 * <li>Any attempt to reach a third module loses all access.</li> 1293 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1294 * all access modes are dropped.</li> 1295 * </ul> 1296 * 1297 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1298 * A small number of Java methods have a special property called caller sensitivity. 1299 * A <em>caller-sensitive</em> method can behave differently depending on the 1300 * identity of its immediate caller. 1301 * <p> 1302 * If a method handle for a caller-sensitive method is requested, 1303 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1304 * but they take account of the lookup class in a special way. 1305 * The resulting method handle behaves as if it were called 1306 * from an instruction contained in the lookup class, 1307 * so that the caller-sensitive method detects the lookup class. 1308 * (By contrast, the invoker of the method handle is disregarded.) 1309 * Thus, in the case of caller-sensitive methods, 1310 * different lookup classes may give rise to 1311 * differently behaving method handles. 1312 * <p> 1313 * In cases where the lookup object is 1314 * {@link MethodHandles#publicLookup() publicLookup()}, 1315 * or some other lookup object without the 1316 * {@linkplain #ORIGINAL original access}, 1317 * the lookup class is disregarded. 1318 * In such cases, no caller-sensitive method handle can be created, 1319 * access is forbidden, and the lookup fails with an 1320 * {@code IllegalAccessException}. 1321 * <p style="font-size:smaller;"> 1322 * <em>Discussion:</em> 1323 * For example, the caller-sensitive method 1324 * {@link java.lang.Class#forName(String) Class.forName(x)} 1325 * can return varying classes or throw varying exceptions, 1326 * depending on the class loader of the class that calls it. 1327 * A public lookup of {@code Class.forName} will fail, because 1328 * there is no reasonable way to determine its bytecode behavior. 1329 * <p style="font-size:smaller;"> 1330 * If an application caches method handles for broad sharing, 1331 * it should use {@code publicLookup()} to create them. 1332 * If there is a lookup of {@code Class.forName}, it will fail, 1333 * and the application must take appropriate action in that case. 1334 * It may be that a later lookup, perhaps during the invocation of a 1335 * bootstrap method, can incorporate the specific identity 1336 * of the caller, making the method accessible. 1337 * <p style="font-size:smaller;"> 1338 * The function {@code MethodHandles.lookup} is caller sensitive 1339 * so that there can be a secure foundation for lookups. 1340 * Nearly all other methods in the JSR 292 API rely on lookup 1341 * objects to check access requests. 1342 */ 1343 public static final 1344 class Lookup { 1345 /** The class on behalf of whom the lookup is being performed. */ 1346 private final Class<?> lookupClass; 1347 1348 /** previous lookup class */ 1349 private final Class<?> prevLookupClass; 1350 1351 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1352 private final int allowedModes; 1353 1354 static { 1355 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1356 } 1357 1358 /** A single-bit mask representing {@code public} access, 1359 * which may contribute to the result of {@link #lookupModes lookupModes}. 1360 * The value, {@code 0x01}, happens to be the same as the value of the 1361 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1362 * <p> 1363 * A {@code Lookup} with this lookup mode performs cross-module access check 1364 * with respect to the {@linkplain #lookupClass() lookup class} and 1365 * {@linkplain #previousLookupClass() previous lookup class} if present. 1366 */ 1367 public static final int PUBLIC = Modifier.PUBLIC; 1368 1369 /** A single-bit mask representing {@code private} access, 1370 * which may contribute to the result of {@link #lookupModes lookupModes}. 1371 * The value, {@code 0x02}, happens to be the same as the value of the 1372 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1373 */ 1374 public static final int PRIVATE = Modifier.PRIVATE; 1375 1376 /** A single-bit mask representing {@code protected} access, 1377 * which may contribute to the result of {@link #lookupModes lookupModes}. 1378 * The value, {@code 0x04}, happens to be the same as the value of the 1379 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1380 */ 1381 public static final int PROTECTED = Modifier.PROTECTED; 1382 1383 /** A single-bit mask representing {@code package} access (default access), 1384 * which may contribute to the result of {@link #lookupModes lookupModes}. 1385 * The value is {@code 0x08}, which does not correspond meaningfully to 1386 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1387 */ 1388 public static final int PACKAGE = Modifier.STATIC; 1389 1390 /** A single-bit mask representing {@code module} access, 1391 * which may contribute to the result of {@link #lookupModes lookupModes}. 1392 * The value is {@code 0x10}, which does not correspond meaningfully to 1393 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1394 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1395 * with this lookup mode can access all public types in the module of the 1396 * lookup class and public types in packages exported by other modules 1397 * to the module of the lookup class. 1398 * <p> 1399 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1400 * previous lookup class} is always {@code null}. 1401 * 1402 * @since 9 1403 */ 1404 public static final int MODULE = PACKAGE << 1; 1405 1406 /** A single-bit mask representing {@code unconditional} access 1407 * which may contribute to the result of {@link #lookupModes lookupModes}. 1408 * The value is {@code 0x20}, which does not correspond meaningfully to 1409 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1410 * A {@code Lookup} with this lookup mode assumes {@linkplain 1411 * java.lang.Module#canRead(java.lang.Module) readability}. 1412 * This lookup mode can access all public members of public types 1413 * of all modules when the type is in a package that is {@link 1414 * java.lang.Module#isExported(String) exported unconditionally}. 1415 * 1416 * <p> 1417 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1418 * previous lookup class} is always {@code null}. 1419 * 1420 * @since 9 1421 * @see #publicLookup() 1422 */ 1423 public static final int UNCONDITIONAL = PACKAGE << 2; 1424 1425 /** A single-bit mask representing {@code original} access 1426 * which may contribute to the result of {@link #lookupModes lookupModes}. 1427 * The value is {@code 0x40}, which does not correspond meaningfully to 1428 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1429 * 1430 * <p> 1431 * If this lookup mode is set, the {@code Lookup} object must be 1432 * created by the original lookup class by calling 1433 * {@link MethodHandles#lookup()} method or by a bootstrap method 1434 * invoked by the VM. The {@code Lookup} object with this lookup 1435 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1436 * 1437 * @since 16 1438 */ 1439 public static final int ORIGINAL = PACKAGE << 3; 1440 1441 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1442 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1443 private static final int TRUSTED = -1; 1444 1445 /* 1446 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1447 * Adjust 0 => PACKAGE 1448 */ 1449 private static int fixmods(int mods) { 1450 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1451 if (Modifier.isPublic(mods)) 1452 mods |= UNCONDITIONAL; 1453 return (mods != 0) ? mods : PACKAGE; 1454 } 1455 1456 /** Tells which class is performing the lookup. It is this class against 1457 * which checks are performed for visibility and access permissions. 1458 * <p> 1459 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1460 * access checks are performed against both the lookup class and the previous lookup class. 1461 * <p> 1462 * The class implies a maximum level of access permission, 1463 * but the permissions may be additionally limited by the bitmask 1464 * {@link #lookupModes lookupModes}, which controls whether non-public members 1465 * can be accessed. 1466 * @return the lookup class, on behalf of which this lookup object finds members 1467 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1468 */ 1469 public Class<?> lookupClass() { 1470 return lookupClass; 1471 } 1472 1473 /** Reports a lookup class in another module that this lookup object 1474 * was previously teleported from, or {@code null}. 1475 * <p> 1476 * A {@code Lookup} object produced by the factory methods, such as the 1477 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1478 * has {@code null} previous lookup class. 1479 * A {@code Lookup} object has a non-null previous lookup class 1480 * when this lookup was teleported from an old lookup class 1481 * in one module to a new lookup class in another module. 1482 * 1483 * @return the lookup class in another module that this lookup object was 1484 * previously teleported from, or {@code null} 1485 * @since 14 1486 * @see #in(Class) 1487 * @see MethodHandles#privateLookupIn(Class, Lookup) 1488 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1489 */ 1490 public Class<?> previousLookupClass() { 1491 return prevLookupClass; 1492 } 1493 1494 // This is just for calling out to MethodHandleImpl. 1495 private Class<?> lookupClassOrNull() { 1496 return (allowedModes == TRUSTED) ? null : lookupClass; 1497 } 1498 1499 /** Tells which access-protection classes of members this lookup object can produce. 1500 * The result is a bit-mask of the bits 1501 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1502 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1503 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1504 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1505 * {@linkplain #MODULE MODULE (0x10)}, 1506 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1507 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1508 * <p> 1509 * A freshly-created lookup object 1510 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1511 * all possible bits set, except {@code UNCONDITIONAL}. 1512 * A lookup object on a new lookup class 1513 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1514 * may have some mode bits set to zero. 1515 * Mode bits can also be 1516 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1517 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1518 * The purpose of this is to restrict access via the new lookup object, 1519 * so that it can access only names which can be reached by the original 1520 * lookup object, and also by the new lookup class. 1521 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1522 * @see #in 1523 * @see #dropLookupMode 1524 */ 1525 public int lookupModes() { 1526 return allowedModes & ALL_MODES; 1527 } 1528 1529 /** Embody the current class (the lookupClass) as a lookup class 1530 * for method handle creation. 1531 * Must be called by from a method in this package, 1532 * which in turn is called by a method not in this package. 1533 */ 1534 Lookup(Class<?> lookupClass) { 1535 this(lookupClass, null, FULL_POWER_MODES); 1536 } 1537 1538 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1539 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1540 && prevLookupClass.getModule() != lookupClass.getModule()); 1541 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1542 this.lookupClass = lookupClass; 1543 this.prevLookupClass = prevLookupClass; 1544 this.allowedModes = allowedModes; 1545 } 1546 1547 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1548 // make sure we haven't accidentally picked up a privileged class: 1549 checkUnprivilegedlookupClass(lookupClass); 1550 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1551 } 1552 1553 /** 1554 * Creates a lookup on the specified new lookup class. 1555 * The resulting object will report the specified 1556 * class as its own {@link #lookupClass() lookupClass}. 1557 * 1558 * <p> 1559 * However, the resulting {@code Lookup} object is guaranteed 1560 * to have no more access capabilities than the original. 1561 * In particular, access capabilities can be lost as follows:<ul> 1562 * <li>If the new lookup class is different from the old lookup class, 1563 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1564 * <li>If the new lookup class is in a different module from the old one, 1565 * i.e. {@link #MODULE MODULE} access is lost. 1566 * <li>If the new lookup class is in a different package 1567 * than the old one, protected and default (package) members will not be accessible, 1568 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1569 * <li>If the new lookup class is not within the same package member 1570 * as the old one, private members will not be accessible, and protected members 1571 * will not be accessible by virtue of inheritance, 1572 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1573 * (Protected members may continue to be accessible because of package sharing.) 1574 * <li>If the new lookup class is not 1575 * {@linkplain #accessClass(Class) accessible} to this lookup, 1576 * then no members, not even public members, will be accessible 1577 * i.e. all access modes are lost. 1578 * <li>If the new lookup class, the old lookup class and the previous lookup class 1579 * are all in different modules i.e. teleporting to a third module, 1580 * all access modes are lost. 1581 * </ul> 1582 * <p> 1583 * The new previous lookup class is chosen as follows: 1584 * <ul> 1585 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1586 * the new previous lookup class is {@code null}. 1587 * <li>If the new lookup class is in the same module as the old lookup class, 1588 * the new previous lookup class is the old previous lookup class. 1589 * <li>If the new lookup class is in a different module from the old lookup class, 1590 * the new previous lookup class is the old lookup class. 1591 *</ul> 1592 * <p> 1593 * The resulting lookup's capabilities for loading classes 1594 * (used during {@link #findClass} invocations) 1595 * are determined by the lookup class' loader, 1596 * which may change due to this operation. 1597 * 1598 * @param requestedLookupClass the desired lookup class for the new lookup object 1599 * @return a lookup object which reports the desired lookup class, or the same object 1600 * if there is no change 1601 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1602 * @throws NullPointerException if the argument is null 1603 * 1604 * @see #accessClass(Class) 1605 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1606 */ 1607 public Lookup in(Class<?> requestedLookupClass) { 1608 Objects.requireNonNull(requestedLookupClass); 1609 if (requestedLookupClass.isPrimitive()) 1610 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1611 if (requestedLookupClass.isArray()) 1612 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1613 1614 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1615 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1616 if (requestedLookupClass == this.lookupClass) 1617 return this; // keep same capabilities 1618 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1619 Module fromModule = this.lookupClass.getModule(); 1620 Module targetModule = requestedLookupClass.getModule(); 1621 Class<?> plc = this.previousLookupClass(); 1622 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1623 assert plc == null; 1624 newModes = UNCONDITIONAL; 1625 } else if (fromModule != targetModule) { 1626 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1627 // allow hopping back and forth between fromModule and plc's module 1628 // but not the third module 1629 newModes = 0; 1630 } 1631 // drop MODULE access 1632 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1633 // teleport from this lookup class 1634 plc = this.lookupClass; 1635 } 1636 if ((newModes & PACKAGE) != 0 1637 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1638 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1639 } 1640 // Allow nestmate lookups to be created without special privilege: 1641 if ((newModes & PRIVATE) != 0 1642 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1643 newModes &= ~(PRIVATE|PROTECTED); 1644 } 1645 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1646 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1647 // The requested class it not accessible from the lookup class. 1648 // No permissions. 1649 newModes = 0; 1650 } 1651 return newLookup(requestedLookupClass, plc, newModes); 1652 } 1653 1654 /** 1655 * Creates a lookup on the same lookup class which this lookup object 1656 * finds members, but with a lookup mode that has lost the given lookup mode. 1657 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1658 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1659 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1660 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1661 * 1662 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1663 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1664 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1665 * lookup has no access. 1666 * 1667 * <p> If this lookup is not a public lookup, then the following applies 1668 * regardless of its {@linkplain #lookupModes() lookup modes}. 1669 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1670 * dropped and so the resulting lookup mode will never have these access 1671 * capabilities. When dropping {@code PACKAGE} 1672 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1673 * access. When dropping {@code MODULE} then the resulting lookup will not 1674 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1675 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1676 * 1677 * @apiNote 1678 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1679 * delegate non-public access within the package of the lookup class without 1680 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1681 * A lookup with {@code MODULE} but not 1682 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1683 * the module of the lookup class without conferring package access. 1684 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1685 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1686 * to public classes accessible to both the module of the lookup class 1687 * and the module of the previous lookup class. 1688 * 1689 * @param modeToDrop the lookup mode to drop 1690 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1691 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1692 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1693 * or {@code UNCONDITIONAL} 1694 * @see MethodHandles#privateLookupIn 1695 * @since 9 1696 */ 1697 public Lookup dropLookupMode(int modeToDrop) { 1698 int oldModes = lookupModes(); 1699 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1700 switch (modeToDrop) { 1701 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1702 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1703 case PACKAGE: newModes &= ~(PRIVATE); break; 1704 case PROTECTED: 1705 case PRIVATE: 1706 case ORIGINAL: 1707 case UNCONDITIONAL: break; 1708 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1709 } 1710 if (newModes == oldModes) return this; // return self if no change 1711 return newLookup(lookupClass(), previousLookupClass(), newModes); 1712 } 1713 1714 /** 1715 * Creates and links a class or interface from {@code bytes} 1716 * with the same class loader and in the same runtime package and 1717 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1718 * {@linkplain #lookupClass() lookup class} as if calling 1719 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1720 * ClassLoader::defineClass}. 1721 * 1722 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1723 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1724 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1725 * that the lookup object was created by a caller in the runtime package (or derived 1726 * from a lookup originally created by suitably privileged code to a target class in 1727 * the runtime package). </p> 1728 * 1729 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1730 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1731 * same package as the lookup class. </p> 1732 * 1733 * <p> This method does not run the class initializer. The class initializer may 1734 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1735 * Specification</em>. </p> 1736 * 1737 * @param bytes the class bytes 1738 * @return the {@code Class} object for the class 1739 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1740 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1741 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1742 * than the lookup class or {@code bytes} is not a class or interface 1743 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1744 * @throws VerifyError if the newly created class cannot be verified 1745 * @throws LinkageError if the newly created class cannot be linked for any other reason 1746 * @throws NullPointerException if {@code bytes} is {@code null} 1747 * @since 9 1748 * @see MethodHandles#privateLookupIn 1749 * @see Lookup#dropLookupMode 1750 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1751 */ 1752 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1753 if ((lookupModes() & PACKAGE) == 0) 1754 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1755 return makeClassDefiner(bytes.clone()).defineClass(false); 1756 } 1757 1758 /** 1759 * The set of class options that specify whether a hidden class created by 1760 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1761 * Lookup::defineHiddenClass} method is dynamically added as a new member 1762 * to the nest of a lookup class and/or whether a hidden class has 1763 * a strong relationship with the class loader marked as its defining loader. 1764 * 1765 * @since 15 1766 */ 1767 public enum ClassOption { 1768 /** 1769 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1770 * of a lookup class as a nestmate. 1771 * 1772 * <p> A hidden nestmate class has access to the private members of all 1773 * classes and interfaces in the same nest. 1774 * 1775 * @see Class#getNestHost() 1776 */ 1777 NESTMATE(NESTMATE_CLASS), 1778 1779 /** 1780 * Specifies that a hidden class has a <em>strong</em> 1781 * relationship with the class loader marked as its defining loader, 1782 * as a normal class or interface has with its own defining loader. 1783 * This means that the hidden class may be unloaded if and only if 1784 * its defining loader is not reachable and thus may be reclaimed 1785 * by a garbage collector (JLS {@jls 12.7}). 1786 * 1787 * <p> By default, a hidden class or interface may be unloaded 1788 * even if the class loader that is marked as its defining loader is 1789 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1790 1791 * 1792 * @jls 12.7 Unloading of Classes and Interfaces 1793 */ 1794 STRONG(STRONG_LOADER_LINK); 1795 1796 /* the flag value is used by VM at define class time */ 1797 private final int flag; 1798 ClassOption(int flag) { 1799 this.flag = flag; 1800 } 1801 1802 static int optionsToFlag(ClassOption[] options) { 1803 int flags = 0; 1804 for (ClassOption cp : options) { 1805 if ((flags & cp.flag) != 0) { 1806 throw new IllegalArgumentException("Duplicate ClassOption " + cp); 1807 } 1808 flags |= cp.flag; 1809 } 1810 return flags; 1811 } 1812 } 1813 1814 /** 1815 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1816 * returning a {@code Lookup} on the newly created class or interface. 1817 * 1818 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1819 * which either defines {@code C} directly or delegates to another class loader. 1820 * A class loader defines {@code C} directly by invoking 1821 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1822 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1823 * to derive {@code C} from a purported representation in {@code class} file format. 1824 * In situations where use of a class loader is undesirable, a class or interface 1825 * {@code C} can be created by this method instead. This method is capable of 1826 * defining {@code C}, and thereby creating it, without invoking 1827 * {@code ClassLoader::defineClass}. 1828 * Instead, this method defines {@code C} as if by arranging for 1829 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1830 * from a purported representation in {@code class} file format 1831 * using the following rules: 1832 * 1833 * <ol> 1834 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1835 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1836 * This level of access is needed to create {@code C} in the module 1837 * of the lookup class of this {@code Lookup}.</li> 1838 * 1839 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1840 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1841 * The major and minor version may differ from the {@code class} file version 1842 * of the lookup class of this {@code Lookup}.</li> 1843 * 1844 * <li> The value of {@code this_class} must be a valid index in the 1845 * {@code constant_pool} table, and the entry at that index must be a valid 1846 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1847 * encoded in internal form that is specified by this structure. {@code N} must 1848 * denote a class or interface in the same package as the lookup class.</li> 1849 * 1850 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1851 * where {@code <suffix>} is an unqualified name. 1852 * 1853 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1854 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1855 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1856 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1857 * refers to the new {@code CONSTANT_Utf8_info} structure. 1858 * 1859 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1860 * 1861 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1862 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1863 * with the following adjustments: 1864 * <ul> 1865 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1866 * that includes a single {@code "."} character, even though this is not a valid 1867 * binary class or interface name in internal form.</li> 1868 * 1869 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1870 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1871 * 1872 * <li> {@code C} is considered to have the same runtime 1873 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1874 * and {@linkplain java.security.ProtectionDomain protection domain} 1875 * as the lookup class of this {@code Lookup}. 1876 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1877 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1878 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1879 * <ul> 1880 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1881 * even though this is not a valid binary class or interface name.</li> 1882 * <li> {@link Class#descriptorString()} returns the string 1883 * {@code "L" + N + "." + <suffix> + ";"}, 1884 * even though this is not a valid type descriptor name.</li> 1885 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1886 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1887 * </ul> 1888 * </ul> 1889 * </li> 1890 * </ol> 1891 * 1892 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1893 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1894 * <ul> 1895 * <li> During verification, whenever it is necessary to load the class named 1896 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 1897 * made of any class loader.</li> 1898 * 1899 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 1900 * by {@code this_class}, the symbolic reference is considered to be resolved to 1901 * {@code C} and resolution always succeeds immediately.</li> 1902 * </ul> 1903 * 1904 * <p> If the {@code initialize} parameter is {@code true}, 1905 * then {@code C} is initialized by the Java Virtual Machine. 1906 * 1907 * <p> The newly created class or interface {@code C} serves as the 1908 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 1909 * returned by this method. {@code C} is <em>hidden</em> in the sense that 1910 * no other class or interface can refer to {@code C} via a constant pool entry. 1911 * That is, a hidden class or interface cannot be named as a supertype, a field type, 1912 * a method parameter type, or a method return type by any other class. 1913 * This is because a hidden class or interface does not have a binary name, so 1914 * there is no internal form available to record in any class's constant pool. 1915 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 1916 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 1917 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 1918 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 1919 * JVM Tool Interface</a>. 1920 * 1921 * <p> A class or interface created by 1922 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1923 * a class loader} has a strong relationship with that class loader. 1924 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 1925 * that {@linkplain Class#getClassLoader() defined it}. 1926 * This means that a class created by a class loader may be unloaded if and 1927 * only if its defining loader is not reachable and thus may be reclaimed 1928 * by a garbage collector (JLS {@jls 12.7}). 1929 * 1930 * By default, however, a hidden class or interface may be unloaded even if 1931 * the class loader that is marked as its defining loader is 1932 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1933 * This behavior is useful when a hidden class or interface serves multiple 1934 * classes defined by arbitrary class loaders. In other cases, a hidden 1935 * class or interface may be linked to a single class (or a small number of classes) 1936 * with the same defining loader as the hidden class or interface. 1937 * In such cases, where the hidden class or interface must be coterminous 1938 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 1939 * option may be passed in {@code options}. 1940 * This arranges for a hidden class to have the same strong relationship 1941 * with the class loader marked as its defining loader, 1942 * as a normal class or interface has with its own defining loader. 1943 * 1944 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 1945 * may still prevent a hidden class or interface from being 1946 * unloaded by ensuring that the {@code Class} object is reachable. 1947 * 1948 * <p> The unloading characteristics are set for each hidden class when it is 1949 * defined, and cannot be changed later. An advantage of allowing hidden classes 1950 * to be unloaded independently of the class loader marked as their defining loader 1951 * is that a very large number of hidden classes may be created by an application. 1952 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 1953 * just as if normal classes were created by class loaders. 1954 * 1955 * <p> Classes and interfaces in a nest are allowed to have mutual access to 1956 * their private members. The nest relationship is determined by 1957 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 1958 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 1959 * By default, a hidden class belongs to a nest consisting only of itself 1960 * because a hidden class has no binary name. 1961 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 1962 * to create a hidden class or interface {@code C} as a member of a nest. 1963 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 1964 * in the {@code ClassFile} structure from which {@code C} was derived. 1965 * Instead, the following rules determine the nest host of {@code C}: 1966 * <ul> 1967 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 1968 * been determined, then let {@code H} be the nest host of the lookup class. 1969 * Otherwise, the nest host of the lookup class is determined using the 1970 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 1971 * <li>The nest host of {@code C} is determined to be {@code H}, 1972 * the nest host of the lookup class.</li> 1973 * </ul> 1974 * 1975 * <p> A hidden class or interface may be serializable, but this requires a custom 1976 * serialization mechanism in order to ensure that instances are properly serialized 1977 * and deserialized. The default serialization mechanism supports only classes and 1978 * interfaces that are discoverable by their class name. 1979 * 1980 * @param bytes the bytes that make up the class data, 1981 * in the format of a valid {@code class} file as defined by 1982 * <cite>The Java Virtual Machine Specification</cite>. 1983 * @param initialize if {@code true} the class will be initialized. 1984 * @param options {@linkplain ClassOption class options} 1985 * @return the {@code Lookup} object on the hidden class, 1986 * with {@linkplain #ORIGINAL original} and 1987 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 1988 * 1989 * @throws IllegalAccessException if this {@code Lookup} does not have 1990 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 1991 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1992 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 1993 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1994 * than the lookup class or {@code bytes} is not a class or interface 1995 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1996 * @throws IncompatibleClassChangeError if the class or interface named as 1997 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 1998 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 1999 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2000 * {@code C} is {@code C} itself 2001 * @throws VerifyError if the newly created class cannot be verified 2002 * @throws LinkageError if the newly created class cannot be linked for any other reason 2003 * @throws NullPointerException if any parameter is {@code null} 2004 * 2005 * @since 15 2006 * @see Class#isHidden() 2007 * @jvms 4.2.1 Binary Class and Interface Names 2008 * @jvms 4.2.2 Unqualified Names 2009 * @jvms 4.7.28 The {@code NestHost} Attribute 2010 * @jvms 4.7.29 The {@code NestMembers} Attribute 2011 * @jvms 5.4.3.1 Class and Interface Resolution 2012 * @jvms 5.4.4 Access Control 2013 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2014 * @jvms 5.4 Linking 2015 * @jvms 5.5 Initialization 2016 * @jls 12.7 Unloading of Classes and Interfaces 2017 */ 2018 @SuppressWarnings("doclint:reference") // cross-module links 2019 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2020 throws IllegalAccessException 2021 { 2022 Objects.requireNonNull(bytes); 2023 int flags = ClassOption.optionsToFlag(options); 2024 if (!hasFullPrivilegeAccess()) { 2025 throw new IllegalAccessException(this + " does not have full privilege access"); 2026 } 2027 2028 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize); 2029 } 2030 2031 /** 2032 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2033 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2034 * returning a {@code Lookup} on the newly created class or interface. 2035 * 2036 * <p> This method is equivalent to calling 2037 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2038 * as if the hidden class is injected with a private static final <i>unnamed</i> 2039 * field which is initialized with the given {@code classData} at 2040 * the first instruction of the class initializer. 2041 * The newly created class is linked by the Java Virtual Machine. 2042 * 2043 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2044 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2045 * methods can be used to retrieve the {@code classData}. 2046 * 2047 * @apiNote 2048 * A framework can create a hidden class with class data with one or more 2049 * objects and load the class data as dynamically-computed constant(s) 2050 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2051 * Class data} is accessible only to the lookup object created by the newly 2052 * defined hidden class but inaccessible to other members in the same nest 2053 * (unlike private static fields that are accessible to nestmates). 2054 * Care should be taken w.r.t. mutability for example when passing 2055 * an array or other mutable structure through the class data. 2056 * Changing any value stored in the class data at runtime may lead to 2057 * unpredictable behavior. 2058 * If the class data is a {@code List}, it is good practice to make it 2059 * unmodifiable for example via {@link List#of List::of}. 2060 * 2061 * @param bytes the class bytes 2062 * @param classData pre-initialized class data 2063 * @param initialize if {@code true} the class will be initialized. 2064 * @param options {@linkplain ClassOption class options} 2065 * @return the {@code Lookup} object on the hidden class, 2066 * with {@linkplain #ORIGINAL original} and 2067 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2068 * 2069 * @throws IllegalAccessException if this {@code Lookup} does not have 2070 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2071 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2072 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2073 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2074 * than the lookup class or {@code bytes} is not a class or interface 2075 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2076 * @throws IncompatibleClassChangeError if the class or interface named as 2077 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2078 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2079 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2080 * {@code C} is {@code C} itself 2081 * @throws VerifyError if the newly created class cannot be verified 2082 * @throws LinkageError if the newly created class cannot be linked for any other reason 2083 * @throws NullPointerException if any parameter is {@code null} 2084 * 2085 * @since 16 2086 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2087 * @see Class#isHidden() 2088 * @see MethodHandles#classData(Lookup, String, Class) 2089 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2090 * @jvms 4.2.1 Binary Class and Interface Names 2091 * @jvms 4.2.2 Unqualified Names 2092 * @jvms 4.7.28 The {@code NestHost} Attribute 2093 * @jvms 4.7.29 The {@code NestMembers} Attribute 2094 * @jvms 5.4.3.1 Class and Interface Resolution 2095 * @jvms 5.4.4 Access Control 2096 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2097 * @jvms 5.4 Linking 2098 * @jvms 5.5 Initialization 2099 * @jls 12.7 Unloading of Classes and Interfaces 2100 */ 2101 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2102 throws IllegalAccessException 2103 { 2104 Objects.requireNonNull(bytes); 2105 Objects.requireNonNull(classData); 2106 2107 int flags = ClassOption.optionsToFlag(options); 2108 2109 if (!hasFullPrivilegeAccess()) { 2110 throw new IllegalAccessException(this + " does not have full privilege access"); 2111 } 2112 2113 return makeHiddenClassDefiner(bytes.clone(), false, flags) 2114 .defineClassAsLookup(initialize, classData); 2115 } 2116 2117 // A default dumper for writing class files passed to Lookup::defineClass 2118 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2119 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2120 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2121 // 2122 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2123 // and LambdaForms and method handle internals. They are dumped via 2124 // different ClassFileDumpers. 2125 private static ClassFileDumper defaultDumper() { 2126 return DEFAULT_DUMPER; 2127 } 2128 2129 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2130 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2131 2132 /** 2133 * This method checks the class file version and the structure of `this_class`. 2134 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2135 * that is in the named package. 2136 * 2137 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2138 * or the class is not in the given package name. 2139 */ 2140 static String validateAndFindInternalName(byte[] bytes, String pkgName) { 2141 int magic = readInt(bytes, 0); 2142 if (magic != ClassFile.MAGIC_NUMBER) { 2143 throw new ClassFormatError("Incompatible magic value: " + magic); 2144 } 2145 // We have to read major and minor this way as ClassFile API throws IAE 2146 // yet we want distinct ClassFormatError and UnsupportedClassVersionError 2147 int minor = readUnsignedShort(bytes, 4); 2148 int major = readUnsignedShort(bytes, 6); 2149 2150 if (!VM.isSupportedClassFileVersion(major, minor)) { 2151 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2152 } 2153 2154 String name; 2155 ClassDesc sym; 2156 int accessFlags; 2157 try { 2158 ClassModel cm = ClassFile.of().parse(bytes); 2159 var thisClass = cm.thisClass(); 2160 name = thisClass.asInternalName(); 2161 sym = thisClass.asSymbol(); 2162 accessFlags = cm.flags().flagsMask(); 2163 } catch (IllegalArgumentException e) { 2164 ClassFormatError cfe = new ClassFormatError(); 2165 cfe.initCause(e); 2166 throw cfe; 2167 } 2168 // must be a class or interface 2169 if ((accessFlags & ACC_MODULE) != 0) { 2170 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2171 } 2172 2173 String pn = sym.packageName(); 2174 if (!pn.equals(pkgName)) { 2175 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2176 } 2177 2178 return name; 2179 } 2180 2181 private static int readInt(byte[] bytes, int offset) { 2182 if ((offset + 4) > bytes.length) { 2183 throw new ClassFormatError("Invalid ClassFile structure"); 2184 } 2185 return ((bytes[offset] & 0xFF) << 24) 2186 | ((bytes[offset + 1] & 0xFF) << 16) 2187 | ((bytes[offset + 2] & 0xFF) << 8) 2188 | (bytes[offset + 3] & 0xFF); 2189 } 2190 2191 private static int readUnsignedShort(byte[] bytes, int offset) { 2192 if ((offset+2) > bytes.length) { 2193 throw new ClassFormatError("Invalid ClassFile structure"); 2194 } 2195 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2196 } 2197 2198 /* 2199 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2200 * from the given bytes. 2201 * 2202 * Caller should make a defensive copy of the arguments if needed 2203 * before calling this factory method. 2204 * 2205 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2206 * {@code bytes} denotes a class in a different package than the lookup class 2207 */ 2208 private ClassDefiner makeClassDefiner(byte[] bytes) { 2209 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2210 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper()); 2211 } 2212 2213 /** 2214 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2215 * from the given bytes. No package name check on the given bytes. 2216 * 2217 * @param internalName internal name 2218 * @param bytes class bytes 2219 * @param dumper dumper to write the given bytes to the dumper's output directory 2220 * @return ClassDefiner that defines a normal class of the given bytes. 2221 */ 2222 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2223 // skip package name validation 2224 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper); 2225 } 2226 2227 /** 2228 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2229 * from the given bytes. The name must be in the same package as the lookup class. 2230 * 2231 * Caller should make a defensive copy of the arguments if needed 2232 * before calling this factory method. 2233 * 2234 * @param bytes class bytes 2235 * @param dumper dumper to write the given bytes to the dumper's output directory 2236 * @return ClassDefiner that defines a hidden class of the given bytes. 2237 * 2238 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2239 * {@code bytes} denotes a class in a different package than the lookup class 2240 */ 2241 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2242 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2243 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2244 } 2245 2246 /** 2247 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2248 * from the given bytes and options. 2249 * The name must be in the same package as the lookup class. 2250 * 2251 * Caller should make a defensive copy of the arguments if needed 2252 * before calling this factory method. 2253 * 2254 * @param bytes class bytes 2255 * @param flags class option flag mask 2256 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2257 * @return ClassDefiner that defines a hidden class of the given bytes and options 2258 * 2259 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2260 * {@code bytes} denotes a class in a different package than the lookup class 2261 */ 2262 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2263 boolean accessVmAnnotations, 2264 int flags) { 2265 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2266 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags); 2267 } 2268 2269 /** 2270 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2271 * from the given bytes and the given options. No package name check on the given bytes. 2272 * 2273 * @param internalName internal name that specifies the prefix of the hidden class 2274 * @param bytes class bytes 2275 * @param dumper dumper to write the given bytes to the dumper's output directory 2276 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2277 */ 2278 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2279 Objects.requireNonNull(dumper); 2280 // skip name and access flags validation 2281 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2282 } 2283 2284 /** 2285 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2286 * from the given bytes and the given options. No package name check on the given bytes. 2287 * 2288 * @param internalName internal name that specifies the prefix of the hidden class 2289 * @param bytes class bytes 2290 * @param flags class options flag mask 2291 * @param dumper dumper to write the given bytes to the dumper's output directory 2292 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2293 */ 2294 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) { 2295 Objects.requireNonNull(dumper); 2296 // skip name and access flags validation 2297 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags); 2298 } 2299 2300 /** 2301 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2302 * from the given class file and options. 2303 * 2304 * @param internalName internal name 2305 * @param bytes Class byte array 2306 * @param flags class option flag mask 2307 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2308 * @param dumper dumper to write the given bytes to the dumper's output directory 2309 */ 2310 private ClassDefiner makeHiddenClassDefiner(String internalName, 2311 byte[] bytes, 2312 boolean accessVmAnnotations, 2313 ClassFileDumper dumper, 2314 int flags) { 2315 flags |= HIDDEN_CLASS; 2316 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2317 // jdk.internal.vm.annotations are permitted for classes 2318 // defined to boot loader and platform loader 2319 flags |= ACCESS_VM_ANNOTATIONS; 2320 } 2321 2322 return new ClassDefiner(this, internalName, bytes, flags, dumper); 2323 } 2324 2325 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) { 2326 ClassDefiner { 2327 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2328 } 2329 2330 Class<?> defineClass(boolean initialize) { 2331 return defineClass(initialize, null); 2332 } 2333 2334 Lookup defineClassAsLookup(boolean initialize) { 2335 Class<?> c = defineClass(initialize, null); 2336 return new Lookup(c, null, FULL_POWER_MODES); 2337 } 2338 2339 /** 2340 * Defines the class of the given bytes and the given classData. 2341 * If {@code initialize} parameter is true, then the class will be initialized. 2342 * 2343 * @param initialize true if the class to be initialized 2344 * @param classData classData or null 2345 * @return the class 2346 * 2347 * @throws LinkageError linkage error 2348 */ 2349 Class<?> defineClass(boolean initialize, Object classData) { 2350 Class<?> lookupClass = lookup.lookupClass(); 2351 ClassLoader loader = lookupClass.getClassLoader(); 2352 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2353 Class<?> c = null; 2354 try { 2355 c = SharedSecrets.getJavaLangAccess() 2356 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData); 2357 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2358 return c; 2359 } finally { 2360 // dump the classfile for debugging 2361 if (dumper.isEnabled()) { 2362 String name = internalName(); 2363 if (c != null) { 2364 dumper.dumpClass(name, c, bytes); 2365 } else { 2366 dumper.dumpFailedClass(name, bytes); 2367 } 2368 } 2369 } 2370 } 2371 2372 /** 2373 * Defines the class of the given bytes and the given classData. 2374 * If {@code initialize} parameter is true, then the class will be initialized. 2375 * 2376 * @param initialize true if the class to be initialized 2377 * @param classData classData or null 2378 * @return a Lookup for the defined class 2379 * 2380 * @throws LinkageError linkage error 2381 */ 2382 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2383 Class<?> c = defineClass(initialize, classData); 2384 return new Lookup(c, null, FULL_POWER_MODES); 2385 } 2386 2387 private boolean isNestmate() { 2388 return (classFlags & NESTMATE_CLASS) != 0; 2389 } 2390 } 2391 2392 private ProtectionDomain lookupClassProtectionDomain() { 2393 ProtectionDomain pd = cachedProtectionDomain; 2394 if (pd == null) { 2395 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2396 } 2397 return pd; 2398 } 2399 2400 // cached protection domain 2401 private volatile ProtectionDomain cachedProtectionDomain; 2402 2403 // Make sure outer class is initialized first. 2404 static { IMPL_NAMES.getClass(); } 2405 2406 /** Package-private version of lookup which is trusted. */ 2407 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2408 2409 /** Version of lookup which is trusted minimally. 2410 * It can only be used to create method handles to publicly accessible 2411 * members in packages that are exported unconditionally. 2412 */ 2413 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2414 2415 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2416 String name = lookupClass.getName(); 2417 if (name.startsWith("java.lang.invoke.")) 2418 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2419 } 2420 2421 /** 2422 * Displays the name of the class from which lookups are to be made, 2423 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2424 * previous lookup class} if present. 2425 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2426 * If there are restrictions on the access permitted to this lookup, 2427 * this is indicated by adding a suffix to the class name, consisting 2428 * of a slash and a keyword. The keyword represents the strongest 2429 * allowed access, and is chosen as follows: 2430 * <ul> 2431 * <li>If no access is allowed, the suffix is "/noaccess". 2432 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2433 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2434 * <li>If only public and module access are allowed, the suffix is "/module". 2435 * <li>If public and package access are allowed, the suffix is "/package". 2436 * <li>If public, package, and private access are allowed, the suffix is "/private". 2437 * </ul> 2438 * If none of the above cases apply, it is the case that 2439 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2440 * (public, module, package, private, and protected) is allowed. 2441 * In this case, no suffix is added. 2442 * This is true only of an object obtained originally from 2443 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2444 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2445 * always have restricted access, and will display a suffix. 2446 * <p> 2447 * (It may seem strange that protected access should be 2448 * stronger than private access. Viewed independently from 2449 * package access, protected access is the first to be lost, 2450 * because it requires a direct subclass relationship between 2451 * caller and callee.) 2452 * @see #in 2453 */ 2454 @Override 2455 public String toString() { 2456 String cname = lookupClass.getName(); 2457 if (prevLookupClass != null) 2458 cname += "/" + prevLookupClass.getName(); 2459 switch (allowedModes) { 2460 case 0: // no privileges 2461 return cname + "/noaccess"; 2462 case UNCONDITIONAL: 2463 return cname + "/publicLookup"; 2464 case PUBLIC: 2465 return cname + "/public"; 2466 case PUBLIC|MODULE: 2467 return cname + "/module"; 2468 case PUBLIC|PACKAGE: 2469 case PUBLIC|MODULE|PACKAGE: 2470 return cname + "/package"; 2471 case PUBLIC|PACKAGE|PRIVATE: 2472 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2473 return cname + "/private"; 2474 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2475 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2476 case FULL_POWER_MODES: 2477 return cname; 2478 case TRUSTED: 2479 return "/trusted"; // internal only; not exported 2480 default: // Should not happen, but it's a bitfield... 2481 cname = cname + "/" + Integer.toHexString(allowedModes); 2482 assert(false) : cname; 2483 return cname; 2484 } 2485 } 2486 2487 /** 2488 * Produces a method handle for a static method. 2489 * The type of the method handle will be that of the method. 2490 * (Since static methods do not take receivers, there is no 2491 * additional receiver argument inserted into the method handle type, 2492 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2493 * The method and all its argument types must be accessible to the lookup object. 2494 * <p> 2495 * The returned method handle will have 2496 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2497 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2498 * <p> 2499 * If the returned method handle is invoked, the method's class will 2500 * be initialized, if it has not already been initialized. 2501 * <p><b>Example:</b> 2502 * {@snippet lang="java" : 2503 import static java.lang.invoke.MethodHandles.*; 2504 import static java.lang.invoke.MethodType.*; 2505 ... 2506 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2507 "asList", methodType(List.class, Object[].class)); 2508 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2509 * } 2510 * @param refc the class from which the method is accessed 2511 * @param name the name of the method 2512 * @param type the type of the method 2513 * @return the desired method handle 2514 * @throws NoSuchMethodException if the method does not exist 2515 * @throws IllegalAccessException if access checking fails, 2516 * or if the method is not {@code static}, 2517 * or if the method's variable arity modifier bit 2518 * is set and {@code asVarargsCollector} fails 2519 * @throws NullPointerException if any argument is null 2520 */ 2521 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2522 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2523 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2524 } 2525 2526 /** 2527 * Produces a method handle for a virtual method. 2528 * The type of the method handle will be that of the method, 2529 * with the receiver type (usually {@code refc}) prepended. 2530 * The method and all its argument types must be accessible to the lookup object. 2531 * <p> 2532 * When called, the handle will treat the first argument as a receiver 2533 * and, for non-private methods, dispatch on the receiver's type to determine which method 2534 * implementation to enter. 2535 * For private methods the named method in {@code refc} will be invoked on the receiver. 2536 * (The dispatching action is identical with that performed by an 2537 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2538 * <p> 2539 * The first argument will be of type {@code refc} if the lookup 2540 * class has full privileges to access the member. Otherwise 2541 * the member must be {@code protected} and the first argument 2542 * will be restricted in type to the lookup class. 2543 * <p> 2544 * The returned method handle will have 2545 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2546 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2547 * <p> 2548 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2549 * instructions and method handles produced by {@code findVirtual}, 2550 * if the class is {@code MethodHandle} and the name string is 2551 * {@code invokeExact} or {@code invoke}, the resulting 2552 * method handle is equivalent to one produced by 2553 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2554 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2555 * with the same {@code type} argument. 2556 * <p> 2557 * If the class is {@code VarHandle} and the name string corresponds to 2558 * the name of a signature-polymorphic access mode method, the resulting 2559 * method handle is equivalent to one produced by 2560 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2561 * the access mode corresponding to the name string and with the same 2562 * {@code type} arguments. 2563 * <p> 2564 * <b>Example:</b> 2565 * {@snippet lang="java" : 2566 import static java.lang.invoke.MethodHandles.*; 2567 import static java.lang.invoke.MethodType.*; 2568 ... 2569 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2570 "concat", methodType(String.class, String.class)); 2571 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2572 "hashCode", methodType(int.class)); 2573 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2574 "hashCode", methodType(int.class)); 2575 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2576 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2577 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2578 // interface method: 2579 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2580 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2581 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2582 // constructor "internal method" must be accessed differently: 2583 MethodType MT_newString = methodType(void.class); //()V for new String() 2584 try { assertEquals("impossible", lookup() 2585 .findVirtual(String.class, "<init>", MT_newString)); 2586 } catch (NoSuchMethodException ex) { } // OK 2587 MethodHandle MH_newString = publicLookup() 2588 .findConstructor(String.class, MT_newString); 2589 assertEquals("", (String) MH_newString.invokeExact()); 2590 * } 2591 * 2592 * @param refc the class or interface from which the method is accessed 2593 * @param name the name of the method 2594 * @param type the type of the method, with the receiver argument omitted 2595 * @return the desired method handle 2596 * @throws NoSuchMethodException if the method does not exist 2597 * @throws IllegalAccessException if access checking fails, 2598 * or if the method is {@code static}, 2599 * or if the method's variable arity modifier bit 2600 * is set and {@code asVarargsCollector} fails 2601 * @throws NullPointerException if any argument is null 2602 */ 2603 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2604 if (refc == MethodHandle.class) { 2605 MethodHandle mh = findVirtualForMH(name, type); 2606 if (mh != null) return mh; 2607 } else if (refc == VarHandle.class) { 2608 MethodHandle mh = findVirtualForVH(name, type); 2609 if (mh != null) return mh; 2610 } 2611 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2612 MemberName method = resolveOrFail(refKind, refc, name, type); 2613 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2614 } 2615 private MethodHandle findVirtualForMH(String name, MethodType type) { 2616 // these names require special lookups because of the implicit MethodType argument 2617 if ("invoke".equals(name)) 2618 return invoker(type); 2619 if ("invokeExact".equals(name)) 2620 return exactInvoker(type); 2621 assert(!MemberName.isMethodHandleInvokeName(name)); 2622 return null; 2623 } 2624 private MethodHandle findVirtualForVH(String name, MethodType type) { 2625 try { 2626 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2627 } catch (IllegalArgumentException e) { 2628 return null; 2629 } 2630 } 2631 2632 /** 2633 * Produces a method handle which creates an object and initializes it, using 2634 * the constructor of the specified type. 2635 * The parameter types of the method handle will be those of the constructor, 2636 * while the return type will be a reference to the constructor's class. 2637 * The constructor and all its argument types must be accessible to the lookup object. 2638 * <p> 2639 * The requested type must have a return type of {@code void}. 2640 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2641 * <p> 2642 * The returned method handle will have 2643 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2644 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2645 * <p> 2646 * If the returned method handle is invoked, the constructor's class will 2647 * be initialized, if it has not already been initialized. 2648 * <p><b>Example:</b> 2649 * {@snippet lang="java" : 2650 import static java.lang.invoke.MethodHandles.*; 2651 import static java.lang.invoke.MethodType.*; 2652 ... 2653 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2654 ArrayList.class, methodType(void.class, Collection.class)); 2655 Collection orig = Arrays.asList("x", "y"); 2656 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2657 assert(orig != copy); 2658 assertEquals(orig, copy); 2659 // a variable-arity constructor: 2660 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2661 ProcessBuilder.class, methodType(void.class, String[].class)); 2662 ProcessBuilder pb = (ProcessBuilder) 2663 MH_newProcessBuilder.invoke("x", "y", "z"); 2664 assertEquals("[x, y, z]", pb.command().toString()); 2665 * } 2666 * @param refc the class or interface from which the method is accessed 2667 * @param type the type of the method, with the receiver argument omitted, and a void return type 2668 * @return the desired method handle 2669 * @throws NoSuchMethodException if the constructor does not exist 2670 * @throws IllegalAccessException if access checking fails 2671 * or if the method's variable arity modifier bit 2672 * is set and {@code asVarargsCollector} fails 2673 * @throws NullPointerException if any argument is null 2674 */ 2675 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2676 if (refc.isArray()) { 2677 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2678 } 2679 String name = ConstantDescs.INIT_NAME; 2680 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2681 return getDirectConstructor(refc, ctor); 2682 } 2683 2684 /** 2685 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2686 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2687 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2688 * and then determines whether the class is accessible to this lookup object. 2689 * <p> 2690 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2691 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2692 * of {@code '['} and followed by the element type as encoded in the 2693 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2694 * <p> 2695 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2696 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2697 * 2698 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2699 * or the string representing an array class 2700 * @return the requested class. 2701 * @throws LinkageError if the linkage fails 2702 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2703 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2704 * modes. 2705 * @throws NullPointerException if {@code targetName} is null 2706 * @since 9 2707 * @jvms 5.4.3.1 Class and Interface Resolution 2708 */ 2709 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2710 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2711 return accessClass(targetClass); 2712 } 2713 2714 /** 2715 * Ensures that {@code targetClass} has been initialized. The class 2716 * to be initialized must be {@linkplain #accessClass accessible} 2717 * to this {@code Lookup} object. This method causes {@code targetClass} 2718 * to be initialized if it has not been already initialized, 2719 * as specified in JVMS {@jvms 5.5}. 2720 * 2721 * <p> 2722 * This method returns when {@code targetClass} is fully initialized, or 2723 * when {@code targetClass} is being initialized by the current thread. 2724 * 2725 * @param <T> the type of the class to be initialized 2726 * @param targetClass the class to be initialized 2727 * @return {@code targetClass} that has been initialized, or that is being 2728 * initialized by the current thread. 2729 * 2730 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2731 * or array class 2732 * @throws IllegalAccessException if {@code targetClass} is not 2733 * {@linkplain #accessClass accessible} to this lookup 2734 * @throws ExceptionInInitializerError if the class initialization provoked 2735 * by this method fails 2736 * @since 15 2737 * @jvms 5.5 Initialization 2738 */ 2739 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2740 if (targetClass.isPrimitive()) 2741 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2742 if (targetClass.isArray()) 2743 throw new IllegalArgumentException(targetClass + " is an array class"); 2744 2745 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2746 throw makeAccessException(targetClass); 2747 } 2748 2749 // ensure class initialization 2750 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2751 return targetClass; 2752 } 2753 2754 /* 2755 * Returns IllegalAccessException due to access violation to the given targetClass. 2756 * 2757 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2758 * which verifies access to a class rather a member. 2759 */ 2760 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2761 String message = "access violation: "+ targetClass; 2762 if (this == MethodHandles.publicLookup()) { 2763 message += ", from public Lookup"; 2764 } else { 2765 Module m = lookupClass().getModule(); 2766 message += ", from " + lookupClass() + " (" + m + ")"; 2767 if (prevLookupClass != null) { 2768 message += ", previous lookup " + 2769 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2770 } 2771 } 2772 return new IllegalAccessException(message); 2773 } 2774 2775 /** 2776 * Determines if a class can be accessed from the lookup context defined by 2777 * this {@code Lookup} object. The static initializer of the class is not run. 2778 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2779 * if the element type of the array class is accessible. Otherwise, 2780 * {@code targetClass} is determined as accessible as follows. 2781 * 2782 * <p> 2783 * If {@code targetClass} is in the same module as the lookup class, 2784 * the lookup class is {@code LC} in module {@code M1} and 2785 * the previous lookup class is in module {@code M0} or 2786 * {@code null} if not present, 2787 * {@code targetClass} is accessible if and only if one of the following is true: 2788 * <ul> 2789 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2790 * {@code LC} or other class in the same nest of {@code LC}.</li> 2791 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2792 * in the same runtime package of {@code LC}.</li> 2793 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2794 * a public type in {@code M1}.</li> 2795 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2796 * a public type in a package exported by {@code M1} to at least {@code M0} 2797 * if the previous lookup class is present; otherwise, {@code targetClass} 2798 * is a public type in a package exported by {@code M1} unconditionally.</li> 2799 * </ul> 2800 * 2801 * <p> 2802 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2803 * can access public types in all modules when the type is in a package 2804 * that is exported unconditionally. 2805 * <p> 2806 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2807 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2808 * is inaccessible. 2809 * <p> 2810 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2811 * {@code M1} is the module containing {@code lookupClass} and 2812 * {@code M2} is the module containing {@code targetClass}, 2813 * then {@code targetClass} is accessible if and only if 2814 * <ul> 2815 * <li>{@code M1} reads {@code M2}, and 2816 * <li>{@code targetClass} is public and in a package exported by 2817 * {@code M2} at least to {@code M1}. 2818 * </ul> 2819 * <p> 2820 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2821 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2822 * containing the previous lookup class, then {@code targetClass} is accessible 2823 * if and only if one of the following is true: 2824 * <ul> 2825 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2826 * {@linkplain Module#canRead(Module)} reads} {@code M0} and the type is 2827 * in a package that is exported to at least {@code M1}. 2828 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2829 * {@linkplain Module#canRead(Module)} reads} {@code M1} and the type is 2830 * in a package that is exported to at least {@code M0}. 2831 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2832 * and {@code M1} reads {@code M2} and the type is in a package 2833 * that is exported to at least both {@code M0} and {@code M2}. 2834 * </ul> 2835 * <p> 2836 * Otherwise, {@code targetClass} is not accessible. 2837 * 2838 * @param <T> the type of the class to be access-checked 2839 * @param targetClass the class to be access-checked 2840 * @return {@code targetClass} that has been access-checked 2841 * @throws IllegalAccessException if the class is not accessible from the lookup class 2842 * and previous lookup class, if present, using the allowed access modes. 2843 * @throws NullPointerException if {@code targetClass} is {@code null} 2844 * @since 9 2845 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2846 */ 2847 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2848 if (!isClassAccessible(targetClass)) { 2849 throw makeAccessException(targetClass); 2850 } 2851 return targetClass; 2852 } 2853 2854 /** 2855 * Produces an early-bound method handle for a virtual method. 2856 * It will bypass checks for overriding methods on the receiver, 2857 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2858 * instruction from within the explicitly specified {@code specialCaller}. 2859 * The type of the method handle will be that of the method, 2860 * with a suitably restricted receiver type prepended. 2861 * (The receiver type will be {@code specialCaller} or a subtype.) 2862 * The method and all its argument types must be accessible 2863 * to the lookup object. 2864 * <p> 2865 * Before method resolution, 2866 * if the explicitly specified caller class is not identical with the 2867 * lookup class, or if this lookup object does not have 2868 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2869 * privileges, the access fails. 2870 * <p> 2871 * The returned method handle will have 2872 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2873 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2874 * <p style="font-size:smaller;"> 2875 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 2876 * are not visible to this API, 2877 * even though the {@code invokespecial} instruction can refer to them 2878 * in special circumstances. Use {@link #findConstructor findConstructor} 2879 * to access instance initialization methods in a safe manner.)</em> 2880 * <p><b>Example:</b> 2881 * {@snippet lang="java" : 2882 import static java.lang.invoke.MethodHandles.*; 2883 import static java.lang.invoke.MethodType.*; 2884 ... 2885 static class Listie extends ArrayList { 2886 public String toString() { return "[wee Listie]"; } 2887 static Lookup lookup() { return MethodHandles.lookup(); } 2888 } 2889 ... 2890 // no access to constructor via invokeSpecial: 2891 MethodHandle MH_newListie = Listie.lookup() 2892 .findConstructor(Listie.class, methodType(void.class)); 2893 Listie l = (Listie) MH_newListie.invokeExact(); 2894 try { assertEquals("impossible", Listie.lookup().findSpecial( 2895 Listie.class, "<init>", methodType(void.class), Listie.class)); 2896 } catch (NoSuchMethodException ex) { } // OK 2897 // access to super and self methods via invokeSpecial: 2898 MethodHandle MH_super = Listie.lookup().findSpecial( 2899 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2900 MethodHandle MH_this = Listie.lookup().findSpecial( 2901 Listie.class, "toString" , methodType(String.class), Listie.class); 2902 MethodHandle MH_duper = Listie.lookup().findSpecial( 2903 Object.class, "toString" , methodType(String.class), Listie.class); 2904 assertEquals("[]", (String) MH_super.invokeExact(l)); 2905 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2906 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2907 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2908 String.class, "toString", methodType(String.class), Listie.class)); 2909 } catch (IllegalAccessException ex) { } // OK 2910 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2911 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2912 * } 2913 * 2914 * @param refc the class or interface from which the method is accessed 2915 * @param name the name of the method (which must not be "<init>") 2916 * @param type the type of the method, with the receiver argument omitted 2917 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2918 * @return the desired method handle 2919 * @throws NoSuchMethodException if the method does not exist 2920 * @throws IllegalAccessException if access checking fails, 2921 * or if the method is {@code static}, 2922 * or if the method's variable arity modifier bit 2923 * is set and {@code asVarargsCollector} fails 2924 * @throws NullPointerException if any argument is null 2925 */ 2926 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 2927 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 2928 checkSpecialCaller(specialCaller, refc); 2929 Lookup specialLookup = this.in(specialCaller); 2930 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 2931 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 2932 } 2933 2934 /** 2935 * Produces a method handle giving read access to a non-static field. 2936 * The type of the method handle will have a return type of the field's 2937 * value type. 2938 * The method handle's single argument will be the instance containing 2939 * the field. 2940 * Access checking is performed immediately on behalf of the lookup class. 2941 * @param refc the class or interface from which the method is accessed 2942 * @param name the field's name 2943 * @param type the field's type 2944 * @return a method handle which can load values from the field 2945 * @throws NoSuchFieldException if the field does not exist 2946 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2947 * @throws NullPointerException if any argument is null 2948 * @see #findVarHandle(Class, String, Class) 2949 */ 2950 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2951 MemberName field = resolveOrFail(REF_getField, refc, name, type); 2952 return getDirectField(REF_getField, refc, field); 2953 } 2954 2955 /** 2956 * Produces a method handle giving write access to a non-static field. 2957 * The type of the method handle will have a void return type. 2958 * The method handle will take two arguments, the instance containing 2959 * the field, and the value to be stored. 2960 * The second argument will be of the field's value type. 2961 * Access checking is performed immediately on behalf of the lookup class. 2962 * @param refc the class or interface from which the method is accessed 2963 * @param name the field's name 2964 * @param type the field's type 2965 * @return a method handle which can store values into the field 2966 * @throws NoSuchFieldException if the field does not exist 2967 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2968 * or {@code final} 2969 * @throws NullPointerException if any argument is null 2970 * @see #findVarHandle(Class, String, Class) 2971 */ 2972 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2973 MemberName field = resolveOrFail(REF_putField, refc, name, type); 2974 return getDirectField(REF_putField, refc, field); 2975 } 2976 2977 /** 2978 * Produces a VarHandle giving access to a non-static field {@code name} 2979 * of type {@code type} declared in a class of type {@code recv}. 2980 * The VarHandle's variable type is {@code type} and it has one 2981 * coordinate type, {@code recv}. 2982 * <p> 2983 * Access checking is performed immediately on behalf of the lookup 2984 * class. 2985 * <p> 2986 * Certain access modes of the returned VarHandle are unsupported under 2987 * the following conditions: 2988 * <ul> 2989 * <li>if the field is declared {@code final}, then the write, atomic 2990 * update, numeric atomic update, and bitwise atomic update access 2991 * modes are unsupported. 2992 * <li>if the field type is anything other than {@code byte}, 2993 * {@code short}, {@code char}, {@code int}, {@code long}, 2994 * {@code float}, or {@code double} then numeric atomic update 2995 * access modes are unsupported. 2996 * <li>if the field type is anything other than {@code boolean}, 2997 * {@code byte}, {@code short}, {@code char}, {@code int} or 2998 * {@code long} then bitwise atomic update access modes are 2999 * unsupported. 3000 * </ul> 3001 * <p> 3002 * If the field is declared {@code volatile} then the returned VarHandle 3003 * will override access to the field (effectively ignore the 3004 * {@code volatile} declaration) in accordance to its specified 3005 * access modes. 3006 * <p> 3007 * If the field type is {@code float} or {@code double} then numeric 3008 * and atomic update access modes compare values using their bitwise 3009 * representation (see {@link Float#floatToRawIntBits} and 3010 * {@link Double#doubleToRawLongBits}, respectively). 3011 * @apiNote 3012 * Bitwise comparison of {@code float} values or {@code double} values, 3013 * as performed by the numeric and atomic update access modes, differ 3014 * from the primitive {@code ==} operator and the {@link Float#equals} 3015 * and {@link Double#equals} methods, specifically with respect to 3016 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3017 * Care should be taken when performing a compare and set or a compare 3018 * and exchange operation with such values since the operation may 3019 * unexpectedly fail. 3020 * There are many possible NaN values that are considered to be 3021 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3022 * provided by Java can distinguish between them. Operation failure can 3023 * occur if the expected or witness value is a NaN value and it is 3024 * transformed (perhaps in a platform specific manner) into another NaN 3025 * value, and thus has a different bitwise representation (see 3026 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3027 * details). 3028 * The values {@code -0.0} and {@code +0.0} have different bitwise 3029 * representations but are considered equal when using the primitive 3030 * {@code ==} operator. Operation failure can occur if, for example, a 3031 * numeric algorithm computes an expected value to be say {@code -0.0} 3032 * and previously computed the witness value to be say {@code +0.0}. 3033 * @param recv the receiver class, of type {@code R}, that declares the 3034 * non-static field 3035 * @param name the field's name 3036 * @param type the field's type, of type {@code T} 3037 * @return a VarHandle giving access to non-static fields. 3038 * @throws NoSuchFieldException if the field does not exist 3039 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3040 * @throws NullPointerException if any argument is null 3041 * @since 9 3042 */ 3043 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3044 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3045 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3046 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3047 } 3048 3049 /** 3050 * Produces a method handle giving read access to a static field. 3051 * The type of the method handle will have a return type of the field's 3052 * value type. 3053 * The method handle will take no arguments. 3054 * Access checking is performed immediately on behalf of the lookup class. 3055 * <p> 3056 * If the returned method handle is invoked, the field's class will 3057 * be initialized, if it has not already been initialized. 3058 * @param refc the class or interface from which the method is accessed 3059 * @param name the field's name 3060 * @param type the field's type 3061 * @return a method handle which can load values from the field 3062 * @throws NoSuchFieldException if the field does not exist 3063 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3064 * @throws NullPointerException if any argument is null 3065 */ 3066 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3067 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3068 return getDirectField(REF_getStatic, refc, field); 3069 } 3070 3071 /** 3072 * Produces a method handle giving write access to a static field. 3073 * The type of the method handle will have a void return type. 3074 * The method handle will take a single 3075 * argument, of the field's value type, the value to be stored. 3076 * Access checking is performed immediately on behalf of the lookup class. 3077 * <p> 3078 * If the returned method handle is invoked, the field's class will 3079 * be initialized, if it has not already been initialized. 3080 * @param refc the class or interface from which the method is accessed 3081 * @param name the field's name 3082 * @param type the field's type 3083 * @return a method handle which can store values into the field 3084 * @throws NoSuchFieldException if the field does not exist 3085 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3086 * or is {@code final} 3087 * @throws NullPointerException if any argument is null 3088 */ 3089 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3090 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3091 return getDirectField(REF_putStatic, refc, field); 3092 } 3093 3094 /** 3095 * Produces a VarHandle giving access to a static field {@code name} of 3096 * type {@code type} declared in a class of type {@code decl}. 3097 * The VarHandle's variable type is {@code type} and it has no 3098 * coordinate types. 3099 * <p> 3100 * Access checking is performed immediately on behalf of the lookup 3101 * class. 3102 * <p> 3103 * If the returned VarHandle is operated on, the declaring class will be 3104 * initialized, if it has not already been initialized. 3105 * <p> 3106 * Certain access modes of the returned VarHandle are unsupported under 3107 * the following conditions: 3108 * <ul> 3109 * <li>if the field is declared {@code final}, then the write, atomic 3110 * update, numeric atomic update, and bitwise atomic update access 3111 * modes are unsupported. 3112 * <li>if the field type is anything other than {@code byte}, 3113 * {@code short}, {@code char}, {@code int}, {@code long}, 3114 * {@code float}, or {@code double}, then numeric atomic update 3115 * access modes are unsupported. 3116 * <li>if the field type is anything other than {@code boolean}, 3117 * {@code byte}, {@code short}, {@code char}, {@code int} or 3118 * {@code long} then bitwise atomic update access modes are 3119 * unsupported. 3120 * </ul> 3121 * <p> 3122 * If the field is declared {@code volatile} then the returned VarHandle 3123 * will override access to the field (effectively ignore the 3124 * {@code volatile} declaration) in accordance to its specified 3125 * access modes. 3126 * <p> 3127 * If the field type is {@code float} or {@code double} then numeric 3128 * and atomic update access modes compare values using their bitwise 3129 * representation (see {@link Float#floatToRawIntBits} and 3130 * {@link Double#doubleToRawLongBits}, respectively). 3131 * @apiNote 3132 * Bitwise comparison of {@code float} values or {@code double} values, 3133 * as performed by the numeric and atomic update access modes, differ 3134 * from the primitive {@code ==} operator and the {@link Float#equals} 3135 * and {@link Double#equals} methods, specifically with respect to 3136 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3137 * Care should be taken when performing a compare and set or a compare 3138 * and exchange operation with such values since the operation may 3139 * unexpectedly fail. 3140 * There are many possible NaN values that are considered to be 3141 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3142 * provided by Java can distinguish between them. Operation failure can 3143 * occur if the expected or witness value is a NaN value and it is 3144 * transformed (perhaps in a platform specific manner) into another NaN 3145 * value, and thus has a different bitwise representation (see 3146 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3147 * details). 3148 * The values {@code -0.0} and {@code +0.0} have different bitwise 3149 * representations but are considered equal when using the primitive 3150 * {@code ==} operator. Operation failure can occur if, for example, a 3151 * numeric algorithm computes an expected value to be say {@code -0.0} 3152 * and previously computed the witness value to be say {@code +0.0}. 3153 * @param decl the class that declares the static field 3154 * @param name the field's name 3155 * @param type the field's type, of type {@code T} 3156 * @return a VarHandle giving access to a static field 3157 * @throws NoSuchFieldException if the field does not exist 3158 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3159 * @throws NullPointerException if any argument is null 3160 * @since 9 3161 */ 3162 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3163 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3164 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3165 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3166 } 3167 3168 /** 3169 * Produces an early-bound method handle for a non-static method. 3170 * The receiver must have a supertype {@code defc} in which a method 3171 * of the given name and type is accessible to the lookup class. 3172 * The method and all its argument types must be accessible to the lookup object. 3173 * The type of the method handle will be that of the method, 3174 * without any insertion of an additional receiver parameter. 3175 * The given receiver will be bound into the method handle, 3176 * so that every call to the method handle will invoke the 3177 * requested method on the given receiver. 3178 * <p> 3179 * The returned method handle will have 3180 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3181 * the method's variable arity modifier bit ({@code 0x0080}) is set 3182 * <em>and</em> the trailing array argument is not the only argument. 3183 * (If the trailing array argument is the only argument, 3184 * the given receiver value will be bound to it.) 3185 * <p> 3186 * This is almost equivalent to the following code, with some differences noted below: 3187 * {@snippet lang="java" : 3188 import static java.lang.invoke.MethodHandles.*; 3189 import static java.lang.invoke.MethodType.*; 3190 ... 3191 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3192 MethodHandle mh1 = mh0.bindTo(receiver); 3193 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3194 return mh1; 3195 * } 3196 * where {@code defc} is either {@code receiver.getClass()} or a super 3197 * type of that class, in which the requested method is accessible 3198 * to the lookup class. 3199 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3200 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3201 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3202 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3203 * @param receiver the object from which the method is accessed 3204 * @param name the name of the method 3205 * @param type the type of the method, with the receiver argument omitted 3206 * @return the desired method handle 3207 * @throws NoSuchMethodException if the method does not exist 3208 * @throws IllegalAccessException if access checking fails 3209 * or if the method's variable arity modifier bit 3210 * is set and {@code asVarargsCollector} fails 3211 * @throws NullPointerException if any argument is null 3212 * @see MethodHandle#bindTo 3213 * @see #findVirtual 3214 */ 3215 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3216 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3217 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3218 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3219 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3220 throw new IllegalAccessException("The restricted defining class " + 3221 mh.type().leadingReferenceParameter().getName() + 3222 " is not assignable from receiver class " + 3223 receiver.getClass().getName()); 3224 } 3225 return mh.bindArgumentL(0, receiver).setVarargs(method); 3226 } 3227 3228 /** 3229 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3230 * to <i>m</i>, if the lookup class has permission. 3231 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3232 * If <i>m</i> is virtual, overriding is respected on every call. 3233 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3234 * The type of the method handle will be that of the method, 3235 * with the receiver type prepended (but only if it is non-static). 3236 * If the method's {@code accessible} flag is not set, 3237 * access checking is performed immediately on behalf of the lookup class. 3238 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3239 * <p> 3240 * The returned method handle will have 3241 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3242 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3243 * <p> 3244 * If <i>m</i> is static, and 3245 * if the returned method handle is invoked, the method's class will 3246 * be initialized, if it has not already been initialized. 3247 * @param m the reflected method 3248 * @return a method handle which can invoke the reflected method 3249 * @throws IllegalAccessException if access checking fails 3250 * or if the method's variable arity modifier bit 3251 * is set and {@code asVarargsCollector} fails 3252 * @throws NullPointerException if the argument is null 3253 */ 3254 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3255 if (m.getDeclaringClass() == MethodHandle.class) { 3256 MethodHandle mh = unreflectForMH(m); 3257 if (mh != null) return mh; 3258 } 3259 if (m.getDeclaringClass() == VarHandle.class) { 3260 MethodHandle mh = unreflectForVH(m); 3261 if (mh != null) return mh; 3262 } 3263 MemberName method = new MemberName(m); 3264 byte refKind = method.getReferenceKind(); 3265 if (refKind == REF_invokeSpecial) 3266 refKind = REF_invokeVirtual; 3267 assert(method.isMethod()); 3268 @SuppressWarnings("deprecation") 3269 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3270 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3271 } 3272 private MethodHandle unreflectForMH(Method m) { 3273 // these names require special lookups because they throw UnsupportedOperationException 3274 if (MemberName.isMethodHandleInvokeName(m.getName())) 3275 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3276 return null; 3277 } 3278 private MethodHandle unreflectForVH(Method m) { 3279 // these names require special lookups because they throw UnsupportedOperationException 3280 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3281 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3282 return null; 3283 } 3284 3285 /** 3286 * Produces a method handle for a reflected method. 3287 * It will bypass checks for overriding methods on the receiver, 3288 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3289 * instruction from within the explicitly specified {@code specialCaller}. 3290 * The type of the method handle will be that of the method, 3291 * with a suitably restricted receiver type prepended. 3292 * (The receiver type will be {@code specialCaller} or a subtype.) 3293 * If the method's {@code accessible} flag is not set, 3294 * access checking is performed immediately on behalf of the lookup class, 3295 * as if {@code invokespecial} instruction were being linked. 3296 * <p> 3297 * Before method resolution, 3298 * if the explicitly specified caller class is not identical with the 3299 * lookup class, or if this lookup object does not have 3300 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3301 * privileges, the access fails. 3302 * <p> 3303 * The returned method handle will have 3304 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3305 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3306 * @param m the reflected method 3307 * @param specialCaller the class nominally calling the method 3308 * @return a method handle which can invoke the reflected method 3309 * @throws IllegalAccessException if access checking fails, 3310 * or if the method is {@code static}, 3311 * or if the method's variable arity modifier bit 3312 * is set and {@code asVarargsCollector} fails 3313 * @throws NullPointerException if any argument is null 3314 */ 3315 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3316 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3317 Lookup specialLookup = this.in(specialCaller); 3318 MemberName method = new MemberName(m, true); 3319 assert(method.isMethod()); 3320 // ignore m.isAccessible: this is a new kind of access 3321 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3322 } 3323 3324 /** 3325 * Produces a method handle for a reflected constructor. 3326 * The type of the method handle will be that of the constructor, 3327 * with the return type changed to the declaring class. 3328 * The method handle will perform a {@code newInstance} operation, 3329 * creating a new instance of the constructor's class on the 3330 * arguments passed to the method handle. 3331 * <p> 3332 * If the constructor's {@code accessible} flag is not set, 3333 * access checking is performed immediately on behalf of the lookup class. 3334 * <p> 3335 * The returned method handle will have 3336 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3337 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3338 * <p> 3339 * If the returned method handle is invoked, the constructor's class will 3340 * be initialized, if it has not already been initialized. 3341 * @param c the reflected constructor 3342 * @return a method handle which can invoke the reflected constructor 3343 * @throws IllegalAccessException if access checking fails 3344 * or if the method's variable arity modifier bit 3345 * is set and {@code asVarargsCollector} fails 3346 * @throws NullPointerException if the argument is null 3347 */ 3348 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3349 MemberName ctor = new MemberName(c); 3350 assert(ctor.isConstructor()); 3351 @SuppressWarnings("deprecation") 3352 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3353 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor); 3354 } 3355 3356 /* 3357 * Produces a method handle that is capable of creating instances of the given class 3358 * and instantiated by the given constructor. 3359 * 3360 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3361 */ 3362 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3363 MemberName ctor = new MemberName(c); 3364 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3365 checkAccess(REF_newInvokeSpecial, decl, ctor); 3366 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3367 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3368 } 3369 3370 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3371 if (decl == ctor.getDeclaringClass()) 3372 return true; 3373 3374 Class<?> cl = decl; 3375 while ((cl = cl.getSuperclass()) != null) { 3376 if (cl == ctor.getDeclaringClass()) { 3377 return true; 3378 } 3379 } 3380 return false; 3381 } 3382 3383 /** 3384 * Produces a method handle giving read access to a reflected field. 3385 * The type of the method handle will have a return type of the field's 3386 * value type. 3387 * If the field is {@code static}, the method handle will take no arguments. 3388 * Otherwise, its single argument will be the instance containing 3389 * the field. 3390 * If the {@code Field} object's {@code accessible} flag is not set, 3391 * access checking is performed immediately on behalf of the lookup class. 3392 * <p> 3393 * If the field is static, and 3394 * if the returned method handle is invoked, the field's class will 3395 * be initialized, if it has not already been initialized. 3396 * @param f the reflected field 3397 * @return a method handle which can load values from the reflected field 3398 * @throws IllegalAccessException if access checking fails 3399 * @throws NullPointerException if the argument is null 3400 */ 3401 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3402 return unreflectField(f, false); 3403 } 3404 3405 /** 3406 * Produces a method handle giving write access to a reflected field. 3407 * The type of the method handle will have a void return type. 3408 * If the field is {@code static}, the method handle will take a single 3409 * argument, of the field's value type, the value to be stored. 3410 * Otherwise, the two arguments will be the instance containing 3411 * the field, and the value to be stored. 3412 * If the {@code Field} object's {@code accessible} flag is not set, 3413 * access checking is performed immediately on behalf of the lookup class. 3414 * <p> 3415 * If the field is {@code final}, write access will not be 3416 * allowed and access checking will fail, except under certain 3417 * narrow circumstances documented for {@link Field#set Field.set}. 3418 * A method handle is returned only if a corresponding call to 3419 * the {@code Field} object's {@code set} method could return 3420 * normally. In particular, fields which are both {@code static} 3421 * and {@code final} may never be set. 3422 * <p> 3423 * If the field is {@code static}, and 3424 * if the returned method handle is invoked, the field's class will 3425 * be initialized, if it has not already been initialized. 3426 * @param f the reflected field 3427 * @return a method handle which can store values into the reflected field 3428 * @throws IllegalAccessException if access checking fails, 3429 * or if the field is {@code final} and write access 3430 * is not enabled on the {@code Field} object 3431 * @throws NullPointerException if the argument is null 3432 */ 3433 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3434 return unreflectField(f, true); 3435 } 3436 3437 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3438 MemberName field = new MemberName(f, isSetter); 3439 if (isSetter && field.isFinal()) { 3440 if (field.isTrustedFinalField()) { 3441 String msg = field.isStatic() ? "static final field has no write access" 3442 : "final field has no write access"; 3443 throw field.makeAccessException(msg, this); 3444 } 3445 } 3446 assert(isSetter 3447 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3448 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3449 @SuppressWarnings("deprecation") 3450 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3451 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field); 3452 } 3453 3454 /** 3455 * Produces a VarHandle giving access to a reflected field {@code f} 3456 * of type {@code T} declared in a class of type {@code R}. 3457 * The VarHandle's variable type is {@code T}. 3458 * If the field is non-static the VarHandle has one coordinate type, 3459 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3460 * coordinate types. 3461 * <p> 3462 * Access checking is performed immediately on behalf of the lookup 3463 * class, regardless of the value of the field's {@code accessible} 3464 * flag. 3465 * <p> 3466 * If the field is static, and if the returned VarHandle is operated 3467 * on, the field's declaring class will be initialized, if it has not 3468 * already been initialized. 3469 * <p> 3470 * Certain access modes of the returned VarHandle are unsupported under 3471 * the following conditions: 3472 * <ul> 3473 * <li>if the field is declared {@code final}, then the write, atomic 3474 * update, numeric atomic update, and bitwise atomic update access 3475 * modes are unsupported. 3476 * <li>if the field type is anything other than {@code byte}, 3477 * {@code short}, {@code char}, {@code int}, {@code long}, 3478 * {@code float}, or {@code double} then numeric atomic update 3479 * access modes are unsupported. 3480 * <li>if the field type is anything other than {@code boolean}, 3481 * {@code byte}, {@code short}, {@code char}, {@code int} or 3482 * {@code long} then bitwise atomic update access modes are 3483 * unsupported. 3484 * </ul> 3485 * <p> 3486 * If the field is declared {@code volatile} then the returned VarHandle 3487 * will override access to the field (effectively ignore the 3488 * {@code volatile} declaration) in accordance to its specified 3489 * access modes. 3490 * <p> 3491 * If the field type is {@code float} or {@code double} then numeric 3492 * and atomic update access modes compare values using their bitwise 3493 * representation (see {@link Float#floatToRawIntBits} and 3494 * {@link Double#doubleToRawLongBits}, respectively). 3495 * @apiNote 3496 * Bitwise comparison of {@code float} values or {@code double} values, 3497 * as performed by the numeric and atomic update access modes, differ 3498 * from the primitive {@code ==} operator and the {@link Float#equals} 3499 * and {@link Double#equals} methods, specifically with respect to 3500 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3501 * Care should be taken when performing a compare and set or a compare 3502 * and exchange operation with such values since the operation may 3503 * unexpectedly fail. 3504 * There are many possible NaN values that are considered to be 3505 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3506 * provided by Java can distinguish between them. Operation failure can 3507 * occur if the expected or witness value is a NaN value and it is 3508 * transformed (perhaps in a platform specific manner) into another NaN 3509 * value, and thus has a different bitwise representation (see 3510 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3511 * details). 3512 * The values {@code -0.0} and {@code +0.0} have different bitwise 3513 * representations but are considered equal when using the primitive 3514 * {@code ==} operator. Operation failure can occur if, for example, a 3515 * numeric algorithm computes an expected value to be say {@code -0.0} 3516 * and previously computed the witness value to be say {@code +0.0}. 3517 * @param f the reflected field, with a field of type {@code T}, and 3518 * a declaring class of type {@code R} 3519 * @return a VarHandle giving access to non-static fields or a static 3520 * field 3521 * @throws IllegalAccessException if access checking fails 3522 * @throws NullPointerException if the argument is null 3523 * @since 9 3524 */ 3525 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3526 MemberName getField = new MemberName(f, false); 3527 MemberName putField = new MemberName(f, true); 3528 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(), 3529 f.getDeclaringClass(), getField, putField); 3530 } 3531 3532 /** 3533 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3534 * created by this lookup object or a similar one. 3535 * Security and access checks are performed to ensure that this lookup object 3536 * is capable of reproducing the target method handle. 3537 * This means that the cracking may fail if target is a direct method handle 3538 * but was created by an unrelated lookup object. 3539 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3540 * and was created by a lookup object for a different class. 3541 * @param target a direct method handle to crack into symbolic reference components 3542 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3543 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3544 * @throws NullPointerException if the target is {@code null} 3545 * @see MethodHandleInfo 3546 * @since 1.8 3547 */ 3548 public MethodHandleInfo revealDirect(MethodHandle target) { 3549 if (!target.isCrackable()) { 3550 throw newIllegalArgumentException("not a direct method handle"); 3551 } 3552 MemberName member = target.internalMemberName(); 3553 Class<?> defc = member.getDeclaringClass(); 3554 byte refKind = member.getReferenceKind(); 3555 assert(MethodHandleNatives.refKindIsValid(refKind)); 3556 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3557 // Devirtualized method invocation is usually formally virtual. 3558 // To avoid creating extra MemberName objects for this common case, 3559 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3560 refKind = REF_invokeVirtual; 3561 if (refKind == REF_invokeVirtual && defc.isInterface()) 3562 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3563 refKind = REF_invokeInterface; 3564 // Check member access before cracking. 3565 try { 3566 checkAccess(refKind, defc, member); 3567 } catch (IllegalAccessException ex) { 3568 throw new IllegalArgumentException(ex); 3569 } 3570 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3571 Class<?> callerClass = target.internalCallerClass(); 3572 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3573 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3574 } 3575 // Produce the handle to the results. 3576 return new InfoFromMemberName(this, member, refKind); 3577 } 3578 3579 //--- Helper methods, all package-private. 3580 3581 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3582 checkSymbolicClass(refc); // do this before attempting to resolve 3583 Objects.requireNonNull(name); 3584 Objects.requireNonNull(type); 3585 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3586 NoSuchFieldException.class); 3587 } 3588 3589 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3590 checkSymbolicClass(refc); // do this before attempting to resolve 3591 Objects.requireNonNull(type); 3592 checkMethodName(refKind, name); // implicit null-check of name 3593 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3594 NoSuchMethodException.class); 3595 } 3596 3597 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3598 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3599 Objects.requireNonNull(member.getName()); 3600 Objects.requireNonNull(member.getType()); 3601 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3602 ReflectiveOperationException.class); 3603 } 3604 3605 MemberName resolveOrNull(byte refKind, MemberName member) { 3606 // do this before attempting to resolve 3607 if (!isClassAccessible(member.getDeclaringClass())) { 3608 return null; 3609 } 3610 Objects.requireNonNull(member.getName()); 3611 Objects.requireNonNull(member.getType()); 3612 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3613 } 3614 3615 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3616 // do this before attempting to resolve 3617 if (!isClassAccessible(refc)) { 3618 return null; 3619 } 3620 Objects.requireNonNull(type); 3621 // implicit null-check of name 3622 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3623 return null; 3624 } 3625 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3626 } 3627 3628 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3629 if (!isClassAccessible(refc)) { 3630 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3631 } 3632 } 3633 3634 boolean isClassAccessible(Class<?> refc) { 3635 Objects.requireNonNull(refc); 3636 Class<?> caller = lookupClassOrNull(); 3637 Class<?> type = refc; 3638 while (type.isArray()) { 3639 type = type.getComponentType(); 3640 } 3641 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3642 } 3643 3644 /** Check name for an illegal leading "<" character. */ 3645 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3646 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3647 throw new NoSuchMethodException("illegal method name: "+name); 3648 } 3649 3650 /** 3651 * Find my trustable caller class if m is a caller sensitive method. 3652 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3653 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3654 */ 3655 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3656 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3657 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3658 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3659 } 3660 return this; 3661 } 3662 3663 /** 3664 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3665 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3666 * 3667 * @deprecated This method was originally designed to test {@code PRIVATE} access 3668 * that implies full privilege access but {@code MODULE} access has since become 3669 * independent of {@code PRIVATE} access. It is recommended to call 3670 * {@link #hasFullPrivilegeAccess()} instead. 3671 * @since 9 3672 */ 3673 @Deprecated(since="14") 3674 public boolean hasPrivateAccess() { 3675 return hasFullPrivilegeAccess(); 3676 } 3677 3678 /** 3679 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3680 * i.e. {@code PRIVATE} and {@code MODULE} access. 3681 * A {@code Lookup} object must have full privilege access in order to 3682 * access all members that are allowed to the 3683 * {@linkplain #lookupClass() lookup class}. 3684 * 3685 * @return {@code true} if this lookup has full privilege access. 3686 * @since 14 3687 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3688 */ 3689 public boolean hasFullPrivilegeAccess() { 3690 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3691 } 3692 3693 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3694 boolean wantStatic = (refKind == REF_invokeStatic); 3695 String message; 3696 if (m.isConstructor()) 3697 message = "expected a method, not a constructor"; 3698 else if (!m.isMethod()) 3699 message = "expected a method"; 3700 else if (wantStatic != m.isStatic()) 3701 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3702 else 3703 { checkAccess(refKind, refc, m); return; } 3704 throw m.makeAccessException(message, this); 3705 } 3706 3707 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3708 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3709 String message; 3710 if (wantStatic != m.isStatic()) 3711 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3712 else 3713 { checkAccess(refKind, refc, m); return; } 3714 throw m.makeAccessException(message, this); 3715 } 3716 3717 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3718 return Modifier.isProtected(m.getModifiers()) && 3719 refKind == REF_invokeVirtual && 3720 m.getDeclaringClass() == Object.class && 3721 m.getName().equals("clone") && 3722 refc.isArray(); 3723 } 3724 3725 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3726 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3727 assert(m.referenceKindIsConsistentWith(refKind) && 3728 MethodHandleNatives.refKindIsValid(refKind) && 3729 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3730 int allowedModes = this.allowedModes; 3731 if (allowedModes == TRUSTED) return; 3732 int mods = m.getModifiers(); 3733 if (isArrayClone(refKind, refc, m)) { 3734 // The JVM does this hack also. 3735 // (See ClassVerifier::verify_invoke_instructions 3736 // and LinkResolver::check_method_accessability.) 3737 // Because the JVM does not allow separate methods on array types, 3738 // there is no separate method for int[].clone. 3739 // All arrays simply inherit Object.clone. 3740 // But for access checking logic, we make Object.clone 3741 // (normally protected) appear to be public. 3742 // Later on, when the DirectMethodHandle is created, 3743 // its leading argument will be restricted to the 3744 // requested array type. 3745 // N.B. The return type is not adjusted, because 3746 // that is *not* the bytecode behavior. 3747 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3748 } 3749 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3750 // cannot "new" a protected ctor in a different package 3751 mods ^= Modifier.PROTECTED; 3752 } 3753 if (Modifier.isFinal(mods) && 3754 MethodHandleNatives.refKindIsSetter(refKind)) 3755 throw m.makeAccessException("unexpected set of a final field", this); 3756 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3757 if ((requestedModes & allowedModes) != 0) { 3758 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3759 mods, lookupClass(), previousLookupClass(), allowedModes)) 3760 return; 3761 } else { 3762 // Protected members can also be checked as if they were package-private. 3763 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3764 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3765 return; 3766 } 3767 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3768 } 3769 3770 String accessFailedMessage(Class<?> refc, MemberName m) { 3771 Class<?> defc = m.getDeclaringClass(); 3772 int mods = m.getModifiers(); 3773 // check the class first: 3774 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3775 (defc == refc || 3776 Modifier.isPublic(refc.getModifiers()))); 3777 if (!classOK && (allowedModes & PACKAGE) != 0) { 3778 // ignore previous lookup class to check if default package access 3779 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3780 (defc == refc || 3781 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3782 } 3783 if (!classOK) 3784 return "class is not public"; 3785 if (Modifier.isPublic(mods)) 3786 return "access to public member failed"; // (how?, module not readable?) 3787 if (Modifier.isPrivate(mods)) 3788 return "member is private"; 3789 if (Modifier.isProtected(mods)) 3790 return "member is protected"; 3791 return "member is private to package"; 3792 } 3793 3794 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3795 int allowedModes = this.allowedModes; 3796 if (allowedModes == TRUSTED) return; 3797 if ((lookupModes() & PRIVATE) == 0 3798 || (specialCaller != lookupClass() 3799 // ensure non-abstract methods in superinterfaces can be special-invoked 3800 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3801 throw new MemberName(specialCaller). 3802 makeAccessException("no private access for invokespecial", this); 3803 } 3804 3805 private boolean restrictProtectedReceiver(MemberName method) { 3806 // The accessing class only has the right to use a protected member 3807 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3808 if (!method.isProtected() || method.isStatic() 3809 || allowedModes == TRUSTED 3810 || method.getDeclaringClass() == lookupClass() 3811 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3812 return false; 3813 return true; 3814 } 3815 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3816 assert(!method.isStatic()); 3817 // receiver type of mh is too wide; narrow to caller 3818 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3819 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3820 } 3821 MethodType rawType = mh.type(); 3822 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3823 MethodType narrowType = rawType.changeParameterType(0, caller); 3824 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3825 assert(mh.viewAsTypeChecks(narrowType, true)); 3826 return mh.copyWith(narrowType, mh.form); 3827 } 3828 3829 /** Check access and get the requested method. */ 3830 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3831 final boolean doRestrict = true; 3832 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup); 3833 } 3834 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3835 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3836 final boolean doRestrict = false; 3837 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup); 3838 } 3839 /** Common code for all methods; do not call directly except from immediately above. */ 3840 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3841 boolean doRestrict, 3842 Lookup boundCaller) throws IllegalAccessException { 3843 checkMethod(refKind, refc, method); 3844 assert(!method.isMethodHandleInvoke()); 3845 3846 if (refKind == REF_invokeSpecial && 3847 refc != lookupClass() && 3848 !refc.isInterface() && !lookupClass().isInterface() && 3849 refc != lookupClass().getSuperclass() && 3850 refc.isAssignableFrom(lookupClass())) { 3851 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 3852 3853 // Per JVMS 6.5, desc. of invokespecial instruction: 3854 // If the method is in a superclass of the LC, 3855 // and if our original search was above LC.super, 3856 // repeat the search (symbolic lookup) from LC.super 3857 // and continue with the direct superclass of that class, 3858 // and so forth, until a match is found or no further superclasses exist. 3859 // FIXME: MemberName.resolve should handle this instead. 3860 Class<?> refcAsSuper = lookupClass(); 3861 MemberName m2; 3862 do { 3863 refcAsSuper = refcAsSuper.getSuperclass(); 3864 m2 = new MemberName(refcAsSuper, 3865 method.getName(), 3866 method.getMethodType(), 3867 REF_invokeSpecial); 3868 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 3869 } while (m2 == null && // no method is found yet 3870 refc != refcAsSuper); // search up to refc 3871 if (m2 == null) throw new InternalError(method.toString()); 3872 method = m2; 3873 refc = refcAsSuper; 3874 // redo basic checks 3875 checkMethod(refKind, refc, method); 3876 } 3877 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 3878 MethodHandle mh = dmh; 3879 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 3880 if ((doRestrict && refKind == REF_invokeSpecial) || 3881 (MethodHandleNatives.refKindHasReceiver(refKind) && 3882 restrictProtectedReceiver(method) && 3883 // All arrays simply inherit the protected Object.clone method. 3884 // The leading argument is already restricted to the requested 3885 // array type (not the lookup class). 3886 !isArrayClone(refKind, refc, method))) { 3887 mh = restrictReceiver(method, dmh, lookupClass()); 3888 } 3889 mh = maybeBindCaller(method, mh, boundCaller); 3890 mh = mh.setVarargs(method); 3891 return mh; 3892 } 3893 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 3894 throws IllegalAccessException { 3895 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 3896 return mh; 3897 3898 // boundCaller must have full privilege access. 3899 // It should have been checked by findBoundCallerLookup. Safe to check this again. 3900 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 3901 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3902 3903 assert boundCaller.hasFullPrivilegeAccess(); 3904 3905 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 3906 // Note: caller will apply varargs after this step happens. 3907 return cbmh; 3908 } 3909 3910 /** Check access and get the requested field. */ 3911 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3912 return getDirectFieldCommon(refKind, refc, field); 3913 } 3914 /** Common code for all fields; do not call directly except from immediately above. */ 3915 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3916 checkField(refKind, refc, field); 3917 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 3918 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 3919 restrictProtectedReceiver(field)); 3920 if (doRestrict) 3921 return restrictReceiver(field, dmh, lookupClass()); 3922 return dmh; 3923 } 3924 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 3925 Class<?> refc, MemberName getField, MemberName putField) 3926 throws IllegalAccessException { 3927 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField); 3928 } 3929 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 3930 Class<?> refc, MemberName getField, 3931 MemberName putField) throws IllegalAccessException { 3932 assert getField.isStatic() == putField.isStatic(); 3933 assert getField.isGetter() && putField.isSetter(); 3934 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 3935 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 3936 3937 checkField(getRefKind, refc, getField); 3938 3939 if (!putField.isFinal()) { 3940 // A VarHandle does not support updates to final fields, any 3941 // such VarHandle to a final field will be read-only and 3942 // therefore the following write-based accessibility checks are 3943 // only required for non-final fields 3944 checkField(putRefKind, refc, putField); 3945 } 3946 3947 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 3948 restrictProtectedReceiver(getField)); 3949 if (doRestrict) { 3950 assert !getField.isStatic(); 3951 // receiver type of VarHandle is too wide; narrow to caller 3952 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 3953 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 3954 } 3955 refc = lookupClass(); 3956 } 3957 return VarHandles.makeFieldHandle(getField, refc, 3958 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 3959 } 3960 /** Check access and get the requested constructor. */ 3961 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3962 return getDirectConstructorCommon(refc, ctor); 3963 } 3964 /** Common code for all constructors; do not call directly except from immediately above. */ 3965 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3966 assert(ctor.isConstructor()); 3967 checkAccess(REF_newInvokeSpecial, refc, ctor); 3968 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3969 return DirectMethodHandle.make(ctor).setVarargs(ctor); 3970 } 3971 3972 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 3973 */ 3974 /*non-public*/ 3975 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 3976 throws ReflectiveOperationException { 3977 if (!(type instanceof Class || type instanceof MethodType)) 3978 throw new InternalError("unresolved MemberName"); 3979 MemberName member = new MemberName(refKind, defc, name, type); 3980 MethodHandle mh = LOOKASIDE_TABLE.get(member); 3981 if (mh != null) { 3982 checkSymbolicClass(defc); 3983 return mh; 3984 } 3985 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 3986 // Treat MethodHandle.invoke and invokeExact specially. 3987 mh = findVirtualForMH(member.getName(), member.getMethodType()); 3988 if (mh != null) { 3989 return mh; 3990 } 3991 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 3992 // Treat signature-polymorphic methods on VarHandle specially. 3993 mh = findVirtualForVH(member.getName(), member.getMethodType()); 3994 if (mh != null) { 3995 return mh; 3996 } 3997 } 3998 MemberName resolved = resolveOrFail(refKind, member); 3999 mh = getDirectMethodForConstant(refKind, defc, resolved); 4000 if (mh instanceof DirectMethodHandle dmh 4001 && canBeCached(refKind, defc, resolved)) { 4002 MemberName key = mh.internalMemberName(); 4003 if (key != null) { 4004 key = key.asNormalOriginal(); 4005 } 4006 if (member.equals(key)) { // better safe than sorry 4007 LOOKASIDE_TABLE.put(key, dmh); 4008 } 4009 } 4010 return mh; 4011 } 4012 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4013 if (refKind == REF_invokeSpecial) { 4014 return false; 4015 } 4016 if (!Modifier.isPublic(defc.getModifiers()) || 4017 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4018 !member.isPublic() || 4019 member.isCallerSensitive()) { 4020 return false; 4021 } 4022 ClassLoader loader = defc.getClassLoader(); 4023 if (loader != null) { 4024 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4025 boolean found = false; 4026 while (sysl != null) { 4027 if (loader == sysl) { found = true; break; } 4028 sysl = sysl.getParent(); 4029 } 4030 if (!found) { 4031 return false; 4032 } 4033 } 4034 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4035 new MemberName(refKind, defc, member.getName(), member.getType())); 4036 if (resolved2 == null) { 4037 return false; 4038 } 4039 return true; 4040 } 4041 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4042 throws ReflectiveOperationException { 4043 if (MethodHandleNatives.refKindIsField(refKind)) { 4044 return getDirectField(refKind, defc, member); 4045 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4046 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member)); 4047 } else if (refKind == REF_newInvokeSpecial) { 4048 return getDirectConstructor(defc, member); 4049 } 4050 // oops 4051 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4052 } 4053 4054 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4055 } 4056 4057 /** 4058 * Produces a method handle constructing arrays of a desired type, 4059 * as if by the {@code anewarray} bytecode. 4060 * The return type of the method handle will be the array type. 4061 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4062 * 4063 * <p> If the returned method handle is invoked with a negative 4064 * array size, a {@code NegativeArraySizeException} will be thrown. 4065 * 4066 * @param arrayClass an array type 4067 * @return a method handle which can create arrays of the given type 4068 * @throws NullPointerException if the argument is {@code null} 4069 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4070 * @see java.lang.reflect.Array#newInstance(Class, int) 4071 * @jvms 6.5 {@code anewarray} Instruction 4072 * @since 9 4073 */ 4074 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4075 if (!arrayClass.isArray()) { 4076 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4077 } 4078 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4079 bindTo(arrayClass.getComponentType()); 4080 return ani.asType(ani.type().changeReturnType(arrayClass)); 4081 } 4082 4083 /** 4084 * Produces a method handle returning the length of an array, 4085 * as if by the {@code arraylength} bytecode. 4086 * The type of the method handle will have {@code int} as return type, 4087 * and its sole argument will be the array type. 4088 * 4089 * <p> If the returned method handle is invoked with a {@code null} 4090 * array reference, a {@code NullPointerException} will be thrown. 4091 * 4092 * @param arrayClass an array type 4093 * @return a method handle which can retrieve the length of an array of the given array type 4094 * @throws NullPointerException if the argument is {@code null} 4095 * @throws IllegalArgumentException if arrayClass is not an array type 4096 * @jvms 6.5 {@code arraylength} Instruction 4097 * @since 9 4098 */ 4099 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4100 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4101 } 4102 4103 /** 4104 * Produces a method handle giving read access to elements of an array, 4105 * as if by the {@code aaload} bytecode. 4106 * The type of the method handle will have a return type of the array's 4107 * element type. Its first argument will be the array type, 4108 * and the second will be {@code int}. 4109 * 4110 * <p> When the returned method handle is invoked, 4111 * the array reference and array index are checked. 4112 * A {@code NullPointerException} will be thrown if the array reference 4113 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4114 * thrown if the index is negative or if it is greater than or equal to 4115 * the length of the array. 4116 * 4117 * @param arrayClass an array type 4118 * @return a method handle which can load values from the given array type 4119 * @throws NullPointerException if the argument is null 4120 * @throws IllegalArgumentException if arrayClass is not an array type 4121 * @jvms 6.5 {@code aaload} Instruction 4122 */ 4123 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4124 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4125 } 4126 4127 /** 4128 * Produces a method handle giving write access to elements of an array, 4129 * as if by the {@code astore} bytecode. 4130 * The type of the method handle will have a void return type. 4131 * Its last argument will be the array's element type. 4132 * The first and second arguments will be the array type and int. 4133 * 4134 * <p> When the returned method handle is invoked, 4135 * the array reference and array index are checked. 4136 * A {@code NullPointerException} will be thrown if the array reference 4137 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4138 * thrown if the index is negative or if it is greater than or equal to 4139 * the length of the array. 4140 * 4141 * @param arrayClass the class of an array 4142 * @return a method handle which can store values into the array type 4143 * @throws NullPointerException if the argument is null 4144 * @throws IllegalArgumentException if arrayClass is not an array type 4145 * @jvms 6.5 {@code aastore} Instruction 4146 */ 4147 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4148 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4149 } 4150 4151 /** 4152 * Produces a VarHandle giving access to elements of an array of type 4153 * {@code arrayClass}. The VarHandle's variable type is the component type 4154 * of {@code arrayClass} and the list of coordinate types is 4155 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4156 * corresponds to an argument that is an index into an array. 4157 * <p> 4158 * Certain access modes of the returned VarHandle are unsupported under 4159 * the following conditions: 4160 * <ul> 4161 * <li>if the component type is anything other than {@code byte}, 4162 * {@code short}, {@code char}, {@code int}, {@code long}, 4163 * {@code float}, or {@code double} then numeric atomic update access 4164 * modes are unsupported. 4165 * <li>if the component type is anything other than {@code boolean}, 4166 * {@code byte}, {@code short}, {@code char}, {@code int} or 4167 * {@code long} then bitwise atomic update access modes are 4168 * unsupported. 4169 * </ul> 4170 * <p> 4171 * If the component type is {@code float} or {@code double} then numeric 4172 * and atomic update access modes compare values using their bitwise 4173 * representation (see {@link Float#floatToRawIntBits} and 4174 * {@link Double#doubleToRawLongBits}, respectively). 4175 * 4176 * <p> When the returned {@code VarHandle} is invoked, 4177 * the array reference and array index are checked. 4178 * A {@code NullPointerException} will be thrown if the array reference 4179 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4180 * thrown if the index is negative or if it is greater than or equal to 4181 * the length of the array. 4182 * 4183 * @apiNote 4184 * Bitwise comparison of {@code float} values or {@code double} values, 4185 * as performed by the numeric and atomic update access modes, differ 4186 * from the primitive {@code ==} operator and the {@link Float#equals} 4187 * and {@link Double#equals} methods, specifically with respect to 4188 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4189 * Care should be taken when performing a compare and set or a compare 4190 * and exchange operation with such values since the operation may 4191 * unexpectedly fail. 4192 * There are many possible NaN values that are considered to be 4193 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4194 * provided by Java can distinguish between them. Operation failure can 4195 * occur if the expected or witness value is a NaN value and it is 4196 * transformed (perhaps in a platform specific manner) into another NaN 4197 * value, and thus has a different bitwise representation (see 4198 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4199 * details). 4200 * The values {@code -0.0} and {@code +0.0} have different bitwise 4201 * representations but are considered equal when using the primitive 4202 * {@code ==} operator. Operation failure can occur if, for example, a 4203 * numeric algorithm computes an expected value to be say {@code -0.0} 4204 * and previously computed the witness value to be say {@code +0.0}. 4205 * @param arrayClass the class of an array, of type {@code T[]} 4206 * @return a VarHandle giving access to elements of an array 4207 * @throws NullPointerException if the arrayClass is null 4208 * @throws IllegalArgumentException if arrayClass is not an array type 4209 * @since 9 4210 */ 4211 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4212 return VarHandles.makeArrayElementHandle(arrayClass); 4213 } 4214 4215 /** 4216 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4217 * viewed as if it were a different primitive array type, such as 4218 * {@code int[]} or {@code long[]}. 4219 * The VarHandle's variable type is the component type of 4220 * {@code viewArrayClass} and the list of coordinate types is 4221 * {@code (byte[], int)}, where the {@code int} coordinate type 4222 * corresponds to an argument that is an index into a {@code byte[]} array. 4223 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4224 * array, composing bytes to or from a value of the component type of 4225 * {@code viewArrayClass} according to the given endianness. 4226 * <p> 4227 * The supported component types (variables types) are {@code short}, 4228 * {@code char}, {@code int}, {@code long}, {@code float} and 4229 * {@code double}. 4230 * <p> 4231 * Access of bytes at a given index will result in an 4232 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4233 * or greater than the {@code byte[]} array length minus the size (in bytes) 4234 * of {@code T}. 4235 * <p> 4236 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4237 * access modes are supported by the returned var handle. For all other access modes, an 4238 * {@link UnsupportedOperationException} will be thrown. 4239 * 4240 * @apiNote if access modes other than plain access are required, clients should 4241 * consider using off-heap memory through 4242 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4243 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4244 * or memory segments backed by a 4245 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4246 * for which stronger alignment guarantees can be made. 4247 * 4248 * @param viewArrayClass the view array class, with a component type of 4249 * type {@code T} 4250 * @param byteOrder the endianness of the view array elements, as 4251 * stored in the underlying {@code byte} array 4252 * @return a VarHandle giving access to elements of a {@code byte[]} array 4253 * viewed as if elements corresponding to the components type of the view 4254 * array class 4255 * @throws NullPointerException if viewArrayClass or byteOrder is null 4256 * @throws IllegalArgumentException if viewArrayClass is not an array type 4257 * @throws UnsupportedOperationException if the component type of 4258 * viewArrayClass is not supported as a variable type 4259 * @since 9 4260 */ 4261 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4262 ByteOrder byteOrder) throws IllegalArgumentException { 4263 Objects.requireNonNull(byteOrder); 4264 return VarHandles.byteArrayViewHandle(viewArrayClass, 4265 byteOrder == ByteOrder.BIG_ENDIAN); 4266 } 4267 4268 /** 4269 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4270 * viewed as if it were an array of elements of a different primitive 4271 * component type to that of {@code byte}, such as {@code int[]} or 4272 * {@code long[]}. 4273 * The VarHandle's variable type is the component type of 4274 * {@code viewArrayClass} and the list of coordinate types is 4275 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4276 * corresponds to an argument that is an index into a {@code byte[]} array. 4277 * The returned VarHandle accesses bytes at an index in a 4278 * {@code ByteBuffer}, composing bytes to or from a value of the component 4279 * type of {@code viewArrayClass} according to the given endianness. 4280 * <p> 4281 * The supported component types (variables types) are {@code short}, 4282 * {@code char}, {@code int}, {@code long}, {@code float} and 4283 * {@code double}. 4284 * <p> 4285 * Access will result in a {@code ReadOnlyBufferException} for anything 4286 * other than the read access modes if the {@code ByteBuffer} is read-only. 4287 * <p> 4288 * Access of bytes at a given index will result in an 4289 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4290 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4291 * {@code T}. 4292 * <p> 4293 * For heap byte buffers, access is always unaligned. As a result, only the plain 4294 * {@linkplain VarHandle.AccessMode#GET get} 4295 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4296 * returned var handle. For all other access modes, an {@link IllegalStateException} 4297 * will be thrown. 4298 * <p> 4299 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4300 * with respect to the underlying memory address, {@code A} say, associated 4301 * with the {@code ByteBuffer} and index. 4302 * If access is misaligned then access for anything other than the 4303 * {@code get} and {@code set} access modes will result in an 4304 * {@code IllegalStateException}. In such cases atomic access is only 4305 * guaranteed with respect to the largest power of two that divides the GCD 4306 * of {@code A} and the size (in bytes) of {@code T}. 4307 * If access is aligned then following access modes are supported and are 4308 * guaranteed to support atomic access: 4309 * <ul> 4310 * <li>read write access modes for all {@code T}. Access modes {@code get} 4311 * and {@code set} for {@code long} and {@code double} are supported but 4312 * have no atomicity guarantee, as described in Section {@jls 17.7} of 4313 * <cite>The Java Language Specification</cite>. 4314 * <li>atomic update access modes for {@code int}, {@code long}, 4315 * {@code float} or {@code double}. 4316 * (Future major platform releases of the JDK may support additional 4317 * types for certain currently unsupported access modes.) 4318 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4319 * (Future major platform releases of the JDK may support additional 4320 * numeric types for certain currently unsupported access modes.) 4321 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4322 * (Future major platform releases of the JDK may support additional 4323 * numeric types for certain currently unsupported access modes.) 4324 * </ul> 4325 * <p> 4326 * Misaligned access, and therefore atomicity guarantees, may be determined 4327 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4328 * {@code index}, {@code T} and its corresponding boxed type, 4329 * {@code T_BOX}, as follows: 4330 * <pre>{@code 4331 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4332 * ByteBuffer bb = ... 4333 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4334 * boolean isMisaligned = misalignedAtIndex != 0; 4335 * }</pre> 4336 * <p> 4337 * If the variable type is {@code float} or {@code double} then atomic 4338 * update access modes compare values using their bitwise representation 4339 * (see {@link Float#floatToRawIntBits} and 4340 * {@link Double#doubleToRawLongBits}, respectively). 4341 * @param viewArrayClass the view array class, with a component type of 4342 * type {@code T} 4343 * @param byteOrder the endianness of the view array elements, as 4344 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4345 * endianness of a {@code ByteBuffer}) 4346 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4347 * viewed as if elements corresponding to the components type of the view 4348 * array class 4349 * @throws NullPointerException if viewArrayClass or byteOrder is null 4350 * @throws IllegalArgumentException if viewArrayClass is not an array type 4351 * @throws UnsupportedOperationException if the component type of 4352 * viewArrayClass is not supported as a variable type 4353 * @since 9 4354 */ 4355 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4356 ByteOrder byteOrder) throws IllegalArgumentException { 4357 Objects.requireNonNull(byteOrder); 4358 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4359 byteOrder == ByteOrder.BIG_ENDIAN); 4360 } 4361 4362 4363 //--- method handle invocation (reflective style) 4364 4365 /** 4366 * Produces a method handle which will invoke any method handle of the 4367 * given {@code type}, with a given number of trailing arguments replaced by 4368 * a single trailing {@code Object[]} array. 4369 * The resulting invoker will be a method handle with the following 4370 * arguments: 4371 * <ul> 4372 * <li>a single {@code MethodHandle} target 4373 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4374 * <li>an {@code Object[]} array containing trailing arguments 4375 * </ul> 4376 * <p> 4377 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4378 * the indicated {@code type}. 4379 * That is, if the target is exactly of the given {@code type}, it will behave 4380 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4381 * is used to convert the target to the required {@code type}. 4382 * <p> 4383 * The type of the returned invoker will not be the given {@code type}, but rather 4384 * will have all parameters except the first {@code leadingArgCount} 4385 * replaced by a single array of type {@code Object[]}, which will be 4386 * the final parameter. 4387 * <p> 4388 * Before invoking its target, the invoker will spread the final array, apply 4389 * reference casts as necessary, and unbox and widen primitive arguments. 4390 * If, when the invoker is called, the supplied array argument does 4391 * not have the correct number of elements, the invoker will throw 4392 * an {@link IllegalArgumentException} instead of invoking the target. 4393 * <p> 4394 * This method is equivalent to the following code (though it may be more efficient): 4395 * {@snippet lang="java" : 4396 MethodHandle invoker = MethodHandles.invoker(type); 4397 int spreadArgCount = type.parameterCount() - leadingArgCount; 4398 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4399 return invoker; 4400 * } 4401 * This method throws no reflective exceptions. 4402 * @param type the desired target type 4403 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4404 * @return a method handle suitable for invoking any method handle of the given type 4405 * @throws NullPointerException if {@code type} is null 4406 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4407 * the range from 0 to {@code type.parameterCount()} inclusive, 4408 * or if the resulting method handle's type would have 4409 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4410 */ 4411 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4412 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4413 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4414 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4415 return type.invokers().spreadInvoker(leadingArgCount); 4416 } 4417 4418 /** 4419 * Produces a special <em>invoker method handle</em> which can be used to 4420 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4421 * The resulting invoker will have a type which is 4422 * exactly equal to the desired type, except that it will accept 4423 * an additional leading argument of type {@code MethodHandle}. 4424 * <p> 4425 * This method is equivalent to the following code (though it may be more efficient): 4426 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4427 * 4428 * <p style="font-size:smaller;"> 4429 * <em>Discussion:</em> 4430 * Invoker method handles can be useful when working with variable method handles 4431 * of unknown types. 4432 * For example, to emulate an {@code invokeExact} call to a variable method 4433 * handle {@code M}, extract its type {@code T}, 4434 * look up the invoker method {@code X} for {@code T}, 4435 * and call the invoker method, as {@code X.invoke(T, A...)}. 4436 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4437 * is unknown.) 4438 * If spreading, collecting, or other argument transformations are required, 4439 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4440 * method handle values, as long as they are compatible with the type of {@code X}. 4441 * <p style="font-size:smaller;"> 4442 * <em>(Note: The invoker method is not available via the Core Reflection API. 4443 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4444 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4445 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4446 * <p> 4447 * This method throws no reflective exceptions. 4448 * @param type the desired target type 4449 * @return a method handle suitable for invoking any method handle of the given type 4450 * @throws IllegalArgumentException if the resulting method handle's type would have 4451 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4452 */ 4453 public static MethodHandle exactInvoker(MethodType type) { 4454 return type.invokers().exactInvoker(); 4455 } 4456 4457 /** 4458 * Produces a special <em>invoker method handle</em> which can be used to 4459 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4460 * The resulting invoker will have a type which is 4461 * exactly equal to the desired type, except that it will accept 4462 * an additional leading argument of type {@code MethodHandle}. 4463 * <p> 4464 * Before invoking its target, if the target differs from the expected type, 4465 * the invoker will apply reference casts as 4466 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4467 * Similarly, the return value will be converted as necessary. 4468 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4469 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4470 * <p> 4471 * This method is equivalent to the following code (though it may be more efficient): 4472 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4473 * <p style="font-size:smaller;"> 4474 * <em>Discussion:</em> 4475 * A {@linkplain MethodType#genericMethodType general method type} is one which 4476 * mentions only {@code Object} arguments and return values. 4477 * An invoker for such a type is capable of calling any method handle 4478 * of the same arity as the general type. 4479 * <p style="font-size:smaller;"> 4480 * <em>(Note: The invoker method is not available via the Core Reflection API. 4481 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4482 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4483 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4484 * <p> 4485 * This method throws no reflective exceptions. 4486 * @param type the desired target type 4487 * @return a method handle suitable for invoking any method handle convertible to the given type 4488 * @throws IllegalArgumentException if the resulting method handle's type would have 4489 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4490 */ 4491 public static MethodHandle invoker(MethodType type) { 4492 return type.invokers().genericInvoker(); 4493 } 4494 4495 /** 4496 * Produces a special <em>invoker method handle</em> which can be used to 4497 * invoke a signature-polymorphic access mode method on any VarHandle whose 4498 * associated access mode type is compatible with the given type. 4499 * The resulting invoker will have a type which is exactly equal to the 4500 * desired given type, except that it will accept an additional leading 4501 * argument of type {@code VarHandle}. 4502 * 4503 * @param accessMode the VarHandle access mode 4504 * @param type the desired target type 4505 * @return a method handle suitable for invoking an access mode method of 4506 * any VarHandle whose access mode type is of the given type. 4507 * @since 9 4508 */ 4509 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4510 return type.invokers().varHandleMethodExactInvoker(accessMode); 4511 } 4512 4513 /** 4514 * Produces a special <em>invoker method handle</em> which can be used to 4515 * invoke a signature-polymorphic access mode method on any VarHandle whose 4516 * associated access mode type is compatible with the given type. 4517 * The resulting invoker will have a type which is exactly equal to the 4518 * desired given type, except that it will accept an additional leading 4519 * argument of type {@code VarHandle}. 4520 * <p> 4521 * Before invoking its target, if the access mode type differs from the 4522 * desired given type, the invoker will apply reference casts as necessary 4523 * and box, unbox, or widen primitive values, as if by 4524 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4525 * converted as necessary. 4526 * <p> 4527 * This method is equivalent to the following code (though it may be more 4528 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4529 * 4530 * @param accessMode the VarHandle access mode 4531 * @param type the desired target type 4532 * @return a method handle suitable for invoking an access mode method of 4533 * any VarHandle whose access mode type is convertible to the given 4534 * type. 4535 * @since 9 4536 */ 4537 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4538 return type.invokers().varHandleMethodInvoker(accessMode); 4539 } 4540 4541 /*non-public*/ 4542 static MethodHandle basicInvoker(MethodType type) { 4543 return type.invokers().basicInvoker(); 4544 } 4545 4546 //--- method handle modification (creation from other method handles) 4547 4548 /** 4549 * Produces a method handle which adapts the type of the 4550 * given method handle to a new type by pairwise argument and return type conversion. 4551 * The original type and new type must have the same number of arguments. 4552 * The resulting method handle is guaranteed to report a type 4553 * which is equal to the desired new type. 4554 * <p> 4555 * If the original type and new type are equal, returns target. 4556 * <p> 4557 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4558 * and some additional conversions are also applied if those conversions fail. 4559 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4560 * if possible, before or instead of any conversions done by {@code asType}: 4561 * <ul> 4562 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4563 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4564 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4565 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4566 * the boolean is converted to a byte value, 1 for true, 0 for false. 4567 * (This treatment follows the usage of the bytecode verifier.) 4568 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4569 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4570 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4571 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4572 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4573 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4574 * widening and/or narrowing.) 4575 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4576 * conversion will be applied at runtime, possibly followed 4577 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4578 * possibly followed by a conversion from byte to boolean by testing 4579 * the low-order bit. 4580 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4581 * and if the reference is null at runtime, a zero value is introduced. 4582 * </ul> 4583 * @param target the method handle to invoke after arguments are retyped 4584 * @param newType the expected type of the new method handle 4585 * @return a method handle which delegates to the target after performing 4586 * any necessary argument conversions, and arranges for any 4587 * necessary return value conversions 4588 * @throws NullPointerException if either argument is null 4589 * @throws WrongMethodTypeException if the conversion cannot be made 4590 * @see MethodHandle#asType 4591 */ 4592 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4593 explicitCastArgumentsChecks(target, newType); 4594 // use the asTypeCache when possible: 4595 MethodType oldType = target.type(); 4596 if (oldType == newType) return target; 4597 if (oldType.explicitCastEquivalentToAsType(newType)) { 4598 return target.asFixedArity().asType(newType); 4599 } 4600 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4601 } 4602 4603 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4604 if (target.type().parameterCount() != newType.parameterCount()) { 4605 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4606 } 4607 } 4608 4609 /** 4610 * Produces a method handle which adapts the calling sequence of the 4611 * given method handle to a new type, by reordering the arguments. 4612 * The resulting method handle is guaranteed to report a type 4613 * which is equal to the desired new type. 4614 * <p> 4615 * The given array controls the reordering. 4616 * Call {@code #I} the number of incoming parameters (the value 4617 * {@code newType.parameterCount()}, and call {@code #O} the number 4618 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4619 * Then the length of the reordering array must be {@code #O}, 4620 * and each element must be a non-negative number less than {@code #I}. 4621 * For every {@code N} less than {@code #O}, the {@code N}-th 4622 * outgoing argument will be taken from the {@code I}-th incoming 4623 * argument, where {@code I} is {@code reorder[N]}. 4624 * <p> 4625 * No argument or return value conversions are applied. 4626 * The type of each incoming argument, as determined by {@code newType}, 4627 * must be identical to the type of the corresponding outgoing parameter 4628 * or parameters in the target method handle. 4629 * The return type of {@code newType} must be identical to the return 4630 * type of the original target. 4631 * <p> 4632 * The reordering array need not specify an actual permutation. 4633 * An incoming argument will be duplicated if its index appears 4634 * more than once in the array, and an incoming argument will be dropped 4635 * if its index does not appear in the array. 4636 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4637 * incoming arguments which are not mentioned in the reordering array 4638 * may be of any type, as determined only by {@code newType}. 4639 * {@snippet lang="java" : 4640 import static java.lang.invoke.MethodHandles.*; 4641 import static java.lang.invoke.MethodType.*; 4642 ... 4643 MethodType intfn1 = methodType(int.class, int.class); 4644 MethodType intfn2 = methodType(int.class, int.class, int.class); 4645 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4646 assert(sub.type().equals(intfn2)); 4647 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4648 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4649 assert((int)rsub.invokeExact(1, 100) == 99); 4650 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4651 assert(add.type().equals(intfn2)); 4652 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4653 assert(twice.type().equals(intfn1)); 4654 assert((int)twice.invokeExact(21) == 42); 4655 * } 4656 * <p> 4657 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4658 * variable-arity method handle}, even if the original target method handle was. 4659 * @param target the method handle to invoke after arguments are reordered 4660 * @param newType the expected type of the new method handle 4661 * @param reorder an index array which controls the reordering 4662 * @return a method handle which delegates to the target after it 4663 * drops unused arguments and moves and/or duplicates the other arguments 4664 * @throws NullPointerException if any argument is null 4665 * @throws IllegalArgumentException if the index array length is not equal to 4666 * the arity of the target, or if any index array element 4667 * not a valid index for a parameter of {@code newType}, 4668 * or if two corresponding parameter types in 4669 * {@code target.type()} and {@code newType} are not identical, 4670 */ 4671 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4672 reorder = reorder.clone(); // get a private copy 4673 MethodType oldType = target.type(); 4674 permuteArgumentChecks(reorder, newType, oldType); 4675 // first detect dropped arguments and handle them separately 4676 int[] originalReorder = reorder; 4677 BoundMethodHandle result = target.rebind(); 4678 LambdaForm form = result.form; 4679 int newArity = newType.parameterCount(); 4680 // Normalize the reordering into a real permutation, 4681 // by removing duplicates and adding dropped elements. 4682 // This somewhat improves lambda form caching, as well 4683 // as simplifying the transform by breaking it up into steps. 4684 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4685 if (ddIdx > 0) { 4686 // We found a duplicated entry at reorder[ddIdx]. 4687 // Example: (x,y,z)->asList(x,y,z) 4688 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4689 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4690 // The starred element corresponds to the argument 4691 // deleted by the dupArgumentForm transform. 4692 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4693 boolean killFirst = false; 4694 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4695 // Set killFirst if the dup is larger than an intervening position. 4696 // This will remove at least one inversion from the permutation. 4697 if (dupVal > val) killFirst = true; 4698 } 4699 if (!killFirst) { 4700 srcPos = dstPos; 4701 dstPos = ddIdx; 4702 } 4703 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4704 assert (reorder[srcPos] == reorder[dstPos]); 4705 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4706 // contract the reordering by removing the element at dstPos 4707 int tailPos = dstPos + 1; 4708 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4709 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4710 } else { 4711 int dropVal = ~ddIdx, insPos = 0; 4712 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4713 // Find first element of reorder larger than dropVal. 4714 // This is where we will insert the dropVal. 4715 insPos += 1; 4716 } 4717 Class<?> ptype = newType.parameterType(dropVal); 4718 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4719 oldType = oldType.insertParameterTypes(insPos, ptype); 4720 // expand the reordering by inserting an element at insPos 4721 int tailPos = insPos + 1; 4722 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4723 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4724 reorder[insPos] = dropVal; 4725 } 4726 assert (permuteArgumentChecks(reorder, newType, oldType)); 4727 } 4728 assert (reorder.length == newArity); // a perfect permutation 4729 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4730 form = form.editor().permuteArgumentsForm(1, reorder); 4731 if (newType == result.type() && form == result.internalForm()) 4732 return result; 4733 return result.copyWith(newType, form); 4734 } 4735 4736 /** 4737 * Return an indication of any duplicate or omission in reorder. 4738 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4739 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4740 * Otherwise, return zero. 4741 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4742 */ 4743 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4744 final int BIT_LIMIT = 63; // max number of bits in bit mask 4745 if (newArity < BIT_LIMIT) { 4746 long mask = 0; 4747 for (int i = 0; i < reorder.length; i++) { 4748 int arg = reorder[i]; 4749 if (arg >= newArity) { 4750 return reorder.length; 4751 } 4752 long bit = 1L << arg; 4753 if ((mask & bit) != 0) { 4754 return i; // >0 indicates a dup 4755 } 4756 mask |= bit; 4757 } 4758 if (mask == (1L << newArity) - 1) { 4759 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4760 return 0; 4761 } 4762 // find first zero 4763 long zeroBit = Long.lowestOneBit(~mask); 4764 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4765 assert(zeroPos <= newArity); 4766 if (zeroPos == newArity) { 4767 return 0; 4768 } 4769 return ~zeroPos; 4770 } else { 4771 // same algorithm, different bit set 4772 BitSet mask = new BitSet(newArity); 4773 for (int i = 0; i < reorder.length; i++) { 4774 int arg = reorder[i]; 4775 if (arg >= newArity) { 4776 return reorder.length; 4777 } 4778 if (mask.get(arg)) { 4779 return i; // >0 indicates a dup 4780 } 4781 mask.set(arg); 4782 } 4783 int zeroPos = mask.nextClearBit(0); 4784 assert(zeroPos <= newArity); 4785 if (zeroPos == newArity) { 4786 return 0; 4787 } 4788 return ~zeroPos; 4789 } 4790 } 4791 4792 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4793 if (newType.returnType() != oldType.returnType()) 4794 throw newIllegalArgumentException("return types do not match", 4795 oldType, newType); 4796 if (reorder.length != oldType.parameterCount()) 4797 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 4798 oldType, Arrays.toString(reorder)); 4799 4800 int limit = newType.parameterCount(); 4801 for (int j = 0; j < reorder.length; j++) { 4802 int i = reorder[j]; 4803 if (i < 0 || i >= limit) { 4804 throw newIllegalArgumentException("index is out of bounds for new type", 4805 i, newType); 4806 } 4807 Class<?> src = newType.parameterType(i); 4808 Class<?> dst = oldType.parameterType(j); 4809 if (src != dst) 4810 throw newIllegalArgumentException("parameter types do not match after reorder", 4811 oldType, newType); 4812 } 4813 return true; 4814 } 4815 4816 /** 4817 * Produces a method handle of the requested return type which returns the given 4818 * constant value every time it is invoked. 4819 * <p> 4820 * Before the method handle is returned, the passed-in value is converted to the requested type. 4821 * If the requested type is primitive, widening primitive conversions are attempted, 4822 * else reference conversions are attempted. 4823 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 4824 * @param type the return type of the desired method handle 4825 * @param value the value to return 4826 * @return a method handle of the given return type and no arguments, which always returns the given value 4827 * @throws NullPointerException if the {@code type} argument is null 4828 * @throws ClassCastException if the value cannot be converted to the required return type 4829 * @throws IllegalArgumentException if the given type is {@code void.class} 4830 */ 4831 public static MethodHandle constant(Class<?> type, Object value) { 4832 if (Objects.requireNonNull(type) == void.class) 4833 throw newIllegalArgumentException("void type"); 4834 return MethodHandleImpl.makeConstantReturning(type, value); 4835 } 4836 4837 /** 4838 * Produces a method handle which returns its sole argument when invoked. 4839 * @param type the type of the sole parameter and return value of the desired method handle 4840 * @return a unary method handle which accepts and returns the given type 4841 * @throws NullPointerException if the argument is null 4842 * @throws IllegalArgumentException if the given type is {@code void.class} 4843 */ 4844 public static MethodHandle identity(Class<?> type) { 4845 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 4846 int pos = btw.ordinal(); 4847 MethodHandle ident = IDENTITY_MHS[pos]; 4848 if (ident == null) { 4849 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 4850 } 4851 if (ident.type().returnType() == type) 4852 return ident; 4853 // something like identity(Foo.class); do not bother to intern these 4854 assert (btw == Wrapper.OBJECT); 4855 return makeIdentity(type); 4856 } 4857 4858 /** 4859 * Produces a constant method handle of the requested return type which 4860 * returns the default value for that type every time it is invoked. 4861 * The resulting constant method handle will have no side effects. 4862 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 4863 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 4864 * since {@code explicitCastArguments} converts {@code null} to default values. 4865 * @param type the expected return type of the desired method handle 4866 * @return a constant method handle that takes no arguments 4867 * and returns the default value of the given type (or void, if the type is void) 4868 * @throws NullPointerException if the argument is null 4869 * @see MethodHandles#constant 4870 * @see MethodHandles#empty 4871 * @see MethodHandles#explicitCastArguments 4872 * @since 9 4873 */ 4874 public static MethodHandle zero(Class<?> type) { 4875 Objects.requireNonNull(type); 4876 return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type)) 4877 : MethodHandleImpl.makeConstantReturning(type, null); 4878 } 4879 4880 private static MethodHandle identityOrVoid(Class<?> type) { 4881 return type == void.class ? zero(type) : identity(type); 4882 } 4883 4884 /** 4885 * Produces a method handle of the requested type which ignores any arguments, does nothing, 4886 * and returns a suitable default depending on the return type. 4887 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 4888 * <p>The returned method handle is equivalent to 4889 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 4890 * 4891 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 4892 * {@code guardWithTest(pred, target, empty(target.type())}. 4893 * @param type the type of the desired method handle 4894 * @return a constant method handle of the given type, which returns a default value of the given return type 4895 * @throws NullPointerException if the argument is null 4896 * @see MethodHandles#zero(Class) 4897 * @see MethodHandles#constant 4898 * @since 9 4899 */ 4900 public static MethodHandle empty(MethodType type) { 4901 Objects.requireNonNull(type); 4902 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 4903 } 4904 4905 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 4906 private static MethodHandle makeIdentity(Class<?> ptype) { 4907 MethodType mtype = methodType(ptype, ptype); // throws IAE for void 4908 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 4909 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 4910 } 4911 4912 private static MethodHandle primitiveZero(Wrapper w) { 4913 assert w != Wrapper.OBJECT : w; 4914 int pos = w.ordinal(); 4915 MethodHandle mh = PRIMITIVE_ZERO_MHS[pos]; 4916 if (mh == null) { 4917 mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w)); 4918 } 4919 assert (mh.type().returnType() == w.primitiveType()) : mh; 4920 return mh; 4921 } 4922 4923 private static MethodHandle makePrimitiveZero(Wrapper w) { 4924 if (w == Wrapper.VOID) { 4925 var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized 4926 return SimpleMethodHandle.make(MethodType.methodType(void.class), lf); 4927 } else { 4928 return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero()); 4929 } 4930 } 4931 4932 private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 4933 4934 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 4935 // Simulate a CAS, to avoid racy duplication of results. 4936 MethodHandle prev = cache[pos]; 4937 if (prev != null) return prev; 4938 return cache[pos] = value; 4939 } 4940 4941 /** 4942 * Provides a target method handle with one or more <em>bound arguments</em> 4943 * in advance of the method handle's invocation. 4944 * The formal parameters to the target corresponding to the bound 4945 * arguments are called <em>bound parameters</em>. 4946 * Returns a new method handle which saves away the bound arguments. 4947 * When it is invoked, it receives arguments for any non-bound parameters, 4948 * binds the saved arguments to their corresponding parameters, 4949 * and calls the original target. 4950 * <p> 4951 * The type of the new method handle will drop the types for the bound 4952 * parameters from the original target type, since the new method handle 4953 * will no longer require those arguments to be supplied by its callers. 4954 * <p> 4955 * Each given argument object must match the corresponding bound parameter type. 4956 * If a bound parameter type is a primitive, the argument object 4957 * must be a wrapper, and will be unboxed to produce the primitive value. 4958 * <p> 4959 * The {@code pos} argument selects which parameters are to be bound. 4960 * It may range between zero and <i>N-L</i> (inclusively), 4961 * where <i>N</i> is the arity of the target method handle 4962 * and <i>L</i> is the length of the values array. 4963 * <p> 4964 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4965 * variable-arity method handle}, even if the original target method handle was. 4966 * @param target the method handle to invoke after the argument is inserted 4967 * @param pos where to insert the argument (zero for the first) 4968 * @param values the series of arguments to insert 4969 * @return a method handle which inserts an additional argument, 4970 * before calling the original method handle 4971 * @throws NullPointerException if the target or the {@code values} array is null 4972 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 4973 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 4974 * is the length of the values array. 4975 * @throws ClassCastException if an argument does not match the corresponding bound parameter 4976 * type. 4977 * @see MethodHandle#bindTo 4978 */ 4979 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 4980 int insCount = values.length; 4981 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 4982 if (insCount == 0) return target; 4983 BoundMethodHandle result = target.rebind(); 4984 for (int i = 0; i < insCount; i++) { 4985 Object value = values[i]; 4986 Class<?> ptype = ptypes[pos+i]; 4987 if (ptype.isPrimitive()) { 4988 result = insertArgumentPrimitive(result, pos, ptype, value); 4989 } else { 4990 value = ptype.cast(value); // throw CCE if needed 4991 result = result.bindArgumentL(pos, value); 4992 } 4993 } 4994 return result; 4995 } 4996 4997 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 4998 Class<?> ptype, Object value) { 4999 Wrapper w = Wrapper.forPrimitiveType(ptype); 5000 // perform unboxing and/or primitive conversion 5001 value = w.convert(value, ptype); 5002 return switch (w) { 5003 case INT -> result.bindArgumentI(pos, (int) value); 5004 case LONG -> result.bindArgumentJ(pos, (long) value); 5005 case FLOAT -> result.bindArgumentF(pos, (float) value); 5006 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5007 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5008 }; 5009 } 5010 5011 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5012 MethodType oldType = target.type(); 5013 int outargs = oldType.parameterCount(); 5014 int inargs = outargs - insCount; 5015 if (inargs < 0) 5016 throw newIllegalArgumentException("too many values to insert"); 5017 if (pos < 0 || pos > inargs) 5018 throw newIllegalArgumentException("no argument type to append"); 5019 return oldType.ptypes(); 5020 } 5021 5022 /** 5023 * Produces a method handle which will discard some dummy arguments 5024 * before calling some other specified <i>target</i> method handle. 5025 * The type of the new method handle will be the same as the target's type, 5026 * except it will also include the dummy argument types, 5027 * at some given position. 5028 * <p> 5029 * The {@code pos} argument may range between zero and <i>N</i>, 5030 * where <i>N</i> is the arity of the target. 5031 * If {@code pos} is zero, the dummy arguments will precede 5032 * the target's real arguments; if {@code pos} is <i>N</i> 5033 * they will come after. 5034 * <p> 5035 * <b>Example:</b> 5036 * {@snippet lang="java" : 5037 import static java.lang.invoke.MethodHandles.*; 5038 import static java.lang.invoke.MethodType.*; 5039 ... 5040 MethodHandle cat = lookup().findVirtual(String.class, 5041 "concat", methodType(String.class, String.class)); 5042 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5043 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5044 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5045 assertEquals(bigType, d0.type()); 5046 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5047 * } 5048 * <p> 5049 * This method is also equivalent to the following code: 5050 * <blockquote><pre> 5051 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5052 * </pre></blockquote> 5053 * @param target the method handle to invoke after the arguments are dropped 5054 * @param pos position of first argument to drop (zero for the leftmost) 5055 * @param valueTypes the type(s) of the argument(s) to drop 5056 * @return a method handle which drops arguments of the given types, 5057 * before calling the original method handle 5058 * @throws NullPointerException if the target is null, 5059 * or if the {@code valueTypes} list or any of its elements is null 5060 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5061 * or if {@code pos} is negative or greater than the arity of the target, 5062 * or if the new method handle's type would have too many parameters 5063 */ 5064 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5065 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5066 } 5067 5068 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5069 MethodType oldType = target.type(); // get NPE 5070 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5071 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5072 if (dropped == 0) return target; 5073 BoundMethodHandle result = target.rebind(); 5074 LambdaForm lform = result.form; 5075 int insertFormArg = 1 + pos; 5076 for (Class<?> ptype : valueTypes) { 5077 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5078 } 5079 result = result.copyWith(newType, lform); 5080 return result; 5081 } 5082 5083 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5084 int dropped = valueTypes.length; 5085 MethodType.checkSlotCount(dropped); 5086 int outargs = oldType.parameterCount(); 5087 int inargs = outargs + dropped; 5088 if (pos < 0 || pos > outargs) 5089 throw newIllegalArgumentException("no argument type to remove" 5090 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5091 ); 5092 return dropped; 5093 } 5094 5095 /** 5096 * Produces a method handle which will discard some dummy arguments 5097 * before calling some other specified <i>target</i> method handle. 5098 * The type of the new method handle will be the same as the target's type, 5099 * except it will also include the dummy argument types, 5100 * at some given position. 5101 * <p> 5102 * The {@code pos} argument may range between zero and <i>N</i>, 5103 * where <i>N</i> is the arity of the target. 5104 * If {@code pos} is zero, the dummy arguments will precede 5105 * the target's real arguments; if {@code pos} is <i>N</i> 5106 * they will come after. 5107 * @apiNote 5108 * {@snippet lang="java" : 5109 import static java.lang.invoke.MethodHandles.*; 5110 import static java.lang.invoke.MethodType.*; 5111 ... 5112 MethodHandle cat = lookup().findVirtual(String.class, 5113 "concat", methodType(String.class, String.class)); 5114 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5115 MethodHandle d0 = dropArguments(cat, 0, String.class); 5116 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5117 MethodHandle d1 = dropArguments(cat, 1, String.class); 5118 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5119 MethodHandle d2 = dropArguments(cat, 2, String.class); 5120 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5121 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5122 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5123 * } 5124 * <p> 5125 * This method is also equivalent to the following code: 5126 * <blockquote><pre> 5127 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5128 * </pre></blockquote> 5129 * @param target the method handle to invoke after the arguments are dropped 5130 * @param pos position of first argument to drop (zero for the leftmost) 5131 * @param valueTypes the type(s) of the argument(s) to drop 5132 * @return a method handle which drops arguments of the given types, 5133 * before calling the original method handle 5134 * @throws NullPointerException if the target is null, 5135 * or if the {@code valueTypes} array or any of its elements is null 5136 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5137 * or if {@code pos} is negative or greater than the arity of the target, 5138 * or if the new method handle's type would have 5139 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5140 */ 5141 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5142 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5143 } 5144 5145 /* Convenience overloads for trusting internal low-arity call-sites */ 5146 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5147 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5148 } 5149 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5150 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5151 } 5152 5153 // private version which allows caller some freedom with error handling 5154 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5155 boolean nullOnFailure) { 5156 Class<?>[] oldTypes = target.type().ptypes(); 5157 int match = oldTypes.length; 5158 if (skip != 0) { 5159 if (skip < 0 || skip > match) { 5160 throw newIllegalArgumentException("illegal skip", skip, target); 5161 } 5162 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5163 match -= skip; 5164 } 5165 Class<?>[] addTypes = newTypes; 5166 int add = addTypes.length; 5167 if (pos != 0) { 5168 if (pos < 0 || pos > add) { 5169 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5170 } 5171 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5172 add -= pos; 5173 assert(addTypes.length == add); 5174 } 5175 // Do not add types which already match the existing arguments. 5176 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5177 if (nullOnFailure) { 5178 return null; 5179 } 5180 throw newIllegalArgumentException("argument lists do not match", 5181 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5182 } 5183 addTypes = Arrays.copyOfRange(addTypes, match, add); 5184 add -= match; 5185 assert(addTypes.length == add); 5186 // newTypes: ( P*[pos], M*[match], A*[add] ) 5187 // target: ( S*[skip], M*[match] ) 5188 MethodHandle adapter = target; 5189 if (add > 0) { 5190 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5191 } 5192 // adapter: (S*[skip], M*[match], A*[add] ) 5193 if (pos > 0) { 5194 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5195 } 5196 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5197 return adapter; 5198 } 5199 5200 /** 5201 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5202 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5203 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5204 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5205 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5206 * {@link #dropArguments(MethodHandle, int, Class[])}. 5207 * <p> 5208 * The resulting handle will have the same return type as the target handle. 5209 * <p> 5210 * In more formal terms, assume these two type lists:<ul> 5211 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5212 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5213 * {@code newTypes}. 5214 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5215 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5216 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5217 * sub-list. 5218 * </ul> 5219 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5220 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5221 * {@link #dropArguments(MethodHandle, int, Class[])}. 5222 * 5223 * @apiNote 5224 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5225 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5226 * {@snippet lang="java" : 5227 import static java.lang.invoke.MethodHandles.*; 5228 import static java.lang.invoke.MethodType.*; 5229 ... 5230 ... 5231 MethodHandle h0 = constant(boolean.class, true); 5232 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5233 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5234 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5235 if (h1.type().parameterCount() < h2.type().parameterCount()) 5236 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5237 else 5238 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5239 MethodHandle h3 = guardWithTest(h0, h1, h2); 5240 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5241 * } 5242 * @param target the method handle to adapt 5243 * @param skip number of targets parameters to disregard (they will be unchanged) 5244 * @param newTypes the list of types to match {@code target}'s parameter type list to 5245 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5246 * @return a possibly adapted method handle 5247 * @throws NullPointerException if either argument is null 5248 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5249 * or if {@code skip} is negative or greater than the arity of the target, 5250 * or if {@code pos} is negative or greater than the newTypes list size, 5251 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5252 * {@code pos}. 5253 * @since 9 5254 */ 5255 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5256 Objects.requireNonNull(target); 5257 Objects.requireNonNull(newTypes); 5258 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5259 } 5260 5261 /** 5262 * Drop the return value of the target handle (if any). 5263 * The returned method handle will have a {@code void} return type. 5264 * 5265 * @param target the method handle to adapt 5266 * @return a possibly adapted method handle 5267 * @throws NullPointerException if {@code target} is null 5268 * @since 16 5269 */ 5270 public static MethodHandle dropReturn(MethodHandle target) { 5271 Objects.requireNonNull(target); 5272 MethodType oldType = target.type(); 5273 Class<?> oldReturnType = oldType.returnType(); 5274 if (oldReturnType == void.class) 5275 return target; 5276 MethodType newType = oldType.changeReturnType(void.class); 5277 BoundMethodHandle result = target.rebind(); 5278 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5279 result = result.copyWith(newType, lform); 5280 return result; 5281 } 5282 5283 /** 5284 * Adapts a target method handle by pre-processing 5285 * one or more of its arguments, each with its own unary filter function, 5286 * and then calling the target with each pre-processed argument 5287 * replaced by the result of its corresponding filter function. 5288 * <p> 5289 * The pre-processing is performed by one or more method handles, 5290 * specified in the elements of the {@code filters} array. 5291 * The first element of the filter array corresponds to the {@code pos} 5292 * argument of the target, and so on in sequence. 5293 * The filter functions are invoked in left to right order. 5294 * <p> 5295 * Null arguments in the array are treated as identity functions, 5296 * and the corresponding arguments left unchanged. 5297 * (If there are no non-null elements in the array, the original target is returned.) 5298 * Each filter is applied to the corresponding argument of the adapter. 5299 * <p> 5300 * If a filter {@code F} applies to the {@code N}th argument of 5301 * the target, then {@code F} must be a method handle which 5302 * takes exactly one argument. The type of {@code F}'s sole argument 5303 * replaces the corresponding argument type of the target 5304 * in the resulting adapted method handle. 5305 * The return type of {@code F} must be identical to the corresponding 5306 * parameter type of the target. 5307 * <p> 5308 * It is an error if there are elements of {@code filters} 5309 * (null or not) 5310 * which do not correspond to argument positions in the target. 5311 * <p><b>Example:</b> 5312 * {@snippet lang="java" : 5313 import static java.lang.invoke.MethodHandles.*; 5314 import static java.lang.invoke.MethodType.*; 5315 ... 5316 MethodHandle cat = lookup().findVirtual(String.class, 5317 "concat", methodType(String.class, String.class)); 5318 MethodHandle upcase = lookup().findVirtual(String.class, 5319 "toUpperCase", methodType(String.class)); 5320 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5321 MethodHandle f0 = filterArguments(cat, 0, upcase); 5322 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5323 MethodHandle f1 = filterArguments(cat, 1, upcase); 5324 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5325 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5326 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5327 * } 5328 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5329 * denotes the return type of both the {@code target} and resulting adapter. 5330 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5331 * of the parameters and arguments that precede and follow the filter position 5332 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5333 * values of the filtered parameters and arguments; they also represent the 5334 * return types of the {@code filter[i]} handles. The latter accept arguments 5335 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5336 * the resulting adapter. 5337 * {@snippet lang="java" : 5338 * T target(P... p, A[i]... a[i], B... b); 5339 * A[i] filter[i](V[i]); 5340 * T adapter(P... p, V[i]... v[i], B... b) { 5341 * return target(p..., filter[i](v[i])..., b...); 5342 * } 5343 * } 5344 * <p> 5345 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5346 * variable-arity method handle}, even if the original target method handle was. 5347 * 5348 * @param target the method handle to invoke after arguments are filtered 5349 * @param pos the position of the first argument to filter 5350 * @param filters method handles to call initially on filtered arguments 5351 * @return method handle which incorporates the specified argument filtering logic 5352 * @throws NullPointerException if the target is null 5353 * or if the {@code filters} array is null 5354 * @throws IllegalArgumentException if a non-null element of {@code filters} 5355 * does not match a corresponding argument type of target as described above, 5356 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5357 * or if the resulting method handle's type would have 5358 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5359 */ 5360 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5361 // In method types arguments start at index 0, while the LF 5362 // editor have the MH receiver at position 0 - adjust appropriately. 5363 final int MH_RECEIVER_OFFSET = 1; 5364 filterArgumentsCheckArity(target, pos, filters); 5365 MethodHandle adapter = target; 5366 5367 // keep track of currently matched filters, as to optimize repeated filters 5368 int index = 0; 5369 int[] positions = new int[filters.length]; 5370 MethodHandle filter = null; 5371 5372 // process filters in reverse order so that the invocation of 5373 // the resulting adapter will invoke the filters in left-to-right order 5374 for (int i = filters.length - 1; i >= 0; --i) { 5375 MethodHandle newFilter = filters[i]; 5376 if (newFilter == null) continue; // ignore null elements of filters 5377 5378 // flush changes on update 5379 if (filter != newFilter) { 5380 if (filter != null) { 5381 if (index > 1) { 5382 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5383 } else { 5384 adapter = filterArgument(adapter, positions[0] - 1, filter); 5385 } 5386 } 5387 filter = newFilter; 5388 index = 0; 5389 } 5390 5391 filterArgumentChecks(target, pos + i, newFilter); 5392 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5393 } 5394 if (index > 1) { 5395 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5396 } else if (index == 1) { 5397 adapter = filterArgument(adapter, positions[0] - 1, filter); 5398 } 5399 return adapter; 5400 } 5401 5402 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5403 MethodType targetType = adapter.type(); 5404 MethodType filterType = filter.type(); 5405 BoundMethodHandle result = adapter.rebind(); 5406 Class<?> newParamType = filterType.parameterType(0); 5407 5408 Class<?>[] ptypes = targetType.ptypes().clone(); 5409 for (int pos : positions) { 5410 ptypes[pos - 1] = newParamType; 5411 } 5412 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5413 5414 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5415 return result.copyWithExtendL(newType, lform, filter); 5416 } 5417 5418 /*non-public*/ 5419 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5420 filterArgumentChecks(target, pos, filter); 5421 MethodType targetType = target.type(); 5422 MethodType filterType = filter.type(); 5423 BoundMethodHandle result = target.rebind(); 5424 Class<?> newParamType = filterType.parameterType(0); 5425 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5426 MethodType newType = targetType.changeParameterType(pos, newParamType); 5427 result = result.copyWithExtendL(newType, lform, filter); 5428 return result; 5429 } 5430 5431 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5432 MethodType targetType = target.type(); 5433 int maxPos = targetType.parameterCount(); 5434 if (pos + filters.length > maxPos) 5435 throw newIllegalArgumentException("too many filters"); 5436 } 5437 5438 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5439 MethodType targetType = target.type(); 5440 MethodType filterType = filter.type(); 5441 if (filterType.parameterCount() != 1 5442 || filterType.returnType() != targetType.parameterType(pos)) 5443 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5444 } 5445 5446 /** 5447 * Adapts a target method handle by pre-processing 5448 * a sub-sequence of its arguments with a filter (another method handle). 5449 * The pre-processed arguments are replaced by the result (if any) of the 5450 * filter function. 5451 * The target is then called on the modified (usually shortened) argument list. 5452 * <p> 5453 * If the filter returns a value, the target must accept that value as 5454 * its argument in position {@code pos}, preceded and/or followed by 5455 * any arguments not passed to the filter. 5456 * If the filter returns void, the target must accept all arguments 5457 * not passed to the filter. 5458 * No arguments are reordered, and a result returned from the filter 5459 * replaces (in order) the whole subsequence of arguments originally 5460 * passed to the adapter. 5461 * <p> 5462 * The argument types (if any) of the filter 5463 * replace zero or one argument types of the target, at position {@code pos}, 5464 * in the resulting adapted method handle. 5465 * The return type of the filter (if any) must be identical to the 5466 * argument type of the target at position {@code pos}, and that target argument 5467 * is supplied by the return value of the filter. 5468 * <p> 5469 * In all cases, {@code pos} must be greater than or equal to zero, and 5470 * {@code pos} must also be less than or equal to the target's arity. 5471 * <p><b>Example:</b> 5472 * {@snippet lang="java" : 5473 import static java.lang.invoke.MethodHandles.*; 5474 import static java.lang.invoke.MethodType.*; 5475 ... 5476 MethodHandle deepToString = publicLookup() 5477 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5478 5479 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5480 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5481 5482 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5483 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5484 5485 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5486 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5487 assertEquals("[top, [up, down], strange]", 5488 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5489 5490 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5491 assertEquals("[top, [up, down], [strange]]", 5492 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5493 5494 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5495 assertEquals("[top, [[up, down, strange], charm], bottom]", 5496 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5497 * } 5498 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5499 * represents the return type of the {@code target} and resulting adapter. 5500 * {@code V}/{@code v} stand for the return type and value of the 5501 * {@code filter}, which are also found in the signature and arguments of 5502 * the {@code target}, respectively, unless {@code V} is {@code void}. 5503 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5504 * and values preceding and following the collection position, {@code pos}, 5505 * in the {@code target}'s signature. They also turn up in the resulting 5506 * adapter's signature and arguments, where they surround 5507 * {@code B}/{@code b}, which represent the parameter types and arguments 5508 * to the {@code filter} (if any). 5509 * {@snippet lang="java" : 5510 * T target(A...,V,C...); 5511 * V filter(B...); 5512 * T adapter(A... a,B... b,C... c) { 5513 * V v = filter(b...); 5514 * return target(a...,v,c...); 5515 * } 5516 * // and if the filter has no arguments: 5517 * T target2(A...,V,C...); 5518 * V filter2(); 5519 * T adapter2(A... a,C... c) { 5520 * V v = filter2(); 5521 * return target2(a...,v,c...); 5522 * } 5523 * // and if the filter has a void return: 5524 * T target3(A...,C...); 5525 * void filter3(B...); 5526 * T adapter3(A... a,B... b,C... c) { 5527 * filter3(b...); 5528 * return target3(a...,c...); 5529 * } 5530 * } 5531 * <p> 5532 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5533 * one which first "folds" the affected arguments, and then drops them, in separate 5534 * steps as follows: 5535 * {@snippet lang="java" : 5536 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5537 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5538 * } 5539 * If the target method handle consumes no arguments besides than the result 5540 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5541 * is equivalent to {@code filterReturnValue(coll, mh)}. 5542 * If the filter method handle {@code coll} consumes one argument and produces 5543 * a non-void result, then {@code collectArguments(mh, N, coll)} 5544 * is equivalent to {@code filterArguments(mh, N, coll)}. 5545 * Other equivalences are possible but would require argument permutation. 5546 * <p> 5547 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5548 * variable-arity method handle}, even if the original target method handle was. 5549 * 5550 * @param target the method handle to invoke after filtering the subsequence of arguments 5551 * @param pos the position of the first adapter argument to pass to the filter, 5552 * and/or the target argument which receives the result of the filter 5553 * @param filter method handle to call on the subsequence of arguments 5554 * @return method handle which incorporates the specified argument subsequence filtering logic 5555 * @throws NullPointerException if either argument is null 5556 * @throws IllegalArgumentException if the return type of {@code filter} 5557 * is non-void and is not the same as the {@code pos} argument of the target, 5558 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5559 * or if the resulting method handle's type would have 5560 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5561 * @see MethodHandles#foldArguments 5562 * @see MethodHandles#filterArguments 5563 * @see MethodHandles#filterReturnValue 5564 */ 5565 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5566 MethodType newType = collectArgumentsChecks(target, pos, filter); 5567 MethodType collectorType = filter.type(); 5568 BoundMethodHandle result = target.rebind(); 5569 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5570 return result.copyWithExtendL(newType, lform, filter); 5571 } 5572 5573 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5574 MethodType targetType = target.type(); 5575 MethodType filterType = filter.type(); 5576 Class<?> rtype = filterType.returnType(); 5577 Class<?>[] filterArgs = filterType.ptypes(); 5578 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5579 (rtype != void.class && pos >= targetType.parameterCount())) { 5580 throw newIllegalArgumentException("position is out of range for target", target, pos); 5581 } 5582 if (rtype == void.class) { 5583 return targetType.insertParameterTypes(pos, filterArgs); 5584 } 5585 if (rtype != targetType.parameterType(pos)) { 5586 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5587 } 5588 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5589 } 5590 5591 /** 5592 * Adapts a target method handle by post-processing 5593 * its return value (if any) with a filter (another method handle). 5594 * The result of the filter is returned from the adapter. 5595 * <p> 5596 * If the target returns a value, the filter must accept that value as 5597 * its only argument. 5598 * If the target returns void, the filter must accept no arguments. 5599 * <p> 5600 * The return type of the filter 5601 * replaces the return type of the target 5602 * in the resulting adapted method handle. 5603 * The argument type of the filter (if any) must be identical to the 5604 * return type of the target. 5605 * <p><b>Example:</b> 5606 * {@snippet lang="java" : 5607 import static java.lang.invoke.MethodHandles.*; 5608 import static java.lang.invoke.MethodType.*; 5609 ... 5610 MethodHandle cat = lookup().findVirtual(String.class, 5611 "concat", methodType(String.class, String.class)); 5612 MethodHandle length = lookup().findVirtual(String.class, 5613 "length", methodType(int.class)); 5614 System.out.println((String) cat.invokeExact("x", "y")); // xy 5615 MethodHandle f0 = filterReturnValue(cat, length); 5616 System.out.println((int) f0.invokeExact("x", "y")); // 2 5617 * } 5618 * <p>Here is pseudocode for the resulting adapter. In the code, 5619 * {@code T}/{@code t} represent the result type and value of the 5620 * {@code target}; {@code V}, the result type of the {@code filter}; and 5621 * {@code A}/{@code a}, the types and values of the parameters and arguments 5622 * of the {@code target} as well as the resulting adapter. 5623 * {@snippet lang="java" : 5624 * T target(A...); 5625 * V filter(T); 5626 * V adapter(A... a) { 5627 * T t = target(a...); 5628 * return filter(t); 5629 * } 5630 * // and if the target has a void return: 5631 * void target2(A...); 5632 * V filter2(); 5633 * V adapter2(A... a) { 5634 * target2(a...); 5635 * return filter2(); 5636 * } 5637 * // and if the filter has a void return: 5638 * T target3(A...); 5639 * void filter3(V); 5640 * void adapter3(A... a) { 5641 * T t = target3(a...); 5642 * filter3(t); 5643 * } 5644 * } 5645 * <p> 5646 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5647 * variable-arity method handle}, even if the original target method handle was. 5648 * @param target the method handle to invoke before filtering the return value 5649 * @param filter method handle to call on the return value 5650 * @return method handle which incorporates the specified return value filtering logic 5651 * @throws NullPointerException if either argument is null 5652 * @throws IllegalArgumentException if the argument list of {@code filter} 5653 * does not match the return type of target as described above 5654 */ 5655 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5656 MethodType targetType = target.type(); 5657 MethodType filterType = filter.type(); 5658 filterReturnValueChecks(targetType, filterType); 5659 BoundMethodHandle result = target.rebind(); 5660 BasicType rtype = BasicType.basicType(filterType.returnType()); 5661 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5662 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5663 result = result.copyWithExtendL(newType, lform, filter); 5664 return result; 5665 } 5666 5667 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5668 Class<?> rtype = targetType.returnType(); 5669 int filterValues = filterType.parameterCount(); 5670 if (filterValues == 0 5671 ? (rtype != void.class) 5672 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5673 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5674 } 5675 5676 /** 5677 * Filter the return value of a target method handle with a filter function. The filter function is 5678 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5679 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5680 * as follows: 5681 * {@snippet lang="java" : 5682 * T target(A...) 5683 * V filter(B... , T) 5684 * V adapter(A... a, B... b) { 5685 * T t = target(a...); 5686 * return filter(b..., t); 5687 * } 5688 * } 5689 * <p> 5690 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5691 * 5692 * @param target the target method handle 5693 * @param filter the filter method handle 5694 * @return the adapter method handle 5695 */ 5696 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5697 MethodType targetType = target.type(); 5698 MethodType filterType = filter.type(); 5699 BoundMethodHandle result = target.rebind(); 5700 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5701 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5702 if (filterType.parameterCount() > 1) { 5703 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5704 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5705 } 5706 } 5707 result = result.copyWithExtendL(newType, lform, filter); 5708 return result; 5709 } 5710 5711 /** 5712 * Adapts a target method handle by pre-processing 5713 * some of its arguments, and then calling the target with 5714 * the result of the pre-processing, inserted into the original 5715 * sequence of arguments. 5716 * <p> 5717 * The pre-processing is performed by {@code combiner}, a second method handle. 5718 * Of the arguments passed to the adapter, the first {@code N} arguments 5719 * are copied to the combiner, which is then called. 5720 * (Here, {@code N} is defined as the parameter count of the combiner.) 5721 * After this, control passes to the target, with any result 5722 * from the combiner inserted before the original {@code N} incoming 5723 * arguments. 5724 * <p> 5725 * If the combiner returns a value, the first parameter type of the target 5726 * must be identical with the return type of the combiner, and the next 5727 * {@code N} parameter types of the target must exactly match the parameters 5728 * of the combiner. 5729 * <p> 5730 * If the combiner has a void return, no result will be inserted, 5731 * and the first {@code N} parameter types of the target 5732 * must exactly match the parameters of the combiner. 5733 * <p> 5734 * The resulting adapter is the same type as the target, except that the 5735 * first parameter type is dropped, 5736 * if it corresponds to the result of the combiner. 5737 * <p> 5738 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5739 * that either the combiner or the target does not wish to receive. 5740 * If some of the incoming arguments are destined only for the combiner, 5741 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5742 * arguments will not need to be live on the stack on entry to the 5743 * target.) 5744 * <p><b>Example:</b> 5745 * {@snippet lang="java" : 5746 import static java.lang.invoke.MethodHandles.*; 5747 import static java.lang.invoke.MethodType.*; 5748 ... 5749 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5750 "println", methodType(void.class, String.class)) 5751 .bindTo(System.out); 5752 MethodHandle cat = lookup().findVirtual(String.class, 5753 "concat", methodType(String.class, String.class)); 5754 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5755 MethodHandle catTrace = foldArguments(cat, trace); 5756 // also prints "boo": 5757 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5758 * } 5759 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5760 * represents the result type of the {@code target} and resulting adapter. 5761 * {@code V}/{@code v} represent the type and value of the parameter and argument 5762 * of {@code target} that precedes the folding position; {@code V} also is 5763 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5764 * types and values of the {@code N} parameters and arguments at the folding 5765 * position. {@code B}/{@code b} represent the types and values of the 5766 * {@code target} parameters and arguments that follow the folded parameters 5767 * and arguments. 5768 * {@snippet lang="java" : 5769 * // there are N arguments in A... 5770 * T target(V, A[N]..., B...); 5771 * V combiner(A...); 5772 * T adapter(A... a, B... b) { 5773 * V v = combiner(a...); 5774 * return target(v, a..., b...); 5775 * } 5776 * // and if the combiner has a void return: 5777 * T target2(A[N]..., B...); 5778 * void combiner2(A...); 5779 * T adapter2(A... a, B... b) { 5780 * combiner2(a...); 5781 * return target2(a..., b...); 5782 * } 5783 * } 5784 * <p> 5785 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5786 * variable-arity method handle}, even if the original target method handle was. 5787 * @param target the method handle to invoke after arguments are combined 5788 * @param combiner method handle to call initially on the incoming arguments 5789 * @return method handle which incorporates the specified argument folding logic 5790 * @throws NullPointerException if either argument is null 5791 * @throws IllegalArgumentException if {@code combiner}'s return type 5792 * is non-void and not the same as the first argument type of 5793 * the target, or if the initial {@code N} argument types 5794 * of the target 5795 * (skipping one matching the {@code combiner}'s return type) 5796 * are not identical with the argument types of {@code combiner} 5797 */ 5798 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5799 return foldArguments(target, 0, combiner); 5800 } 5801 5802 /** 5803 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 5804 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 5805 * before the folded arguments. 5806 * <p> 5807 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 5808 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 5809 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 5810 * 0. 5811 * 5812 * @apiNote Example: 5813 * {@snippet lang="java" : 5814 import static java.lang.invoke.MethodHandles.*; 5815 import static java.lang.invoke.MethodType.*; 5816 ... 5817 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5818 "println", methodType(void.class, String.class)) 5819 .bindTo(System.out); 5820 MethodHandle cat = lookup().findVirtual(String.class, 5821 "concat", methodType(String.class, String.class)); 5822 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5823 MethodHandle catTrace = foldArguments(cat, 1, trace); 5824 // also prints "jum": 5825 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5826 * } 5827 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5828 * represents the result type of the {@code target} and resulting adapter. 5829 * {@code V}/{@code v} represent the type and value of the parameter and argument 5830 * of {@code target} that precedes the folding position; {@code V} also is 5831 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5832 * types and values of the {@code N} parameters and arguments at the folding 5833 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 5834 * and values of the {@code target} parameters and arguments that precede and 5835 * follow the folded parameters and arguments starting at {@code pos}, 5836 * respectively. 5837 * {@snippet lang="java" : 5838 * // there are N arguments in A... 5839 * T target(Z..., V, A[N]..., B...); 5840 * V combiner(A...); 5841 * T adapter(Z... z, A... a, B... b) { 5842 * V v = combiner(a...); 5843 * return target(z..., v, a..., b...); 5844 * } 5845 * // and if the combiner has a void return: 5846 * T target2(Z..., A[N]..., B...); 5847 * void combiner2(A...); 5848 * T adapter2(Z... z, A... a, B... b) { 5849 * combiner2(a...); 5850 * return target2(z..., a..., b...); 5851 * } 5852 * } 5853 * <p> 5854 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5855 * variable-arity method handle}, even if the original target method handle was. 5856 * 5857 * @param target the method handle to invoke after arguments are combined 5858 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 5859 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5860 * @param combiner method handle to call initially on the incoming arguments 5861 * @return method handle which incorporates the specified argument folding logic 5862 * @throws NullPointerException if either argument is null 5863 * @throws IllegalArgumentException if either of the following two conditions holds: 5864 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5865 * {@code pos} of the target signature; 5866 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 5867 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 5868 * 5869 * @see #foldArguments(MethodHandle, MethodHandle) 5870 * @since 9 5871 */ 5872 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 5873 MethodType targetType = target.type(); 5874 MethodType combinerType = combiner.type(); 5875 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 5876 BoundMethodHandle result = target.rebind(); 5877 boolean dropResult = rtype == void.class; 5878 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 5879 MethodType newType = targetType; 5880 if (!dropResult) { 5881 newType = newType.dropParameterTypes(pos, pos + 1); 5882 } 5883 result = result.copyWithExtendL(newType, lform, combiner); 5884 return result; 5885 } 5886 5887 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 5888 int foldArgs = combinerType.parameterCount(); 5889 Class<?> rtype = combinerType.returnType(); 5890 int foldVals = rtype == void.class ? 0 : 1; 5891 int afterInsertPos = foldPos + foldVals; 5892 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 5893 if (ok) { 5894 for (int i = 0; i < foldArgs; i++) { 5895 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 5896 ok = false; 5897 break; 5898 } 5899 } 5900 } 5901 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 5902 ok = false; 5903 if (!ok) 5904 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5905 return rtype; 5906 } 5907 5908 /** 5909 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 5910 * of the pre-processing replacing the argument at the given position. 5911 * 5912 * @param target the method handle to invoke after arguments are combined 5913 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5914 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5915 * @param combiner method handle to call initially on the incoming arguments 5916 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5917 * @return method handle which incorporates the specified argument folding logic 5918 * @throws NullPointerException if either argument is null 5919 * @throws IllegalArgumentException if either of the following two conditions holds: 5920 * (1) {@code combiner}'s return type is not the same as the argument type at position 5921 * {@code pos} of the target signature; 5922 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 5923 * not identical with the argument types of {@code combiner}. 5924 */ 5925 /*non-public*/ 5926 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5927 return argumentsWithCombiner(true, target, position, combiner, argPositions); 5928 } 5929 5930 /** 5931 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 5932 * the pre-processing inserted into the original sequence of arguments at the given position. 5933 * 5934 * @param target the method handle to invoke after arguments are combined 5935 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5936 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5937 * @param combiner method handle to call initially on the incoming arguments 5938 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5939 * @return method handle which incorporates the specified argument folding logic 5940 * @throws NullPointerException if either argument is null 5941 * @throws IllegalArgumentException if either of the following two conditions holds: 5942 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5943 * {@code pos} of the target signature; 5944 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 5945 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 5946 * with the argument types of {@code combiner}. 5947 */ 5948 /*non-public*/ 5949 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5950 return argumentsWithCombiner(false, target, position, combiner, argPositions); 5951 } 5952 5953 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5954 MethodType targetType = target.type(); 5955 MethodType combinerType = combiner.type(); 5956 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 5957 BoundMethodHandle result = target.rebind(); 5958 5959 MethodType newType = targetType; 5960 LambdaForm lform; 5961 if (filter) { 5962 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 5963 } else { 5964 boolean dropResult = rtype == void.class; 5965 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 5966 if (!dropResult) { 5967 newType = newType.dropParameterTypes(position, position + 1); 5968 } 5969 } 5970 result = result.copyWithExtendL(newType, lform, combiner); 5971 return result; 5972 } 5973 5974 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 5975 int combinerArgs = combinerType.parameterCount(); 5976 if (argPos.length != combinerArgs) { 5977 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 5978 } 5979 Class<?> rtype = combinerType.returnType(); 5980 5981 for (int i = 0; i < combinerArgs; i++) { 5982 int arg = argPos[i]; 5983 if (arg < 0 || arg > targetType.parameterCount()) { 5984 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 5985 } 5986 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 5987 throw newIllegalArgumentException("target argument type at position " + arg 5988 + " must match combiner argument type at index " + i + ": " + targetType 5989 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 5990 } 5991 } 5992 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 5993 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5994 } 5995 return rtype; 5996 } 5997 5998 /** 5999 * Makes a method handle which adapts a target method handle, 6000 * by guarding it with a test, a boolean-valued method handle. 6001 * If the guard fails, a fallback handle is called instead. 6002 * All three method handles must have the same corresponding 6003 * argument and return types, except that the return type 6004 * of the test must be boolean, and the test is allowed 6005 * to have fewer arguments than the other two method handles. 6006 * <p> 6007 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6008 * represents the uniform result type of the three involved handles; 6009 * {@code A}/{@code a}, the types and values of the {@code target} 6010 * parameters and arguments that are consumed by the {@code test}; and 6011 * {@code B}/{@code b}, those types and values of the {@code target} 6012 * parameters and arguments that are not consumed by the {@code test}. 6013 * {@snippet lang="java" : 6014 * boolean test(A...); 6015 * T target(A...,B...); 6016 * T fallback(A...,B...); 6017 * T adapter(A... a,B... b) { 6018 * if (test(a...)) 6019 * return target(a..., b...); 6020 * else 6021 * return fallback(a..., b...); 6022 * } 6023 * } 6024 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6025 * be modified by execution of the test, and so are passed unchanged 6026 * from the caller to the target or fallback as appropriate. 6027 * @param test method handle used for test, must return boolean 6028 * @param target method handle to call if test passes 6029 * @param fallback method handle to call if test fails 6030 * @return method handle which incorporates the specified if/then/else logic 6031 * @throws NullPointerException if any argument is null 6032 * @throws IllegalArgumentException if {@code test} does not return boolean, 6033 * or if all three method types do not match (with the return 6034 * type of {@code test} changed to match that of the target). 6035 */ 6036 public static MethodHandle guardWithTest(MethodHandle test, 6037 MethodHandle target, 6038 MethodHandle fallback) { 6039 MethodType gtype = test.type(); 6040 MethodType ttype = target.type(); 6041 MethodType ftype = fallback.type(); 6042 if (!ttype.equals(ftype)) 6043 throw misMatchedTypes("target and fallback types", ttype, ftype); 6044 if (gtype.returnType() != boolean.class) 6045 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6046 6047 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6048 if (test == null) { 6049 throw misMatchedTypes("target and test types", ttype, gtype); 6050 } 6051 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6052 } 6053 6054 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6055 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6056 } 6057 6058 /** 6059 * Makes a method handle which adapts a target method handle, 6060 * by running it inside an exception handler. 6061 * If the target returns normally, the adapter returns that value. 6062 * If an exception matching the specified type is thrown, the fallback 6063 * handle is called instead on the exception, plus the original arguments. 6064 * <p> 6065 * The target and handler must have the same corresponding 6066 * argument and return types, except that handler may omit trailing arguments 6067 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6068 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6069 * <p> 6070 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6071 * represents the return type of the {@code target} and {@code handler}, 6072 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6073 * the types and values of arguments to the resulting handle consumed by 6074 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6075 * resulting handle discarded by {@code handler}. 6076 * {@snippet lang="java" : 6077 * T target(A..., B...); 6078 * T handler(ExType, A...); 6079 * T adapter(A... a, B... b) { 6080 * try { 6081 * return target(a..., b...); 6082 * } catch (ExType ex) { 6083 * return handler(ex, a...); 6084 * } 6085 * } 6086 * } 6087 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6088 * be modified by execution of the target, and so are passed unchanged 6089 * from the caller to the handler, if the handler is invoked. 6090 * <p> 6091 * The target and handler must return the same type, even if the handler 6092 * always throws. (This might happen, for instance, because the handler 6093 * is simulating a {@code finally} clause). 6094 * To create such a throwing handler, compose the handler creation logic 6095 * with {@link #throwException throwException}, 6096 * in order to create a method handle of the correct return type. 6097 * @param target method handle to call 6098 * @param exType the type of exception which the handler will catch 6099 * @param handler method handle to call if a matching exception is thrown 6100 * @return method handle which incorporates the specified try/catch logic 6101 * @throws NullPointerException if any argument is null 6102 * @throws IllegalArgumentException if {@code handler} does not accept 6103 * the given exception type, or if the method handle types do 6104 * not match in their return types and their 6105 * corresponding parameters 6106 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6107 */ 6108 public static MethodHandle catchException(MethodHandle target, 6109 Class<? extends Throwable> exType, 6110 MethodHandle handler) { 6111 MethodType ttype = target.type(); 6112 MethodType htype = handler.type(); 6113 if (!Throwable.class.isAssignableFrom(exType)) 6114 throw new ClassCastException(exType.getName()); 6115 if (htype.parameterCount() < 1 || 6116 !htype.parameterType(0).isAssignableFrom(exType)) 6117 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6118 if (htype.returnType() != ttype.returnType()) 6119 throw misMatchedTypes("target and handler return types", ttype, htype); 6120 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6121 if (handler == null) { 6122 throw misMatchedTypes("target and handler types", ttype, htype); 6123 } 6124 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6125 } 6126 6127 /** 6128 * Produces a method handle which will throw exceptions of the given {@code exType}. 6129 * The method handle will accept a single argument of {@code exType}, 6130 * and immediately throw it as an exception. 6131 * The method type will nominally specify a return of {@code returnType}. 6132 * The return type may be anything convenient: It doesn't matter to the 6133 * method handle's behavior, since it will never return normally. 6134 * @param returnType the return type of the desired method handle 6135 * @param exType the parameter type of the desired method handle 6136 * @return method handle which can throw the given exceptions 6137 * @throws NullPointerException if either argument is null 6138 */ 6139 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6140 if (!Throwable.class.isAssignableFrom(exType)) 6141 throw new ClassCastException(exType.getName()); 6142 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6143 } 6144 6145 /** 6146 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6147 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6148 * delivers the loop's result, which is the return value of the resulting handle. 6149 * <p> 6150 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6151 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6152 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6153 * terms of method handles, each clause will specify up to four independent actions:<ul> 6154 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6155 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6156 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6157 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6158 * </ul> 6159 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6160 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6161 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6162 * <p> 6163 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6164 * this case. See below for a detailed description. 6165 * <p> 6166 * <em>Parameters optional everywhere:</em> 6167 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6168 * As an exception, the init functions cannot take any {@code v} parameters, 6169 * because those values are not yet computed when the init functions are executed. 6170 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6171 * In fact, any clause function may take no arguments at all. 6172 * <p> 6173 * <em>Loop parameters:</em> 6174 * A clause function may take all the iteration variable values it is entitled to, in which case 6175 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6176 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6177 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6178 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6179 * init function is automatically a loop parameter {@code a}.) 6180 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6181 * These loop parameters act as loop-invariant values visible across the whole loop. 6182 * <p> 6183 * <em>Parameters visible everywhere:</em> 6184 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6185 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6186 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6187 * Most clause functions will not need all of this information, but they will be formally connected to it 6188 * as if by {@link #dropArguments}. 6189 * <a id="astar"></a> 6190 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6191 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6192 * In that notation, the general form of an init function parameter list 6193 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6194 * <p> 6195 * <em>Checking clause structure:</em> 6196 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6197 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6198 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6199 * met by the inputs to the loop combinator. 6200 * <p> 6201 * <em>Effectively identical sequences:</em> 6202 * <a id="effid"></a> 6203 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6204 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6205 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6206 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6207 * that longest list. 6208 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6209 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6210 * <p> 6211 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6212 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6213 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6214 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6215 * four. Padding takes place by appending elements to the array. 6216 * <li>Clauses with all {@code null}s are disregarded. 6217 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6218 * </ol> 6219 * <p> 6220 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6221 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6222 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6223 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6224 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6225 * iteration variable type. 6226 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6227 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6228 * </ol> 6229 * <p> 6230 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6231 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6232 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6233 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6234 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6235 * (These types will be checked in step 2, along with all the clause function types.) 6236 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6237 * <li>All of the collected parameter lists must be effectively identical. 6238 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6239 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6240 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6241 * the "internal parameter list". 6242 * </ul> 6243 * <p> 6244 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6245 * <li>Examine fini function return types, disregarding omitted fini functions. 6246 * <li>If there are no fini functions, the loop return type is {@code void}. 6247 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6248 * type. 6249 * </ol> 6250 * <p> 6251 * <em>Step 1D: Check other types.</em><ol type="a"> 6252 * <li>There must be at least one non-omitted pred function. 6253 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6254 * </ol> 6255 * <p> 6256 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6257 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6258 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6259 * (Note that their parameter lists are already effectively identical to this list.) 6260 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6261 * effectively identical to the internal parameter list {@code (V... A...)}. 6262 * </ol> 6263 * <p> 6264 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6265 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6266 * type. 6267 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6268 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6269 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6270 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6271 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6272 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6273 * loop return type. 6274 * </ol> 6275 * <p> 6276 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6277 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6278 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6279 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6280 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6281 * pad out the end of the list. 6282 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6283 * </ol> 6284 * <p> 6285 * <em>Final observations.</em><ol type="a"> 6286 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6287 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6288 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6289 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6290 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6291 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6292 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6293 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6294 * </ol> 6295 * <p> 6296 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6297 * <ul> 6298 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6299 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6300 * (Only one {@code Pn} has to be non-{@code null}.) 6301 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6302 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6303 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6304 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6305 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6306 * the resulting loop handle's parameter types {@code (A...)}. 6307 * </ul> 6308 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6309 * which is natural if most of the loop computation happens in the steps. For some loops, 6310 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6311 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6312 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6313 * where the init functions will need the extra parameters. For such reasons, the rules for 6314 * determining these parameters are as symmetric as possible, across all clause parts. 6315 * In general, the loop parameters function as common invariant values across the whole 6316 * loop, while the iteration variables function as common variant values, or (if there is 6317 * no step function) as internal loop invariant temporaries. 6318 * <p> 6319 * <em>Loop execution.</em><ol type="a"> 6320 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6321 * every clause function. These locals are loop invariant. 6322 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6323 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6324 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6325 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6326 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6327 * (in argument order). 6328 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6329 * returns {@code false}. 6330 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6331 * sequence {@code (v...)} of loop variables. 6332 * The updated value is immediately visible to all subsequent function calls. 6333 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6334 * (of type {@code R}) is returned from the loop as a whole. 6335 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6336 * except by throwing an exception. 6337 * </ol> 6338 * <p> 6339 * <em>Usage tips.</em> 6340 * <ul> 6341 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6342 * sometimes a step function only needs to observe the current value of its own variable. 6343 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6344 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6345 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6346 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6347 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6348 * <li>If some of the clause functions are virtual methods on an instance, the instance 6349 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6350 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6351 * will be the first iteration variable value, and it will be easy to use virtual 6352 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6353 * </ul> 6354 * <p> 6355 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6356 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6357 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6358 * {@snippet lang="java" : 6359 * V... init...(A...); 6360 * boolean pred...(V..., A...); 6361 * V... step...(V..., A...); 6362 * R fini...(V..., A...); 6363 * R loop(A... a) { 6364 * V... v... = init...(a...); 6365 * for (;;) { 6366 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6367 * v = s(v..., a...); 6368 * if (!p(v..., a...)) { 6369 * return f(v..., a...); 6370 * } 6371 * } 6372 * } 6373 * } 6374 * } 6375 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6376 * to their full length, even though individual clause functions may neglect to take them all. 6377 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6378 * 6379 * @apiNote Example: 6380 * {@snippet lang="java" : 6381 * // iterative implementation of the factorial function as a loop handle 6382 * static int one(int k) { return 1; } 6383 * static int inc(int i, int acc, int k) { return i + 1; } 6384 * static int mult(int i, int acc, int k) { return i * acc; } 6385 * static boolean pred(int i, int acc, int k) { return i < k; } 6386 * static int fin(int i, int acc, int k) { return acc; } 6387 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6388 * // null initializer for counter, should initialize to 0 6389 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6390 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6391 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6392 * assertEquals(120, loop.invoke(5)); 6393 * } 6394 * The same example, dropping arguments and using combinators: 6395 * {@snippet lang="java" : 6396 * // simplified implementation of the factorial function as a loop handle 6397 * static int inc(int i) { return i + 1; } // drop acc, k 6398 * static int mult(int i, int acc) { return i * acc; } //drop k 6399 * static boolean cmp(int i, int k) { return i < k; } 6400 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6401 * // null initializer for counter, should initialize to 0 6402 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6403 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6404 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6405 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6406 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6407 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6408 * assertEquals(720, loop.invoke(6)); 6409 * } 6410 * A similar example, using a helper object to hold a loop parameter: 6411 * {@snippet lang="java" : 6412 * // instance-based implementation of the factorial function as a loop handle 6413 * static class FacLoop { 6414 * final int k; 6415 * FacLoop(int k) { this.k = k; } 6416 * int inc(int i) { return i + 1; } 6417 * int mult(int i, int acc) { return i * acc; } 6418 * boolean pred(int i) { return i < k; } 6419 * int fin(int i, int acc) { return acc; } 6420 * } 6421 * // assume MH_FacLoop is a handle to the constructor 6422 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6423 * // null initializer for counter, should initialize to 0 6424 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6425 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6426 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6427 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6428 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6429 * assertEquals(5040, loop.invoke(7)); 6430 * } 6431 * 6432 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6433 * 6434 * @return a method handle embodying the looping behavior as defined by the arguments. 6435 * 6436 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6437 * 6438 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6439 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6440 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6441 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6442 * @since 9 6443 */ 6444 public static MethodHandle loop(MethodHandle[]... clauses) { 6445 // Step 0: determine clause structure. 6446 loopChecks0(clauses); 6447 6448 List<MethodHandle> init = new ArrayList<>(); 6449 List<MethodHandle> step = new ArrayList<>(); 6450 List<MethodHandle> pred = new ArrayList<>(); 6451 List<MethodHandle> fini = new ArrayList<>(); 6452 6453 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6454 init.add(clause[0]); // all clauses have at least length 1 6455 step.add(clause.length <= 1 ? null : clause[1]); 6456 pred.add(clause.length <= 2 ? null : clause[2]); 6457 fini.add(clause.length <= 3 ? null : clause[3]); 6458 }); 6459 6460 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6461 final int nclauses = init.size(); 6462 6463 // Step 1A: determine iteration variables (V...). 6464 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6465 for (int i = 0; i < nclauses; ++i) { 6466 MethodHandle in = init.get(i); 6467 MethodHandle st = step.get(i); 6468 if (in == null && st == null) { 6469 iterationVariableTypes.add(void.class); 6470 } else if (in != null && st != null) { 6471 loopChecks1a(i, in, st); 6472 iterationVariableTypes.add(in.type().returnType()); 6473 } else { 6474 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6475 } 6476 } 6477 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6478 6479 // Step 1B: determine loop parameters (A...). 6480 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6481 loopChecks1b(init, commonSuffix); 6482 6483 // Step 1C: determine loop return type. 6484 // Step 1D: check other types. 6485 // local variable required here; see JDK-8223553 6486 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6487 .map(MethodType::returnType); 6488 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6489 loopChecks1cd(pred, fini, loopReturnType); 6490 6491 // Step 2: determine parameter lists. 6492 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6493 commonParameterSequence.addAll(commonSuffix); 6494 loopChecks2(step, pred, fini, commonParameterSequence); 6495 // Step 3: fill in omitted functions. 6496 for (int i = 0; i < nclauses; ++i) { 6497 Class<?> t = iterationVariableTypes.get(i); 6498 if (init.get(i) == null) { 6499 init.set(i, empty(methodType(t, commonSuffix))); 6500 } 6501 if (step.get(i) == null) { 6502 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6503 } 6504 if (pred.get(i) == null) { 6505 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6506 } 6507 if (fini.get(i) == null) { 6508 fini.set(i, empty(methodType(t, commonParameterSequence))); 6509 } 6510 } 6511 6512 // Step 4: fill in missing parameter types. 6513 // Also convert all handles to fixed-arity handles. 6514 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6515 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6516 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6517 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6518 6519 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6520 allMatch(pl -> pl.equals(commonSuffix)); 6521 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6522 allMatch(pl -> pl.equals(commonParameterSequence)); 6523 6524 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6525 } 6526 6527 private static void loopChecks0(MethodHandle[][] clauses) { 6528 if (clauses == null || clauses.length == 0) { 6529 throw newIllegalArgumentException("null or no clauses passed"); 6530 } 6531 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6532 throw newIllegalArgumentException("null clauses are not allowed"); 6533 } 6534 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6535 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6536 } 6537 } 6538 6539 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6540 if (in.type().returnType() != st.type().returnType()) { 6541 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6542 st.type().returnType()); 6543 } 6544 } 6545 6546 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6547 return mhs.filter(Objects::nonNull) 6548 // take only those that can contribute to a common suffix because they are longer than the prefix 6549 .map(MethodHandle::type) 6550 .filter(t -> t.parameterCount() > skipSize) 6551 .max(Comparator.comparingInt(MethodType::parameterCount)) 6552 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6553 .orElse(List.of()); 6554 } 6555 6556 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6557 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6558 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6559 return longest1.size() >= longest2.size() ? longest1 : longest2; 6560 } 6561 6562 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6563 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6564 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6565 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6566 " (common suffix: " + commonSuffix + ")"); 6567 } 6568 } 6569 6570 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6571 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6572 anyMatch(t -> t != loopReturnType)) { 6573 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6574 loopReturnType + ")"); 6575 } 6576 6577 if (pred.stream().noneMatch(Objects::nonNull)) { 6578 throw newIllegalArgumentException("no predicate found", pred); 6579 } 6580 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6581 anyMatch(t -> t != boolean.class)) { 6582 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6583 } 6584 } 6585 6586 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6587 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6588 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6589 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6590 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6591 } 6592 } 6593 6594 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6595 return hs.stream().map(h -> { 6596 int pc = h.type().parameterCount(); 6597 int tpsize = targetParams.size(); 6598 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6599 }).toList(); 6600 } 6601 6602 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6603 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6604 } 6605 6606 /** 6607 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6608 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6609 * <p> 6610 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6611 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6612 * evaluates to {@code true}). 6613 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6614 * <p> 6615 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6616 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6617 * and updated with the value returned from its invocation. The result of loop execution will be 6618 * the final value of the additional loop-local variable (if present). 6619 * <p> 6620 * The following rules hold for these argument handles:<ul> 6621 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6622 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6623 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6624 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6625 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6626 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6627 * It will constrain the parameter lists of the other loop parts. 6628 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6629 * list {@code (A...)} is called the <em>external parameter list</em>. 6630 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6631 * additional state variable of the loop. 6632 * The body must both accept and return a value of this type {@code V}. 6633 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6634 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6635 * <a href="MethodHandles.html#effid">effectively identical</a> 6636 * to the external parameter list {@code (A...)}. 6637 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6638 * {@linkplain #empty default value}. 6639 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6640 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6641 * effectively identical to the internal parameter list. 6642 * </ul> 6643 * <p> 6644 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6645 * <li>The loop handle's result type is the result type {@code V} of the body. 6646 * <li>The loop handle's parameter types are the types {@code (A...)}, 6647 * from the external parameter list. 6648 * </ul> 6649 * <p> 6650 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6651 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6652 * passed to the loop. 6653 * {@snippet lang="java" : 6654 * V init(A...); 6655 * boolean pred(V, A...); 6656 * V body(V, A...); 6657 * V whileLoop(A... a...) { 6658 * V v = init(a...); 6659 * while (pred(v, a...)) { 6660 * v = body(v, a...); 6661 * } 6662 * return v; 6663 * } 6664 * } 6665 * 6666 * @apiNote Example: 6667 * {@snippet lang="java" : 6668 * // implement the zip function for lists as a loop handle 6669 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6670 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6671 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6672 * zip.add(a.next()); 6673 * zip.add(b.next()); 6674 * return zip; 6675 * } 6676 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6677 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6678 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6679 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6680 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6681 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6682 * } 6683 * 6684 * 6685 * @apiNote The implementation of this method can be expressed as follows: 6686 * {@snippet lang="java" : 6687 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6688 * MethodHandle fini = (body.type().returnType() == void.class 6689 * ? null : identity(body.type().returnType())); 6690 * MethodHandle[] 6691 * checkExit = { null, null, pred, fini }, 6692 * varBody = { init, body }; 6693 * return loop(checkExit, varBody); 6694 * } 6695 * } 6696 * 6697 * @param init optional initializer, providing the initial value of the loop variable. 6698 * May be {@code null}, implying a default initial value. See above for other constraints. 6699 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6700 * above for other constraints. 6701 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6702 * See above for other constraints. 6703 * 6704 * @return a method handle implementing the {@code while} loop as described by the arguments. 6705 * @throws IllegalArgumentException if the rules for the arguments are violated. 6706 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6707 * 6708 * @see #loop(MethodHandle[][]) 6709 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6710 * @since 9 6711 */ 6712 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6713 whileLoopChecks(init, pred, body); 6714 MethodHandle fini = identityOrVoid(body.type().returnType()); 6715 MethodHandle[] checkExit = { null, null, pred, fini }; 6716 MethodHandle[] varBody = { init, body }; 6717 return loop(checkExit, varBody); 6718 } 6719 6720 /** 6721 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6722 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6723 * <p> 6724 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6725 * method will, in each iteration, first execute its body and then evaluate the predicate. 6726 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6727 * <p> 6728 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6729 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6730 * and updated with the value returned from its invocation. The result of loop execution will be 6731 * the final value of the additional loop-local variable (if present). 6732 * <p> 6733 * The following rules hold for these argument handles:<ul> 6734 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6735 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6736 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6737 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6738 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6739 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6740 * It will constrain the parameter lists of the other loop parts. 6741 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6742 * list {@code (A...)} is called the <em>external parameter list</em>. 6743 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6744 * additional state variable of the loop. 6745 * The body must both accept and return a value of this type {@code V}. 6746 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6747 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6748 * <a href="MethodHandles.html#effid">effectively identical</a> 6749 * to the external parameter list {@code (A...)}. 6750 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6751 * {@linkplain #empty default value}. 6752 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6753 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6754 * effectively identical to the internal parameter list. 6755 * </ul> 6756 * <p> 6757 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6758 * <li>The loop handle's result type is the result type {@code V} of the body. 6759 * <li>The loop handle's parameter types are the types {@code (A...)}, 6760 * from the external parameter list. 6761 * </ul> 6762 * <p> 6763 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6764 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6765 * passed to the loop. 6766 * {@snippet lang="java" : 6767 * V init(A...); 6768 * boolean pred(V, A...); 6769 * V body(V, A...); 6770 * V doWhileLoop(A... a...) { 6771 * V v = init(a...); 6772 * do { 6773 * v = body(v, a...); 6774 * } while (pred(v, a...)); 6775 * return v; 6776 * } 6777 * } 6778 * 6779 * @apiNote Example: 6780 * {@snippet lang="java" : 6781 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6782 * static int zero(int limit) { return 0; } 6783 * static int step(int i, int limit) { return i + 1; } 6784 * static boolean pred(int i, int limit) { return i < limit; } 6785 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6786 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6787 * assertEquals(23, loop.invoke(23)); 6788 * } 6789 * 6790 * 6791 * @apiNote The implementation of this method can be expressed as follows: 6792 * {@snippet lang="java" : 6793 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6794 * MethodHandle fini = (body.type().returnType() == void.class 6795 * ? null : identity(body.type().returnType())); 6796 * MethodHandle[] clause = { init, body, pred, fini }; 6797 * return loop(clause); 6798 * } 6799 * } 6800 * 6801 * @param init optional initializer, providing the initial value of the loop variable. 6802 * May be {@code null}, implying a default initial value. See above for other constraints. 6803 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6804 * See above for other constraints. 6805 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6806 * above for other constraints. 6807 * 6808 * @return a method handle implementing the {@code while} loop as described by the arguments. 6809 * @throws IllegalArgumentException if the rules for the arguments are violated. 6810 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6811 * 6812 * @see #loop(MethodHandle[][]) 6813 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 6814 * @since 9 6815 */ 6816 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6817 whileLoopChecks(init, pred, body); 6818 MethodHandle fini = identityOrVoid(body.type().returnType()); 6819 MethodHandle[] clause = {init, body, pred, fini }; 6820 return loop(clause); 6821 } 6822 6823 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 6824 Objects.requireNonNull(pred); 6825 Objects.requireNonNull(body); 6826 MethodType bodyType = body.type(); 6827 Class<?> returnType = bodyType.returnType(); 6828 List<Class<?>> innerList = bodyType.parameterList(); 6829 List<Class<?>> outerList = innerList; 6830 if (returnType == void.class) { 6831 // OK 6832 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 6833 // leading V argument missing => error 6834 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6835 throw misMatchedTypes("body function", bodyType, expected); 6836 } else { 6837 outerList = innerList.subList(1, innerList.size()); 6838 } 6839 MethodType predType = pred.type(); 6840 if (predType.returnType() != boolean.class || 6841 !predType.effectivelyIdenticalParameters(0, innerList)) { 6842 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 6843 } 6844 if (init != null) { 6845 MethodType initType = init.type(); 6846 if (initType.returnType() != returnType || 6847 !initType.effectivelyIdenticalParameters(0, outerList)) { 6848 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6849 } 6850 } 6851 } 6852 6853 /** 6854 * Constructs a loop that runs a given number of iterations. 6855 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6856 * <p> 6857 * The number of iterations is determined by the {@code iterations} handle evaluation result. 6858 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 6859 * It will be initialized to 0 and incremented by 1 in each iteration. 6860 * <p> 6861 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6862 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6863 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6864 * <p> 6865 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6866 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6867 * iteration variable. 6868 * The result of the loop handle execution will be the final {@code V} value of that variable 6869 * (or {@code void} if there is no {@code V} variable). 6870 * <p> 6871 * The following rules hold for the argument handles:<ul> 6872 * <li>The {@code iterations} handle must not be {@code null}, and must return 6873 * the type {@code int}, referred to here as {@code I} in parameter type lists. 6874 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6875 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6876 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6877 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6878 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6879 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6880 * of types called the <em>internal parameter list</em>. 6881 * It will constrain the parameter lists of the other loop parts. 6882 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6883 * with no additional {@code A} types, then the internal parameter list is extended by 6884 * the argument types {@code A...} of the {@code iterations} handle. 6885 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6886 * list {@code (A...)} is called the <em>external parameter list</em>. 6887 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6888 * additional state variable of the loop. 6889 * The body must both accept a leading parameter and return a value of this type {@code V}. 6890 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6891 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6892 * <a href="MethodHandles.html#effid">effectively identical</a> 6893 * to the external parameter list {@code (A...)}. 6894 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6895 * {@linkplain #empty default value}. 6896 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 6897 * effectively identical to the external parameter list {@code (A...)}. 6898 * </ul> 6899 * <p> 6900 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6901 * <li>The loop handle's result type is the result type {@code V} of the body. 6902 * <li>The loop handle's parameter types are the types {@code (A...)}, 6903 * from the external parameter list. 6904 * </ul> 6905 * <p> 6906 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6907 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6908 * arguments passed to the loop. 6909 * {@snippet lang="java" : 6910 * int iterations(A...); 6911 * V init(A...); 6912 * V body(V, int, A...); 6913 * V countedLoop(A... a...) { 6914 * int end = iterations(a...); 6915 * V v = init(a...); 6916 * for (int i = 0; i < end; ++i) { 6917 * v = body(v, i, a...); 6918 * } 6919 * return v; 6920 * } 6921 * } 6922 * 6923 * @apiNote Example with a fully conformant body method: 6924 * {@snippet lang="java" : 6925 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6926 * // => a variation on a well known theme 6927 * static String step(String v, int counter, String init) { return "na " + v; } 6928 * // assume MH_step is a handle to the method above 6929 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 6930 * MethodHandle start = MethodHandles.identity(String.class); 6931 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 6932 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 6933 * } 6934 * 6935 * @apiNote Example with the simplest possible body method type, 6936 * and passing the number of iterations to the loop invocation: 6937 * {@snippet lang="java" : 6938 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6939 * // => a variation on a well known theme 6940 * static String step(String v, int counter ) { return "na " + v; } 6941 * // assume MH_step is a handle to the method above 6942 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 6943 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 6944 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 6945 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 6946 * } 6947 * 6948 * @apiNote Example that treats the number of iterations, string to append to, and string to append 6949 * as loop parameters: 6950 * {@snippet lang="java" : 6951 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6952 * // => a variation on a well known theme 6953 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 6954 * // assume MH_step is a handle to the method above 6955 * MethodHandle count = MethodHandles.identity(int.class); 6956 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 6957 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 6958 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 6959 * } 6960 * 6961 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 6962 * to enforce a loop type: 6963 * {@snippet lang="java" : 6964 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6965 * // => a variation on a well known theme 6966 * static String step(String v, int counter, String pre) { return pre + " " + v; } 6967 * // assume MH_step is a handle to the method above 6968 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 6969 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 6970 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 6971 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 6972 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 6973 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 6974 * } 6975 * 6976 * @apiNote The implementation of this method can be expressed as follows: 6977 * {@snippet lang="java" : 6978 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6979 * return countedLoop(empty(iterations.type()), iterations, init, body); 6980 * } 6981 * } 6982 * 6983 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 6984 * result type must be {@code int}. See above for other constraints. 6985 * @param init optional initializer, providing the initial value of the loop variable. 6986 * May be {@code null}, implying a default initial value. See above for other constraints. 6987 * @param body body of the loop, which may not be {@code null}. 6988 * It controls the loop parameters and result type in the standard case (see above for details). 6989 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6990 * and may accept any number of additional types. 6991 * See above for other constraints. 6992 * 6993 * @return a method handle representing the loop. 6994 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 6995 * @throws IllegalArgumentException if any argument violates the rules formulated above. 6996 * 6997 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 6998 * @since 9 6999 */ 7000 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7001 return countedLoop(empty(iterations.type()), iterations, init, body); 7002 } 7003 7004 /** 7005 * Constructs a loop that counts over a range of numbers. 7006 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7007 * <p> 7008 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7009 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7010 * values of the loop counter. 7011 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7012 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7013 * <p> 7014 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7015 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7016 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7017 * <p> 7018 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7019 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7020 * iteration variable. 7021 * The result of the loop handle execution will be the final {@code V} value of that variable 7022 * (or {@code void} if there is no {@code V} variable). 7023 * <p> 7024 * The following rules hold for the argument handles:<ul> 7025 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7026 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7027 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7028 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7029 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7030 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7031 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7032 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7033 * of types called the <em>internal parameter list</em>. 7034 * It will constrain the parameter lists of the other loop parts. 7035 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7036 * with no additional {@code A} types, then the internal parameter list is extended by 7037 * the argument types {@code A...} of the {@code end} handle. 7038 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7039 * list {@code (A...)} is called the <em>external parameter list</em>. 7040 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7041 * additional state variable of the loop. 7042 * The body must both accept a leading parameter and return a value of this type {@code V}. 7043 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7044 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7045 * <a href="MethodHandles.html#effid">effectively identical</a> 7046 * to the external parameter list {@code (A...)}. 7047 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7048 * {@linkplain #empty default value}. 7049 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7050 * effectively identical to the external parameter list {@code (A...)}. 7051 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7052 * to the external parameter list. 7053 * </ul> 7054 * <p> 7055 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7056 * <li>The loop handle's result type is the result type {@code V} of the body. 7057 * <li>The loop handle's parameter types are the types {@code (A...)}, 7058 * from the external parameter list. 7059 * </ul> 7060 * <p> 7061 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7062 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7063 * arguments passed to the loop. 7064 * {@snippet lang="java" : 7065 * int start(A...); 7066 * int end(A...); 7067 * V init(A...); 7068 * V body(V, int, A...); 7069 * V countedLoop(A... a...) { 7070 * int e = end(a...); 7071 * int s = start(a...); 7072 * V v = init(a...); 7073 * for (int i = s; i < e; ++i) { 7074 * v = body(v, i, a...); 7075 * } 7076 * return v; 7077 * } 7078 * } 7079 * 7080 * @apiNote The implementation of this method can be expressed as follows: 7081 * {@snippet lang="java" : 7082 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7083 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7084 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7085 * // the following semantics: 7086 * // MH_increment: (int limit, int counter) -> counter + 1 7087 * // MH_predicate: (int limit, int counter) -> counter < limit 7088 * Class<?> counterType = start.type().returnType(); // int 7089 * Class<?> returnType = body.type().returnType(); 7090 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7091 * if (returnType != void.class) { // ignore the V variable 7092 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7093 * pred = dropArguments(pred, 1, returnType); // ditto 7094 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7095 * } 7096 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7097 * MethodHandle[] 7098 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7099 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7100 * indexVar = { start, incr }; // i = start(); i = i + 1 7101 * return loop(loopLimit, bodyClause, indexVar); 7102 * } 7103 * } 7104 * 7105 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7106 * See above for other constraints. 7107 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7108 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7109 * @param init optional initializer, providing the initial value of the loop variable. 7110 * May be {@code null}, implying a default initial value. See above for other constraints. 7111 * @param body body of the loop, which may not be {@code null}. 7112 * It controls the loop parameters and result type in the standard case (see above for details). 7113 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7114 * and may accept any number of additional types. 7115 * See above for other constraints. 7116 * 7117 * @return a method handle representing the loop. 7118 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7119 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7120 * 7121 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7122 * @since 9 7123 */ 7124 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7125 countedLoopChecks(start, end, init, body); 7126 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7127 Class<?> limitType = end.type().returnType(); // yes, int again 7128 Class<?> returnType = body.type().returnType(); 7129 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7130 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7131 MethodHandle retv = null; 7132 if (returnType != void.class) { 7133 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7134 pred = dropArguments(pred, 1, returnType); // ditto 7135 retv = dropArguments(identity(returnType), 0, counterType); 7136 } 7137 body = dropArguments(body, 0, counterType); // ignore the limit variable 7138 MethodHandle[] 7139 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7140 bodyClause = { init, body }, // v = init(); v = body(v, i) 7141 indexVar = { start, incr }; // i = start(); i = i + 1 7142 return loop(loopLimit, bodyClause, indexVar); 7143 } 7144 7145 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7146 Objects.requireNonNull(start); 7147 Objects.requireNonNull(end); 7148 Objects.requireNonNull(body); 7149 Class<?> counterType = start.type().returnType(); 7150 if (counterType != int.class) { 7151 MethodType expected = start.type().changeReturnType(int.class); 7152 throw misMatchedTypes("start function", start.type(), expected); 7153 } else if (end.type().returnType() != counterType) { 7154 MethodType expected = end.type().changeReturnType(counterType); 7155 throw misMatchedTypes("end function", end.type(), expected); 7156 } 7157 MethodType bodyType = body.type(); 7158 Class<?> returnType = bodyType.returnType(); 7159 List<Class<?>> innerList = bodyType.parameterList(); 7160 // strip leading V value if present 7161 int vsize = (returnType == void.class ? 0 : 1); 7162 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7163 // argument list has no "V" => error 7164 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7165 throw misMatchedTypes("body function", bodyType, expected); 7166 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7167 // missing I type => error 7168 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7169 throw misMatchedTypes("body function", bodyType, expected); 7170 } 7171 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7172 if (outerList.isEmpty()) { 7173 // special case; take lists from end handle 7174 outerList = end.type().parameterList(); 7175 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7176 } 7177 MethodType expected = methodType(counterType, outerList); 7178 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7179 throw misMatchedTypes("start parameter types", start.type(), expected); 7180 } 7181 if (end.type() != start.type() && 7182 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7183 throw misMatchedTypes("end parameter types", end.type(), expected); 7184 } 7185 if (init != null) { 7186 MethodType initType = init.type(); 7187 if (initType.returnType() != returnType || 7188 !initType.effectivelyIdenticalParameters(0, outerList)) { 7189 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7190 } 7191 } 7192 } 7193 7194 /** 7195 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7196 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7197 * <p> 7198 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7199 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7200 * <p> 7201 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7202 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7203 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7204 * <p> 7205 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7206 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7207 * iteration variable. 7208 * The result of the loop handle execution will be the final {@code V} value of that variable 7209 * (or {@code void} if there is no {@code V} variable). 7210 * <p> 7211 * The following rules hold for the argument handles:<ul> 7212 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7213 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7214 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7215 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7216 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7217 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7218 * of types called the <em>internal parameter list</em>. 7219 * It will constrain the parameter lists of the other loop parts. 7220 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7221 * with no additional {@code A} types, then the internal parameter list is extended by 7222 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7223 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7224 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7225 * list {@code (A...)} is called the <em>external parameter list</em>. 7226 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7227 * additional state variable of the loop. 7228 * The body must both accept a leading parameter and return a value of this type {@code V}. 7229 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7230 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7231 * <a href="MethodHandles.html#effid">effectively identical</a> 7232 * to the external parameter list {@code (A...)}. 7233 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7234 * {@linkplain #empty default value}. 7235 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7236 * type {@code java.util.Iterator} or a subtype thereof. 7237 * The iterator it produces when the loop is executed will be assumed 7238 * to yield values which can be converted to type {@code T}. 7239 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7240 * effectively identical to the external parameter list {@code (A...)}. 7241 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7242 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7243 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7244 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7245 * the {@link MethodHandle#asType asType} conversion method. 7246 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7247 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7248 * </ul> 7249 * <p> 7250 * The type {@code T} may be either a primitive or reference. 7251 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7252 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7253 * as if by the {@link MethodHandle#asType asType} conversion method. 7254 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7255 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7256 * <p> 7257 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7258 * <li>The loop handle's result type is the result type {@code V} of the body. 7259 * <li>The loop handle's parameter types are the types {@code (A...)}, 7260 * from the external parameter list. 7261 * </ul> 7262 * <p> 7263 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7264 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7265 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7266 * {@snippet lang="java" : 7267 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7268 * V init(A...); 7269 * V body(V,T,A...); 7270 * V iteratedLoop(A... a...) { 7271 * Iterator<T> it = iterator(a...); 7272 * V v = init(a...); 7273 * while (it.hasNext()) { 7274 * T t = it.next(); 7275 * v = body(v, t, a...); 7276 * } 7277 * return v; 7278 * } 7279 * } 7280 * 7281 * @apiNote Example: 7282 * {@snippet lang="java" : 7283 * // get an iterator from a list 7284 * static List<String> reverseStep(List<String> r, String e) { 7285 * r.add(0, e); 7286 * return r; 7287 * } 7288 * static List<String> newArrayList() { return new ArrayList<>(); } 7289 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7290 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7291 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7292 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7293 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7294 * } 7295 * 7296 * @apiNote The implementation of this method can be expressed approximately as follows: 7297 * {@snippet lang="java" : 7298 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7299 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7300 * Class<?> returnType = body.type().returnType(); 7301 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7302 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7303 * MethodHandle retv = null, step = body, startIter = iterator; 7304 * if (returnType != void.class) { 7305 * // the simple thing first: in (I V A...), drop the I to get V 7306 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7307 * // body type signature (V T A...), internal loop types (I V A...) 7308 * step = swapArguments(body, 0, 1); // swap V <-> T 7309 * } 7310 * if (startIter == null) startIter = MH_getIter; 7311 * MethodHandle[] 7312 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7313 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7314 * return loop(iterVar, bodyClause); 7315 * } 7316 * } 7317 * 7318 * @param iterator an optional handle to return the iterator to start the loop. 7319 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7320 * See above for other constraints. 7321 * @param init optional initializer, providing the initial value of the loop variable. 7322 * May be {@code null}, implying a default initial value. See above for other constraints. 7323 * @param body body of the loop, which may not be {@code null}. 7324 * It controls the loop parameters and result type in the standard case (see above for details). 7325 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7326 * and may accept any number of additional types. 7327 * See above for other constraints. 7328 * 7329 * @return a method handle embodying the iteration loop functionality. 7330 * @throws NullPointerException if the {@code body} handle is {@code null}. 7331 * @throws IllegalArgumentException if any argument violates the above requirements. 7332 * 7333 * @since 9 7334 */ 7335 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7336 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7337 Class<?> returnType = body.type().returnType(); 7338 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7339 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7340 MethodHandle startIter; 7341 MethodHandle nextVal; 7342 { 7343 MethodType iteratorType; 7344 if (iterator == null) { 7345 // derive argument type from body, if available, else use Iterable 7346 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7347 iteratorType = startIter.type().changeParameterType(0, iterableType); 7348 } else { 7349 // force return type to the internal iterator class 7350 iteratorType = iterator.type().changeReturnType(Iterator.class); 7351 startIter = iterator; 7352 } 7353 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7354 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7355 7356 // perform the asType transforms under an exception transformer, as per spec.: 7357 try { 7358 startIter = startIter.asType(iteratorType); 7359 nextVal = nextRaw.asType(nextValType); 7360 } catch (WrongMethodTypeException ex) { 7361 throw new IllegalArgumentException(ex); 7362 } 7363 } 7364 7365 MethodHandle retv = null, step = body; 7366 if (returnType != void.class) { 7367 // the simple thing first: in (I V A...), drop the I to get V 7368 retv = dropArguments(identity(returnType), 0, Iterator.class); 7369 // body type signature (V T A...), internal loop types (I V A...) 7370 step = swapArguments(body, 0, 1); // swap V <-> T 7371 } 7372 7373 MethodHandle[] 7374 iterVar = { startIter, null, hasNext, retv }, 7375 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7376 return loop(iterVar, bodyClause); 7377 } 7378 7379 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7380 Objects.requireNonNull(body); 7381 MethodType bodyType = body.type(); 7382 Class<?> returnType = bodyType.returnType(); 7383 List<Class<?>> internalParamList = bodyType.parameterList(); 7384 // strip leading V value if present 7385 int vsize = (returnType == void.class ? 0 : 1); 7386 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7387 // argument list has no "V" => error 7388 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7389 throw misMatchedTypes("body function", bodyType, expected); 7390 } else if (internalParamList.size() <= vsize) { 7391 // missing T type => error 7392 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7393 throw misMatchedTypes("body function", bodyType, expected); 7394 } 7395 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7396 Class<?> iterableType = null; 7397 if (iterator != null) { 7398 // special case; if the body handle only declares V and T then 7399 // the external parameter list is obtained from iterator handle 7400 if (externalParamList.isEmpty()) { 7401 externalParamList = iterator.type().parameterList(); 7402 } 7403 MethodType itype = iterator.type(); 7404 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7405 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7406 } 7407 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7408 MethodType expected = methodType(itype.returnType(), externalParamList); 7409 throw misMatchedTypes("iterator parameters", itype, expected); 7410 } 7411 } else { 7412 if (externalParamList.isEmpty()) { 7413 // special case; if the iterator handle is null and the body handle 7414 // only declares V and T then the external parameter list consists 7415 // of Iterable 7416 externalParamList = List.of(Iterable.class); 7417 iterableType = Iterable.class; 7418 } else { 7419 // special case; if the iterator handle is null and the external 7420 // parameter list is not empty then the first parameter must be 7421 // assignable to Iterable 7422 iterableType = externalParamList.get(0); 7423 if (!Iterable.class.isAssignableFrom(iterableType)) { 7424 throw newIllegalArgumentException( 7425 "inferred first loop argument must inherit from Iterable: " + iterableType); 7426 } 7427 } 7428 } 7429 if (init != null) { 7430 MethodType initType = init.type(); 7431 if (initType.returnType() != returnType || 7432 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7433 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7434 } 7435 } 7436 return iterableType; // help the caller a bit 7437 } 7438 7439 /*non-public*/ 7440 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7441 // there should be a better way to uncross my wires 7442 int arity = mh.type().parameterCount(); 7443 int[] order = new int[arity]; 7444 for (int k = 0; k < arity; k++) order[k] = k; 7445 order[i] = j; order[j] = i; 7446 Class<?>[] types = mh.type().parameterArray(); 7447 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7448 MethodType swapType = methodType(mh.type().returnType(), types); 7449 return permuteArguments(mh, swapType, order); 7450 } 7451 7452 /** 7453 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7454 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7455 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7456 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7457 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7458 * {@code try-finally} handle. 7459 * <p> 7460 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7461 * The first is the exception thrown during the 7462 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7463 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7464 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7465 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7466 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7467 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7468 * <p> 7469 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7470 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7471 * two extra leading parameters:<ul> 7472 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7473 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7474 * the result from the execution of the {@code target} handle. 7475 * This parameter is not present if the {@code target} returns {@code void}. 7476 * </ul> 7477 * <p> 7478 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7479 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7480 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7481 * the cleanup. 7482 * {@snippet lang="java" : 7483 * V target(A..., B...); 7484 * V cleanup(Throwable, V, A...); 7485 * V adapter(A... a, B... b) { 7486 * V result = (zero value for V); 7487 * Throwable throwable = null; 7488 * try { 7489 * result = target(a..., b...); 7490 * } catch (Throwable t) { 7491 * throwable = t; 7492 * throw t; 7493 * } finally { 7494 * result = cleanup(throwable, result, a...); 7495 * } 7496 * return result; 7497 * } 7498 * } 7499 * <p> 7500 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7501 * be modified by execution of the target, and so are passed unchanged 7502 * from the caller to the cleanup, if it is invoked. 7503 * <p> 7504 * The target and cleanup must return the same type, even if the cleanup 7505 * always throws. 7506 * To create such a throwing cleanup, compose the cleanup logic 7507 * with {@link #throwException throwException}, 7508 * in order to create a method handle of the correct return type. 7509 * <p> 7510 * Note that {@code tryFinally} never converts exceptions into normal returns. 7511 * In rare cases where exceptions must be converted in that way, first wrap 7512 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7513 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7514 * <p> 7515 * It is recommended that the first parameter type of {@code cleanup} be 7516 * declared {@code Throwable} rather than a narrower subtype. This ensures 7517 * {@code cleanup} will always be invoked with whatever exception that 7518 * {@code target} throws. Declaring a narrower type may result in a 7519 * {@code ClassCastException} being thrown by the {@code try-finally} 7520 * handle if the type of the exception thrown by {@code target} is not 7521 * assignable to the first parameter type of {@code cleanup}. Note that 7522 * various exception types of {@code VirtualMachineError}, 7523 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7524 * thrown by almost any kind of Java code, and a finally clause that 7525 * catches (say) only {@code IOException} would mask any of the others 7526 * behind a {@code ClassCastException}. 7527 * 7528 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7529 * @param cleanup the handle that is invoked in the finally block. 7530 * 7531 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7532 * @throws NullPointerException if any argument is null 7533 * @throws IllegalArgumentException if {@code cleanup} does not accept 7534 * the required leading arguments, or if the method handle types do 7535 * not match in their return types and their 7536 * corresponding trailing parameters 7537 * 7538 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7539 * @since 9 7540 */ 7541 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7542 Class<?>[] targetParamTypes = target.type().ptypes(); 7543 Class<?> rtype = target.type().returnType(); 7544 7545 tryFinallyChecks(target, cleanup); 7546 7547 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7548 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7549 // target parameter list. 7550 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7551 7552 // Ensure that the intrinsic type checks the instance thrown by the 7553 // target against the first parameter of cleanup 7554 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7555 7556 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7557 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7558 } 7559 7560 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7561 Class<?> rtype = target.type().returnType(); 7562 if (rtype != cleanup.type().returnType()) { 7563 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7564 } 7565 MethodType cleanupType = cleanup.type(); 7566 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7567 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7568 } 7569 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7570 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7571 } 7572 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7573 // target parameter list. 7574 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7575 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7576 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7577 cleanup.type(), target.type()); 7578 } 7579 } 7580 7581 /** 7582 * Creates a table switch method handle, which can be used to switch over a set of target 7583 * method handles, based on a given target index, called selector. 7584 * <p> 7585 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7586 * and where {@code N} is the number of target method handles, the table switch method 7587 * handle will invoke the n-th target method handle from the list of target method handles. 7588 * <p> 7589 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7590 * method handle will invoke the given fallback method handle. 7591 * <p> 7592 * All method handles passed to this method must have the same type, with the additional 7593 * requirement that the leading parameter be of type {@code int}. The leading parameter 7594 * represents the selector. 7595 * <p> 7596 * Any trailing parameters present in the type will appear on the returned table switch 7597 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7598 * together with the selector value, to the selected method handle when invoking it. 7599 * 7600 * @apiNote Example: 7601 * The cases each drop the {@code selector} value they are given, and take an additional 7602 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7603 * to a specific constant label string for each case: 7604 * {@snippet lang="java" : 7605 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7606 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7607 * MethodType.methodType(String.class, String.class)); 7608 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7609 * 7610 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7611 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7612 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7613 * 7614 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7615 * caseDefault, 7616 * case0, 7617 * case1 7618 * ); 7619 * 7620 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7621 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7622 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7623 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7624 * } 7625 * 7626 * @param fallback the fallback method handle that is called when the selector is not 7627 * within the range {@code [0, N)}. 7628 * @param targets array of target method handles. 7629 * @return the table switch method handle. 7630 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7631 * any of the elements of the {@code targets} array are 7632 * {@code null}. 7633 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7634 * parameter of the fallback handle or any of the target 7635 * handles is not {@code int}, or if the types of 7636 * the fallback handle and all of target handles are 7637 * not the same. 7638 * 7639 * @since 17 7640 */ 7641 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7642 Objects.requireNonNull(fallback); 7643 Objects.requireNonNull(targets); 7644 targets = targets.clone(); 7645 MethodType type = tableSwitchChecks(fallback, targets); 7646 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7647 } 7648 7649 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7650 if (caseActions.length == 0) 7651 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7652 7653 MethodType expectedType = defaultCase.type(); 7654 7655 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7656 throw new IllegalArgumentException( 7657 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7658 7659 for (MethodHandle mh : caseActions) { 7660 Objects.requireNonNull(mh); 7661 if (mh.type() != expectedType) 7662 throw new IllegalArgumentException( 7663 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7664 } 7665 7666 return expectedType; 7667 } 7668 7669 /** 7670 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7671 * <p> 7672 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7673 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7674 * to the target var handle. 7675 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7676 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7677 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7678 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7679 * <p> 7680 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7681 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7682 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7683 * will be appended to the coordinates of the target var handle). 7684 * <p> 7685 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7686 * throw an {@link IllegalStateException}. 7687 * <p> 7688 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7689 * atomic access guarantees as those featured by the target var handle. 7690 * 7691 * @param target the target var handle 7692 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7693 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7694 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7695 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7696 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7697 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7698 * @throws NullPointerException if any of the arguments is {@code null}. 7699 * @since 22 7700 */ 7701 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7702 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7703 } 7704 7705 /** 7706 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7707 * <p> 7708 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7709 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7710 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7711 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7712 * by the adaptation) to the target var handle. 7713 * <p> 7714 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7715 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7716 * <p> 7717 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7718 * throw an {@link IllegalStateException}. 7719 * <p> 7720 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7721 * atomic access guarantees as those featured by the target var handle. 7722 * 7723 * @param target the target var handle 7724 * @param pos the position of the first coordinate to be transformed 7725 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7726 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7727 * to the new coordinate values. 7728 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7729 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7730 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7731 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7732 * or if it's determined that any of the filters throws any checked exceptions. 7733 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 7734 * @since 22 7735 */ 7736 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 7737 return VarHandles.filterCoordinates(target, pos, filters); 7738 } 7739 7740 /** 7741 * Provides a target var handle with one or more <em>bound coordinates</em> 7742 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 7743 * coordinate types than the target var handle. 7744 * <p> 7745 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 7746 * are joined with bound coordinate values, and then passed to the target var handle. 7747 * <p> 7748 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 7749 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7750 * <p> 7751 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7752 * atomic access guarantees as those featured by the target var handle. 7753 * 7754 * @param target the var handle to invoke after the bound coordinates are inserted 7755 * @param pos the position of the first coordinate to be inserted 7756 * @param values the series of bound coordinates to insert 7757 * @return an adapter var handle which inserts additional coordinates, 7758 * before calling the target var handle 7759 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7760 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 7761 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 7762 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 7763 * of the target var handle. 7764 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 7765 * @since 22 7766 */ 7767 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 7768 return VarHandles.insertCoordinates(target, pos, values); 7769 } 7770 7771 /** 7772 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 7773 * so that the new coordinates match the provided ones. 7774 * <p> 7775 * The given array controls the reordering. 7776 * Call {@code #I} the number of incoming coordinates (the value 7777 * {@code newCoordinates.size()}), and call {@code #O} the number 7778 * of outgoing coordinates (the number of coordinates associated with the target var handle). 7779 * Then the length of the reordering array must be {@code #O}, 7780 * and each element must be a non-negative number less than {@code #I}. 7781 * For every {@code N} less than {@code #O}, the {@code N}-th 7782 * outgoing coordinate will be taken from the {@code I}-th incoming 7783 * coordinate, where {@code I} is {@code reorder[N]}. 7784 * <p> 7785 * No coordinate value conversions are applied. 7786 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 7787 * must be identical to the type of the corresponding outgoing coordinate 7788 * in the target var handle. 7789 * <p> 7790 * The reordering array need not specify an actual permutation. 7791 * An incoming coordinate will be duplicated if its index appears 7792 * more than once in the array, and an incoming coordinate will be dropped 7793 * if its index does not appear in the array. 7794 * <p> 7795 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7796 * atomic access guarantees as those featured by the target var handle. 7797 * @param target the var handle to invoke after the coordinates have been reordered 7798 * @param newCoordinates the new coordinate types 7799 * @param reorder an index array which controls the reordering 7800 * @return an adapter var handle which re-arranges the incoming coordinate values, 7801 * before calling the target var handle 7802 * @throws IllegalArgumentException if the index array length is not equal to 7803 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 7804 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 7805 * the target var handle and in {@code newCoordinates} are not identical. 7806 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 7807 * @since 22 7808 */ 7809 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 7810 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 7811 } 7812 7813 /** 7814 * Adapts a target var handle by pre-processing 7815 * a sub-sequence of its coordinate values with a filter (a method handle). 7816 * The pre-processed coordinates are replaced by the result (if any) of the 7817 * filter function and the target var handle is then called on the modified (usually shortened) 7818 * coordinate list. 7819 * <p> 7820 * If {@code R} is the return type of the filter, then: 7821 * <ul> 7822 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 7823 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 7824 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 7825 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 7826 * target var handle.</li> 7827 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 7828 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 7829 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 7830 * downstream invocation of the target var handle.</li> 7831 * </ul> 7832 * <p> 7833 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7834 * throw an {@link IllegalStateException}. 7835 * <p> 7836 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7837 * atomic access guarantees as those featured by the target var handle. 7838 * 7839 * @param target the var handle to invoke after the coordinates have been filtered 7840 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 7841 * @param filter the filter method handle 7842 * @return an adapter var handle which filters the incoming coordinate values, 7843 * before calling the target var handle 7844 * @throws IllegalArgumentException if the return type of {@code filter} 7845 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 7846 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7847 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 7848 * or if it's determined that {@code filter} throws any checked exceptions. 7849 * @throws NullPointerException if any of the arguments is {@code null}. 7850 * @since 22 7851 */ 7852 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 7853 return VarHandles.collectCoordinates(target, pos, filter); 7854 } 7855 7856 /** 7857 * Returns a var handle which will discard some dummy coordinates before delegating to the 7858 * target var handle. As a consequence, the resulting var handle will feature more 7859 * coordinate types than the target var handle. 7860 * <p> 7861 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 7862 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 7863 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 7864 * <p> 7865 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7866 * atomic access guarantees as those featured by the target var handle. 7867 * 7868 * @param target the var handle to invoke after the dummy coordinates are dropped 7869 * @param pos position of the first coordinate to drop (zero for the leftmost) 7870 * @param valueTypes the type(s) of the coordinate(s) to drop 7871 * @return an adapter var handle which drops some dummy coordinates, 7872 * before calling the target var handle 7873 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 7874 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 7875 * @since 22 7876 */ 7877 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 7878 return VarHandles.dropCoordinates(target, pos, valueTypes); 7879 } 7880 }