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 * 2667 * 2668 * @param refc the class or interface from which the method is accessed 2669 * @param type the type of the method, with the receiver argument omitted, and a void return type 2670 * @return the desired method handle 2671 * @throws NoSuchMethodException if the constructor does not exist 2672 * @throws IllegalAccessException if access checking fails 2673 * or if the method's variable arity modifier bit 2674 * is set and {@code asVarargsCollector} fails 2675 * @throws NullPointerException if any argument is null 2676 */ 2677 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2678 if (refc.isArray()) { 2679 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2680 } 2681 if (type.returnType() != void.class) { 2682 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName()); 2683 } 2684 String name = ConstantDescs.INIT_NAME; 2685 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2686 return getDirectConstructor(refc, ctor); 2687 } 2688 2689 /** 2690 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2691 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2692 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2693 * and then determines whether the class is accessible to this lookup object. 2694 * <p> 2695 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2696 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2697 * of {@code '['} and followed by the element type as encoded in the 2698 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2699 * <p> 2700 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2701 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2702 * 2703 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2704 * or the string representing an array class 2705 * @return the requested class. 2706 * @throws LinkageError if the linkage fails 2707 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2708 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2709 * modes. 2710 * @throws NullPointerException if {@code targetName} is null 2711 * @since 9 2712 * @jvms 5.4.3.1 Class and Interface Resolution 2713 */ 2714 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2715 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2716 return accessClass(targetClass); 2717 } 2718 2719 /** 2720 * Ensures that {@code targetClass} has been initialized. The class 2721 * to be initialized must be {@linkplain #accessClass accessible} 2722 * to this {@code Lookup} object. This method causes {@code targetClass} 2723 * to be initialized if it has not been already initialized, 2724 * as specified in JVMS {@jvms 5.5}. 2725 * 2726 * <p> 2727 * This method returns when {@code targetClass} is fully initialized, or 2728 * when {@code targetClass} is being initialized by the current thread. 2729 * 2730 * @param <T> the type of the class to be initialized 2731 * @param targetClass the class to be initialized 2732 * @return {@code targetClass} that has been initialized, or that is being 2733 * initialized by the current thread. 2734 * 2735 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2736 * or array class 2737 * @throws IllegalAccessException if {@code targetClass} is not 2738 * {@linkplain #accessClass accessible} to this lookup 2739 * @throws ExceptionInInitializerError if the class initialization provoked 2740 * by this method fails 2741 * @since 15 2742 * @jvms 5.5 Initialization 2743 */ 2744 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2745 if (targetClass.isPrimitive()) 2746 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2747 if (targetClass.isArray()) 2748 throw new IllegalArgumentException(targetClass + " is an array class"); 2749 2750 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2751 throw makeAccessException(targetClass); 2752 } 2753 2754 // ensure class initialization 2755 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2756 return targetClass; 2757 } 2758 2759 /* 2760 * Returns IllegalAccessException due to access violation to the given targetClass. 2761 * 2762 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2763 * which verifies access to a class rather a member. 2764 */ 2765 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2766 String message = "access violation: "+ targetClass; 2767 if (this == MethodHandles.publicLookup()) { 2768 message += ", from public Lookup"; 2769 } else { 2770 Module m = lookupClass().getModule(); 2771 message += ", from " + lookupClass() + " (" + m + ")"; 2772 if (prevLookupClass != null) { 2773 message += ", previous lookup " + 2774 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2775 } 2776 } 2777 return new IllegalAccessException(message); 2778 } 2779 2780 /** 2781 * Determines if a class can be accessed from the lookup context defined by 2782 * this {@code Lookup} object. The static initializer of the class is not run. 2783 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2784 * if the element type of the array class is accessible. Otherwise, 2785 * {@code targetClass} is determined as accessible as follows. 2786 * 2787 * <p> 2788 * If {@code targetClass} is in the same module as the lookup class, 2789 * the lookup class is {@code LC} in module {@code M1} and 2790 * the previous lookup class is in module {@code M0} or 2791 * {@code null} if not present, 2792 * {@code targetClass} is accessible if and only if one of the following is true: 2793 * <ul> 2794 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2795 * {@code LC} or other class in the same nest of {@code LC}.</li> 2796 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2797 * in the same runtime package of {@code LC}.</li> 2798 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2799 * a public type in {@code M1}.</li> 2800 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2801 * a public type in a package exported by {@code M1} to at least {@code M0} 2802 * if the previous lookup class is present; otherwise, {@code targetClass} 2803 * is a public type in a package exported by {@code M1} unconditionally.</li> 2804 * </ul> 2805 * 2806 * <p> 2807 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2808 * can access public types in all modules when the type is in a package 2809 * that is exported unconditionally. 2810 * <p> 2811 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2812 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2813 * is inaccessible. 2814 * <p> 2815 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2816 * {@code M1} is the module containing {@code lookupClass} and 2817 * {@code M2} is the module containing {@code targetClass}, 2818 * then {@code targetClass} is accessible if and only if 2819 * <ul> 2820 * <li>{@code M1} reads {@code M2}, and 2821 * <li>{@code targetClass} is public and in a package exported by 2822 * {@code M2} at least to {@code M1}. 2823 * </ul> 2824 * <p> 2825 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2826 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2827 * containing the previous lookup class, then {@code targetClass} is accessible 2828 * if and only if one of the following is true: 2829 * <ul> 2830 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2831 * {@linkplain Module#canRead(Module)} reads} {@code M0} and the type is 2832 * in a package that is exported to at least {@code M1}. 2833 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2834 * {@linkplain Module#canRead(Module)} reads} {@code M1} and the type is 2835 * in a package that is exported to at least {@code M0}. 2836 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2837 * and {@code M1} reads {@code M2} and the type is in a package 2838 * that is exported to at least both {@code M0} and {@code M2}. 2839 * </ul> 2840 * <p> 2841 * Otherwise, {@code targetClass} is not accessible. 2842 * 2843 * @param <T> the type of the class to be access-checked 2844 * @param targetClass the class to be access-checked 2845 * @return {@code targetClass} that has been access-checked 2846 * @throws IllegalAccessException if the class is not accessible from the lookup class 2847 * and previous lookup class, if present, using the allowed access modes. 2848 * @throws NullPointerException if {@code targetClass} is {@code null} 2849 * @since 9 2850 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2851 */ 2852 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2853 if (!isClassAccessible(targetClass)) { 2854 throw makeAccessException(targetClass); 2855 } 2856 return targetClass; 2857 } 2858 2859 /** 2860 * Produces an early-bound method handle for a virtual method. 2861 * It will bypass checks for overriding methods on the receiver, 2862 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2863 * instruction from within the explicitly specified {@code specialCaller}. 2864 * The type of the method handle will be that of the method, 2865 * with a suitably restricted receiver type prepended. 2866 * (The receiver type will be {@code specialCaller} or a subtype.) 2867 * The method and all its argument types must be accessible 2868 * to the lookup object. 2869 * <p> 2870 * Before method resolution, 2871 * if the explicitly specified caller class is not identical with the 2872 * lookup class, or if this lookup object does not have 2873 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2874 * privileges, the access fails. 2875 * <p> 2876 * The returned method handle will have 2877 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2878 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2879 * <p style="font-size:smaller;"> 2880 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 2881 * are not visible to this API, 2882 * even though the {@code invokespecial} instruction can refer to them 2883 * in special circumstances. Use {@link #findConstructor findConstructor} 2884 * to access instance initialization methods in a safe manner.)</em> 2885 * <p><b>Example:</b> 2886 * {@snippet lang="java" : 2887 import static java.lang.invoke.MethodHandles.*; 2888 import static java.lang.invoke.MethodType.*; 2889 ... 2890 static class Listie extends ArrayList { 2891 public String toString() { return "[wee Listie]"; } 2892 static Lookup lookup() { return MethodHandles.lookup(); } 2893 } 2894 ... 2895 // no access to constructor via invokeSpecial: 2896 MethodHandle MH_newListie = Listie.lookup() 2897 .findConstructor(Listie.class, methodType(void.class)); 2898 Listie l = (Listie) MH_newListie.invokeExact(); 2899 try { assertEquals("impossible", Listie.lookup().findSpecial( 2900 Listie.class, "<init>", methodType(void.class), Listie.class)); 2901 } catch (NoSuchMethodException ex) { } // OK 2902 // access to super and self methods via invokeSpecial: 2903 MethodHandle MH_super = Listie.lookup().findSpecial( 2904 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2905 MethodHandle MH_this = Listie.lookup().findSpecial( 2906 Listie.class, "toString" , methodType(String.class), Listie.class); 2907 MethodHandle MH_duper = Listie.lookup().findSpecial( 2908 Object.class, "toString" , methodType(String.class), Listie.class); 2909 assertEquals("[]", (String) MH_super.invokeExact(l)); 2910 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2911 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2912 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2913 String.class, "toString", methodType(String.class), Listie.class)); 2914 } catch (IllegalAccessException ex) { } // OK 2915 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2916 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2917 * } 2918 * 2919 * @param refc the class or interface from which the method is accessed 2920 * @param name the name of the method (which must not be "<init>") 2921 * @param type the type of the method, with the receiver argument omitted 2922 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2923 * @return the desired method handle 2924 * @throws NoSuchMethodException if the method does not exist 2925 * @throws IllegalAccessException if access checking fails, 2926 * or if the method is {@code static}, 2927 * or if the method's variable arity modifier bit 2928 * is set and {@code asVarargsCollector} fails 2929 * @throws NullPointerException if any argument is null 2930 */ 2931 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 2932 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 2933 checkSpecialCaller(specialCaller, refc); 2934 Lookup specialLookup = this.in(specialCaller); 2935 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 2936 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 2937 } 2938 2939 /** 2940 * Produces a method handle giving read access to a non-static field. 2941 * The type of the method handle will have a return type of the field's 2942 * value type. 2943 * The method handle's single argument will be the instance containing 2944 * the field. 2945 * Access checking is performed immediately on behalf of the lookup class. 2946 * @param refc the class or interface from which the method is accessed 2947 * @param name the field's name 2948 * @param type the field's type 2949 * @return a method handle which can load values from the field 2950 * @throws NoSuchFieldException if the field does not exist 2951 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2952 * @throws NullPointerException if any argument is null 2953 * @see #findVarHandle(Class, String, Class) 2954 */ 2955 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2956 MemberName field = resolveOrFail(REF_getField, refc, name, type); 2957 return getDirectField(REF_getField, refc, field); 2958 } 2959 2960 /** 2961 * Produces a method handle giving write access to a non-static field. 2962 * The type of the method handle will have a void return type. 2963 * The method handle will take two arguments, the instance containing 2964 * the field, and the value to be stored. 2965 * The second argument will be of the field's value type. 2966 * Access checking is performed immediately on behalf of the lookup class. 2967 * @param refc the class or interface from which the method is accessed 2968 * @param name the field's name 2969 * @param type the field's type 2970 * @return a method handle which can store values into the field 2971 * @throws NoSuchFieldException if the field does not exist 2972 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2973 * or {@code final} 2974 * @throws NullPointerException if any argument is null 2975 * @see #findVarHandle(Class, String, Class) 2976 */ 2977 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2978 MemberName field = resolveOrFail(REF_putField, refc, name, type); 2979 return getDirectField(REF_putField, refc, field); 2980 } 2981 2982 /** 2983 * Produces a VarHandle giving access to a non-static field {@code name} 2984 * of type {@code type} declared in a class of type {@code recv}. 2985 * The VarHandle's variable type is {@code type} and it has one 2986 * coordinate type, {@code recv}. 2987 * <p> 2988 * Access checking is performed immediately on behalf of the lookup 2989 * class. 2990 * <p> 2991 * Certain access modes of the returned VarHandle are unsupported under 2992 * the following conditions: 2993 * <ul> 2994 * <li>if the field is declared {@code final}, then the write, atomic 2995 * update, numeric atomic update, and bitwise atomic update access 2996 * modes are unsupported. 2997 * <li>if the field type is anything other than {@code byte}, 2998 * {@code short}, {@code char}, {@code int}, {@code long}, 2999 * {@code float}, or {@code double} then numeric atomic update 3000 * access modes are unsupported. 3001 * <li>if the field type is anything other than {@code boolean}, 3002 * {@code byte}, {@code short}, {@code char}, {@code int} or 3003 * {@code long} then bitwise atomic update access modes are 3004 * unsupported. 3005 * </ul> 3006 * <p> 3007 * If the field is declared {@code volatile} then the returned VarHandle 3008 * will override access to the field (effectively ignore the 3009 * {@code volatile} declaration) in accordance to its specified 3010 * access modes. 3011 * <p> 3012 * If the field type is {@code float} or {@code double} then numeric 3013 * and atomic update access modes compare values using their bitwise 3014 * representation (see {@link Float#floatToRawIntBits} and 3015 * {@link Double#doubleToRawLongBits}, respectively). 3016 * @apiNote 3017 * Bitwise comparison of {@code float} values or {@code double} values, 3018 * as performed by the numeric and atomic update access modes, differ 3019 * from the primitive {@code ==} operator and the {@link Float#equals} 3020 * and {@link Double#equals} methods, specifically with respect to 3021 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3022 * Care should be taken when performing a compare and set or a compare 3023 * and exchange operation with such values since the operation may 3024 * unexpectedly fail. 3025 * There are many possible NaN values that are considered to be 3026 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3027 * provided by Java can distinguish between them. Operation failure can 3028 * occur if the expected or witness value is a NaN value and it is 3029 * transformed (perhaps in a platform specific manner) into another NaN 3030 * value, and thus has a different bitwise representation (see 3031 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3032 * details). 3033 * The values {@code -0.0} and {@code +0.0} have different bitwise 3034 * representations but are considered equal when using the primitive 3035 * {@code ==} operator. Operation failure can occur if, for example, a 3036 * numeric algorithm computes an expected value to be say {@code -0.0} 3037 * and previously computed the witness value to be say {@code +0.0}. 3038 * @param recv the receiver class, of type {@code R}, that declares the 3039 * non-static field 3040 * @param name the field's name 3041 * @param type the field's type, of type {@code T} 3042 * @return a VarHandle giving access to non-static fields. 3043 * @throws NoSuchFieldException if the field does not exist 3044 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3045 * @throws NullPointerException if any argument is null 3046 * @since 9 3047 */ 3048 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3049 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3050 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3051 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3052 } 3053 3054 /** 3055 * Produces a method handle giving read access to a static field. 3056 * The type of the method handle will have a return type of the field's 3057 * value type. 3058 * The method handle will take no arguments. 3059 * Access checking is performed immediately on behalf of the lookup class. 3060 * <p> 3061 * If the returned method handle is invoked, the field's class will 3062 * be initialized, if it has not already been initialized. 3063 * @param refc the class or interface from which the method is accessed 3064 * @param name the field's name 3065 * @param type the field's type 3066 * @return a method handle which can load values from the field 3067 * @throws NoSuchFieldException if the field does not exist 3068 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3069 * @throws NullPointerException if any argument is null 3070 */ 3071 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3072 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3073 return getDirectField(REF_getStatic, refc, field); 3074 } 3075 3076 /** 3077 * Produces a method handle giving write access to a static field. 3078 * The type of the method handle will have a void return type. 3079 * The method handle will take a single 3080 * argument, of the field's value type, the value to be stored. 3081 * Access checking is performed immediately on behalf of the lookup class. 3082 * <p> 3083 * If the returned method handle is invoked, the field's class will 3084 * be initialized, if it has not already been initialized. 3085 * @param refc the class or interface from which the method is accessed 3086 * @param name the field's name 3087 * @param type the field's type 3088 * @return a method handle which can store values into the field 3089 * @throws NoSuchFieldException if the field does not exist 3090 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3091 * or is {@code final} 3092 * @throws NullPointerException if any argument is null 3093 */ 3094 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3095 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3096 return getDirectField(REF_putStatic, refc, field); 3097 } 3098 3099 /** 3100 * Produces a VarHandle giving access to a static field {@code name} of 3101 * type {@code type} declared in a class of type {@code decl}. 3102 * The VarHandle's variable type is {@code type} and it has no 3103 * coordinate types. 3104 * <p> 3105 * Access checking is performed immediately on behalf of the lookup 3106 * class. 3107 * <p> 3108 * If the returned VarHandle is operated on, the declaring class will be 3109 * initialized, if it has not already been initialized. 3110 * <p> 3111 * Certain access modes of the returned VarHandle are unsupported under 3112 * the following conditions: 3113 * <ul> 3114 * <li>if the field is declared {@code final}, then the write, atomic 3115 * update, numeric atomic update, and bitwise atomic update access 3116 * modes are unsupported. 3117 * <li>if the field type is anything other than {@code byte}, 3118 * {@code short}, {@code char}, {@code int}, {@code long}, 3119 * {@code float}, or {@code double}, then numeric atomic update 3120 * access modes are unsupported. 3121 * <li>if the field type is anything other than {@code boolean}, 3122 * {@code byte}, {@code short}, {@code char}, {@code int} or 3123 * {@code long} then bitwise atomic update access modes are 3124 * unsupported. 3125 * </ul> 3126 * <p> 3127 * If the field is declared {@code volatile} then the returned VarHandle 3128 * will override access to the field (effectively ignore the 3129 * {@code volatile} declaration) in accordance to its specified 3130 * access modes. 3131 * <p> 3132 * If the field type is {@code float} or {@code double} then numeric 3133 * and atomic update access modes compare values using their bitwise 3134 * representation (see {@link Float#floatToRawIntBits} and 3135 * {@link Double#doubleToRawLongBits}, respectively). 3136 * @apiNote 3137 * Bitwise comparison of {@code float} values or {@code double} values, 3138 * as performed by the numeric and atomic update access modes, differ 3139 * from the primitive {@code ==} operator and the {@link Float#equals} 3140 * and {@link Double#equals} methods, specifically with respect to 3141 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3142 * Care should be taken when performing a compare and set or a compare 3143 * and exchange operation with such values since the operation may 3144 * unexpectedly fail. 3145 * There are many possible NaN values that are considered to be 3146 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3147 * provided by Java can distinguish between them. Operation failure can 3148 * occur if the expected or witness value is a NaN value and it is 3149 * transformed (perhaps in a platform specific manner) into another NaN 3150 * value, and thus has a different bitwise representation (see 3151 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3152 * details). 3153 * The values {@code -0.0} and {@code +0.0} have different bitwise 3154 * representations but are considered equal when using the primitive 3155 * {@code ==} operator. Operation failure can occur if, for example, a 3156 * numeric algorithm computes an expected value to be say {@code -0.0} 3157 * and previously computed the witness value to be say {@code +0.0}. 3158 * @param decl the class that declares the static field 3159 * @param name the field's name 3160 * @param type the field's type, of type {@code T} 3161 * @return a VarHandle giving access to a static field 3162 * @throws NoSuchFieldException if the field does not exist 3163 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3164 * @throws NullPointerException if any argument is null 3165 * @since 9 3166 */ 3167 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3168 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3169 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3170 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3171 } 3172 3173 /** 3174 * Produces an early-bound method handle for a non-static method. 3175 * The receiver must have a supertype {@code defc} in which a method 3176 * of the given name and type is accessible to the lookup class. 3177 * The method and all its argument types must be accessible to the lookup object. 3178 * The type of the method handle will be that of the method, 3179 * without any insertion of an additional receiver parameter. 3180 * The given receiver will be bound into the method handle, 3181 * so that every call to the method handle will invoke the 3182 * requested method on the given receiver. 3183 * <p> 3184 * The returned method handle will have 3185 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3186 * the method's variable arity modifier bit ({@code 0x0080}) is set 3187 * <em>and</em> the trailing array argument is not the only argument. 3188 * (If the trailing array argument is the only argument, 3189 * the given receiver value will be bound to it.) 3190 * <p> 3191 * This is almost equivalent to the following code, with some differences noted below: 3192 * {@snippet lang="java" : 3193 import static java.lang.invoke.MethodHandles.*; 3194 import static java.lang.invoke.MethodType.*; 3195 ... 3196 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3197 MethodHandle mh1 = mh0.bindTo(receiver); 3198 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3199 return mh1; 3200 * } 3201 * where {@code defc} is either {@code receiver.getClass()} or a super 3202 * type of that class, in which the requested method is accessible 3203 * to the lookup class. 3204 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3205 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3206 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3207 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3208 * @param receiver the object from which the method is accessed 3209 * @param name the name of the method 3210 * @param type the type of the method, with the receiver argument omitted 3211 * @return the desired method handle 3212 * @throws NoSuchMethodException if the method does not exist 3213 * @throws IllegalAccessException if access checking fails 3214 * or if the method's variable arity modifier bit 3215 * is set and {@code asVarargsCollector} fails 3216 * @throws NullPointerException if any argument is null 3217 * @see MethodHandle#bindTo 3218 * @see #findVirtual 3219 */ 3220 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3221 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3222 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3223 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3224 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3225 throw new IllegalAccessException("The restricted defining class " + 3226 mh.type().leadingReferenceParameter().getName() + 3227 " is not assignable from receiver class " + 3228 receiver.getClass().getName()); 3229 } 3230 return mh.bindArgumentL(0, receiver).setVarargs(method); 3231 } 3232 3233 /** 3234 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3235 * to <i>m</i>, if the lookup class has permission. 3236 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3237 * If <i>m</i> is virtual, overriding is respected on every call. 3238 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3239 * The type of the method handle will be that of the method, 3240 * with the receiver type prepended (but only if it is non-static). 3241 * If the method's {@code accessible} flag is not set, 3242 * access checking is performed immediately on behalf of the lookup class. 3243 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3244 * <p> 3245 * The returned method handle will have 3246 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3247 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3248 * <p> 3249 * If <i>m</i> is static, and 3250 * if the returned method handle is invoked, the method's class will 3251 * be initialized, if it has not already been initialized. 3252 * @param m the reflected method 3253 * @return a method handle which can invoke the reflected method 3254 * @throws IllegalAccessException if access checking fails 3255 * or if the method's variable arity modifier bit 3256 * is set and {@code asVarargsCollector} fails 3257 * @throws NullPointerException if the argument is null 3258 */ 3259 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3260 if (m.getDeclaringClass() == MethodHandle.class) { 3261 MethodHandle mh = unreflectForMH(m); 3262 if (mh != null) return mh; 3263 } 3264 if (m.getDeclaringClass() == VarHandle.class) { 3265 MethodHandle mh = unreflectForVH(m); 3266 if (mh != null) return mh; 3267 } 3268 MemberName method = new MemberName(m); 3269 byte refKind = method.getReferenceKind(); 3270 if (refKind == REF_invokeSpecial) 3271 refKind = REF_invokeVirtual; 3272 assert(method.isMethod()); 3273 @SuppressWarnings("deprecation") 3274 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3275 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3276 } 3277 private MethodHandle unreflectForMH(Method m) { 3278 // these names require special lookups because they throw UnsupportedOperationException 3279 if (MemberName.isMethodHandleInvokeName(m.getName())) 3280 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3281 return null; 3282 } 3283 private MethodHandle unreflectForVH(Method m) { 3284 // these names require special lookups because they throw UnsupportedOperationException 3285 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3286 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3287 return null; 3288 } 3289 3290 /** 3291 * Produces a method handle for a reflected method. 3292 * It will bypass checks for overriding methods on the receiver, 3293 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3294 * instruction from within the explicitly specified {@code specialCaller}. 3295 * The type of the method handle will be that of the method, 3296 * with a suitably restricted receiver type prepended. 3297 * (The receiver type will be {@code specialCaller} or a subtype.) 3298 * If the method's {@code accessible} flag is not set, 3299 * access checking is performed immediately on behalf of the lookup class, 3300 * as if {@code invokespecial} instruction were being linked. 3301 * <p> 3302 * Before method resolution, 3303 * if the explicitly specified caller class is not identical with the 3304 * lookup class, or if this lookup object does not have 3305 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3306 * privileges, the access fails. 3307 * <p> 3308 * The returned method handle will have 3309 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3310 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3311 * @param m the reflected method 3312 * @param specialCaller the class nominally calling the method 3313 * @return a method handle which can invoke the reflected method 3314 * @throws IllegalAccessException if access checking fails, 3315 * or if the method is {@code static}, 3316 * or if the method's variable arity modifier bit 3317 * is set and {@code asVarargsCollector} fails 3318 * @throws NullPointerException if any argument is null 3319 */ 3320 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3321 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3322 Lookup specialLookup = this.in(specialCaller); 3323 MemberName method = new MemberName(m, true); 3324 assert(method.isMethod()); 3325 // ignore m.isAccessible: this is a new kind of access 3326 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3327 } 3328 3329 /** 3330 * Produces a method handle for a reflected constructor. 3331 * The type of the method handle will be that of the constructor, 3332 * with the return type changed to the declaring class. 3333 * The method handle will perform a {@code newInstance} operation, 3334 * creating a new instance of the constructor's class on the 3335 * arguments passed to the method handle. 3336 * <p> 3337 * If the constructor's {@code accessible} flag is not set, 3338 * access checking is performed immediately on behalf of the lookup class. 3339 * <p> 3340 * The returned method handle will have 3341 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3342 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3343 * <p> 3344 * If the returned method handle is invoked, the constructor's class will 3345 * be initialized, if it has not already been initialized. 3346 * @param c the reflected constructor 3347 * @return a method handle which can invoke the reflected constructor 3348 * @throws IllegalAccessException if access checking fails 3349 * or if the method's variable arity modifier bit 3350 * is set and {@code asVarargsCollector} fails 3351 * @throws NullPointerException if the argument is null 3352 */ 3353 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3354 MemberName ctor = new MemberName(c); 3355 assert(ctor.isConstructor()); 3356 @SuppressWarnings("deprecation") 3357 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3358 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor); 3359 } 3360 3361 /* 3362 * Produces a method handle that is capable of creating instances of the given class 3363 * and instantiated by the given constructor. 3364 * 3365 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3366 */ 3367 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3368 MemberName ctor = new MemberName(c); 3369 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3370 checkAccess(REF_newInvokeSpecial, decl, ctor); 3371 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3372 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3373 } 3374 3375 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3376 if (decl == ctor.getDeclaringClass()) 3377 return true; 3378 3379 Class<?> cl = decl; 3380 while ((cl = cl.getSuperclass()) != null) { 3381 if (cl == ctor.getDeclaringClass()) { 3382 return true; 3383 } 3384 } 3385 return false; 3386 } 3387 3388 /** 3389 * Produces a method handle giving read access to a reflected field. 3390 * The type of the method handle will have a return type of the field's 3391 * value type. 3392 * If the field is {@code static}, the method handle will take no arguments. 3393 * Otherwise, its single argument will be the instance containing 3394 * the field. 3395 * If the {@code Field} object's {@code accessible} flag is not set, 3396 * access checking is performed immediately on behalf of the lookup class. 3397 * <p> 3398 * If the field is static, and 3399 * if the returned method handle is invoked, the field's class will 3400 * be initialized, if it has not already been initialized. 3401 * @param f the reflected field 3402 * @return a method handle which can load values from the reflected field 3403 * @throws IllegalAccessException if access checking fails 3404 * @throws NullPointerException if the argument is null 3405 */ 3406 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3407 return unreflectField(f, false); 3408 } 3409 3410 /** 3411 * Produces a method handle giving write access to a reflected field. 3412 * The type of the method handle will have a void return type. 3413 * If the field is {@code static}, the method handle will take a single 3414 * argument, of the field's value type, the value to be stored. 3415 * Otherwise, the two arguments will be the instance containing 3416 * the field, and the value to be stored. 3417 * If the {@code Field} object's {@code accessible} flag is not set, 3418 * access checking is performed immediately on behalf of the lookup class. 3419 * <p> 3420 * If the field is {@code final}, write access will not be 3421 * allowed and access checking will fail, except under certain 3422 * narrow circumstances documented for {@link Field#set Field.set}. 3423 * A method handle is returned only if a corresponding call to 3424 * the {@code Field} object's {@code set} method could return 3425 * normally. In particular, fields which are both {@code static} 3426 * and {@code final} may never be set. 3427 * <p> 3428 * If the field is {@code static}, and 3429 * if the returned method handle is invoked, the field's class will 3430 * be initialized, if it has not already been initialized. 3431 * @param f the reflected field 3432 * @return a method handle which can store values into the reflected field 3433 * @throws IllegalAccessException if access checking fails, 3434 * or if the field is {@code final} and write access 3435 * is not enabled on the {@code Field} object 3436 * @throws NullPointerException if the argument is null 3437 */ 3438 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3439 return unreflectField(f, true); 3440 } 3441 3442 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3443 MemberName field = new MemberName(f, isSetter); 3444 if (isSetter && field.isFinal()) { 3445 if (field.isTrustedFinalField()) { 3446 String msg = field.isStatic() ? "static final field has no write access" 3447 : "final field has no write access"; 3448 throw field.makeAccessException(msg, this); 3449 } 3450 } 3451 assert(isSetter 3452 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3453 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3454 @SuppressWarnings("deprecation") 3455 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3456 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field); 3457 } 3458 3459 /** 3460 * Produces a VarHandle giving access to a reflected field {@code f} 3461 * of type {@code T} declared in a class of type {@code R}. 3462 * The VarHandle's variable type is {@code T}. 3463 * If the field is non-static the VarHandle has one coordinate type, 3464 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3465 * coordinate types. 3466 * <p> 3467 * Access checking is performed immediately on behalf of the lookup 3468 * class, regardless of the value of the field's {@code accessible} 3469 * flag. 3470 * <p> 3471 * If the field is static, and if the returned VarHandle is operated 3472 * on, the field's declaring class will be initialized, if it has not 3473 * already been initialized. 3474 * <p> 3475 * Certain access modes of the returned VarHandle are unsupported under 3476 * the following conditions: 3477 * <ul> 3478 * <li>if the field is declared {@code final}, then the write, atomic 3479 * update, numeric atomic update, and bitwise atomic update access 3480 * modes are unsupported. 3481 * <li>if the field type is anything other than {@code byte}, 3482 * {@code short}, {@code char}, {@code int}, {@code long}, 3483 * {@code float}, or {@code double} then numeric atomic update 3484 * access modes are unsupported. 3485 * <li>if the field type is anything other than {@code boolean}, 3486 * {@code byte}, {@code short}, {@code char}, {@code int} or 3487 * {@code long} then bitwise atomic update access modes are 3488 * unsupported. 3489 * </ul> 3490 * <p> 3491 * If the field is declared {@code volatile} then the returned VarHandle 3492 * will override access to the field (effectively ignore the 3493 * {@code volatile} declaration) in accordance to its specified 3494 * access modes. 3495 * <p> 3496 * If the field type is {@code float} or {@code double} then numeric 3497 * and atomic update access modes compare values using their bitwise 3498 * representation (see {@link Float#floatToRawIntBits} and 3499 * {@link Double#doubleToRawLongBits}, respectively). 3500 * @apiNote 3501 * Bitwise comparison of {@code float} values or {@code double} values, 3502 * as performed by the numeric and atomic update access modes, differ 3503 * from the primitive {@code ==} operator and the {@link Float#equals} 3504 * and {@link Double#equals} methods, specifically with respect to 3505 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3506 * Care should be taken when performing a compare and set or a compare 3507 * and exchange operation with such values since the operation may 3508 * unexpectedly fail. 3509 * There are many possible NaN values that are considered to be 3510 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3511 * provided by Java can distinguish between them. Operation failure can 3512 * occur if the expected or witness value is a NaN value and it is 3513 * transformed (perhaps in a platform specific manner) into another NaN 3514 * value, and thus has a different bitwise representation (see 3515 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3516 * details). 3517 * The values {@code -0.0} and {@code +0.0} have different bitwise 3518 * representations but are considered equal when using the primitive 3519 * {@code ==} operator. Operation failure can occur if, for example, a 3520 * numeric algorithm computes an expected value to be say {@code -0.0} 3521 * and previously computed the witness value to be say {@code +0.0}. 3522 * @param f the reflected field, with a field of type {@code T}, and 3523 * a declaring class of type {@code R} 3524 * @return a VarHandle giving access to non-static fields or a static 3525 * field 3526 * @throws IllegalAccessException if access checking fails 3527 * @throws NullPointerException if the argument is null 3528 * @since 9 3529 */ 3530 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3531 MemberName getField = new MemberName(f, false); 3532 MemberName putField = new MemberName(f, true); 3533 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(), 3534 f.getDeclaringClass(), getField, putField); 3535 } 3536 3537 /** 3538 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3539 * created by this lookup object or a similar one. 3540 * Security and access checks are performed to ensure that this lookup object 3541 * is capable of reproducing the target method handle. 3542 * This means that the cracking may fail if target is a direct method handle 3543 * but was created by an unrelated lookup object. 3544 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3545 * and was created by a lookup object for a different class. 3546 * @param target a direct method handle to crack into symbolic reference components 3547 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3548 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3549 * @throws NullPointerException if the target is {@code null} 3550 * @see MethodHandleInfo 3551 * @since 1.8 3552 */ 3553 public MethodHandleInfo revealDirect(MethodHandle target) { 3554 if (!target.isCrackable()) { 3555 throw newIllegalArgumentException("not a direct method handle"); 3556 } 3557 MemberName member = target.internalMemberName(); 3558 Class<?> defc = member.getDeclaringClass(); 3559 byte refKind = member.getReferenceKind(); 3560 assert(MethodHandleNatives.refKindIsValid(refKind)); 3561 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3562 // Devirtualized method invocation is usually formally virtual. 3563 // To avoid creating extra MemberName objects for this common case, 3564 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3565 refKind = REF_invokeVirtual; 3566 if (refKind == REF_invokeVirtual && defc.isInterface()) 3567 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3568 refKind = REF_invokeInterface; 3569 // Check member access before cracking. 3570 try { 3571 checkAccess(refKind, defc, member); 3572 } catch (IllegalAccessException ex) { 3573 throw new IllegalArgumentException(ex); 3574 } 3575 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3576 Class<?> callerClass = target.internalCallerClass(); 3577 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3578 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3579 } 3580 // Produce the handle to the results. 3581 return new InfoFromMemberName(this, member, refKind); 3582 } 3583 3584 //--- Helper methods, all package-private. 3585 3586 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3587 checkSymbolicClass(refc); // do this before attempting to resolve 3588 Objects.requireNonNull(name); 3589 Objects.requireNonNull(type); 3590 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3591 NoSuchFieldException.class); 3592 } 3593 3594 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3595 checkSymbolicClass(refc); // do this before attempting to resolve 3596 Objects.requireNonNull(type); 3597 checkMethodName(refKind, name); // implicit null-check of name 3598 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3599 NoSuchMethodException.class); 3600 } 3601 3602 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3603 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3604 Objects.requireNonNull(member.getName()); 3605 Objects.requireNonNull(member.getType()); 3606 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3607 ReflectiveOperationException.class); 3608 } 3609 3610 MemberName resolveOrNull(byte refKind, MemberName member) { 3611 // do this before attempting to resolve 3612 if (!isClassAccessible(member.getDeclaringClass())) { 3613 return null; 3614 } 3615 Objects.requireNonNull(member.getName()); 3616 Objects.requireNonNull(member.getType()); 3617 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3618 } 3619 3620 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3621 // do this before attempting to resolve 3622 if (!isClassAccessible(refc)) { 3623 return null; 3624 } 3625 Objects.requireNonNull(type); 3626 // implicit null-check of name 3627 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3628 return null; 3629 } 3630 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3631 } 3632 3633 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3634 if (!isClassAccessible(refc)) { 3635 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3636 } 3637 } 3638 3639 boolean isClassAccessible(Class<?> refc) { 3640 Objects.requireNonNull(refc); 3641 Class<?> caller = lookupClassOrNull(); 3642 Class<?> type = refc; 3643 while (type.isArray()) { 3644 type = type.getComponentType(); 3645 } 3646 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3647 } 3648 3649 /** Check name for an illegal leading "<" character. */ 3650 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3651 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3652 throw new NoSuchMethodException("illegal method name: "+name); 3653 } 3654 3655 /** 3656 * Find my trustable caller class if m is a caller sensitive method. 3657 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3658 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3659 */ 3660 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3661 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3662 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3663 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3664 } 3665 return this; 3666 } 3667 3668 /** 3669 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3670 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3671 * 3672 * @deprecated This method was originally designed to test {@code PRIVATE} access 3673 * that implies full privilege access but {@code MODULE} access has since become 3674 * independent of {@code PRIVATE} access. It is recommended to call 3675 * {@link #hasFullPrivilegeAccess()} instead. 3676 * @since 9 3677 */ 3678 @Deprecated(since="14") 3679 public boolean hasPrivateAccess() { 3680 return hasFullPrivilegeAccess(); 3681 } 3682 3683 /** 3684 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3685 * i.e. {@code PRIVATE} and {@code MODULE} access. 3686 * A {@code Lookup} object must have full privilege access in order to 3687 * access all members that are allowed to the 3688 * {@linkplain #lookupClass() lookup class}. 3689 * 3690 * @return {@code true} if this lookup has full privilege access. 3691 * @since 14 3692 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3693 */ 3694 public boolean hasFullPrivilegeAccess() { 3695 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3696 } 3697 3698 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3699 boolean wantStatic = (refKind == REF_invokeStatic); 3700 String message; 3701 if (m.isConstructor()) 3702 message = "expected a method, not a constructor"; 3703 else if (!m.isMethod()) 3704 message = "expected a method"; 3705 else if (wantStatic != m.isStatic()) 3706 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3707 else 3708 { checkAccess(refKind, refc, m); return; } 3709 throw m.makeAccessException(message, this); 3710 } 3711 3712 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3713 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3714 String message; 3715 if (wantStatic != m.isStatic()) 3716 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3717 else 3718 { checkAccess(refKind, refc, m); return; } 3719 throw m.makeAccessException(message, this); 3720 } 3721 3722 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3723 return Modifier.isProtected(m.getModifiers()) && 3724 refKind == REF_invokeVirtual && 3725 m.getDeclaringClass() == Object.class && 3726 m.getName().equals("clone") && 3727 refc.isArray(); 3728 } 3729 3730 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3731 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3732 assert(m.referenceKindIsConsistentWith(refKind) && 3733 MethodHandleNatives.refKindIsValid(refKind) && 3734 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3735 int allowedModes = this.allowedModes; 3736 if (allowedModes == TRUSTED) return; 3737 int mods = m.getModifiers(); 3738 if (isArrayClone(refKind, refc, m)) { 3739 // The JVM does this hack also. 3740 // (See ClassVerifier::verify_invoke_instructions 3741 // and LinkResolver::check_method_accessability.) 3742 // Because the JVM does not allow separate methods on array types, 3743 // there is no separate method for int[].clone. 3744 // All arrays simply inherit Object.clone. 3745 // But for access checking logic, we make Object.clone 3746 // (normally protected) appear to be public. 3747 // Later on, when the DirectMethodHandle is created, 3748 // its leading argument will be restricted to the 3749 // requested array type. 3750 // N.B. The return type is not adjusted, because 3751 // that is *not* the bytecode behavior. 3752 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3753 } 3754 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3755 // cannot "new" a protected ctor in a different package 3756 mods ^= Modifier.PROTECTED; 3757 } 3758 if (Modifier.isFinal(mods) && 3759 MethodHandleNatives.refKindIsSetter(refKind)) 3760 throw m.makeAccessException("unexpected set of a final field", this); 3761 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3762 if ((requestedModes & allowedModes) != 0) { 3763 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3764 mods, lookupClass(), previousLookupClass(), allowedModes)) 3765 return; 3766 } else { 3767 // Protected members can also be checked as if they were package-private. 3768 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3769 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3770 return; 3771 } 3772 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3773 } 3774 3775 String accessFailedMessage(Class<?> refc, MemberName m) { 3776 Class<?> defc = m.getDeclaringClass(); 3777 int mods = m.getModifiers(); 3778 // check the class first: 3779 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3780 (defc == refc || 3781 Modifier.isPublic(refc.getModifiers()))); 3782 if (!classOK && (allowedModes & PACKAGE) != 0) { 3783 // ignore previous lookup class to check if default package access 3784 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3785 (defc == refc || 3786 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3787 } 3788 if (!classOK) 3789 return "class is not public"; 3790 if (Modifier.isPublic(mods)) 3791 return "access to public member failed"; // (how?, module not readable?) 3792 if (Modifier.isPrivate(mods)) 3793 return "member is private"; 3794 if (Modifier.isProtected(mods)) 3795 return "member is protected"; 3796 return "member is private to package"; 3797 } 3798 3799 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3800 int allowedModes = this.allowedModes; 3801 if (allowedModes == TRUSTED) return; 3802 if ((lookupModes() & PRIVATE) == 0 3803 || (specialCaller != lookupClass() 3804 // ensure non-abstract methods in superinterfaces can be special-invoked 3805 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3806 throw new MemberName(specialCaller). 3807 makeAccessException("no private access for invokespecial", this); 3808 } 3809 3810 private boolean restrictProtectedReceiver(MemberName method) { 3811 // The accessing class only has the right to use a protected member 3812 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3813 if (!method.isProtected() || method.isStatic() 3814 || allowedModes == TRUSTED 3815 || method.getDeclaringClass() == lookupClass() 3816 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3817 return false; 3818 return true; 3819 } 3820 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3821 assert(!method.isStatic()); 3822 // receiver type of mh is too wide; narrow to caller 3823 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3824 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3825 } 3826 MethodType rawType = mh.type(); 3827 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3828 MethodType narrowType = rawType.changeParameterType(0, caller); 3829 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3830 assert(mh.viewAsTypeChecks(narrowType, true)); 3831 return mh.copyWith(narrowType, mh.form); 3832 } 3833 3834 /** Check access and get the requested method. */ 3835 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3836 final boolean doRestrict = true; 3837 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup); 3838 } 3839 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3840 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3841 final boolean doRestrict = false; 3842 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup); 3843 } 3844 /** Common code for all methods; do not call directly except from immediately above. */ 3845 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3846 boolean doRestrict, 3847 Lookup boundCaller) throws IllegalAccessException { 3848 checkMethod(refKind, refc, method); 3849 assert(!method.isMethodHandleInvoke()); 3850 if (refKind == REF_invokeSpecial && 3851 refc != lookupClass() && 3852 !refc.isInterface() && !lookupClass().isInterface() && 3853 refc != lookupClass().getSuperclass() && 3854 refc.isAssignableFrom(lookupClass())) { 3855 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 3856 3857 // Per JVMS 6.5, desc. of invokespecial instruction: 3858 // If the method is in a superclass of the LC, 3859 // and if our original search was above LC.super, 3860 // repeat the search (symbolic lookup) from LC.super 3861 // and continue with the direct superclass of that class, 3862 // and so forth, until a match is found or no further superclasses exist. 3863 // FIXME: MemberName.resolve should handle this instead. 3864 Class<?> refcAsSuper = lookupClass(); 3865 MemberName m2; 3866 do { 3867 refcAsSuper = refcAsSuper.getSuperclass(); 3868 m2 = new MemberName(refcAsSuper, 3869 method.getName(), 3870 method.getMethodType(), 3871 REF_invokeSpecial); 3872 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 3873 } while (m2 == null && // no method is found yet 3874 refc != refcAsSuper); // search up to refc 3875 if (m2 == null) throw new InternalError(method.toString()); 3876 method = m2; 3877 refc = refcAsSuper; 3878 // redo basic checks 3879 checkMethod(refKind, refc, method); 3880 } 3881 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 3882 MethodHandle mh = dmh; 3883 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 3884 if ((doRestrict && refKind == REF_invokeSpecial) || 3885 (MethodHandleNatives.refKindHasReceiver(refKind) && 3886 restrictProtectedReceiver(method) && 3887 // All arrays simply inherit the protected Object.clone method. 3888 // The leading argument is already restricted to the requested 3889 // array type (not the lookup class). 3890 !isArrayClone(refKind, refc, method))) { 3891 mh = restrictReceiver(method, dmh, lookupClass()); 3892 } 3893 mh = maybeBindCaller(method, mh, boundCaller); 3894 mh = mh.setVarargs(method); 3895 return mh; 3896 } 3897 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 3898 throws IllegalAccessException { 3899 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 3900 return mh; 3901 3902 // boundCaller must have full privilege access. 3903 // It should have been checked by findBoundCallerLookup. Safe to check this again. 3904 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 3905 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3906 3907 assert boundCaller.hasFullPrivilegeAccess(); 3908 3909 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 3910 // Note: caller will apply varargs after this step happens. 3911 return cbmh; 3912 } 3913 3914 /** Check access and get the requested field. */ 3915 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3916 return getDirectFieldCommon(refKind, refc, field); 3917 } 3918 /** Common code for all fields; do not call directly except from immediately above. */ 3919 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3920 checkField(refKind, refc, field); 3921 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 3922 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 3923 restrictProtectedReceiver(field)); 3924 if (doRestrict) 3925 return restrictReceiver(field, dmh, lookupClass()); 3926 return dmh; 3927 } 3928 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 3929 Class<?> refc, MemberName getField, MemberName putField) 3930 throws IllegalAccessException { 3931 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField); 3932 } 3933 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 3934 Class<?> refc, MemberName getField, 3935 MemberName putField) throws IllegalAccessException { 3936 assert getField.isStatic() == putField.isStatic(); 3937 assert getField.isGetter() && putField.isSetter(); 3938 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 3939 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 3940 3941 checkField(getRefKind, refc, getField); 3942 3943 if (!putField.isFinal()) { 3944 // A VarHandle does not support updates to final fields, any 3945 // such VarHandle to a final field will be read-only and 3946 // therefore the following write-based accessibility checks are 3947 // only required for non-final fields 3948 checkField(putRefKind, refc, putField); 3949 } 3950 3951 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 3952 restrictProtectedReceiver(getField)); 3953 if (doRestrict) { 3954 assert !getField.isStatic(); 3955 // receiver type of VarHandle is too wide; narrow to caller 3956 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 3957 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 3958 } 3959 refc = lookupClass(); 3960 } 3961 return VarHandles.makeFieldHandle(getField, refc, 3962 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 3963 } 3964 /** Check access and get the requested constructor. */ 3965 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3966 return getDirectConstructorCommon(refc, ctor); 3967 } 3968 /** Common code for all constructors; do not call directly except from immediately above. */ 3969 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3970 assert(ctor.isConstructor()); 3971 checkAccess(REF_newInvokeSpecial, refc, ctor); 3972 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3973 return DirectMethodHandle.make(ctor).setVarargs(ctor); 3974 } 3975 3976 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 3977 */ 3978 /*non-public*/ 3979 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 3980 throws ReflectiveOperationException { 3981 if (!(type instanceof Class || type instanceof MethodType)) 3982 throw new InternalError("unresolved MemberName"); 3983 MemberName member = new MemberName(refKind, defc, name, type); 3984 MethodHandle mh = LOOKASIDE_TABLE.get(member); 3985 if (mh != null) { 3986 checkSymbolicClass(defc); 3987 return mh; 3988 } 3989 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 3990 // Treat MethodHandle.invoke and invokeExact specially. 3991 mh = findVirtualForMH(member.getName(), member.getMethodType()); 3992 if (mh != null) { 3993 return mh; 3994 } 3995 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 3996 // Treat signature-polymorphic methods on VarHandle specially. 3997 mh = findVirtualForVH(member.getName(), member.getMethodType()); 3998 if (mh != null) { 3999 return mh; 4000 } 4001 } 4002 MemberName resolved = resolveOrFail(refKind, member); 4003 mh = getDirectMethodForConstant(refKind, defc, resolved); 4004 if (mh instanceof DirectMethodHandle dmh 4005 && canBeCached(refKind, defc, resolved)) { 4006 MemberName key = mh.internalMemberName(); 4007 if (key != null) { 4008 key = key.asNormalOriginal(); 4009 } 4010 if (member.equals(key)) { // better safe than sorry 4011 LOOKASIDE_TABLE.put(key, dmh); 4012 } 4013 } 4014 return mh; 4015 } 4016 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4017 if (refKind == REF_invokeSpecial) { 4018 return false; 4019 } 4020 if (!Modifier.isPublic(defc.getModifiers()) || 4021 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4022 !member.isPublic() || 4023 member.isCallerSensitive()) { 4024 return false; 4025 } 4026 ClassLoader loader = defc.getClassLoader(); 4027 if (loader != null) { 4028 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4029 boolean found = false; 4030 while (sysl != null) { 4031 if (loader == sysl) { found = true; break; } 4032 sysl = sysl.getParent(); 4033 } 4034 if (!found) { 4035 return false; 4036 } 4037 } 4038 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4039 new MemberName(refKind, defc, member.getName(), member.getType())); 4040 if (resolved2 == null) { 4041 return false; 4042 } 4043 return true; 4044 } 4045 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4046 throws ReflectiveOperationException { 4047 if (MethodHandleNatives.refKindIsField(refKind)) { 4048 return getDirectField(refKind, defc, member); 4049 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4050 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member)); 4051 } else if (refKind == REF_newInvokeSpecial) { 4052 return getDirectConstructor(defc, member); 4053 } 4054 // oops 4055 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4056 } 4057 4058 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4059 } 4060 4061 /** 4062 * Produces a method handle constructing arrays of a desired type, 4063 * as if by the {@code anewarray} bytecode. 4064 * The return type of the method handle will be the array type. 4065 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4066 * 4067 * <p> If the returned method handle is invoked with a negative 4068 * array size, a {@code NegativeArraySizeException} will be thrown. 4069 * 4070 * @param arrayClass an array type 4071 * @return a method handle which can create arrays of the given type 4072 * @throws NullPointerException if the argument is {@code null} 4073 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4074 * @see java.lang.reflect.Array#newInstance(Class, int) 4075 * @jvms 6.5 {@code anewarray} Instruction 4076 * @since 9 4077 */ 4078 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4079 if (!arrayClass.isArray()) { 4080 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4081 } 4082 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4083 bindTo(arrayClass.getComponentType()); 4084 return ani.asType(ani.type().changeReturnType(arrayClass)); 4085 } 4086 4087 /** 4088 * Produces a method handle returning the length of an array, 4089 * as if by the {@code arraylength} bytecode. 4090 * The type of the method handle will have {@code int} as return type, 4091 * and its sole argument will be the array type. 4092 * 4093 * <p> If the returned method handle is invoked with a {@code null} 4094 * array reference, a {@code NullPointerException} will be thrown. 4095 * 4096 * @param arrayClass an array type 4097 * @return a method handle which can retrieve the length of an array of the given array type 4098 * @throws NullPointerException if the argument is {@code null} 4099 * @throws IllegalArgumentException if arrayClass is not an array type 4100 * @jvms 6.5 {@code arraylength} Instruction 4101 * @since 9 4102 */ 4103 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4104 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4105 } 4106 4107 /** 4108 * Produces a method handle giving read access to elements of an array, 4109 * as if by the {@code aaload} bytecode. 4110 * The type of the method handle will have a return type of the array's 4111 * element type. Its first argument will be the array type, 4112 * and the second will be {@code int}. 4113 * 4114 * <p> When the returned method handle is invoked, 4115 * the array reference and array index are checked. 4116 * A {@code NullPointerException} will be thrown if the array reference 4117 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4118 * thrown if the index is negative or if it is greater than or equal to 4119 * the length of the array. 4120 * 4121 * @param arrayClass an array type 4122 * @return a method handle which can load values from the given array type 4123 * @throws NullPointerException if the argument is null 4124 * @throws IllegalArgumentException if arrayClass is not an array type 4125 * @jvms 6.5 {@code aaload} Instruction 4126 */ 4127 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4128 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4129 } 4130 4131 /** 4132 * Produces a method handle giving write access to elements of an array, 4133 * as if by the {@code astore} bytecode. 4134 * The type of the method handle will have a void return type. 4135 * Its last argument will be the array's element type. 4136 * The first and second arguments will be the array type and int. 4137 * 4138 * <p> When the returned method handle is invoked, 4139 * the array reference and array index are checked. 4140 * A {@code NullPointerException} will be thrown if the array reference 4141 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4142 * thrown if the index is negative or if it is greater than or equal to 4143 * the length of the array. 4144 * 4145 * @param arrayClass the class of an array 4146 * @return a method handle which can store values into the array type 4147 * @throws NullPointerException if the argument is null 4148 * @throws IllegalArgumentException if arrayClass is not an array type 4149 * @jvms 6.5 {@code aastore} Instruction 4150 */ 4151 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4152 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4153 } 4154 4155 /** 4156 * Produces a VarHandle giving access to elements of an array of type 4157 * {@code arrayClass}. The VarHandle's variable type is the component type 4158 * of {@code arrayClass} and the list of coordinate types is 4159 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4160 * corresponds to an argument that is an index into an array. 4161 * <p> 4162 * Certain access modes of the returned VarHandle are unsupported under 4163 * the following conditions: 4164 * <ul> 4165 * <li>if the component type is anything other than {@code byte}, 4166 * {@code short}, {@code char}, {@code int}, {@code long}, 4167 * {@code float}, or {@code double} then numeric atomic update access 4168 * modes are unsupported. 4169 * <li>if the component type is anything other than {@code boolean}, 4170 * {@code byte}, {@code short}, {@code char}, {@code int} or 4171 * {@code long} then bitwise atomic update access modes are 4172 * unsupported. 4173 * </ul> 4174 * <p> 4175 * If the component type is {@code float} or {@code double} then numeric 4176 * and atomic update access modes compare values using their bitwise 4177 * representation (see {@link Float#floatToRawIntBits} and 4178 * {@link Double#doubleToRawLongBits}, respectively). 4179 * 4180 * <p> When the returned {@code VarHandle} is invoked, 4181 * the array reference and array index are checked. 4182 * A {@code NullPointerException} will be thrown if the array reference 4183 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4184 * thrown if the index is negative or if it is greater than or equal to 4185 * the length of the array. 4186 * 4187 * @apiNote 4188 * Bitwise comparison of {@code float} values or {@code double} values, 4189 * as performed by the numeric and atomic update access modes, differ 4190 * from the primitive {@code ==} operator and the {@link Float#equals} 4191 * and {@link Double#equals} methods, specifically with respect to 4192 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4193 * Care should be taken when performing a compare and set or a compare 4194 * and exchange operation with such values since the operation may 4195 * unexpectedly fail. 4196 * There are many possible NaN values that are considered to be 4197 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4198 * provided by Java can distinguish between them. Operation failure can 4199 * occur if the expected or witness value is a NaN value and it is 4200 * transformed (perhaps in a platform specific manner) into another NaN 4201 * value, and thus has a different bitwise representation (see 4202 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4203 * details). 4204 * The values {@code -0.0} and {@code +0.0} have different bitwise 4205 * representations but are considered equal when using the primitive 4206 * {@code ==} operator. Operation failure can occur if, for example, a 4207 * numeric algorithm computes an expected value to be say {@code -0.0} 4208 * and previously computed the witness value to be say {@code +0.0}. 4209 * @param arrayClass the class of an array, of type {@code T[]} 4210 * @return a VarHandle giving access to elements of an array 4211 * @throws NullPointerException if the arrayClass is null 4212 * @throws IllegalArgumentException if arrayClass is not an array type 4213 * @since 9 4214 */ 4215 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4216 return VarHandles.makeArrayElementHandle(arrayClass); 4217 } 4218 4219 /** 4220 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4221 * viewed as if it were a different primitive array type, such as 4222 * {@code int[]} or {@code long[]}. 4223 * The VarHandle's variable type is the component type of 4224 * {@code viewArrayClass} and the list of coordinate types is 4225 * {@code (byte[], int)}, where the {@code int} coordinate type 4226 * corresponds to an argument that is an index into a {@code byte[]} array. 4227 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4228 * array, composing bytes to or from a value of the component type of 4229 * {@code viewArrayClass} according to the given endianness. 4230 * <p> 4231 * The supported component types (variables types) are {@code short}, 4232 * {@code char}, {@code int}, {@code long}, {@code float} and 4233 * {@code double}. 4234 * <p> 4235 * Access of bytes at a given index will result in an 4236 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4237 * or greater than the {@code byte[]} array length minus the size (in bytes) 4238 * of {@code T}. 4239 * <p> 4240 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4241 * access modes are supported by the returned var handle. For all other access modes, an 4242 * {@link UnsupportedOperationException} will be thrown. 4243 * 4244 * @apiNote if access modes other than plain access are required, clients should 4245 * consider using off-heap memory through 4246 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4247 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4248 * or memory segments backed by a 4249 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4250 * for which stronger alignment guarantees can be made. 4251 * 4252 * @param viewArrayClass the view array class, with a component type of 4253 * type {@code T} 4254 * @param byteOrder the endianness of the view array elements, as 4255 * stored in the underlying {@code byte} array 4256 * @return a VarHandle giving access to elements of a {@code byte[]} array 4257 * viewed as if elements corresponding to the components type of the view 4258 * array class 4259 * @throws NullPointerException if viewArrayClass or byteOrder is null 4260 * @throws IllegalArgumentException if viewArrayClass is not an array type 4261 * @throws UnsupportedOperationException if the component type of 4262 * viewArrayClass is not supported as a variable type 4263 * @since 9 4264 */ 4265 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4266 ByteOrder byteOrder) throws IllegalArgumentException { 4267 Objects.requireNonNull(byteOrder); 4268 return VarHandles.byteArrayViewHandle(viewArrayClass, 4269 byteOrder == ByteOrder.BIG_ENDIAN); 4270 } 4271 4272 /** 4273 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4274 * viewed as if it were an array of elements of a different primitive 4275 * component type to that of {@code byte}, such as {@code int[]} or 4276 * {@code long[]}. 4277 * The VarHandle's variable type is the component type of 4278 * {@code viewArrayClass} and the list of coordinate types is 4279 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4280 * corresponds to an argument that is an index into a {@code byte[]} array. 4281 * The returned VarHandle accesses bytes at an index in a 4282 * {@code ByteBuffer}, composing bytes to or from a value of the component 4283 * type of {@code viewArrayClass} according to the given endianness. 4284 * <p> 4285 * The supported component types (variables types) are {@code short}, 4286 * {@code char}, {@code int}, {@code long}, {@code float} and 4287 * {@code double}. 4288 * <p> 4289 * Access will result in a {@code ReadOnlyBufferException} for anything 4290 * other than the read access modes if the {@code ByteBuffer} is read-only. 4291 * <p> 4292 * Access of bytes at a given index will result in an 4293 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4294 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4295 * {@code T}. 4296 * <p> 4297 * For heap byte buffers, access is always unaligned. As a result, only the plain 4298 * {@linkplain VarHandle.AccessMode#GET get} 4299 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4300 * returned var handle. For all other access modes, an {@link IllegalStateException} 4301 * will be thrown. 4302 * <p> 4303 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4304 * with respect to the underlying memory address, {@code A} say, associated 4305 * with the {@code ByteBuffer} and index. 4306 * If access is misaligned then access for anything other than the 4307 * {@code get} and {@code set} access modes will result in an 4308 * {@code IllegalStateException}. In such cases atomic access is only 4309 * guaranteed with respect to the largest power of two that divides the GCD 4310 * of {@code A} and the size (in bytes) of {@code T}. 4311 * If access is aligned then following access modes are supported and are 4312 * guaranteed to support atomic access: 4313 * <ul> 4314 * <li>read write access modes for all {@code T}. Access modes {@code get} 4315 * and {@code set} for {@code long} and {@code double} are supported but 4316 * have no atomicity guarantee, as described in Section {@jls 17.7} of 4317 * <cite>The Java Language Specification</cite>. 4318 * <li>atomic update access modes for {@code int}, {@code long}, 4319 * {@code float} or {@code double}. 4320 * (Future major platform releases of the JDK may support additional 4321 * types for certain currently unsupported access modes.) 4322 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4323 * (Future major platform releases of the JDK may support additional 4324 * numeric types for certain currently unsupported access modes.) 4325 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4326 * (Future major platform releases of the JDK may support additional 4327 * numeric types for certain currently unsupported access modes.) 4328 * </ul> 4329 * <p> 4330 * Misaligned access, and therefore atomicity guarantees, may be determined 4331 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4332 * {@code index}, {@code T} and its corresponding boxed type, 4333 * {@code T_BOX}, as follows: 4334 * <pre>{@code 4335 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4336 * ByteBuffer bb = ... 4337 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4338 * boolean isMisaligned = misalignedAtIndex != 0; 4339 * }</pre> 4340 * <p> 4341 * If the variable type is {@code float} or {@code double} then atomic 4342 * update access modes compare values using their bitwise representation 4343 * (see {@link Float#floatToRawIntBits} and 4344 * {@link Double#doubleToRawLongBits}, respectively). 4345 * @param viewArrayClass the view array class, with a component type of 4346 * type {@code T} 4347 * @param byteOrder the endianness of the view array elements, as 4348 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4349 * endianness of a {@code ByteBuffer}) 4350 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4351 * viewed as if elements corresponding to the components type of the view 4352 * array class 4353 * @throws NullPointerException if viewArrayClass or byteOrder is null 4354 * @throws IllegalArgumentException if viewArrayClass is not an array type 4355 * @throws UnsupportedOperationException if the component type of 4356 * viewArrayClass is not supported as a variable type 4357 * @since 9 4358 */ 4359 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4360 ByteOrder byteOrder) throws IllegalArgumentException { 4361 Objects.requireNonNull(byteOrder); 4362 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4363 byteOrder == ByteOrder.BIG_ENDIAN); 4364 } 4365 4366 4367 //--- method handle invocation (reflective style) 4368 4369 /** 4370 * Produces a method handle which will invoke any method handle of the 4371 * given {@code type}, with a given number of trailing arguments replaced by 4372 * a single trailing {@code Object[]} array. 4373 * The resulting invoker will be a method handle with the following 4374 * arguments: 4375 * <ul> 4376 * <li>a single {@code MethodHandle} target 4377 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4378 * <li>an {@code Object[]} array containing trailing arguments 4379 * </ul> 4380 * <p> 4381 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4382 * the indicated {@code type}. 4383 * That is, if the target is exactly of the given {@code type}, it will behave 4384 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4385 * is used to convert the target to the required {@code type}. 4386 * <p> 4387 * The type of the returned invoker will not be the given {@code type}, but rather 4388 * will have all parameters except the first {@code leadingArgCount} 4389 * replaced by a single array of type {@code Object[]}, which will be 4390 * the final parameter. 4391 * <p> 4392 * Before invoking its target, the invoker will spread the final array, apply 4393 * reference casts as necessary, and unbox and widen primitive arguments. 4394 * If, when the invoker is called, the supplied array argument does 4395 * not have the correct number of elements, the invoker will throw 4396 * an {@link IllegalArgumentException} instead of invoking the target. 4397 * <p> 4398 * This method is equivalent to the following code (though it may be more efficient): 4399 * {@snippet lang="java" : 4400 MethodHandle invoker = MethodHandles.invoker(type); 4401 int spreadArgCount = type.parameterCount() - leadingArgCount; 4402 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4403 return invoker; 4404 * } 4405 * This method throws no reflective exceptions. 4406 * @param type the desired target type 4407 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4408 * @return a method handle suitable for invoking any method handle of the given type 4409 * @throws NullPointerException if {@code type} is null 4410 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4411 * the range from 0 to {@code type.parameterCount()} inclusive, 4412 * or if the resulting method handle's type would have 4413 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4414 */ 4415 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4416 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4417 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4418 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4419 return type.invokers().spreadInvoker(leadingArgCount); 4420 } 4421 4422 /** 4423 * Produces a special <em>invoker method handle</em> which can be used to 4424 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4425 * The resulting invoker will have a type which is 4426 * exactly equal to the desired type, except that it will accept 4427 * an additional leading argument of type {@code MethodHandle}. 4428 * <p> 4429 * This method is equivalent to the following code (though it may be more efficient): 4430 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4431 * 4432 * <p style="font-size:smaller;"> 4433 * <em>Discussion:</em> 4434 * Invoker method handles can be useful when working with variable method handles 4435 * of unknown types. 4436 * For example, to emulate an {@code invokeExact} call to a variable method 4437 * handle {@code M}, extract its type {@code T}, 4438 * look up the invoker method {@code X} for {@code T}, 4439 * and call the invoker method, as {@code X.invoke(T, A...)}. 4440 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4441 * is unknown.) 4442 * If spreading, collecting, or other argument transformations are required, 4443 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4444 * method handle values, as long as they are compatible with the type of {@code X}. 4445 * <p style="font-size:smaller;"> 4446 * <em>(Note: The invoker method is not available via the Core Reflection API. 4447 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4448 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4449 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4450 * <p> 4451 * This method throws no reflective exceptions. 4452 * @param type the desired target type 4453 * @return a method handle suitable for invoking any method handle of the given type 4454 * @throws IllegalArgumentException if the resulting method handle's type would have 4455 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4456 */ 4457 public static MethodHandle exactInvoker(MethodType type) { 4458 return type.invokers().exactInvoker(); 4459 } 4460 4461 /** 4462 * Produces a special <em>invoker method handle</em> which can be used to 4463 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4464 * The resulting invoker will have a type which is 4465 * exactly equal to the desired type, except that it will accept 4466 * an additional leading argument of type {@code MethodHandle}. 4467 * <p> 4468 * Before invoking its target, if the target differs from the expected type, 4469 * the invoker will apply reference casts as 4470 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4471 * Similarly, the return value will be converted as necessary. 4472 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4473 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4474 * <p> 4475 * This method is equivalent to the following code (though it may be more efficient): 4476 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4477 * <p style="font-size:smaller;"> 4478 * <em>Discussion:</em> 4479 * A {@linkplain MethodType#genericMethodType general method type} is one which 4480 * mentions only {@code Object} arguments and return values. 4481 * An invoker for such a type is capable of calling any method handle 4482 * of the same arity as the general type. 4483 * <p style="font-size:smaller;"> 4484 * <em>(Note: The invoker method is not available via the Core Reflection API. 4485 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4486 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4487 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4488 * <p> 4489 * This method throws no reflective exceptions. 4490 * @param type the desired target type 4491 * @return a method handle suitable for invoking any method handle convertible to the given type 4492 * @throws IllegalArgumentException if the resulting method handle's type would have 4493 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4494 */ 4495 public static MethodHandle invoker(MethodType type) { 4496 return type.invokers().genericInvoker(); 4497 } 4498 4499 /** 4500 * Produces a special <em>invoker method handle</em> which can be used to 4501 * invoke a signature-polymorphic access mode method on any VarHandle whose 4502 * associated access mode type is compatible with the given type. 4503 * The resulting invoker will have a type which is exactly equal to the 4504 * desired given type, except that it will accept an additional leading 4505 * argument of type {@code VarHandle}. 4506 * 4507 * @param accessMode the VarHandle access mode 4508 * @param type the desired target type 4509 * @return a method handle suitable for invoking an access mode method of 4510 * any VarHandle whose access mode type is of the given type. 4511 * @since 9 4512 */ 4513 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4514 return type.invokers().varHandleMethodExactInvoker(accessMode); 4515 } 4516 4517 /** 4518 * Produces a special <em>invoker method handle</em> which can be used to 4519 * invoke a signature-polymorphic access mode method on any VarHandle whose 4520 * associated access mode type is compatible with the given type. 4521 * The resulting invoker will have a type which is exactly equal to the 4522 * desired given type, except that it will accept an additional leading 4523 * argument of type {@code VarHandle}. 4524 * <p> 4525 * Before invoking its target, if the access mode type differs from the 4526 * desired given type, the invoker will apply reference casts as necessary 4527 * and box, unbox, or widen primitive values, as if by 4528 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4529 * converted as necessary. 4530 * <p> 4531 * This method is equivalent to the following code (though it may be more 4532 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4533 * 4534 * @param accessMode the VarHandle access mode 4535 * @param type the desired target type 4536 * @return a method handle suitable for invoking an access mode method of 4537 * any VarHandle whose access mode type is convertible to the given 4538 * type. 4539 * @since 9 4540 */ 4541 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4542 return type.invokers().varHandleMethodInvoker(accessMode); 4543 } 4544 4545 /*non-public*/ 4546 static MethodHandle basicInvoker(MethodType type) { 4547 return type.invokers().basicInvoker(); 4548 } 4549 4550 //--- method handle modification (creation from other method handles) 4551 4552 /** 4553 * Produces a method handle which adapts the type of the 4554 * given method handle to a new type by pairwise argument and return type conversion. 4555 * The original type and new type must have the same number of arguments. 4556 * The resulting method handle is guaranteed to report a type 4557 * which is equal to the desired new type. 4558 * <p> 4559 * If the original type and new type are equal, returns target. 4560 * <p> 4561 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4562 * and some additional conversions are also applied if those conversions fail. 4563 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4564 * if possible, before or instead of any conversions done by {@code asType}: 4565 * <ul> 4566 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4567 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4568 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4569 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4570 * the boolean is converted to a byte value, 1 for true, 0 for false. 4571 * (This treatment follows the usage of the bytecode verifier.) 4572 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4573 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4574 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4575 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4576 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4577 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4578 * widening and/or narrowing.) 4579 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4580 * conversion will be applied at runtime, possibly followed 4581 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4582 * possibly followed by a conversion from byte to boolean by testing 4583 * the low-order bit. 4584 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4585 * and if the reference is null at runtime, a zero value is introduced. 4586 * </ul> 4587 * @param target the method handle to invoke after arguments are retyped 4588 * @param newType the expected type of the new method handle 4589 * @return a method handle which delegates to the target after performing 4590 * any necessary argument conversions, and arranges for any 4591 * necessary return value conversions 4592 * @throws NullPointerException if either argument is null 4593 * @throws WrongMethodTypeException if the conversion cannot be made 4594 * @see MethodHandle#asType 4595 */ 4596 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4597 explicitCastArgumentsChecks(target, newType); 4598 // use the asTypeCache when possible: 4599 MethodType oldType = target.type(); 4600 if (oldType == newType) return target; 4601 if (oldType.explicitCastEquivalentToAsType(newType)) { 4602 return target.asFixedArity().asType(newType); 4603 } 4604 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4605 } 4606 4607 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4608 if (target.type().parameterCount() != newType.parameterCount()) { 4609 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4610 } 4611 } 4612 4613 /** 4614 * Produces a method handle which adapts the calling sequence of the 4615 * given method handle to a new type, by reordering the arguments. 4616 * The resulting method handle is guaranteed to report a type 4617 * which is equal to the desired new type. 4618 * <p> 4619 * The given array controls the reordering. 4620 * Call {@code #I} the number of incoming parameters (the value 4621 * {@code newType.parameterCount()}, and call {@code #O} the number 4622 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4623 * Then the length of the reordering array must be {@code #O}, 4624 * and each element must be a non-negative number less than {@code #I}. 4625 * For every {@code N} less than {@code #O}, the {@code N}-th 4626 * outgoing argument will be taken from the {@code I}-th incoming 4627 * argument, where {@code I} is {@code reorder[N]}. 4628 * <p> 4629 * No argument or return value conversions are applied. 4630 * The type of each incoming argument, as determined by {@code newType}, 4631 * must be identical to the type of the corresponding outgoing parameter 4632 * or parameters in the target method handle. 4633 * The return type of {@code newType} must be identical to the return 4634 * type of the original target. 4635 * <p> 4636 * The reordering array need not specify an actual permutation. 4637 * An incoming argument will be duplicated if its index appears 4638 * more than once in the array, and an incoming argument will be dropped 4639 * if its index does not appear in the array. 4640 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4641 * incoming arguments which are not mentioned in the reordering array 4642 * may be of any type, as determined only by {@code newType}. 4643 * {@snippet lang="java" : 4644 import static java.lang.invoke.MethodHandles.*; 4645 import static java.lang.invoke.MethodType.*; 4646 ... 4647 MethodType intfn1 = methodType(int.class, int.class); 4648 MethodType intfn2 = methodType(int.class, int.class, int.class); 4649 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4650 assert(sub.type().equals(intfn2)); 4651 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4652 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4653 assert((int)rsub.invokeExact(1, 100) == 99); 4654 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4655 assert(add.type().equals(intfn2)); 4656 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4657 assert(twice.type().equals(intfn1)); 4658 assert((int)twice.invokeExact(21) == 42); 4659 * } 4660 * <p> 4661 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4662 * variable-arity method handle}, even if the original target method handle was. 4663 * @param target the method handle to invoke after arguments are reordered 4664 * @param newType the expected type of the new method handle 4665 * @param reorder an index array which controls the reordering 4666 * @return a method handle which delegates to the target after it 4667 * drops unused arguments and moves and/or duplicates the other arguments 4668 * @throws NullPointerException if any argument is null 4669 * @throws IllegalArgumentException if the index array length is not equal to 4670 * the arity of the target, or if any index array element 4671 * not a valid index for a parameter of {@code newType}, 4672 * or if two corresponding parameter types in 4673 * {@code target.type()} and {@code newType} are not identical, 4674 */ 4675 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4676 reorder = reorder.clone(); // get a private copy 4677 MethodType oldType = target.type(); 4678 permuteArgumentChecks(reorder, newType, oldType); 4679 // first detect dropped arguments and handle them separately 4680 int[] originalReorder = reorder; 4681 BoundMethodHandle result = target.rebind(); 4682 LambdaForm form = result.form; 4683 int newArity = newType.parameterCount(); 4684 // Normalize the reordering into a real permutation, 4685 // by removing duplicates and adding dropped elements. 4686 // This somewhat improves lambda form caching, as well 4687 // as simplifying the transform by breaking it up into steps. 4688 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4689 if (ddIdx > 0) { 4690 // We found a duplicated entry at reorder[ddIdx]. 4691 // Example: (x,y,z)->asList(x,y,z) 4692 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4693 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4694 // The starred element corresponds to the argument 4695 // deleted by the dupArgumentForm transform. 4696 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4697 boolean killFirst = false; 4698 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4699 // Set killFirst if the dup is larger than an intervening position. 4700 // This will remove at least one inversion from the permutation. 4701 if (dupVal > val) killFirst = true; 4702 } 4703 if (!killFirst) { 4704 srcPos = dstPos; 4705 dstPos = ddIdx; 4706 } 4707 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4708 assert (reorder[srcPos] == reorder[dstPos]); 4709 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4710 // contract the reordering by removing the element at dstPos 4711 int tailPos = dstPos + 1; 4712 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4713 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4714 } else { 4715 int dropVal = ~ddIdx, insPos = 0; 4716 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4717 // Find first element of reorder larger than dropVal. 4718 // This is where we will insert the dropVal. 4719 insPos += 1; 4720 } 4721 Class<?> ptype = newType.parameterType(dropVal); 4722 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4723 oldType = oldType.insertParameterTypes(insPos, ptype); 4724 // expand the reordering by inserting an element at insPos 4725 int tailPos = insPos + 1; 4726 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4727 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4728 reorder[insPos] = dropVal; 4729 } 4730 assert (permuteArgumentChecks(reorder, newType, oldType)); 4731 } 4732 assert (reorder.length == newArity); // a perfect permutation 4733 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4734 form = form.editor().permuteArgumentsForm(1, reorder); 4735 if (newType == result.type() && form == result.internalForm()) 4736 return result; 4737 return result.copyWith(newType, form); 4738 } 4739 4740 /** 4741 * Return an indication of any duplicate or omission in reorder. 4742 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4743 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4744 * Otherwise, return zero. 4745 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4746 */ 4747 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4748 final int BIT_LIMIT = 63; // max number of bits in bit mask 4749 if (newArity < BIT_LIMIT) { 4750 long mask = 0; 4751 for (int i = 0; i < reorder.length; i++) { 4752 int arg = reorder[i]; 4753 if (arg >= newArity) { 4754 return reorder.length; 4755 } 4756 long bit = 1L << arg; 4757 if ((mask & bit) != 0) { 4758 return i; // >0 indicates a dup 4759 } 4760 mask |= bit; 4761 } 4762 if (mask == (1L << newArity) - 1) { 4763 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4764 return 0; 4765 } 4766 // find first zero 4767 long zeroBit = Long.lowestOneBit(~mask); 4768 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4769 assert(zeroPos <= newArity); 4770 if (zeroPos == newArity) { 4771 return 0; 4772 } 4773 return ~zeroPos; 4774 } else { 4775 // same algorithm, different bit set 4776 BitSet mask = new BitSet(newArity); 4777 for (int i = 0; i < reorder.length; i++) { 4778 int arg = reorder[i]; 4779 if (arg >= newArity) { 4780 return reorder.length; 4781 } 4782 if (mask.get(arg)) { 4783 return i; // >0 indicates a dup 4784 } 4785 mask.set(arg); 4786 } 4787 int zeroPos = mask.nextClearBit(0); 4788 assert(zeroPos <= newArity); 4789 if (zeroPos == newArity) { 4790 return 0; 4791 } 4792 return ~zeroPos; 4793 } 4794 } 4795 4796 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4797 if (newType.returnType() != oldType.returnType()) 4798 throw newIllegalArgumentException("return types do not match", 4799 oldType, newType); 4800 if (reorder.length != oldType.parameterCount()) 4801 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 4802 oldType, Arrays.toString(reorder)); 4803 4804 int limit = newType.parameterCount(); 4805 for (int j = 0; j < reorder.length; j++) { 4806 int i = reorder[j]; 4807 if (i < 0 || i >= limit) { 4808 throw newIllegalArgumentException("index is out of bounds for new type", 4809 i, newType); 4810 } 4811 Class<?> src = newType.parameterType(i); 4812 Class<?> dst = oldType.parameterType(j); 4813 if (src != dst) 4814 throw newIllegalArgumentException("parameter types do not match after reorder", 4815 oldType, newType); 4816 } 4817 return true; 4818 } 4819 4820 /** 4821 * Produces a method handle of the requested return type which returns the given 4822 * constant value every time it is invoked. 4823 * <p> 4824 * Before the method handle is returned, the passed-in value is converted to the requested type. 4825 * If the requested type is primitive, widening primitive conversions are attempted, 4826 * else reference conversions are attempted. 4827 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 4828 * @param type the return type of the desired method handle 4829 * @param value the value to return 4830 * @return a method handle of the given return type and no arguments, which always returns the given value 4831 * @throws NullPointerException if the {@code type} argument is null 4832 * @throws ClassCastException if the value cannot be converted to the required return type 4833 * @throws IllegalArgumentException if the given type is {@code void.class} 4834 */ 4835 public static MethodHandle constant(Class<?> type, Object value) { 4836 if (Objects.requireNonNull(type) == void.class) 4837 throw newIllegalArgumentException("void type"); 4838 return MethodHandleImpl.makeConstantReturning(type, value); 4839 } 4840 4841 /** 4842 * Produces a method handle which returns its sole argument when invoked. 4843 * @param type the type of the sole parameter and return value of the desired method handle 4844 * @return a unary method handle which accepts and returns the given type 4845 * @throws NullPointerException if the argument is null 4846 * @throws IllegalArgumentException if the given type is {@code void.class} 4847 */ 4848 public static MethodHandle identity(Class<?> type) { 4849 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 4850 int pos = btw.ordinal(); 4851 MethodHandle ident = IDENTITY_MHS[pos]; 4852 if (ident == null) { 4853 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 4854 } 4855 if (ident.type().returnType() == type) 4856 return ident; 4857 // something like identity(Foo.class); do not bother to intern these 4858 assert (btw == Wrapper.OBJECT); 4859 return makeIdentity(type); 4860 } 4861 4862 /** 4863 * Produces a constant method handle of the requested return type which 4864 * returns the default value for that type every time it is invoked. 4865 * The resulting constant method handle will have no side effects. 4866 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 4867 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 4868 * since {@code explicitCastArguments} converts {@code null} to default values. 4869 * @param type the expected return type of the desired method handle 4870 * @return a constant method handle that takes no arguments 4871 * and returns the default value of the given type (or void, if the type is void) 4872 * @throws NullPointerException if the argument is null 4873 * @see MethodHandles#constant 4874 * @see MethodHandles#empty 4875 * @see MethodHandles#explicitCastArguments 4876 * @since 9 4877 */ 4878 public static MethodHandle zero(Class<?> type) { 4879 Objects.requireNonNull(type); 4880 return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type)) 4881 : MethodHandleImpl.makeConstantReturning(type, null); 4882 } 4883 4884 private static MethodHandle identityOrVoid(Class<?> type) { 4885 return type == void.class ? zero(type) : identity(type); 4886 } 4887 4888 /** 4889 * Produces a method handle of the requested type which ignores any arguments, does nothing, 4890 * and returns a suitable default depending on the return type. 4891 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 4892 * <p>The returned method handle is equivalent to 4893 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 4894 * 4895 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 4896 * {@code guardWithTest(pred, target, empty(target.type())}. 4897 * @param type the type of the desired method handle 4898 * @return a constant method handle of the given type, which returns a default value of the given return type 4899 * @throws NullPointerException if the argument is null 4900 * @see MethodHandles#zero(Class) 4901 * @see MethodHandles#constant 4902 * @since 9 4903 */ 4904 public static MethodHandle empty(MethodType type) { 4905 Objects.requireNonNull(type); 4906 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 4907 } 4908 4909 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 4910 private static MethodHandle makeIdentity(Class<?> ptype) { 4911 MethodType mtype = methodType(ptype, ptype); // throws IAE for void 4912 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 4913 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 4914 } 4915 4916 private static MethodHandle primitiveZero(Wrapper w) { 4917 assert w != Wrapper.OBJECT : w; 4918 int pos = w.ordinal(); 4919 MethodHandle mh = PRIMITIVE_ZERO_MHS[pos]; 4920 if (mh == null) { 4921 mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w)); 4922 } 4923 assert (mh.type().returnType() == w.primitiveType()) : mh; 4924 return mh; 4925 } 4926 4927 private static MethodHandle makePrimitiveZero(Wrapper w) { 4928 if (w == Wrapper.VOID) { 4929 var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized 4930 return SimpleMethodHandle.make(MethodType.methodType(void.class), lf); 4931 } else { 4932 return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero()); 4933 } 4934 } 4935 4936 private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 4937 4938 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 4939 // Simulate a CAS, to avoid racy duplication of results. 4940 MethodHandle prev = cache[pos]; 4941 if (prev != null) return prev; 4942 return cache[pos] = value; 4943 } 4944 4945 /** 4946 * Provides a target method handle with one or more <em>bound arguments</em> 4947 * in advance of the method handle's invocation. 4948 * The formal parameters to the target corresponding to the bound 4949 * arguments are called <em>bound parameters</em>. 4950 * Returns a new method handle which saves away the bound arguments. 4951 * When it is invoked, it receives arguments for any non-bound parameters, 4952 * binds the saved arguments to their corresponding parameters, 4953 * and calls the original target. 4954 * <p> 4955 * The type of the new method handle will drop the types for the bound 4956 * parameters from the original target type, since the new method handle 4957 * will no longer require those arguments to be supplied by its callers. 4958 * <p> 4959 * Each given argument object must match the corresponding bound parameter type. 4960 * If a bound parameter type is a primitive, the argument object 4961 * must be a wrapper, and will be unboxed to produce the primitive value. 4962 * <p> 4963 * The {@code pos} argument selects which parameters are to be bound. 4964 * It may range between zero and <i>N-L</i> (inclusively), 4965 * where <i>N</i> is the arity of the target method handle 4966 * and <i>L</i> is the length of the values array. 4967 * <p> 4968 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4969 * variable-arity method handle}, even if the original target method handle was. 4970 * @param target the method handle to invoke after the argument is inserted 4971 * @param pos where to insert the argument (zero for the first) 4972 * @param values the series of arguments to insert 4973 * @return a method handle which inserts an additional argument, 4974 * before calling the original method handle 4975 * @throws NullPointerException if the target or the {@code values} array is null 4976 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 4977 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 4978 * is the length of the values array. 4979 * @throws ClassCastException if an argument does not match the corresponding bound parameter 4980 * type. 4981 * @see MethodHandle#bindTo 4982 */ 4983 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 4984 int insCount = values.length; 4985 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 4986 if (insCount == 0) return target; 4987 BoundMethodHandle result = target.rebind(); 4988 for (int i = 0; i < insCount; i++) { 4989 Object value = values[i]; 4990 Class<?> ptype = ptypes[pos+i]; 4991 if (ptype.isPrimitive()) { 4992 result = insertArgumentPrimitive(result, pos, ptype, value); 4993 } else { 4994 value = ptype.cast(value); // throw CCE if needed 4995 result = result.bindArgumentL(pos, value); 4996 } 4997 } 4998 return result; 4999 } 5000 5001 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5002 Class<?> ptype, Object value) { 5003 Wrapper w = Wrapper.forPrimitiveType(ptype); 5004 // perform unboxing and/or primitive conversion 5005 value = w.convert(value, ptype); 5006 return switch (w) { 5007 case INT -> result.bindArgumentI(pos, (int) value); 5008 case LONG -> result.bindArgumentJ(pos, (long) value); 5009 case FLOAT -> result.bindArgumentF(pos, (float) value); 5010 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5011 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5012 }; 5013 } 5014 5015 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5016 MethodType oldType = target.type(); 5017 int outargs = oldType.parameterCount(); 5018 int inargs = outargs - insCount; 5019 if (inargs < 0) 5020 throw newIllegalArgumentException("too many values to insert"); 5021 if (pos < 0 || pos > inargs) 5022 throw newIllegalArgumentException("no argument type to append"); 5023 return oldType.ptypes(); 5024 } 5025 5026 /** 5027 * Produces a method handle which will discard some dummy arguments 5028 * before calling some other specified <i>target</i> method handle. 5029 * The type of the new method handle will be the same as the target's type, 5030 * except it will also include the dummy argument types, 5031 * at some given position. 5032 * <p> 5033 * The {@code pos} argument may range between zero and <i>N</i>, 5034 * where <i>N</i> is the arity of the target. 5035 * If {@code pos} is zero, the dummy arguments will precede 5036 * the target's real arguments; if {@code pos} is <i>N</i> 5037 * they will come after. 5038 * <p> 5039 * <b>Example:</b> 5040 * {@snippet lang="java" : 5041 import static java.lang.invoke.MethodHandles.*; 5042 import static java.lang.invoke.MethodType.*; 5043 ... 5044 MethodHandle cat = lookup().findVirtual(String.class, 5045 "concat", methodType(String.class, String.class)); 5046 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5047 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5048 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5049 assertEquals(bigType, d0.type()); 5050 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5051 * } 5052 * <p> 5053 * This method is also equivalent to the following code: 5054 * <blockquote><pre> 5055 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5056 * </pre></blockquote> 5057 * @param target the method handle to invoke after the arguments are dropped 5058 * @param pos position of first argument to drop (zero for the leftmost) 5059 * @param valueTypes the type(s) of the argument(s) to drop 5060 * @return a method handle which drops arguments of the given types, 5061 * before calling the original method handle 5062 * @throws NullPointerException if the target is null, 5063 * or if the {@code valueTypes} list or any of its elements is null 5064 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5065 * or if {@code pos} is negative or greater than the arity of the target, 5066 * or if the new method handle's type would have too many parameters 5067 */ 5068 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5069 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5070 } 5071 5072 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5073 MethodType oldType = target.type(); // get NPE 5074 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5075 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5076 if (dropped == 0) return target; 5077 BoundMethodHandle result = target.rebind(); 5078 LambdaForm lform = result.form; 5079 int insertFormArg = 1 + pos; 5080 for (Class<?> ptype : valueTypes) { 5081 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5082 } 5083 result = result.copyWith(newType, lform); 5084 return result; 5085 } 5086 5087 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5088 int dropped = valueTypes.length; 5089 MethodType.checkSlotCount(dropped); 5090 int outargs = oldType.parameterCount(); 5091 int inargs = outargs + dropped; 5092 if (pos < 0 || pos > outargs) 5093 throw newIllegalArgumentException("no argument type to remove" 5094 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5095 ); 5096 return dropped; 5097 } 5098 5099 /** 5100 * Produces a method handle which will discard some dummy arguments 5101 * before calling some other specified <i>target</i> method handle. 5102 * The type of the new method handle will be the same as the target's type, 5103 * except it will also include the dummy argument types, 5104 * at some given position. 5105 * <p> 5106 * The {@code pos} argument may range between zero and <i>N</i>, 5107 * where <i>N</i> is the arity of the target. 5108 * If {@code pos} is zero, the dummy arguments will precede 5109 * the target's real arguments; if {@code pos} is <i>N</i> 5110 * they will come after. 5111 * @apiNote 5112 * {@snippet lang="java" : 5113 import static java.lang.invoke.MethodHandles.*; 5114 import static java.lang.invoke.MethodType.*; 5115 ... 5116 MethodHandle cat = lookup().findVirtual(String.class, 5117 "concat", methodType(String.class, String.class)); 5118 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5119 MethodHandle d0 = dropArguments(cat, 0, String.class); 5120 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5121 MethodHandle d1 = dropArguments(cat, 1, String.class); 5122 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5123 MethodHandle d2 = dropArguments(cat, 2, String.class); 5124 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5125 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5126 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5127 * } 5128 * <p> 5129 * This method is also equivalent to the following code: 5130 * <blockquote><pre> 5131 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5132 * </pre></blockquote> 5133 * @param target the method handle to invoke after the arguments are dropped 5134 * @param pos position of first argument to drop (zero for the leftmost) 5135 * @param valueTypes the type(s) of the argument(s) to drop 5136 * @return a method handle which drops arguments of the given types, 5137 * before calling the original method handle 5138 * @throws NullPointerException if the target is null, 5139 * or if the {@code valueTypes} array or any of its elements is null 5140 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5141 * or if {@code pos} is negative or greater than the arity of the target, 5142 * or if the new method handle's type would have 5143 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5144 */ 5145 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5146 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5147 } 5148 5149 /* Convenience overloads for trusting internal low-arity call-sites */ 5150 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5151 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5152 } 5153 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5154 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5155 } 5156 5157 // private version which allows caller some freedom with error handling 5158 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5159 boolean nullOnFailure) { 5160 Class<?>[] oldTypes = target.type().ptypes(); 5161 int match = oldTypes.length; 5162 if (skip != 0) { 5163 if (skip < 0 || skip > match) { 5164 throw newIllegalArgumentException("illegal skip", skip, target); 5165 } 5166 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5167 match -= skip; 5168 } 5169 Class<?>[] addTypes = newTypes; 5170 int add = addTypes.length; 5171 if (pos != 0) { 5172 if (pos < 0 || pos > add) { 5173 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5174 } 5175 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5176 add -= pos; 5177 assert(addTypes.length == add); 5178 } 5179 // Do not add types which already match the existing arguments. 5180 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5181 if (nullOnFailure) { 5182 return null; 5183 } 5184 throw newIllegalArgumentException("argument lists do not match", 5185 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5186 } 5187 addTypes = Arrays.copyOfRange(addTypes, match, add); 5188 add -= match; 5189 assert(addTypes.length == add); 5190 // newTypes: ( P*[pos], M*[match], A*[add] ) 5191 // target: ( S*[skip], M*[match] ) 5192 MethodHandle adapter = target; 5193 if (add > 0) { 5194 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5195 } 5196 // adapter: (S*[skip], M*[match], A*[add] ) 5197 if (pos > 0) { 5198 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5199 } 5200 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5201 return adapter; 5202 } 5203 5204 /** 5205 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5206 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5207 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5208 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5209 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5210 * {@link #dropArguments(MethodHandle, int, Class[])}. 5211 * <p> 5212 * The resulting handle will have the same return type as the target handle. 5213 * <p> 5214 * In more formal terms, assume these two type lists:<ul> 5215 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5216 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5217 * {@code newTypes}. 5218 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5219 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5220 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5221 * sub-list. 5222 * </ul> 5223 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5224 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5225 * {@link #dropArguments(MethodHandle, int, Class[])}. 5226 * 5227 * @apiNote 5228 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5229 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5230 * {@snippet lang="java" : 5231 import static java.lang.invoke.MethodHandles.*; 5232 import static java.lang.invoke.MethodType.*; 5233 ... 5234 ... 5235 MethodHandle h0 = constant(boolean.class, true); 5236 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5237 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5238 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5239 if (h1.type().parameterCount() < h2.type().parameterCount()) 5240 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5241 else 5242 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5243 MethodHandle h3 = guardWithTest(h0, h1, h2); 5244 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5245 * } 5246 * @param target the method handle to adapt 5247 * @param skip number of targets parameters to disregard (they will be unchanged) 5248 * @param newTypes the list of types to match {@code target}'s parameter type list to 5249 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5250 * @return a possibly adapted method handle 5251 * @throws NullPointerException if either argument is null 5252 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5253 * or if {@code skip} is negative or greater than the arity of the target, 5254 * or if {@code pos} is negative or greater than the newTypes list size, 5255 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5256 * {@code pos}. 5257 * @since 9 5258 */ 5259 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5260 Objects.requireNonNull(target); 5261 Objects.requireNonNull(newTypes); 5262 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5263 } 5264 5265 /** 5266 * Drop the return value of the target handle (if any). 5267 * The returned method handle will have a {@code void} return type. 5268 * 5269 * @param target the method handle to adapt 5270 * @return a possibly adapted method handle 5271 * @throws NullPointerException if {@code target} is null 5272 * @since 16 5273 */ 5274 public static MethodHandle dropReturn(MethodHandle target) { 5275 Objects.requireNonNull(target); 5276 MethodType oldType = target.type(); 5277 Class<?> oldReturnType = oldType.returnType(); 5278 if (oldReturnType == void.class) 5279 return target; 5280 MethodType newType = oldType.changeReturnType(void.class); 5281 BoundMethodHandle result = target.rebind(); 5282 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5283 result = result.copyWith(newType, lform); 5284 return result; 5285 } 5286 5287 /** 5288 * Adapts a target method handle by pre-processing 5289 * one or more of its arguments, each with its own unary filter function, 5290 * and then calling the target with each pre-processed argument 5291 * replaced by the result of its corresponding filter function. 5292 * <p> 5293 * The pre-processing is performed by one or more method handles, 5294 * specified in the elements of the {@code filters} array. 5295 * The first element of the filter array corresponds to the {@code pos} 5296 * argument of the target, and so on in sequence. 5297 * The filter functions are invoked in left to right order. 5298 * <p> 5299 * Null arguments in the array are treated as identity functions, 5300 * and the corresponding arguments left unchanged. 5301 * (If there are no non-null elements in the array, the original target is returned.) 5302 * Each filter is applied to the corresponding argument of the adapter. 5303 * <p> 5304 * If a filter {@code F} applies to the {@code N}th argument of 5305 * the target, then {@code F} must be a method handle which 5306 * takes exactly one argument. The type of {@code F}'s sole argument 5307 * replaces the corresponding argument type of the target 5308 * in the resulting adapted method handle. 5309 * The return type of {@code F} must be identical to the corresponding 5310 * parameter type of the target. 5311 * <p> 5312 * It is an error if there are elements of {@code filters} 5313 * (null or not) 5314 * which do not correspond to argument positions in the target. 5315 * <p><b>Example:</b> 5316 * {@snippet lang="java" : 5317 import static java.lang.invoke.MethodHandles.*; 5318 import static java.lang.invoke.MethodType.*; 5319 ... 5320 MethodHandle cat = lookup().findVirtual(String.class, 5321 "concat", methodType(String.class, String.class)); 5322 MethodHandle upcase = lookup().findVirtual(String.class, 5323 "toUpperCase", methodType(String.class)); 5324 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5325 MethodHandle f0 = filterArguments(cat, 0, upcase); 5326 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5327 MethodHandle f1 = filterArguments(cat, 1, upcase); 5328 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5329 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5330 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5331 * } 5332 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5333 * denotes the return type of both the {@code target} and resulting adapter. 5334 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5335 * of the parameters and arguments that precede and follow the filter position 5336 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5337 * values of the filtered parameters and arguments; they also represent the 5338 * return types of the {@code filter[i]} handles. The latter accept arguments 5339 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5340 * the resulting adapter. 5341 * {@snippet lang="java" : 5342 * T target(P... p, A[i]... a[i], B... b); 5343 * A[i] filter[i](V[i]); 5344 * T adapter(P... p, V[i]... v[i], B... b) { 5345 * return target(p..., filter[i](v[i])..., b...); 5346 * } 5347 * } 5348 * <p> 5349 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5350 * variable-arity method handle}, even if the original target method handle was. 5351 * 5352 * @param target the method handle to invoke after arguments are filtered 5353 * @param pos the position of the first argument to filter 5354 * @param filters method handles to call initially on filtered arguments 5355 * @return method handle which incorporates the specified argument filtering logic 5356 * @throws NullPointerException if the target is null 5357 * or if the {@code filters} array is null 5358 * @throws IllegalArgumentException if a non-null element of {@code filters} 5359 * does not match a corresponding argument type of target as described above, 5360 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5361 * or if the resulting method handle's type would have 5362 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5363 */ 5364 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5365 // In method types arguments start at index 0, while the LF 5366 // editor have the MH receiver at position 0 - adjust appropriately. 5367 final int MH_RECEIVER_OFFSET = 1; 5368 filterArgumentsCheckArity(target, pos, filters); 5369 MethodHandle adapter = target; 5370 5371 // keep track of currently matched filters, as to optimize repeated filters 5372 int index = 0; 5373 int[] positions = new int[filters.length]; 5374 MethodHandle filter = null; 5375 5376 // process filters in reverse order so that the invocation of 5377 // the resulting adapter will invoke the filters in left-to-right order 5378 for (int i = filters.length - 1; i >= 0; --i) { 5379 MethodHandle newFilter = filters[i]; 5380 if (newFilter == null) continue; // ignore null elements of filters 5381 5382 // flush changes on update 5383 if (filter != newFilter) { 5384 if (filter != null) { 5385 if (index > 1) { 5386 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5387 } else { 5388 adapter = filterArgument(adapter, positions[0] - 1, filter); 5389 } 5390 } 5391 filter = newFilter; 5392 index = 0; 5393 } 5394 5395 filterArgumentChecks(target, pos + i, newFilter); 5396 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5397 } 5398 if (index > 1) { 5399 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5400 } else if (index == 1) { 5401 adapter = filterArgument(adapter, positions[0] - 1, filter); 5402 } 5403 return adapter; 5404 } 5405 5406 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5407 MethodType targetType = adapter.type(); 5408 MethodType filterType = filter.type(); 5409 BoundMethodHandle result = adapter.rebind(); 5410 Class<?> newParamType = filterType.parameterType(0); 5411 5412 Class<?>[] ptypes = targetType.ptypes().clone(); 5413 for (int pos : positions) { 5414 ptypes[pos - 1] = newParamType; 5415 } 5416 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5417 5418 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5419 return result.copyWithExtendL(newType, lform, filter); 5420 } 5421 5422 /*non-public*/ 5423 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5424 filterArgumentChecks(target, pos, filter); 5425 MethodType targetType = target.type(); 5426 MethodType filterType = filter.type(); 5427 BoundMethodHandle result = target.rebind(); 5428 Class<?> newParamType = filterType.parameterType(0); 5429 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5430 MethodType newType = targetType.changeParameterType(pos, newParamType); 5431 result = result.copyWithExtendL(newType, lform, filter); 5432 return result; 5433 } 5434 5435 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5436 MethodType targetType = target.type(); 5437 int maxPos = targetType.parameterCount(); 5438 if (pos + filters.length > maxPos) 5439 throw newIllegalArgumentException("too many filters"); 5440 } 5441 5442 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5443 MethodType targetType = target.type(); 5444 MethodType filterType = filter.type(); 5445 if (filterType.parameterCount() != 1 5446 || filterType.returnType() != targetType.parameterType(pos)) 5447 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5448 } 5449 5450 /** 5451 * Adapts a target method handle by pre-processing 5452 * a sub-sequence of its arguments with a filter (another method handle). 5453 * The pre-processed arguments are replaced by the result (if any) of the 5454 * filter function. 5455 * The target is then called on the modified (usually shortened) argument list. 5456 * <p> 5457 * If the filter returns a value, the target must accept that value as 5458 * its argument in position {@code pos}, preceded and/or followed by 5459 * any arguments not passed to the filter. 5460 * If the filter returns void, the target must accept all arguments 5461 * not passed to the filter. 5462 * No arguments are reordered, and a result returned from the filter 5463 * replaces (in order) the whole subsequence of arguments originally 5464 * passed to the adapter. 5465 * <p> 5466 * The argument types (if any) of the filter 5467 * replace zero or one argument types of the target, at position {@code pos}, 5468 * in the resulting adapted method handle. 5469 * The return type of the filter (if any) must be identical to the 5470 * argument type of the target at position {@code pos}, and that target argument 5471 * is supplied by the return value of the filter. 5472 * <p> 5473 * In all cases, {@code pos} must be greater than or equal to zero, and 5474 * {@code pos} must also be less than or equal to the target's arity. 5475 * <p><b>Example:</b> 5476 * {@snippet lang="java" : 5477 import static java.lang.invoke.MethodHandles.*; 5478 import static java.lang.invoke.MethodType.*; 5479 ... 5480 MethodHandle deepToString = publicLookup() 5481 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5482 5483 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5484 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5485 5486 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5487 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5488 5489 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5490 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5491 assertEquals("[top, [up, down], strange]", 5492 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5493 5494 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5495 assertEquals("[top, [up, down], [strange]]", 5496 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5497 5498 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5499 assertEquals("[top, [[up, down, strange], charm], bottom]", 5500 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5501 * } 5502 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5503 * represents the return type of the {@code target} and resulting adapter. 5504 * {@code V}/{@code v} stand for the return type and value of the 5505 * {@code filter}, which are also found in the signature and arguments of 5506 * the {@code target}, respectively, unless {@code V} is {@code void}. 5507 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5508 * and values preceding and following the collection position, {@code pos}, 5509 * in the {@code target}'s signature. They also turn up in the resulting 5510 * adapter's signature and arguments, where they surround 5511 * {@code B}/{@code b}, which represent the parameter types and arguments 5512 * to the {@code filter} (if any). 5513 * {@snippet lang="java" : 5514 * T target(A...,V,C...); 5515 * V filter(B...); 5516 * T adapter(A... a,B... b,C... c) { 5517 * V v = filter(b...); 5518 * return target(a...,v,c...); 5519 * } 5520 * // and if the filter has no arguments: 5521 * T target2(A...,V,C...); 5522 * V filter2(); 5523 * T adapter2(A... a,C... c) { 5524 * V v = filter2(); 5525 * return target2(a...,v,c...); 5526 * } 5527 * // and if the filter has a void return: 5528 * T target3(A...,C...); 5529 * void filter3(B...); 5530 * T adapter3(A... a,B... b,C... c) { 5531 * filter3(b...); 5532 * return target3(a...,c...); 5533 * } 5534 * } 5535 * <p> 5536 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5537 * one which first "folds" the affected arguments, and then drops them, in separate 5538 * steps as follows: 5539 * {@snippet lang="java" : 5540 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5541 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5542 * } 5543 * If the target method handle consumes no arguments besides than the result 5544 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5545 * is equivalent to {@code filterReturnValue(coll, mh)}. 5546 * If the filter method handle {@code coll} consumes one argument and produces 5547 * a non-void result, then {@code collectArguments(mh, N, coll)} 5548 * is equivalent to {@code filterArguments(mh, N, coll)}. 5549 * Other equivalences are possible but would require argument permutation. 5550 * <p> 5551 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5552 * variable-arity method handle}, even if the original target method handle was. 5553 * 5554 * @param target the method handle to invoke after filtering the subsequence of arguments 5555 * @param pos the position of the first adapter argument to pass to the filter, 5556 * and/or the target argument which receives the result of the filter 5557 * @param filter method handle to call on the subsequence of arguments 5558 * @return method handle which incorporates the specified argument subsequence filtering logic 5559 * @throws NullPointerException if either argument is null 5560 * @throws IllegalArgumentException if the return type of {@code filter} 5561 * is non-void and is not the same as the {@code pos} argument of the target, 5562 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5563 * or if the resulting method handle's type would have 5564 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5565 * @see MethodHandles#foldArguments 5566 * @see MethodHandles#filterArguments 5567 * @see MethodHandles#filterReturnValue 5568 */ 5569 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5570 MethodType newType = collectArgumentsChecks(target, pos, filter); 5571 MethodType collectorType = filter.type(); 5572 BoundMethodHandle result = target.rebind(); 5573 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5574 return result.copyWithExtendL(newType, lform, filter); 5575 } 5576 5577 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5578 MethodType targetType = target.type(); 5579 MethodType filterType = filter.type(); 5580 Class<?> rtype = filterType.returnType(); 5581 Class<?>[] filterArgs = filterType.ptypes(); 5582 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5583 (rtype != void.class && pos >= targetType.parameterCount())) { 5584 throw newIllegalArgumentException("position is out of range for target", target, pos); 5585 } 5586 if (rtype == void.class) { 5587 return targetType.insertParameterTypes(pos, filterArgs); 5588 } 5589 if (rtype != targetType.parameterType(pos)) { 5590 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5591 } 5592 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5593 } 5594 5595 /** 5596 * Adapts a target method handle by post-processing 5597 * its return value (if any) with a filter (another method handle). 5598 * The result of the filter is returned from the adapter. 5599 * <p> 5600 * If the target returns a value, the filter must accept that value as 5601 * its only argument. 5602 * If the target returns void, the filter must accept no arguments. 5603 * <p> 5604 * The return type of the filter 5605 * replaces the return type of the target 5606 * in the resulting adapted method handle. 5607 * The argument type of the filter (if any) must be identical to the 5608 * return type of the target. 5609 * <p><b>Example:</b> 5610 * {@snippet lang="java" : 5611 import static java.lang.invoke.MethodHandles.*; 5612 import static java.lang.invoke.MethodType.*; 5613 ... 5614 MethodHandle cat = lookup().findVirtual(String.class, 5615 "concat", methodType(String.class, String.class)); 5616 MethodHandle length = lookup().findVirtual(String.class, 5617 "length", methodType(int.class)); 5618 System.out.println((String) cat.invokeExact("x", "y")); // xy 5619 MethodHandle f0 = filterReturnValue(cat, length); 5620 System.out.println((int) f0.invokeExact("x", "y")); // 2 5621 * } 5622 * <p>Here is pseudocode for the resulting adapter. In the code, 5623 * {@code T}/{@code t} represent the result type and value of the 5624 * {@code target}; {@code V}, the result type of the {@code filter}; and 5625 * {@code A}/{@code a}, the types and values of the parameters and arguments 5626 * of the {@code target} as well as the resulting adapter. 5627 * {@snippet lang="java" : 5628 * T target(A...); 5629 * V filter(T); 5630 * V adapter(A... a) { 5631 * T t = target(a...); 5632 * return filter(t); 5633 * } 5634 * // and if the target has a void return: 5635 * void target2(A...); 5636 * V filter2(); 5637 * V adapter2(A... a) { 5638 * target2(a...); 5639 * return filter2(); 5640 * } 5641 * // and if the filter has a void return: 5642 * T target3(A...); 5643 * void filter3(V); 5644 * void adapter3(A... a) { 5645 * T t = target3(a...); 5646 * filter3(t); 5647 * } 5648 * } 5649 * <p> 5650 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5651 * variable-arity method handle}, even if the original target method handle was. 5652 * @param target the method handle to invoke before filtering the return value 5653 * @param filter method handle to call on the return value 5654 * @return method handle which incorporates the specified return value filtering logic 5655 * @throws NullPointerException if either argument is null 5656 * @throws IllegalArgumentException if the argument list of {@code filter} 5657 * does not match the return type of target as described above 5658 */ 5659 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5660 MethodType targetType = target.type(); 5661 MethodType filterType = filter.type(); 5662 filterReturnValueChecks(targetType, filterType); 5663 BoundMethodHandle result = target.rebind(); 5664 BasicType rtype = BasicType.basicType(filterType.returnType()); 5665 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5666 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5667 result = result.copyWithExtendL(newType, lform, filter); 5668 return result; 5669 } 5670 5671 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5672 Class<?> rtype = targetType.returnType(); 5673 int filterValues = filterType.parameterCount(); 5674 if (filterValues == 0 5675 ? (rtype != void.class) 5676 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5677 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5678 } 5679 5680 /** 5681 * Filter the return value of a target method handle with a filter function. The filter function is 5682 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5683 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5684 * as follows: 5685 * {@snippet lang="java" : 5686 * T target(A...) 5687 * V filter(B... , T) 5688 * V adapter(A... a, B... b) { 5689 * T t = target(a...); 5690 * return filter(b..., t); 5691 * } 5692 * } 5693 * <p> 5694 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5695 * 5696 * @param target the target method handle 5697 * @param filter the filter method handle 5698 * @return the adapter method handle 5699 */ 5700 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5701 MethodType targetType = target.type(); 5702 MethodType filterType = filter.type(); 5703 BoundMethodHandle result = target.rebind(); 5704 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5705 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5706 if (filterType.parameterCount() > 1) { 5707 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5708 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5709 } 5710 } 5711 result = result.copyWithExtendL(newType, lform, filter); 5712 return result; 5713 } 5714 5715 /** 5716 * Adapts a target method handle by pre-processing 5717 * some of its arguments, and then calling the target with 5718 * the result of the pre-processing, inserted into the original 5719 * sequence of arguments. 5720 * <p> 5721 * The pre-processing is performed by {@code combiner}, a second method handle. 5722 * Of the arguments passed to the adapter, the first {@code N} arguments 5723 * are copied to the combiner, which is then called. 5724 * (Here, {@code N} is defined as the parameter count of the combiner.) 5725 * After this, control passes to the target, with any result 5726 * from the combiner inserted before the original {@code N} incoming 5727 * arguments. 5728 * <p> 5729 * If the combiner returns a value, the first parameter type of the target 5730 * must be identical with the return type of the combiner, and the next 5731 * {@code N} parameter types of the target must exactly match the parameters 5732 * of the combiner. 5733 * <p> 5734 * If the combiner has a void return, no result will be inserted, 5735 * and the first {@code N} parameter types of the target 5736 * must exactly match the parameters of the combiner. 5737 * <p> 5738 * The resulting adapter is the same type as the target, except that the 5739 * first parameter type is dropped, 5740 * if it corresponds to the result of the combiner. 5741 * <p> 5742 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5743 * that either the combiner or the target does not wish to receive. 5744 * If some of the incoming arguments are destined only for the combiner, 5745 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5746 * arguments will not need to be live on the stack on entry to the 5747 * target.) 5748 * <p><b>Example:</b> 5749 * {@snippet lang="java" : 5750 import static java.lang.invoke.MethodHandles.*; 5751 import static java.lang.invoke.MethodType.*; 5752 ... 5753 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5754 "println", methodType(void.class, String.class)) 5755 .bindTo(System.out); 5756 MethodHandle cat = lookup().findVirtual(String.class, 5757 "concat", methodType(String.class, String.class)); 5758 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5759 MethodHandle catTrace = foldArguments(cat, trace); 5760 // also prints "boo": 5761 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5762 * } 5763 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5764 * represents the result type of the {@code target} and resulting adapter. 5765 * {@code V}/{@code v} represent the type and value of the parameter and argument 5766 * of {@code target} that precedes the folding position; {@code V} also is 5767 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5768 * types and values of the {@code N} parameters and arguments at the folding 5769 * position. {@code B}/{@code b} represent the types and values of the 5770 * {@code target} parameters and arguments that follow the folded parameters 5771 * and arguments. 5772 * {@snippet lang="java" : 5773 * // there are N arguments in A... 5774 * T target(V, A[N]..., B...); 5775 * V combiner(A...); 5776 * T adapter(A... a, B... b) { 5777 * V v = combiner(a...); 5778 * return target(v, a..., b...); 5779 * } 5780 * // and if the combiner has a void return: 5781 * T target2(A[N]..., B...); 5782 * void combiner2(A...); 5783 * T adapter2(A... a, B... b) { 5784 * combiner2(a...); 5785 * return target2(a..., b...); 5786 * } 5787 * } 5788 * <p> 5789 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5790 * variable-arity method handle}, even if the original target method handle was. 5791 * @param target the method handle to invoke after arguments are combined 5792 * @param combiner method handle to call initially on the incoming arguments 5793 * @return method handle which incorporates the specified argument folding logic 5794 * @throws NullPointerException if either argument is null 5795 * @throws IllegalArgumentException if {@code combiner}'s return type 5796 * is non-void and not the same as the first argument type of 5797 * the target, or if the initial {@code N} argument types 5798 * of the target 5799 * (skipping one matching the {@code combiner}'s return type) 5800 * are not identical with the argument types of {@code combiner} 5801 */ 5802 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5803 return foldArguments(target, 0, combiner); 5804 } 5805 5806 /** 5807 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 5808 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 5809 * before the folded arguments. 5810 * <p> 5811 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 5812 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 5813 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 5814 * 0. 5815 * 5816 * @apiNote Example: 5817 * {@snippet lang="java" : 5818 import static java.lang.invoke.MethodHandles.*; 5819 import static java.lang.invoke.MethodType.*; 5820 ... 5821 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5822 "println", methodType(void.class, String.class)) 5823 .bindTo(System.out); 5824 MethodHandle cat = lookup().findVirtual(String.class, 5825 "concat", methodType(String.class, String.class)); 5826 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5827 MethodHandle catTrace = foldArguments(cat, 1, trace); 5828 // also prints "jum": 5829 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5830 * } 5831 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5832 * represents the result type of the {@code target} and resulting adapter. 5833 * {@code V}/{@code v} represent the type and value of the parameter and argument 5834 * of {@code target} that precedes the folding position; {@code V} also is 5835 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5836 * types and values of the {@code N} parameters and arguments at the folding 5837 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 5838 * and values of the {@code target} parameters and arguments that precede and 5839 * follow the folded parameters and arguments starting at {@code pos}, 5840 * respectively. 5841 * {@snippet lang="java" : 5842 * // there are N arguments in A... 5843 * T target(Z..., V, A[N]..., B...); 5844 * V combiner(A...); 5845 * T adapter(Z... z, A... a, B... b) { 5846 * V v = combiner(a...); 5847 * return target(z..., v, a..., b...); 5848 * } 5849 * // and if the combiner has a void return: 5850 * T target2(Z..., A[N]..., B...); 5851 * void combiner2(A...); 5852 * T adapter2(Z... z, A... a, B... b) { 5853 * combiner2(a...); 5854 * return target2(z..., a..., b...); 5855 * } 5856 * } 5857 * <p> 5858 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5859 * variable-arity method handle}, even if the original target method handle was. 5860 * 5861 * @param target the method handle to invoke after arguments are combined 5862 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 5863 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5864 * @param combiner method handle to call initially on the incoming arguments 5865 * @return method handle which incorporates the specified argument folding logic 5866 * @throws NullPointerException if either argument is null 5867 * @throws IllegalArgumentException if either of the following two conditions holds: 5868 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5869 * {@code pos} of the target signature; 5870 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 5871 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 5872 * 5873 * @see #foldArguments(MethodHandle, MethodHandle) 5874 * @since 9 5875 */ 5876 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 5877 MethodType targetType = target.type(); 5878 MethodType combinerType = combiner.type(); 5879 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 5880 BoundMethodHandle result = target.rebind(); 5881 boolean dropResult = rtype == void.class; 5882 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 5883 MethodType newType = targetType; 5884 if (!dropResult) { 5885 newType = newType.dropParameterTypes(pos, pos + 1); 5886 } 5887 result = result.copyWithExtendL(newType, lform, combiner); 5888 return result; 5889 } 5890 5891 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 5892 int foldArgs = combinerType.parameterCount(); 5893 Class<?> rtype = combinerType.returnType(); 5894 int foldVals = rtype == void.class ? 0 : 1; 5895 int afterInsertPos = foldPos + foldVals; 5896 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 5897 if (ok) { 5898 for (int i = 0; i < foldArgs; i++) { 5899 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 5900 ok = false; 5901 break; 5902 } 5903 } 5904 } 5905 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 5906 ok = false; 5907 if (!ok) 5908 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5909 return rtype; 5910 } 5911 5912 /** 5913 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 5914 * of the pre-processing replacing the argument at the given position. 5915 * 5916 * @param target the method handle to invoke after arguments are combined 5917 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5918 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5919 * @param combiner method handle to call initially on the incoming arguments 5920 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5921 * @return method handle which incorporates the specified argument folding logic 5922 * @throws NullPointerException if either argument is null 5923 * @throws IllegalArgumentException if either of the following two conditions holds: 5924 * (1) {@code combiner}'s return type is not the same as the argument type at position 5925 * {@code pos} of the target signature; 5926 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 5927 * not identical with the argument types of {@code combiner}. 5928 */ 5929 /*non-public*/ 5930 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5931 return argumentsWithCombiner(true, target, position, combiner, argPositions); 5932 } 5933 5934 /** 5935 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 5936 * the pre-processing inserted into the original sequence of arguments at the given position. 5937 * 5938 * @param target the method handle to invoke after arguments are combined 5939 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5940 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5941 * @param combiner method handle to call initially on the incoming arguments 5942 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5943 * @return method handle which incorporates the specified argument folding logic 5944 * @throws NullPointerException if either argument is null 5945 * @throws IllegalArgumentException if either of the following two conditions holds: 5946 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5947 * {@code pos} of the target signature; 5948 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 5949 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 5950 * with the argument types of {@code combiner}. 5951 */ 5952 /*non-public*/ 5953 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5954 return argumentsWithCombiner(false, target, position, combiner, argPositions); 5955 } 5956 5957 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5958 MethodType targetType = target.type(); 5959 MethodType combinerType = combiner.type(); 5960 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 5961 BoundMethodHandle result = target.rebind(); 5962 5963 MethodType newType = targetType; 5964 LambdaForm lform; 5965 if (filter) { 5966 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 5967 } else { 5968 boolean dropResult = rtype == void.class; 5969 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 5970 if (!dropResult) { 5971 newType = newType.dropParameterTypes(position, position + 1); 5972 } 5973 } 5974 result = result.copyWithExtendL(newType, lform, combiner); 5975 return result; 5976 } 5977 5978 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 5979 int combinerArgs = combinerType.parameterCount(); 5980 if (argPos.length != combinerArgs) { 5981 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 5982 } 5983 Class<?> rtype = combinerType.returnType(); 5984 5985 for (int i = 0; i < combinerArgs; i++) { 5986 int arg = argPos[i]; 5987 if (arg < 0 || arg > targetType.parameterCount()) { 5988 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 5989 } 5990 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 5991 throw newIllegalArgumentException("target argument type at position " + arg 5992 + " must match combiner argument type at index " + i + ": " + targetType 5993 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 5994 } 5995 } 5996 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 5997 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5998 } 5999 return rtype; 6000 } 6001 6002 /** 6003 * Makes a method handle which adapts a target method handle, 6004 * by guarding it with a test, a boolean-valued method handle. 6005 * If the guard fails, a fallback handle is called instead. 6006 * All three method handles must have the same corresponding 6007 * argument and return types, except that the return type 6008 * of the test must be boolean, and the test is allowed 6009 * to have fewer arguments than the other two method handles. 6010 * <p> 6011 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6012 * represents the uniform result type of the three involved handles; 6013 * {@code A}/{@code a}, the types and values of the {@code target} 6014 * parameters and arguments that are consumed by the {@code test}; and 6015 * {@code B}/{@code b}, those types and values of the {@code target} 6016 * parameters and arguments that are not consumed by the {@code test}. 6017 * {@snippet lang="java" : 6018 * boolean test(A...); 6019 * T target(A...,B...); 6020 * T fallback(A...,B...); 6021 * T adapter(A... a,B... b) { 6022 * if (test(a...)) 6023 * return target(a..., b...); 6024 * else 6025 * return fallback(a..., b...); 6026 * } 6027 * } 6028 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6029 * be modified by execution of the test, and so are passed unchanged 6030 * from the caller to the target or fallback as appropriate. 6031 * @param test method handle used for test, must return boolean 6032 * @param target method handle to call if test passes 6033 * @param fallback method handle to call if test fails 6034 * @return method handle which incorporates the specified if/then/else logic 6035 * @throws NullPointerException if any argument is null 6036 * @throws IllegalArgumentException if {@code test} does not return boolean, 6037 * or if all three method types do not match (with the return 6038 * type of {@code test} changed to match that of the target). 6039 */ 6040 public static MethodHandle guardWithTest(MethodHandle test, 6041 MethodHandle target, 6042 MethodHandle fallback) { 6043 MethodType gtype = test.type(); 6044 MethodType ttype = target.type(); 6045 MethodType ftype = fallback.type(); 6046 if (!ttype.equals(ftype)) 6047 throw misMatchedTypes("target and fallback types", ttype, ftype); 6048 if (gtype.returnType() != boolean.class) 6049 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6050 6051 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6052 if (test == null) { 6053 throw misMatchedTypes("target and test types", ttype, gtype); 6054 } 6055 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6056 } 6057 6058 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6059 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6060 } 6061 6062 /** 6063 * Makes a method handle which adapts a target method handle, 6064 * by running it inside an exception handler. 6065 * If the target returns normally, the adapter returns that value. 6066 * If an exception matching the specified type is thrown, the fallback 6067 * handle is called instead on the exception, plus the original arguments. 6068 * <p> 6069 * The target and handler must have the same corresponding 6070 * argument and return types, except that handler may omit trailing arguments 6071 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6072 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6073 * <p> 6074 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6075 * represents the return type of the {@code target} and {@code handler}, 6076 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6077 * the types and values of arguments to the resulting handle consumed by 6078 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6079 * resulting handle discarded by {@code handler}. 6080 * {@snippet lang="java" : 6081 * T target(A..., B...); 6082 * T handler(ExType, A...); 6083 * T adapter(A... a, B... b) { 6084 * try { 6085 * return target(a..., b...); 6086 * } catch (ExType ex) { 6087 * return handler(ex, a...); 6088 * } 6089 * } 6090 * } 6091 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6092 * be modified by execution of the target, and so are passed unchanged 6093 * from the caller to the handler, if the handler is invoked. 6094 * <p> 6095 * The target and handler must return the same type, even if the handler 6096 * always throws. (This might happen, for instance, because the handler 6097 * is simulating a {@code finally} clause). 6098 * To create such a throwing handler, compose the handler creation logic 6099 * with {@link #throwException throwException}, 6100 * in order to create a method handle of the correct return type. 6101 * @param target method handle to call 6102 * @param exType the type of exception which the handler will catch 6103 * @param handler method handle to call if a matching exception is thrown 6104 * @return method handle which incorporates the specified try/catch logic 6105 * @throws NullPointerException if any argument is null 6106 * @throws IllegalArgumentException if {@code handler} does not accept 6107 * the given exception type, or if the method handle types do 6108 * not match in their return types and their 6109 * corresponding parameters 6110 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6111 */ 6112 public static MethodHandle catchException(MethodHandle target, 6113 Class<? extends Throwable> exType, 6114 MethodHandle handler) { 6115 MethodType ttype = target.type(); 6116 MethodType htype = handler.type(); 6117 if (!Throwable.class.isAssignableFrom(exType)) 6118 throw new ClassCastException(exType.getName()); 6119 if (htype.parameterCount() < 1 || 6120 !htype.parameterType(0).isAssignableFrom(exType)) 6121 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6122 if (htype.returnType() != ttype.returnType()) 6123 throw misMatchedTypes("target and handler return types", ttype, htype); 6124 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6125 if (handler == null) { 6126 throw misMatchedTypes("target and handler types", ttype, htype); 6127 } 6128 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6129 } 6130 6131 /** 6132 * Produces a method handle which will throw exceptions of the given {@code exType}. 6133 * The method handle will accept a single argument of {@code exType}, 6134 * and immediately throw it as an exception. 6135 * The method type will nominally specify a return of {@code returnType}. 6136 * The return type may be anything convenient: It doesn't matter to the 6137 * method handle's behavior, since it will never return normally. 6138 * @param returnType the return type of the desired method handle 6139 * @param exType the parameter type of the desired method handle 6140 * @return method handle which can throw the given exceptions 6141 * @throws NullPointerException if either argument is null 6142 */ 6143 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6144 if (!Throwable.class.isAssignableFrom(exType)) 6145 throw new ClassCastException(exType.getName()); 6146 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6147 } 6148 6149 /** 6150 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6151 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6152 * delivers the loop's result, which is the return value of the resulting handle. 6153 * <p> 6154 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6155 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6156 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6157 * terms of method handles, each clause will specify up to four independent actions:<ul> 6158 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6159 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6160 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6161 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6162 * </ul> 6163 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6164 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6165 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6166 * <p> 6167 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6168 * this case. See below for a detailed description. 6169 * <p> 6170 * <em>Parameters optional everywhere:</em> 6171 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6172 * As an exception, the init functions cannot take any {@code v} parameters, 6173 * because those values are not yet computed when the init functions are executed. 6174 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6175 * In fact, any clause function may take no arguments at all. 6176 * <p> 6177 * <em>Loop parameters:</em> 6178 * A clause function may take all the iteration variable values it is entitled to, in which case 6179 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6180 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6181 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6182 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6183 * init function is automatically a loop parameter {@code a}.) 6184 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6185 * These loop parameters act as loop-invariant values visible across the whole loop. 6186 * <p> 6187 * <em>Parameters visible everywhere:</em> 6188 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6189 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6190 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6191 * Most clause functions will not need all of this information, but they will be formally connected to it 6192 * as if by {@link #dropArguments}. 6193 * <a id="astar"></a> 6194 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6195 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6196 * In that notation, the general form of an init function parameter list 6197 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6198 * <p> 6199 * <em>Checking clause structure:</em> 6200 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6201 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6202 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6203 * met by the inputs to the loop combinator. 6204 * <p> 6205 * <em>Effectively identical sequences:</em> 6206 * <a id="effid"></a> 6207 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6208 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6209 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6210 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6211 * that longest list. 6212 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6213 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6214 * <p> 6215 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6216 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6217 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6218 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6219 * four. Padding takes place by appending elements to the array. 6220 * <li>Clauses with all {@code null}s are disregarded. 6221 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6222 * </ol> 6223 * <p> 6224 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6225 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6226 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6227 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6228 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6229 * iteration variable type. 6230 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6231 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6232 * </ol> 6233 * <p> 6234 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6235 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6236 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6237 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6238 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6239 * (These types will be checked in step 2, along with all the clause function types.) 6240 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6241 * <li>All of the collected parameter lists must be effectively identical. 6242 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6243 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6244 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6245 * the "internal parameter list". 6246 * </ul> 6247 * <p> 6248 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6249 * <li>Examine fini function return types, disregarding omitted fini functions. 6250 * <li>If there are no fini functions, the loop return type is {@code void}. 6251 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6252 * type. 6253 * </ol> 6254 * <p> 6255 * <em>Step 1D: Check other types.</em><ol type="a"> 6256 * <li>There must be at least one non-omitted pred function. 6257 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6258 * </ol> 6259 * <p> 6260 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6261 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6262 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6263 * (Note that their parameter lists are already effectively identical to this list.) 6264 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6265 * effectively identical to the internal parameter list {@code (V... A...)}. 6266 * </ol> 6267 * <p> 6268 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6269 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6270 * type. 6271 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6272 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6273 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6274 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6275 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6276 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6277 * loop return type. 6278 * </ol> 6279 * <p> 6280 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6281 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6282 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6283 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6284 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6285 * pad out the end of the list. 6286 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6287 * </ol> 6288 * <p> 6289 * <em>Final observations.</em><ol type="a"> 6290 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6291 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6292 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6293 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6294 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6295 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6296 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6297 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6298 * </ol> 6299 * <p> 6300 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6301 * <ul> 6302 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6303 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6304 * (Only one {@code Pn} has to be non-{@code null}.) 6305 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6306 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6307 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6308 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6309 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6310 * the resulting loop handle's parameter types {@code (A...)}. 6311 * </ul> 6312 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6313 * which is natural if most of the loop computation happens in the steps. For some loops, 6314 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6315 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6316 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6317 * where the init functions will need the extra parameters. For such reasons, the rules for 6318 * determining these parameters are as symmetric as possible, across all clause parts. 6319 * In general, the loop parameters function as common invariant values across the whole 6320 * loop, while the iteration variables function as common variant values, or (if there is 6321 * no step function) as internal loop invariant temporaries. 6322 * <p> 6323 * <em>Loop execution.</em><ol type="a"> 6324 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6325 * every clause function. These locals are loop invariant. 6326 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6327 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6328 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6329 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6330 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6331 * (in argument order). 6332 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6333 * returns {@code false}. 6334 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6335 * sequence {@code (v...)} of loop variables. 6336 * The updated value is immediately visible to all subsequent function calls. 6337 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6338 * (of type {@code R}) is returned from the loop as a whole. 6339 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6340 * except by throwing an exception. 6341 * </ol> 6342 * <p> 6343 * <em>Usage tips.</em> 6344 * <ul> 6345 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6346 * sometimes a step function only needs to observe the current value of its own variable. 6347 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6348 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6349 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6350 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6351 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6352 * <li>If some of the clause functions are virtual methods on an instance, the instance 6353 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6354 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6355 * will be the first iteration variable value, and it will be easy to use virtual 6356 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6357 * </ul> 6358 * <p> 6359 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6360 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6361 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6362 * {@snippet lang="java" : 6363 * V... init...(A...); 6364 * boolean pred...(V..., A...); 6365 * V... step...(V..., A...); 6366 * R fini...(V..., A...); 6367 * R loop(A... a) { 6368 * V... v... = init...(a...); 6369 * for (;;) { 6370 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6371 * v = s(v..., a...); 6372 * if (!p(v..., a...)) { 6373 * return f(v..., a...); 6374 * } 6375 * } 6376 * } 6377 * } 6378 * } 6379 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6380 * to their full length, even though individual clause functions may neglect to take them all. 6381 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6382 * 6383 * @apiNote Example: 6384 * {@snippet lang="java" : 6385 * // iterative implementation of the factorial function as a loop handle 6386 * static int one(int k) { return 1; } 6387 * static int inc(int i, int acc, int k) { return i + 1; } 6388 * static int mult(int i, int acc, int k) { return i * acc; } 6389 * static boolean pred(int i, int acc, int k) { return i < k; } 6390 * static int fin(int i, int acc, int k) { return acc; } 6391 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6392 * // null initializer for counter, should initialize to 0 6393 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6394 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6395 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6396 * assertEquals(120, loop.invoke(5)); 6397 * } 6398 * The same example, dropping arguments and using combinators: 6399 * {@snippet lang="java" : 6400 * // simplified implementation of the factorial function as a loop handle 6401 * static int inc(int i) { return i + 1; } // drop acc, k 6402 * static int mult(int i, int acc) { return i * acc; } //drop k 6403 * static boolean cmp(int i, int k) { return i < k; } 6404 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6405 * // null initializer for counter, should initialize to 0 6406 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6407 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6408 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6409 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6410 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6411 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6412 * assertEquals(720, loop.invoke(6)); 6413 * } 6414 * A similar example, using a helper object to hold a loop parameter: 6415 * {@snippet lang="java" : 6416 * // instance-based implementation of the factorial function as a loop handle 6417 * static class FacLoop { 6418 * final int k; 6419 * FacLoop(int k) { this.k = k; } 6420 * int inc(int i) { return i + 1; } 6421 * int mult(int i, int acc) { return i * acc; } 6422 * boolean pred(int i) { return i < k; } 6423 * int fin(int i, int acc) { return acc; } 6424 * } 6425 * // assume MH_FacLoop is a handle to the constructor 6426 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6427 * // null initializer for counter, should initialize to 0 6428 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6429 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6430 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6431 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6432 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6433 * assertEquals(5040, loop.invoke(7)); 6434 * } 6435 * 6436 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6437 * 6438 * @return a method handle embodying the looping behavior as defined by the arguments. 6439 * 6440 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6441 * 6442 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6443 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6444 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6445 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6446 * @since 9 6447 */ 6448 public static MethodHandle loop(MethodHandle[]... clauses) { 6449 // Step 0: determine clause structure. 6450 loopChecks0(clauses); 6451 6452 List<MethodHandle> init = new ArrayList<>(); 6453 List<MethodHandle> step = new ArrayList<>(); 6454 List<MethodHandle> pred = new ArrayList<>(); 6455 List<MethodHandle> fini = new ArrayList<>(); 6456 6457 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6458 init.add(clause[0]); // all clauses have at least length 1 6459 step.add(clause.length <= 1 ? null : clause[1]); 6460 pred.add(clause.length <= 2 ? null : clause[2]); 6461 fini.add(clause.length <= 3 ? null : clause[3]); 6462 }); 6463 6464 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6465 final int nclauses = init.size(); 6466 6467 // Step 1A: determine iteration variables (V...). 6468 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6469 for (int i = 0; i < nclauses; ++i) { 6470 MethodHandle in = init.get(i); 6471 MethodHandle st = step.get(i); 6472 if (in == null && st == null) { 6473 iterationVariableTypes.add(void.class); 6474 } else if (in != null && st != null) { 6475 loopChecks1a(i, in, st); 6476 iterationVariableTypes.add(in.type().returnType()); 6477 } else { 6478 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6479 } 6480 } 6481 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6482 6483 // Step 1B: determine loop parameters (A...). 6484 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6485 loopChecks1b(init, commonSuffix); 6486 6487 // Step 1C: determine loop return type. 6488 // Step 1D: check other types. 6489 // local variable required here; see JDK-8223553 6490 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6491 .map(MethodType::returnType); 6492 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6493 loopChecks1cd(pred, fini, loopReturnType); 6494 6495 // Step 2: determine parameter lists. 6496 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6497 commonParameterSequence.addAll(commonSuffix); 6498 loopChecks2(step, pred, fini, commonParameterSequence); 6499 // Step 3: fill in omitted functions. 6500 for (int i = 0; i < nclauses; ++i) { 6501 Class<?> t = iterationVariableTypes.get(i); 6502 if (init.get(i) == null) { 6503 init.set(i, empty(methodType(t, commonSuffix))); 6504 } 6505 if (step.get(i) == null) { 6506 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6507 } 6508 if (pred.get(i) == null) { 6509 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6510 } 6511 if (fini.get(i) == null) { 6512 fini.set(i, empty(methodType(t, commonParameterSequence))); 6513 } 6514 } 6515 6516 // Step 4: fill in missing parameter types. 6517 // Also convert all handles to fixed-arity handles. 6518 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6519 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6520 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6521 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6522 6523 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6524 allMatch(pl -> pl.equals(commonSuffix)); 6525 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6526 allMatch(pl -> pl.equals(commonParameterSequence)); 6527 6528 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6529 } 6530 6531 private static void loopChecks0(MethodHandle[][] clauses) { 6532 if (clauses == null || clauses.length == 0) { 6533 throw newIllegalArgumentException("null or no clauses passed"); 6534 } 6535 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6536 throw newIllegalArgumentException("null clauses are not allowed"); 6537 } 6538 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6539 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6540 } 6541 } 6542 6543 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6544 if (in.type().returnType() != st.type().returnType()) { 6545 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6546 st.type().returnType()); 6547 } 6548 } 6549 6550 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6551 return mhs.filter(Objects::nonNull) 6552 // take only those that can contribute to a common suffix because they are longer than the prefix 6553 .map(MethodHandle::type) 6554 .filter(t -> t.parameterCount() > skipSize) 6555 .max(Comparator.comparingInt(MethodType::parameterCount)) 6556 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6557 .orElse(List.of()); 6558 } 6559 6560 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6561 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6562 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6563 return longest1.size() >= longest2.size() ? longest1 : longest2; 6564 } 6565 6566 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6567 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6568 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6569 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6570 " (common suffix: " + commonSuffix + ")"); 6571 } 6572 } 6573 6574 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6575 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6576 anyMatch(t -> t != loopReturnType)) { 6577 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6578 loopReturnType + ")"); 6579 } 6580 6581 if (pred.stream().noneMatch(Objects::nonNull)) { 6582 throw newIllegalArgumentException("no predicate found", pred); 6583 } 6584 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6585 anyMatch(t -> t != boolean.class)) { 6586 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6587 } 6588 } 6589 6590 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6591 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6592 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6593 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6594 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6595 } 6596 } 6597 6598 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6599 return hs.stream().map(h -> { 6600 int pc = h.type().parameterCount(); 6601 int tpsize = targetParams.size(); 6602 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6603 }).toList(); 6604 } 6605 6606 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6607 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6608 } 6609 6610 /** 6611 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6612 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6613 * <p> 6614 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6615 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6616 * evaluates to {@code true}). 6617 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6618 * <p> 6619 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6620 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6621 * and updated with the value returned from its invocation. The result of loop execution will be 6622 * the final value of the additional loop-local variable (if present). 6623 * <p> 6624 * The following rules hold for these argument handles:<ul> 6625 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6626 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6627 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6628 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6629 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6630 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6631 * It will constrain the parameter lists of the other loop parts. 6632 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6633 * list {@code (A...)} is called the <em>external parameter list</em>. 6634 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6635 * additional state variable of the loop. 6636 * The body must both accept and return a value of this type {@code V}. 6637 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6638 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6639 * <a href="MethodHandles.html#effid">effectively identical</a> 6640 * to the external parameter list {@code (A...)}. 6641 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6642 * {@linkplain #empty default value}. 6643 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6644 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6645 * effectively identical to the internal parameter list. 6646 * </ul> 6647 * <p> 6648 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6649 * <li>The loop handle's result type is the result type {@code V} of the body. 6650 * <li>The loop handle's parameter types are the types {@code (A...)}, 6651 * from the external parameter list. 6652 * </ul> 6653 * <p> 6654 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6655 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6656 * passed to the loop. 6657 * {@snippet lang="java" : 6658 * V init(A...); 6659 * boolean pred(V, A...); 6660 * V body(V, A...); 6661 * V whileLoop(A... a...) { 6662 * V v = init(a...); 6663 * while (pred(v, a...)) { 6664 * v = body(v, a...); 6665 * } 6666 * return v; 6667 * } 6668 * } 6669 * 6670 * @apiNote Example: 6671 * {@snippet lang="java" : 6672 * // implement the zip function for lists as a loop handle 6673 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6674 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6675 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6676 * zip.add(a.next()); 6677 * zip.add(b.next()); 6678 * return zip; 6679 * } 6680 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6681 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6682 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6683 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6684 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6685 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6686 * } 6687 * 6688 * 6689 * @apiNote The implementation of this method can be expressed as follows: 6690 * {@snippet lang="java" : 6691 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6692 * MethodHandle fini = (body.type().returnType() == void.class 6693 * ? null : identity(body.type().returnType())); 6694 * MethodHandle[] 6695 * checkExit = { null, null, pred, fini }, 6696 * varBody = { init, body }; 6697 * return loop(checkExit, varBody); 6698 * } 6699 * } 6700 * 6701 * @param init optional initializer, providing the initial value of the loop variable. 6702 * May be {@code null}, implying a default initial value. See above for other constraints. 6703 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6704 * above for other constraints. 6705 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6706 * See above for other constraints. 6707 * 6708 * @return a method handle implementing the {@code while} loop as described by the arguments. 6709 * @throws IllegalArgumentException if the rules for the arguments are violated. 6710 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6711 * 6712 * @see #loop(MethodHandle[][]) 6713 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6714 * @since 9 6715 */ 6716 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6717 whileLoopChecks(init, pred, body); 6718 MethodHandle fini = identityOrVoid(body.type().returnType()); 6719 MethodHandle[] checkExit = { null, null, pred, fini }; 6720 MethodHandle[] varBody = { init, body }; 6721 return loop(checkExit, varBody); 6722 } 6723 6724 /** 6725 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6726 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6727 * <p> 6728 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6729 * method will, in each iteration, first execute its body and then evaluate the predicate. 6730 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6731 * <p> 6732 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6733 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6734 * and updated with the value returned from its invocation. The result of loop execution will be 6735 * the final value of the additional loop-local variable (if present). 6736 * <p> 6737 * The following rules hold for these argument handles:<ul> 6738 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6739 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6740 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6741 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6742 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6743 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6744 * It will constrain the parameter lists of the other loop parts. 6745 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6746 * list {@code (A...)} is called the <em>external parameter list</em>. 6747 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6748 * additional state variable of the loop. 6749 * The body must both accept and return a value of this type {@code V}. 6750 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6751 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6752 * <a href="MethodHandles.html#effid">effectively identical</a> 6753 * to the external parameter list {@code (A...)}. 6754 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6755 * {@linkplain #empty default value}. 6756 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6757 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6758 * effectively identical to the internal parameter list. 6759 * </ul> 6760 * <p> 6761 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6762 * <li>The loop handle's result type is the result type {@code V} of the body. 6763 * <li>The loop handle's parameter types are the types {@code (A...)}, 6764 * from the external parameter list. 6765 * </ul> 6766 * <p> 6767 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6768 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6769 * passed to the loop. 6770 * {@snippet lang="java" : 6771 * V init(A...); 6772 * boolean pred(V, A...); 6773 * V body(V, A...); 6774 * V doWhileLoop(A... a...) { 6775 * V v = init(a...); 6776 * do { 6777 * v = body(v, a...); 6778 * } while (pred(v, a...)); 6779 * return v; 6780 * } 6781 * } 6782 * 6783 * @apiNote Example: 6784 * {@snippet lang="java" : 6785 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6786 * static int zero(int limit) { return 0; } 6787 * static int step(int i, int limit) { return i + 1; } 6788 * static boolean pred(int i, int limit) { return i < limit; } 6789 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6790 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6791 * assertEquals(23, loop.invoke(23)); 6792 * } 6793 * 6794 * 6795 * @apiNote The implementation of this method can be expressed as follows: 6796 * {@snippet lang="java" : 6797 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6798 * MethodHandle fini = (body.type().returnType() == void.class 6799 * ? null : identity(body.type().returnType())); 6800 * MethodHandle[] clause = { init, body, pred, fini }; 6801 * return loop(clause); 6802 * } 6803 * } 6804 * 6805 * @param init optional initializer, providing the initial value of the loop variable. 6806 * May be {@code null}, implying a default initial value. See above for other constraints. 6807 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6808 * See above for other constraints. 6809 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6810 * above for other constraints. 6811 * 6812 * @return a method handle implementing the {@code while} loop as described by the arguments. 6813 * @throws IllegalArgumentException if the rules for the arguments are violated. 6814 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6815 * 6816 * @see #loop(MethodHandle[][]) 6817 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 6818 * @since 9 6819 */ 6820 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6821 whileLoopChecks(init, pred, body); 6822 MethodHandle fini = identityOrVoid(body.type().returnType()); 6823 MethodHandle[] clause = {init, body, pred, fini }; 6824 return loop(clause); 6825 } 6826 6827 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 6828 Objects.requireNonNull(pred); 6829 Objects.requireNonNull(body); 6830 MethodType bodyType = body.type(); 6831 Class<?> returnType = bodyType.returnType(); 6832 List<Class<?>> innerList = bodyType.parameterList(); 6833 List<Class<?>> outerList = innerList; 6834 if (returnType == void.class) { 6835 // OK 6836 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 6837 // leading V argument missing => error 6838 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6839 throw misMatchedTypes("body function", bodyType, expected); 6840 } else { 6841 outerList = innerList.subList(1, innerList.size()); 6842 } 6843 MethodType predType = pred.type(); 6844 if (predType.returnType() != boolean.class || 6845 !predType.effectivelyIdenticalParameters(0, innerList)) { 6846 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 6847 } 6848 if (init != null) { 6849 MethodType initType = init.type(); 6850 if (initType.returnType() != returnType || 6851 !initType.effectivelyIdenticalParameters(0, outerList)) { 6852 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6853 } 6854 } 6855 } 6856 6857 /** 6858 * Constructs a loop that runs a given number of iterations. 6859 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6860 * <p> 6861 * The number of iterations is determined by the {@code iterations} handle evaluation result. 6862 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 6863 * It will be initialized to 0 and incremented by 1 in each iteration. 6864 * <p> 6865 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6866 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6867 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6868 * <p> 6869 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6870 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6871 * iteration variable. 6872 * The result of the loop handle execution will be the final {@code V} value of that variable 6873 * (or {@code void} if there is no {@code V} variable). 6874 * <p> 6875 * The following rules hold for the argument handles:<ul> 6876 * <li>The {@code iterations} handle must not be {@code null}, and must return 6877 * the type {@code int}, referred to here as {@code I} in parameter type lists. 6878 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6879 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6880 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6881 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6882 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6883 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6884 * of types called the <em>internal parameter list</em>. 6885 * It will constrain the parameter lists of the other loop parts. 6886 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6887 * with no additional {@code A} types, then the internal parameter list is extended by 6888 * the argument types {@code A...} of the {@code iterations} handle. 6889 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6890 * list {@code (A...)} is called the <em>external parameter list</em>. 6891 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6892 * additional state variable of the loop. 6893 * The body must both accept a leading parameter and return a value of this type {@code V}. 6894 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6895 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6896 * <a href="MethodHandles.html#effid">effectively identical</a> 6897 * to the external parameter list {@code (A...)}. 6898 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6899 * {@linkplain #empty default value}. 6900 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 6901 * effectively identical to the external parameter list {@code (A...)}. 6902 * </ul> 6903 * <p> 6904 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6905 * <li>The loop handle's result type is the result type {@code V} of the body. 6906 * <li>The loop handle's parameter types are the types {@code (A...)}, 6907 * from the external parameter list. 6908 * </ul> 6909 * <p> 6910 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6911 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6912 * arguments passed to the loop. 6913 * {@snippet lang="java" : 6914 * int iterations(A...); 6915 * V init(A...); 6916 * V body(V, int, A...); 6917 * V countedLoop(A... a...) { 6918 * int end = iterations(a...); 6919 * V v = init(a...); 6920 * for (int i = 0; i < end; ++i) { 6921 * v = body(v, i, a...); 6922 * } 6923 * return v; 6924 * } 6925 * } 6926 * 6927 * @apiNote Example with a fully conformant body method: 6928 * {@snippet lang="java" : 6929 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6930 * // => a variation on a well known theme 6931 * static String step(String v, int counter, String init) { return "na " + v; } 6932 * // assume MH_step is a handle to the method above 6933 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 6934 * MethodHandle start = MethodHandles.identity(String.class); 6935 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 6936 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 6937 * } 6938 * 6939 * @apiNote Example with the simplest possible body method type, 6940 * and passing the number of iterations to the loop invocation: 6941 * {@snippet lang="java" : 6942 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6943 * // => a variation on a well known theme 6944 * static String step(String v, int counter ) { return "na " + v; } 6945 * // assume MH_step is a handle to the method above 6946 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 6947 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 6948 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 6949 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 6950 * } 6951 * 6952 * @apiNote Example that treats the number of iterations, string to append to, and string to append 6953 * as loop parameters: 6954 * {@snippet lang="java" : 6955 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6956 * // => a variation on a well known theme 6957 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 6958 * // assume MH_step is a handle to the method above 6959 * MethodHandle count = MethodHandles.identity(int.class); 6960 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 6961 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 6962 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 6963 * } 6964 * 6965 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 6966 * to enforce a loop type: 6967 * {@snippet lang="java" : 6968 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6969 * // => a variation on a well known theme 6970 * static String step(String v, int counter, String pre) { return pre + " " + v; } 6971 * // assume MH_step is a handle to the method above 6972 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 6973 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 6974 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 6975 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 6976 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 6977 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 6978 * } 6979 * 6980 * @apiNote The implementation of this method can be expressed as follows: 6981 * {@snippet lang="java" : 6982 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6983 * return countedLoop(empty(iterations.type()), iterations, init, body); 6984 * } 6985 * } 6986 * 6987 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 6988 * result type must be {@code int}. See above for other constraints. 6989 * @param init optional initializer, providing the initial value of the loop variable. 6990 * May be {@code null}, implying a default initial value. See above for other constraints. 6991 * @param body body of the loop, which may not be {@code null}. 6992 * It controls the loop parameters and result type in the standard case (see above for details). 6993 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6994 * and may accept any number of additional types. 6995 * See above for other constraints. 6996 * 6997 * @return a method handle representing the loop. 6998 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 6999 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7000 * 7001 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7002 * @since 9 7003 */ 7004 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7005 return countedLoop(empty(iterations.type()), iterations, init, body); 7006 } 7007 7008 /** 7009 * Constructs a loop that counts over a range of numbers. 7010 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7011 * <p> 7012 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7013 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7014 * values of the loop counter. 7015 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7016 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7017 * <p> 7018 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7019 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7020 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7021 * <p> 7022 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7023 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7024 * iteration variable. 7025 * The result of the loop handle execution will be the final {@code V} value of that variable 7026 * (or {@code void} if there is no {@code V} variable). 7027 * <p> 7028 * The following rules hold for the argument handles:<ul> 7029 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7030 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7031 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7032 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7033 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7034 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7035 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7036 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7037 * of types called the <em>internal parameter list</em>. 7038 * It will constrain the parameter lists of the other loop parts. 7039 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7040 * with no additional {@code A} types, then the internal parameter list is extended by 7041 * the argument types {@code A...} of the {@code end} handle. 7042 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7043 * list {@code (A...)} is called the <em>external parameter list</em>. 7044 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7045 * additional state variable of the loop. 7046 * The body must both accept a leading parameter and return a value of this type {@code V}. 7047 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7048 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7049 * <a href="MethodHandles.html#effid">effectively identical</a> 7050 * to the external parameter list {@code (A...)}. 7051 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7052 * {@linkplain #empty default value}. 7053 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7054 * effectively identical to the external parameter list {@code (A...)}. 7055 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7056 * to the external parameter list. 7057 * </ul> 7058 * <p> 7059 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7060 * <li>The loop handle's result type is the result type {@code V} of the body. 7061 * <li>The loop handle's parameter types are the types {@code (A...)}, 7062 * from the external parameter list. 7063 * </ul> 7064 * <p> 7065 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7066 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7067 * arguments passed to the loop. 7068 * {@snippet lang="java" : 7069 * int start(A...); 7070 * int end(A...); 7071 * V init(A...); 7072 * V body(V, int, A...); 7073 * V countedLoop(A... a...) { 7074 * int e = end(a...); 7075 * int s = start(a...); 7076 * V v = init(a...); 7077 * for (int i = s; i < e; ++i) { 7078 * v = body(v, i, a...); 7079 * } 7080 * return v; 7081 * } 7082 * } 7083 * 7084 * @apiNote The implementation of this method can be expressed as follows: 7085 * {@snippet lang="java" : 7086 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7087 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7088 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7089 * // the following semantics: 7090 * // MH_increment: (int limit, int counter) -> counter + 1 7091 * // MH_predicate: (int limit, int counter) -> counter < limit 7092 * Class<?> counterType = start.type().returnType(); // int 7093 * Class<?> returnType = body.type().returnType(); 7094 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7095 * if (returnType != void.class) { // ignore the V variable 7096 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7097 * pred = dropArguments(pred, 1, returnType); // ditto 7098 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7099 * } 7100 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7101 * MethodHandle[] 7102 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7103 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7104 * indexVar = { start, incr }; // i = start(); i = i + 1 7105 * return loop(loopLimit, bodyClause, indexVar); 7106 * } 7107 * } 7108 * 7109 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7110 * See above for other constraints. 7111 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7112 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7113 * @param init optional initializer, providing the initial value of the loop variable. 7114 * May be {@code null}, implying a default initial value. See above for other constraints. 7115 * @param body body of the loop, which may not be {@code null}. 7116 * It controls the loop parameters and result type in the standard case (see above for details). 7117 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7118 * and may accept any number of additional types. 7119 * See above for other constraints. 7120 * 7121 * @return a method handle representing the loop. 7122 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7123 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7124 * 7125 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7126 * @since 9 7127 */ 7128 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7129 countedLoopChecks(start, end, init, body); 7130 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7131 Class<?> limitType = end.type().returnType(); // yes, int again 7132 Class<?> returnType = body.type().returnType(); 7133 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7134 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7135 MethodHandle retv = null; 7136 if (returnType != void.class) { 7137 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7138 pred = dropArguments(pred, 1, returnType); // ditto 7139 retv = dropArguments(identity(returnType), 0, counterType); 7140 } 7141 body = dropArguments(body, 0, counterType); // ignore the limit variable 7142 MethodHandle[] 7143 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7144 bodyClause = { init, body }, // v = init(); v = body(v, i) 7145 indexVar = { start, incr }; // i = start(); i = i + 1 7146 return loop(loopLimit, bodyClause, indexVar); 7147 } 7148 7149 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7150 Objects.requireNonNull(start); 7151 Objects.requireNonNull(end); 7152 Objects.requireNonNull(body); 7153 Class<?> counterType = start.type().returnType(); 7154 if (counterType != int.class) { 7155 MethodType expected = start.type().changeReturnType(int.class); 7156 throw misMatchedTypes("start function", start.type(), expected); 7157 } else if (end.type().returnType() != counterType) { 7158 MethodType expected = end.type().changeReturnType(counterType); 7159 throw misMatchedTypes("end function", end.type(), expected); 7160 } 7161 MethodType bodyType = body.type(); 7162 Class<?> returnType = bodyType.returnType(); 7163 List<Class<?>> innerList = bodyType.parameterList(); 7164 // strip leading V value if present 7165 int vsize = (returnType == void.class ? 0 : 1); 7166 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7167 // argument list has no "V" => error 7168 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7169 throw misMatchedTypes("body function", bodyType, expected); 7170 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7171 // missing I type => error 7172 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7173 throw misMatchedTypes("body function", bodyType, expected); 7174 } 7175 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7176 if (outerList.isEmpty()) { 7177 // special case; take lists from end handle 7178 outerList = end.type().parameterList(); 7179 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7180 } 7181 MethodType expected = methodType(counterType, outerList); 7182 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7183 throw misMatchedTypes("start parameter types", start.type(), expected); 7184 } 7185 if (end.type() != start.type() && 7186 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7187 throw misMatchedTypes("end parameter types", end.type(), expected); 7188 } 7189 if (init != null) { 7190 MethodType initType = init.type(); 7191 if (initType.returnType() != returnType || 7192 !initType.effectivelyIdenticalParameters(0, outerList)) { 7193 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7194 } 7195 } 7196 } 7197 7198 /** 7199 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7200 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7201 * <p> 7202 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7203 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7204 * <p> 7205 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7206 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7207 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7208 * <p> 7209 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7210 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7211 * iteration variable. 7212 * The result of the loop handle execution will be the final {@code V} value of that variable 7213 * (or {@code void} if there is no {@code V} variable). 7214 * <p> 7215 * The following rules hold for the argument handles:<ul> 7216 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7217 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7218 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7219 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7220 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7221 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7222 * of types called the <em>internal parameter list</em>. 7223 * It will constrain the parameter lists of the other loop parts. 7224 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7225 * with no additional {@code A} types, then the internal parameter list is extended by 7226 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7227 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7228 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7229 * list {@code (A...)} is called the <em>external parameter list</em>. 7230 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7231 * additional state variable of the loop. 7232 * The body must both accept a leading parameter and return a value of this type {@code V}. 7233 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7234 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7235 * <a href="MethodHandles.html#effid">effectively identical</a> 7236 * to the external parameter list {@code (A...)}. 7237 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7238 * {@linkplain #empty default value}. 7239 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7240 * type {@code java.util.Iterator} or a subtype thereof. 7241 * The iterator it produces when the loop is executed will be assumed 7242 * to yield values which can be converted to type {@code T}. 7243 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7244 * effectively identical to the external parameter list {@code (A...)}. 7245 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7246 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7247 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7248 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7249 * the {@link MethodHandle#asType asType} conversion method. 7250 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7251 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7252 * </ul> 7253 * <p> 7254 * The type {@code T} may be either a primitive or reference. 7255 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7256 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7257 * as if by the {@link MethodHandle#asType asType} conversion method. 7258 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7259 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7260 * <p> 7261 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7262 * <li>The loop handle's result type is the result type {@code V} of the body. 7263 * <li>The loop handle's parameter types are the types {@code (A...)}, 7264 * from the external parameter list. 7265 * </ul> 7266 * <p> 7267 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7268 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7269 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7270 * {@snippet lang="java" : 7271 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7272 * V init(A...); 7273 * V body(V,T,A...); 7274 * V iteratedLoop(A... a...) { 7275 * Iterator<T> it = iterator(a...); 7276 * V v = init(a...); 7277 * while (it.hasNext()) { 7278 * T t = it.next(); 7279 * v = body(v, t, a...); 7280 * } 7281 * return v; 7282 * } 7283 * } 7284 * 7285 * @apiNote Example: 7286 * {@snippet lang="java" : 7287 * // get an iterator from a list 7288 * static List<String> reverseStep(List<String> r, String e) { 7289 * r.add(0, e); 7290 * return r; 7291 * } 7292 * static List<String> newArrayList() { return new ArrayList<>(); } 7293 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7294 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7295 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7296 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7297 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7298 * } 7299 * 7300 * @apiNote The implementation of this method can be expressed approximately as follows: 7301 * {@snippet lang="java" : 7302 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7303 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7304 * Class<?> returnType = body.type().returnType(); 7305 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7306 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7307 * MethodHandle retv = null, step = body, startIter = iterator; 7308 * if (returnType != void.class) { 7309 * // the simple thing first: in (I V A...), drop the I to get V 7310 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7311 * // body type signature (V T A...), internal loop types (I V A...) 7312 * step = swapArguments(body, 0, 1); // swap V <-> T 7313 * } 7314 * if (startIter == null) startIter = MH_getIter; 7315 * MethodHandle[] 7316 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7317 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7318 * return loop(iterVar, bodyClause); 7319 * } 7320 * } 7321 * 7322 * @param iterator an optional handle to return the iterator to start the loop. 7323 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7324 * See above for other constraints. 7325 * @param init optional initializer, providing the initial value of the loop variable. 7326 * May be {@code null}, implying a default initial value. See above for other constraints. 7327 * @param body body of the loop, which may not be {@code null}. 7328 * It controls the loop parameters and result type in the standard case (see above for details). 7329 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7330 * and may accept any number of additional types. 7331 * See above for other constraints. 7332 * 7333 * @return a method handle embodying the iteration loop functionality. 7334 * @throws NullPointerException if the {@code body} handle is {@code null}. 7335 * @throws IllegalArgumentException if any argument violates the above requirements. 7336 * 7337 * @since 9 7338 */ 7339 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7340 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7341 Class<?> returnType = body.type().returnType(); 7342 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7343 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7344 MethodHandle startIter; 7345 MethodHandle nextVal; 7346 { 7347 MethodType iteratorType; 7348 if (iterator == null) { 7349 // derive argument type from body, if available, else use Iterable 7350 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7351 iteratorType = startIter.type().changeParameterType(0, iterableType); 7352 } else { 7353 // force return type to the internal iterator class 7354 iteratorType = iterator.type().changeReturnType(Iterator.class); 7355 startIter = iterator; 7356 } 7357 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7358 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7359 7360 // perform the asType transforms under an exception transformer, as per spec.: 7361 try { 7362 startIter = startIter.asType(iteratorType); 7363 nextVal = nextRaw.asType(nextValType); 7364 } catch (WrongMethodTypeException ex) { 7365 throw new IllegalArgumentException(ex); 7366 } 7367 } 7368 7369 MethodHandle retv = null, step = body; 7370 if (returnType != void.class) { 7371 // the simple thing first: in (I V A...), drop the I to get V 7372 retv = dropArguments(identity(returnType), 0, Iterator.class); 7373 // body type signature (V T A...), internal loop types (I V A...) 7374 step = swapArguments(body, 0, 1); // swap V <-> T 7375 } 7376 7377 MethodHandle[] 7378 iterVar = { startIter, null, hasNext, retv }, 7379 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7380 return loop(iterVar, bodyClause); 7381 } 7382 7383 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7384 Objects.requireNonNull(body); 7385 MethodType bodyType = body.type(); 7386 Class<?> returnType = bodyType.returnType(); 7387 List<Class<?>> internalParamList = bodyType.parameterList(); 7388 // strip leading V value if present 7389 int vsize = (returnType == void.class ? 0 : 1); 7390 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7391 // argument list has no "V" => error 7392 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7393 throw misMatchedTypes("body function", bodyType, expected); 7394 } else if (internalParamList.size() <= vsize) { 7395 // missing T type => error 7396 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7397 throw misMatchedTypes("body function", bodyType, expected); 7398 } 7399 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7400 Class<?> iterableType = null; 7401 if (iterator != null) { 7402 // special case; if the body handle only declares V and T then 7403 // the external parameter list is obtained from iterator handle 7404 if (externalParamList.isEmpty()) { 7405 externalParamList = iterator.type().parameterList(); 7406 } 7407 MethodType itype = iterator.type(); 7408 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7409 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7410 } 7411 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7412 MethodType expected = methodType(itype.returnType(), externalParamList); 7413 throw misMatchedTypes("iterator parameters", itype, expected); 7414 } 7415 } else { 7416 if (externalParamList.isEmpty()) { 7417 // special case; if the iterator handle is null and the body handle 7418 // only declares V and T then the external parameter list consists 7419 // of Iterable 7420 externalParamList = List.of(Iterable.class); 7421 iterableType = Iterable.class; 7422 } else { 7423 // special case; if the iterator handle is null and the external 7424 // parameter list is not empty then the first parameter must be 7425 // assignable to Iterable 7426 iterableType = externalParamList.get(0); 7427 if (!Iterable.class.isAssignableFrom(iterableType)) { 7428 throw newIllegalArgumentException( 7429 "inferred first loop argument must inherit from Iterable: " + iterableType); 7430 } 7431 } 7432 } 7433 if (init != null) { 7434 MethodType initType = init.type(); 7435 if (initType.returnType() != returnType || 7436 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7437 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7438 } 7439 } 7440 return iterableType; // help the caller a bit 7441 } 7442 7443 /*non-public*/ 7444 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7445 // there should be a better way to uncross my wires 7446 int arity = mh.type().parameterCount(); 7447 int[] order = new int[arity]; 7448 for (int k = 0; k < arity; k++) order[k] = k; 7449 order[i] = j; order[j] = i; 7450 Class<?>[] types = mh.type().parameterArray(); 7451 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7452 MethodType swapType = methodType(mh.type().returnType(), types); 7453 return permuteArguments(mh, swapType, order); 7454 } 7455 7456 /** 7457 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7458 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7459 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7460 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7461 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7462 * {@code try-finally} handle. 7463 * <p> 7464 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7465 * The first is the exception thrown during the 7466 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7467 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7468 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7469 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7470 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7471 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7472 * <p> 7473 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7474 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7475 * two extra leading parameters:<ul> 7476 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7477 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7478 * the result from the execution of the {@code target} handle. 7479 * This parameter is not present if the {@code target} returns {@code void}. 7480 * </ul> 7481 * <p> 7482 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7483 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7484 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7485 * the cleanup. 7486 * {@snippet lang="java" : 7487 * V target(A..., B...); 7488 * V cleanup(Throwable, V, A...); 7489 * V adapter(A... a, B... b) { 7490 * V result = (zero value for V); 7491 * Throwable throwable = null; 7492 * try { 7493 * result = target(a..., b...); 7494 * } catch (Throwable t) { 7495 * throwable = t; 7496 * throw t; 7497 * } finally { 7498 * result = cleanup(throwable, result, a...); 7499 * } 7500 * return result; 7501 * } 7502 * } 7503 * <p> 7504 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7505 * be modified by execution of the target, and so are passed unchanged 7506 * from the caller to the cleanup, if it is invoked. 7507 * <p> 7508 * The target and cleanup must return the same type, even if the cleanup 7509 * always throws. 7510 * To create such a throwing cleanup, compose the cleanup logic 7511 * with {@link #throwException throwException}, 7512 * in order to create a method handle of the correct return type. 7513 * <p> 7514 * Note that {@code tryFinally} never converts exceptions into normal returns. 7515 * In rare cases where exceptions must be converted in that way, first wrap 7516 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7517 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7518 * <p> 7519 * It is recommended that the first parameter type of {@code cleanup} be 7520 * declared {@code Throwable} rather than a narrower subtype. This ensures 7521 * {@code cleanup} will always be invoked with whatever exception that 7522 * {@code target} throws. Declaring a narrower type may result in a 7523 * {@code ClassCastException} being thrown by the {@code try-finally} 7524 * handle if the type of the exception thrown by {@code target} is not 7525 * assignable to the first parameter type of {@code cleanup}. Note that 7526 * various exception types of {@code VirtualMachineError}, 7527 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7528 * thrown by almost any kind of Java code, and a finally clause that 7529 * catches (say) only {@code IOException} would mask any of the others 7530 * behind a {@code ClassCastException}. 7531 * 7532 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7533 * @param cleanup the handle that is invoked in the finally block. 7534 * 7535 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7536 * @throws NullPointerException if any argument is null 7537 * @throws IllegalArgumentException if {@code cleanup} does not accept 7538 * the required leading arguments, or if the method handle types do 7539 * not match in their return types and their 7540 * corresponding trailing parameters 7541 * 7542 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7543 * @since 9 7544 */ 7545 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7546 Class<?>[] targetParamTypes = target.type().ptypes(); 7547 Class<?> rtype = target.type().returnType(); 7548 7549 tryFinallyChecks(target, cleanup); 7550 7551 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7552 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7553 // target parameter list. 7554 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7555 7556 // Ensure that the intrinsic type checks the instance thrown by the 7557 // target against the first parameter of cleanup 7558 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7559 7560 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7561 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7562 } 7563 7564 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7565 Class<?> rtype = target.type().returnType(); 7566 if (rtype != cleanup.type().returnType()) { 7567 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7568 } 7569 MethodType cleanupType = cleanup.type(); 7570 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7571 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7572 } 7573 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7574 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7575 } 7576 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7577 // target parameter list. 7578 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7579 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7580 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7581 cleanup.type(), target.type()); 7582 } 7583 } 7584 7585 /** 7586 * Creates a table switch method handle, which can be used to switch over a set of target 7587 * method handles, based on a given target index, called selector. 7588 * <p> 7589 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7590 * and where {@code N} is the number of target method handles, the table switch method 7591 * handle will invoke the n-th target method handle from the list of target method handles. 7592 * <p> 7593 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7594 * method handle will invoke the given fallback method handle. 7595 * <p> 7596 * All method handles passed to this method must have the same type, with the additional 7597 * requirement that the leading parameter be of type {@code int}. The leading parameter 7598 * represents the selector. 7599 * <p> 7600 * Any trailing parameters present in the type will appear on the returned table switch 7601 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7602 * together with the selector value, to the selected method handle when invoking it. 7603 * 7604 * @apiNote Example: 7605 * The cases each drop the {@code selector} value they are given, and take an additional 7606 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7607 * to a specific constant label string for each case: 7608 * {@snippet lang="java" : 7609 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7610 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7611 * MethodType.methodType(String.class, String.class)); 7612 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7613 * 7614 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7615 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7616 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7617 * 7618 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7619 * caseDefault, 7620 * case0, 7621 * case1 7622 * ); 7623 * 7624 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7625 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7626 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7627 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7628 * } 7629 * 7630 * @param fallback the fallback method handle that is called when the selector is not 7631 * within the range {@code [0, N)}. 7632 * @param targets array of target method handles. 7633 * @return the table switch method handle. 7634 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7635 * any of the elements of the {@code targets} array are 7636 * {@code null}. 7637 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7638 * parameter of the fallback handle or any of the target 7639 * handles is not {@code int}, or if the types of 7640 * the fallback handle and all of target handles are 7641 * not the same. 7642 * 7643 * @since 17 7644 */ 7645 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7646 Objects.requireNonNull(fallback); 7647 Objects.requireNonNull(targets); 7648 targets = targets.clone(); 7649 MethodType type = tableSwitchChecks(fallback, targets); 7650 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7651 } 7652 7653 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7654 if (caseActions.length == 0) 7655 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7656 7657 MethodType expectedType = defaultCase.type(); 7658 7659 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7660 throw new IllegalArgumentException( 7661 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7662 7663 for (MethodHandle mh : caseActions) { 7664 Objects.requireNonNull(mh); 7665 if (mh.type() != expectedType) 7666 throw new IllegalArgumentException( 7667 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7668 } 7669 7670 return expectedType; 7671 } 7672 7673 /** 7674 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7675 * <p> 7676 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7677 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7678 * to the target var handle. 7679 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7680 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7681 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7682 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7683 * <p> 7684 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7685 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7686 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7687 * will be appended to the coordinates of the target var handle). 7688 * <p> 7689 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7690 * throw an {@link IllegalStateException}. 7691 * <p> 7692 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7693 * atomic access guarantees as those featured by the target var handle. 7694 * 7695 * @param target the target var handle 7696 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7697 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7698 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7699 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7700 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7701 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7702 * @throws NullPointerException if any of the arguments is {@code null}. 7703 * @since 22 7704 */ 7705 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7706 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7707 } 7708 7709 /** 7710 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7711 * <p> 7712 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7713 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7714 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7715 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7716 * by the adaptation) to the target var handle. 7717 * <p> 7718 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7719 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7720 * <p> 7721 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7722 * throw an {@link IllegalStateException}. 7723 * <p> 7724 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7725 * atomic access guarantees as those featured by the target var handle. 7726 * 7727 * @param target the target var handle 7728 * @param pos the position of the first coordinate to be transformed 7729 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7730 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7731 * to the new coordinate values. 7732 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7733 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7734 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7735 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7736 * or if it's determined that any of the filters throws any checked exceptions. 7737 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 7738 * @since 22 7739 */ 7740 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 7741 return VarHandles.filterCoordinates(target, pos, filters); 7742 } 7743 7744 /** 7745 * Provides a target var handle with one or more <em>bound coordinates</em> 7746 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 7747 * coordinate types than the target var handle. 7748 * <p> 7749 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 7750 * are joined with bound coordinate values, and then passed to the target var handle. 7751 * <p> 7752 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 7753 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7754 * <p> 7755 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7756 * atomic access guarantees as those featured by the target var handle. 7757 * 7758 * @param target the var handle to invoke after the bound coordinates are inserted 7759 * @param pos the position of the first coordinate to be inserted 7760 * @param values the series of bound coordinates to insert 7761 * @return an adapter var handle which inserts additional coordinates, 7762 * before calling the target var handle 7763 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7764 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 7765 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 7766 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 7767 * of the target var handle. 7768 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 7769 * @since 22 7770 */ 7771 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 7772 return VarHandles.insertCoordinates(target, pos, values); 7773 } 7774 7775 /** 7776 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 7777 * so that the new coordinates match the provided ones. 7778 * <p> 7779 * The given array controls the reordering. 7780 * Call {@code #I} the number of incoming coordinates (the value 7781 * {@code newCoordinates.size()}), and call {@code #O} the number 7782 * of outgoing coordinates (the number of coordinates associated with the target var handle). 7783 * Then the length of the reordering array must be {@code #O}, 7784 * and each element must be a non-negative number less than {@code #I}. 7785 * For every {@code N} less than {@code #O}, the {@code N}-th 7786 * outgoing coordinate will be taken from the {@code I}-th incoming 7787 * coordinate, where {@code I} is {@code reorder[N]}. 7788 * <p> 7789 * No coordinate value conversions are applied. 7790 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 7791 * must be identical to the type of the corresponding outgoing coordinate 7792 * in the target var handle. 7793 * <p> 7794 * The reordering array need not specify an actual permutation. 7795 * An incoming coordinate will be duplicated if its index appears 7796 * more than once in the array, and an incoming coordinate will be dropped 7797 * if its index does not appear in the array. 7798 * <p> 7799 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7800 * atomic access guarantees as those featured by the target var handle. 7801 * @param target the var handle to invoke after the coordinates have been reordered 7802 * @param newCoordinates the new coordinate types 7803 * @param reorder an index array which controls the reordering 7804 * @return an adapter var handle which re-arranges the incoming coordinate values, 7805 * before calling the target var handle 7806 * @throws IllegalArgumentException if the index array length is not equal to 7807 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 7808 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 7809 * the target var handle and in {@code newCoordinates} are not identical. 7810 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 7811 * @since 22 7812 */ 7813 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 7814 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 7815 } 7816 7817 /** 7818 * Adapts a target var handle by pre-processing 7819 * a sub-sequence of its coordinate values with a filter (a method handle). 7820 * The pre-processed coordinates are replaced by the result (if any) of the 7821 * filter function and the target var handle is then called on the modified (usually shortened) 7822 * coordinate list. 7823 * <p> 7824 * If {@code R} is the return type of the filter, then: 7825 * <ul> 7826 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 7827 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 7828 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 7829 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 7830 * target var handle.</li> 7831 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 7832 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 7833 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 7834 * downstream invocation of the target var handle.</li> 7835 * </ul> 7836 * <p> 7837 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7838 * throw an {@link IllegalStateException}. 7839 * <p> 7840 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7841 * atomic access guarantees as those featured by the target var handle. 7842 * 7843 * @param target the var handle to invoke after the coordinates have been filtered 7844 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 7845 * @param filter the filter method handle 7846 * @return an adapter var handle which filters the incoming coordinate values, 7847 * before calling the target var handle 7848 * @throws IllegalArgumentException if the return type of {@code filter} 7849 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 7850 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7851 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 7852 * or if it's determined that {@code filter} throws any checked exceptions. 7853 * @throws NullPointerException if any of the arguments is {@code null}. 7854 * @since 22 7855 */ 7856 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 7857 return VarHandles.collectCoordinates(target, pos, filter); 7858 } 7859 7860 /** 7861 * Returns a var handle which will discard some dummy coordinates before delegating to the 7862 * target var handle. As a consequence, the resulting var handle will feature more 7863 * coordinate types than the target var handle. 7864 * <p> 7865 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 7866 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 7867 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 7868 * <p> 7869 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7870 * atomic access guarantees as those featured by the target var handle. 7871 * 7872 * @param target the var handle to invoke after the dummy coordinates are dropped 7873 * @param pos position of the first coordinate to drop (zero for the leftmost) 7874 * @param valueTypes the type(s) of the coordinate(s) to drop 7875 * @return an adapter var handle which drops some dummy coordinates, 7876 * before calling the target var handle 7877 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 7878 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 7879 * @since 22 7880 */ 7881 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 7882 return VarHandles.dropCoordinates(target, pos, valueTypes); 7883 } 7884 }