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.ForceInline; 36 import jdk.internal.vm.annotation.Stable; 37 import sun.invoke.util.ValueConversions; 38 import sun.invoke.util.VerifyAccess; 39 import sun.invoke.util.Wrapper; 40 41 import java.lang.classfile.ClassFile; 42 import java.lang.classfile.ClassModel; 43 import java.lang.constant.ClassDesc; 44 import java.lang.constant.ConstantDescs; 45 import java.lang.invoke.LambdaForm.BasicType; 46 import java.lang.invoke.MethodHandleImpl.Intrinsic; 47 import java.lang.reflect.Constructor; 48 import java.lang.reflect.Field; 49 import java.lang.reflect.Member; 50 import java.lang.reflect.Method; 51 import java.lang.reflect.Modifier; 52 import java.nio.ByteOrder; 53 import java.security.ProtectionDomain; 54 import java.util.ArrayList; 55 import java.util.Arrays; 56 import java.util.BitSet; 57 import java.util.Comparator; 58 import java.util.Iterator; 59 import java.util.List; 60 import java.util.Objects; 61 import java.util.Set; 62 import java.util.concurrent.ConcurrentHashMap; 63 import java.util.stream.Stream; 64 65 import static java.lang.classfile.ClassFile.*; 66 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 67 import static java.lang.invoke.MethodHandleNatives.Constants.*; 68 import static java.lang.invoke.MethodHandleStatics.*; 69 import static java.lang.invoke.MethodType.methodType; 70 71 /** 72 * This class consists exclusively of static methods that operate on or return 73 * method handles. They fall into several categories: 74 * <ul> 75 * <li>Lookup methods which help create method handles for methods and fields. 76 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 77 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 78 * </ul> 79 * A lookup, combinator, or factory method will fail and throw an 80 * {@code IllegalArgumentException} if the created method handle's type 81 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 82 * 83 * @author John Rose, JSR 292 EG 84 * @since 1.7 85 */ 86 public final class MethodHandles { 87 88 private MethodHandles() { } // do not instantiate 89 90 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 91 92 // See IMPL_LOOKUP below. 93 94 //--- Method handle creation from ordinary methods. 95 96 /** 97 * Returns a {@link Lookup lookup object} with 98 * full capabilities to emulate all supported bytecode behaviors of the caller. 99 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 100 * Factory methods on the lookup object can create 101 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 102 * for any member that the caller has access to via bytecodes, 103 * including protected and private fields and methods. 104 * This lookup object is created by the original lookup class 105 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 106 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 107 * Do not store it in place where untrusted code can access it. 108 * <p> 109 * This method is caller sensitive, which means that it may return different 110 * values to different callers. 111 * In cases where {@code MethodHandles.lookup} is called from a context where 112 * there is no caller frame on the stack (e.g. when called directly 113 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 114 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 115 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 116 * to obtain a low-privileged lookup instead. 117 * @return a lookup object for the caller of this method, with 118 * {@linkplain Lookup#ORIGINAL original} and 119 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 120 * @throws IllegalCallerException if there is no caller frame on the stack. 121 */ 122 @CallerSensitive 123 @ForceInline // to ensure Reflection.getCallerClass optimization 124 public static Lookup lookup() { 125 final Class<?> c = Reflection.getCallerClass(); 126 if (c == null) { 127 throw new IllegalCallerException("no caller frame"); 128 } 129 return new Lookup(c); 130 } 131 132 /** 133 * This lookup method is the alternate implementation of 134 * the lookup method with a leading caller class argument which is 135 * non-caller-sensitive. This method is only invoked by reflection 136 * and method handle. 137 */ 138 @CallerSensitiveAdapter 139 private static Lookup lookup(Class<?> caller) { 140 if (caller.getClassLoader() == null) { 141 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 142 } 143 return new Lookup(caller); 144 } 145 146 /** 147 * Returns a {@link Lookup lookup object} which is trusted minimally. 148 * The lookup has the {@code UNCONDITIONAL} mode. 149 * It can only be used to create method handles to public members of 150 * public classes in packages that are exported unconditionally. 151 * <p> 152 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 153 * of this lookup object will be {@link java.lang.Object}. 154 * 155 * @apiNote The use of Object is conventional, and because the lookup modes are 156 * limited, there is no special access provided to the internals of Object, its package 157 * or its module. This public lookup object or other lookup object with 158 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 159 * is not used to determine the lookup context. 160 * 161 * <p style="font-size:smaller;"> 162 * <em>Discussion:</em> 163 * The lookup class can be changed to any other class {@code C} using an expression of the form 164 * {@link Lookup#in publicLookup().in(C.class)}. 165 * Also, it cannot access 166 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 167 * @return a lookup object which is trusted minimally 168 */ 169 public static Lookup publicLookup() { 170 return Lookup.PUBLIC_LOOKUP; 171 } 172 173 /** 174 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 175 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 176 * The returned lookup object can provide access to classes in modules and packages, 177 * and members of those classes, outside the normal rules of Java access control, 178 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 179 * <p> 180 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 181 * allowed to do deep reflection on module {@code M2} and package of the target class 182 * if and only if all of the following conditions are {@code true}: 183 * <ul> 184 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 185 * full privilege access}. Specifically: 186 * <ul> 187 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 188 * (This is because otherwise there would be no way to ensure the original lookup 189 * creator was a member of any particular module, and so any subsequent checks 190 * for readability and qualified exports would become ineffective.) 191 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 192 * (This is because an application intending to share intra-module access 193 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 194 * deep reflection to its own module.) 195 * </ul> 196 * <li>The target class must be a proper class, not a primitive or array class. 197 * (Thus, {@code M2} is well-defined.) 198 * <li>If the caller module {@code M1} differs from 199 * the target module {@code M2} then both of the following must be true: 200 * <ul> 201 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 202 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 203 * containing the target class to at least {@code M1}.</li> 204 * </ul> 205 * </ul> 206 * <p> 207 * If any of the above checks is violated, this method fails with an 208 * exception. 209 * <p> 210 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 211 * returns a {@code Lookup} on {@code targetClass} with 212 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 213 * with {@code null} previous lookup class. 214 * <p> 215 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 216 * returns a {@code Lookup} on {@code targetClass} that records 217 * the lookup class of the caller as the new previous lookup class with 218 * {@code PRIVATE} access but no {@code MODULE} access. 219 * <p> 220 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 221 * 222 * @apiNote The {@code Lookup} object returned by this method is allowed to 223 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 224 * of {@code targetClass}. Extreme caution should be taken when opening a package 225 * to another module as such defined classes have the same full privilege 226 * access as other members in {@code targetClass}'s module. 227 * 228 * @param targetClass the target class 229 * @param caller the caller lookup object 230 * @return a lookup object for the target class, with private access 231 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 232 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 233 * @throws IllegalAccessException if any of the other access checks specified above fails 234 * @since 9 235 * @see Lookup#dropLookupMode 236 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 237 */ 238 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 239 if (caller.allowedModes == Lookup.TRUSTED) { 240 return new Lookup(targetClass); 241 } 242 243 if (targetClass.isPrimitive()) 244 throw new IllegalArgumentException(targetClass + " is a primitive class"); 245 if (targetClass.isArray()) 246 throw new IllegalArgumentException(targetClass + " is an array class"); 247 // Ensure that we can reason accurately about private and module access. 248 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 249 if ((caller.lookupModes() & requireAccess) != requireAccess) 250 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 251 252 // previous lookup class is never set if it has MODULE access 253 assert caller.previousLookupClass() == null; 254 255 Class<?> callerClass = caller.lookupClass(); 256 Module callerModule = callerClass.getModule(); // M1 257 Module targetModule = targetClass.getModule(); // M2 258 Class<?> newPreviousClass = null; 259 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 260 261 if (targetModule != callerModule) { 262 if (!callerModule.canRead(targetModule)) 263 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 264 if (targetModule.isNamed()) { 265 String pn = targetClass.getPackageName(); 266 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 267 if (!targetModule.isOpen(pn, callerModule)) 268 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 269 } 270 271 // M2 != M1, set previous lookup class to M1 and drop MODULE access 272 newPreviousClass = callerClass; 273 newModes &= ~Lookup.MODULE; 274 } 275 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 276 } 277 278 /** 279 * Returns the <em>class data</em> associated with the lookup class 280 * of the given {@code caller} lookup object, or {@code null}. 281 * 282 * <p> A hidden class with class data can be created by calling 283 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 284 * Lookup::defineHiddenClassWithClassData}. 285 * This method will cause the static class initializer of the lookup 286 * class of the given {@code caller} lookup object be executed if 287 * it has not been initialized. 288 * 289 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 290 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 291 * {@code null} is returned if this method is called on the lookup object 292 * on these classes. 293 * 294 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 295 * must have {@linkplain Lookup#ORIGINAL original access} 296 * in order to retrieve the class data. 297 * 298 * @apiNote 299 * This method can be called as a bootstrap method for a dynamically computed 300 * constant. A framework can create a hidden class with class data, for 301 * example that can be {@code Class} or {@code MethodHandle} object. 302 * The class data is accessible only to the lookup object 303 * created by the original caller but inaccessible to other members 304 * in the same nest. If a framework passes security sensitive objects 305 * to a hidden class via class data, it is recommended to load the value 306 * of class data as a dynamically computed constant instead of storing 307 * the class data in private static field(s) which are accessible to 308 * other nestmates. 309 * 310 * @param <T> the type to cast the class data object to 311 * @param caller the lookup context describing the class performing the 312 * operation (normally stacked by the JVM) 313 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 314 * ({@code "_"}) 315 * @param type the type of the class data 316 * @return the value of the class data if present in the lookup class; 317 * otherwise {@code null} 318 * @throws IllegalArgumentException if name is not {@code "_"} 319 * @throws IllegalAccessException if the lookup context does not have 320 * {@linkplain Lookup#ORIGINAL original} access 321 * @throws ClassCastException if the class data cannot be converted to 322 * the given {@code type} 323 * @throws NullPointerException if {@code caller} or {@code type} argument 324 * is {@code null} 325 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 326 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 327 * @since 16 328 * @jvms 5.5 Initialization 329 */ 330 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 331 Objects.requireNonNull(caller); 332 Objects.requireNonNull(type); 333 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 334 throw new IllegalArgumentException("name must be \"_\": " + name); 335 } 336 337 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 338 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 339 } 340 341 Object classdata = classData(caller.lookupClass()); 342 if (classdata == null) return null; 343 344 try { 345 return BootstrapMethodInvoker.widenAndCast(classdata, type); 346 } catch (RuntimeException|Error e) { 347 throw e; // let CCE and other runtime exceptions through 348 } catch (Throwable e) { 349 throw new InternalError(e); 350 } 351 } 352 353 /* 354 * Returns the class data set by the VM in the Class::classData field. 355 * 356 * This is also invoked by LambdaForms as it cannot use condy via 357 * MethodHandles::classData due to bootstrapping issue. 358 */ 359 static Object classData(Class<?> c) { 360 UNSAFE.ensureClassInitialized(c); 361 return SharedSecrets.getJavaLangAccess().classData(c); 362 } 363 364 /** 365 * Returns the element at the specified index in the 366 * {@linkplain #classData(Lookup, String, Class) class data}, 367 * if the class data associated with the lookup class 368 * of the given {@code caller} lookup object is a {@code List}. 369 * If the class data is not present in this lookup class, this method 370 * returns {@code null}. 371 * 372 * <p> A hidden class with class data can be created by calling 373 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 374 * Lookup::defineHiddenClassWithClassData}. 375 * This method will cause the static class initializer of the lookup 376 * class of the given {@code caller} lookup object be executed if 377 * it has not been initialized. 378 * 379 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 380 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 381 * {@code null} is returned if this method is called on the lookup object 382 * on these classes. 383 * 384 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 385 * must have {@linkplain Lookup#ORIGINAL original access} 386 * in order to retrieve the class data. 387 * 388 * @apiNote 389 * This method can be called as a bootstrap method for a dynamically computed 390 * constant. A framework can create a hidden class with class data, for 391 * example that can be {@code List.of(o1, o2, o3....)} containing more than 392 * one object and use this method to load one element at a specific index. 393 * The class data is accessible only to the lookup object 394 * created by the original caller but inaccessible to other members 395 * in the same nest. If a framework passes security sensitive objects 396 * to a hidden class via class data, it is recommended to load the value 397 * of class data as a dynamically computed constant instead of storing 398 * the class data in private static field(s) which are accessible to other 399 * nestmates. 400 * 401 * @param <T> the type to cast the result object to 402 * @param caller the lookup context describing the class performing the 403 * operation (normally stacked by the JVM) 404 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 405 * ({@code "_"}) 406 * @param type the type of the element at the given index in the class data 407 * @param index index of the element in the class data 408 * @return the element at the given index in the class data 409 * if the class data is present; otherwise {@code null} 410 * @throws IllegalArgumentException if name is not {@code "_"} 411 * @throws IllegalAccessException if the lookup context does not have 412 * {@linkplain Lookup#ORIGINAL original} access 413 * @throws ClassCastException if the class data cannot be converted to {@code List} 414 * or the element at the specified index cannot be converted to the given type 415 * @throws IndexOutOfBoundsException if the index is out of range 416 * @throws NullPointerException if {@code caller} or {@code type} argument is 417 * {@code null}; or if unboxing operation fails because 418 * the element at the given index is {@code null} 419 * 420 * @since 16 421 * @see #classData(Lookup, String, Class) 422 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 423 */ 424 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 425 throws IllegalAccessException 426 { 427 @SuppressWarnings("unchecked") 428 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 429 if (classdata == null) return null; 430 431 try { 432 Object element = classdata.get(index); 433 return BootstrapMethodInvoker.widenAndCast(element, type); 434 } catch (RuntimeException|Error e) { 435 throw e; // let specified exceptions and other runtime exceptions/errors through 436 } catch (Throwable e) { 437 throw new InternalError(e); 438 } 439 } 440 441 /** 442 * Performs an unchecked "crack" of a 443 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 444 * The result is as if the user had obtained a lookup object capable enough 445 * to crack the target method handle, called 446 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 447 * on the target to obtain its symbolic reference, and then called 448 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 449 * to resolve the symbolic reference to a member. 450 * @param <T> the desired type of the result, either {@link Member} or a subtype 451 * @param expected a class object representing the desired result type {@code T} 452 * @param target a direct method handle to crack into symbolic reference components 453 * @return a reference to the method, constructor, or field object 454 * @throws NullPointerException if either argument is {@code null} 455 * @throws IllegalArgumentException if the target is not a direct method handle 456 * @throws ClassCastException if the member is not of the expected type 457 * @since 1.8 458 */ 459 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 460 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 461 return lookup.revealDirect(target).reflectAs(expected, lookup); 462 } 463 464 /** 465 * A <em>lookup object</em> is a factory for creating method handles, 466 * when the creation requires access checking. 467 * Method handles do not perform 468 * access checks when they are called, but rather when they are created. 469 * Therefore, method handle access 470 * restrictions must be enforced when a method handle is created. 471 * The caller class against which those restrictions are enforced 472 * is known as the {@linkplain #lookupClass() lookup class}. 473 * <p> 474 * A lookup class which needs to create method handles will call 475 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 476 * When the {@code Lookup} factory object is created, the identity of the lookup class is 477 * determined, and securely stored in the {@code Lookup} object. 478 * The lookup class (or its delegates) may then use factory methods 479 * on the {@code Lookup} object to create method handles for access-checked members. 480 * This includes all methods, constructors, and fields which are allowed to the lookup class, 481 * even private ones. 482 * 483 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 484 * The factory methods on a {@code Lookup} object correspond to all major 485 * use cases for methods, constructors, and fields. 486 * Each method handle created by a factory method is the functional 487 * equivalent of a particular <em>bytecode behavior</em>. 488 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 489 * the Java Virtual Machine Specification.) 490 * Here is a summary of the correspondence between these factory methods and 491 * the behavior of the resulting method handles: 492 * <table class="striped"> 493 * <caption style="display:none">lookup method behaviors</caption> 494 * <thead> 495 * <tr> 496 * <th scope="col"><a id="equiv"></a>lookup expression</th> 497 * <th scope="col">member</th> 498 * <th scope="col">bytecode behavior</th> 499 * </tr> 500 * </thead> 501 * <tbody> 502 * <tr> 503 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 504 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 505 * </tr> 506 * <tr> 507 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 508 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 509 * </tr> 510 * <tr> 511 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 512 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 513 * </tr> 514 * <tr> 515 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 516 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 517 * </tr> 518 * <tr> 519 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 520 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 521 * </tr> 522 * <tr> 523 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 524 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 525 * </tr> 526 * <tr> 527 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 528 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 529 * </tr> 530 * <tr> 531 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 532 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 533 * </tr> 534 * <tr> 535 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 536 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 537 * </tr> 538 * <tr> 539 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 540 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 541 * </tr> 542 * <tr> 543 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 544 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 545 * </tr> 546 * <tr> 547 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 548 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 549 * </tr> 550 * <tr> 551 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 552 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 553 * </tr> 554 * <tr> 555 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 556 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 557 * </tr> 558 * </tbody> 559 * </table> 560 * 561 * Here, the type {@code C} is the class or interface being searched for a member, 562 * documented as a parameter named {@code refc} in the lookup methods. 563 * The method type {@code MT} is composed from the return type {@code T} 564 * and the sequence of argument types {@code A*}. 565 * The constructor also has a sequence of argument types {@code A*} and 566 * is deemed to return the newly-created object of type {@code C}. 567 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 568 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 569 * if it is present, it is always the leading argument to the method handle invocation. 570 * (In the case of some {@code protected} members, {@code this} may be 571 * restricted in type to the lookup class; see below.) 572 * The name {@code arg} stands for all the other method handle arguments. 573 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 574 * stands for a null reference if the accessed method or field is static, 575 * and {@code this} otherwise. 576 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 577 * for reflective objects corresponding to the given members declared in type {@code C}. 578 * <p> 579 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 580 * as if by {@code ldc CONSTANT_Class}. 581 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 582 * <p> 583 * In cases where the given member is of variable arity (i.e., a method or constructor) 584 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 585 * In all other cases, the returned method handle will be of fixed arity. 586 * <p style="font-size:smaller;"> 587 * <em>Discussion:</em> 588 * The equivalence between looked-up method handles and underlying 589 * class members and bytecode behaviors 590 * can break down in a few ways: 591 * <ul style="font-size:smaller;"> 592 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 593 * the lookup can still succeed, even when there is no equivalent 594 * Java expression or bytecoded constant. 595 * <li>Likewise, if {@code T} or {@code MT} 596 * is not symbolically accessible from the lookup class's loader, 597 * the lookup can still succeed. 598 * For example, lookups for {@code MethodHandle.invokeExact} and 599 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 600 * <li>If the looked-up method has a 601 * <a href="MethodHandle.html#maxarity">very large arity</a>, 602 * the method handle creation may fail with an 603 * {@code IllegalArgumentException}, due to the method handle type having 604 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 605 * </ul> 606 * 607 * <h2><a id="access"></a>Access checking</h2> 608 * Access checks are applied in the factory methods of {@code Lookup}, 609 * when a method handle is created. 610 * This is a key difference from the Core Reflection API, since 611 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 612 * performs access checking against every caller, on every call. 613 * <p> 614 * All access checks start from a {@code Lookup} object, which 615 * compares its recorded lookup class against all requests to 616 * create method handles. 617 * A single {@code Lookup} object can be used to create any number 618 * of access-checked method handles, all checked against a single 619 * lookup class. 620 * <p> 621 * A {@code Lookup} object can be shared with other trusted code, 622 * such as a metaobject protocol. 623 * A shared {@code Lookup} object delegates the capability 624 * to create method handles on private members of the lookup class. 625 * Even if privileged code uses the {@code Lookup} object, 626 * the access checking is confined to the privileges of the 627 * original lookup class. 628 * <p> 629 * A lookup can fail, because 630 * the containing class is not accessible to the lookup class, or 631 * because the desired class member is missing, or because the 632 * desired class member is not accessible to the lookup class, or 633 * because the lookup object is not trusted enough to access the member. 634 * In the case of a field setter function on a {@code final} field, 635 * finality enforcement is treated as a kind of access control, 636 * and the lookup will fail, except in special cases of 637 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 638 * In any of these cases, a {@code ReflectiveOperationException} will be 639 * thrown from the attempted lookup. The exact class will be one of 640 * the following: 641 * <ul> 642 * <li>NoSuchMethodException — if a method is requested but does not exist 643 * <li>NoSuchFieldException — if a field is requested but does not exist 644 * <li>IllegalAccessException — if the member exists but an access check fails 645 * </ul> 646 * <p> 647 * In general, the conditions under which a method handle may be 648 * looked up for a method {@code M} are no more restrictive than the conditions 649 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 650 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 651 * a method handle lookup will generally raise a corresponding 652 * checked exception, such as {@code NoSuchMethodException}. 653 * And the effect of invoking the method handle resulting from the lookup 654 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 655 * to executing the compiled, verified, and resolved call to {@code M}. 656 * The same point is true of fields and constructors. 657 * <p style="font-size:smaller;"> 658 * <em>Discussion:</em> 659 * Access checks only apply to named and reflected methods, 660 * constructors, and fields. 661 * Other method handle creation methods, such as 662 * {@link MethodHandle#asType MethodHandle.asType}, 663 * do not require any access checks, and are used 664 * independently of any {@code Lookup} object. 665 * <p> 666 * If the desired member is {@code protected}, the usual JVM rules apply, 667 * including the requirement that the lookup class must either be in the 668 * same package as the desired member, or must inherit that member. 669 * (See the Java Virtual Machine Specification, sections {@jvms 670 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 671 * In addition, if the desired member is a non-static field or method 672 * in a different package, the resulting method handle may only be applied 673 * to objects of the lookup class or one of its subclasses. 674 * This requirement is enforced by narrowing the type of the leading 675 * {@code this} parameter from {@code C} 676 * (which will necessarily be a superclass of the lookup class) 677 * to the lookup class itself. 678 * <p> 679 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 680 * that the receiver argument must match both the resolved method <em>and</em> 681 * the current class. Again, this requirement is enforced by narrowing the 682 * type of the leading parameter to the resulting method handle. 683 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 684 * <p> 685 * The JVM represents constructors and static initializer blocks as internal methods 686 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 687 * ConstantDescs#CLASS_INIT_NAME}). 688 * The internal syntax of invocation instructions allows them to refer to such internal 689 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 690 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 691 * <p> 692 * If the relationship between nested types is expressed directly through the 693 * {@code NestHost} and {@code NestMembers} attributes 694 * (see the Java Virtual Machine Specification, sections {@jvms 695 * 4.7.28} and {@jvms 4.7.29}), 696 * then the associated {@code Lookup} object provides direct access to 697 * the lookup class and all of its nestmates 698 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 699 * Otherwise, access between nested classes is obtained by the Java compiler creating 700 * a wrapper method to access a private method of another class in the same nest. 701 * For example, a nested class {@code C.D} 702 * can access private members within other related classes such as 703 * {@code C}, {@code C.D.E}, or {@code C.B}, 704 * but the Java compiler may need to generate wrapper methods in 705 * those related classes. In such cases, a {@code Lookup} object on 706 * {@code C.E} would be unable to access those private members. 707 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 708 * which can transform a lookup on {@code C.E} into one on any of those other 709 * classes, without special elevation of privilege. 710 * <p> 711 * The accesses permitted to a given lookup object may be limited, 712 * according to its set of {@link #lookupModes lookupModes}, 713 * to a subset of members normally accessible to the lookup class. 714 * For example, the {@link MethodHandles#publicLookup publicLookup} 715 * method produces a lookup object which is only allowed to access 716 * public members in public classes of exported packages. 717 * The caller sensitive method {@link MethodHandles#lookup lookup} 718 * produces a lookup object with full capabilities relative to 719 * its caller class, to emulate all supported bytecode behaviors. 720 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 721 * with fewer access modes than the original lookup object. 722 * 723 * <p style="font-size:smaller;"> 724 * <a id="privacc"></a> 725 * <em>Discussion of private and module access:</em> 726 * We say that a lookup has <em>private access</em> 727 * if its {@linkplain #lookupModes lookup modes} 728 * include the possibility of accessing {@code private} members 729 * (which includes the private members of nestmates). 730 * As documented in the relevant methods elsewhere, 731 * only lookups with private access possess the following capabilities: 732 * <ul style="font-size:smaller;"> 733 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 734 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 735 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 736 * within the same package member 737 * </ul> 738 * <p style="font-size:smaller;"> 739 * Similarly, a lookup with module access ensures that the original lookup creator was 740 * a member in the same module as the lookup class. 741 * <p style="font-size:smaller;"> 742 * Private and module access are independently determined modes; a lookup may have 743 * either or both or neither. A lookup which possesses both access modes is said to 744 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 745 * <p style="font-size:smaller;"> 746 * A lookup with <em>original access</em> ensures that this lookup is created by 747 * the original lookup class and the bootstrap method invoked by the VM. 748 * Such a lookup with original access also has private and module access 749 * which has the following additional capability: 750 * <ul style="font-size:smaller;"> 751 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 752 * such as {@code Class.forName} 753 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 754 * class data} associated with the lookup class</li> 755 * </ul> 756 * <p style="font-size:smaller;"> 757 * Each of these permissions is a consequence of the fact that a lookup object 758 * with private access can be securely traced back to an originating class, 759 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 760 * can be reliably determined and emulated by method handles. 761 * 762 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 763 * When a lookup class in one module {@code M1} accesses a class in another module 764 * {@code M2}, extra access checking is performed beyond the access mode bits. 765 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 766 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 767 * and when the type is in a package of {@code M2} that is exported to 768 * at least {@code M1}. 769 * <p> 770 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 771 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 772 * MethodHandles.privateLookupIn} methods. 773 * Teleporting across modules will always record the original lookup class as 774 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 775 * and drops {@link Lookup#MODULE MODULE} access. 776 * If the target class is in the same module as the lookup class {@code C}, 777 * then the target class becomes the new lookup class 778 * and there is no change to the previous lookup class. 779 * If the target class is in a different module from {@code M1} ({@code C}'s module), 780 * {@code C} becomes the new previous lookup class 781 * and the target class becomes the new lookup class. 782 * In that case, if there was already a previous lookup class in {@code M0}, 783 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 784 * drops all privileges. 785 * For example, 786 * {@snippet lang="java" : 787 * Lookup lookup = MethodHandles.lookup(); // in class C 788 * Lookup lookup2 = lookup.in(D.class); 789 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 790 * } 791 * <p> 792 * The {@link #lookup()} factory method produces a {@code Lookup} object 793 * with {@code null} previous lookup class. 794 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 795 * to class {@code D} without elevation of privileges. 796 * If {@code C} and {@code D} are in the same module, 797 * {@code lookup2} records {@code D} as the new lookup class and keeps the 798 * same previous lookup class as the original {@code lookup}, or 799 * {@code null} if not present. 800 * <p> 801 * When a {@code Lookup} teleports from a class 802 * in one nest to another nest, {@code PRIVATE} access is dropped. 803 * When a {@code Lookup} teleports from a class in one package to 804 * another package, {@code PACKAGE} access is dropped. 805 * When a {@code Lookup} teleports from a class in one module to another module, 806 * {@code MODULE} access is dropped. 807 * Teleporting across modules drops the ability to access non-exported classes 808 * in both the module of the new lookup class and the module of the old lookup class 809 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 810 * A {@code Lookup} can teleport back and forth to a class in the module of 811 * the lookup class and the module of the previous class lookup. 812 * Teleporting across modules can only decrease access but cannot increase it. 813 * Teleporting to some third module drops all accesses. 814 * <p> 815 * In the above example, if {@code C} and {@code D} are in different modules, 816 * {@code lookup2} records {@code D} as its lookup class and 817 * {@code C} as its previous lookup class and {@code lookup2} has only 818 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 819 * {@code C}'s module and {@code D}'s module. 820 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 821 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 822 * class {@code D} is recorded as its previous lookup class. 823 * <p> 824 * Teleporting across modules restricts access to the public types that 825 * both the lookup class and the previous lookup class can equally access 826 * (see below). 827 * <p> 828 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 829 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 830 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 831 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 832 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 833 * to call {@code privateLookupIn}. 834 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 835 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 836 * produces a new {@code Lookup} on {@code T} with full capabilities. 837 * A {@code lookup} on {@code C} is also allowed 838 * to do deep reflection on {@code T} in another module {@code M2} if 839 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 840 * the package containing {@code T} to at least {@code M1}. 841 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 842 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 843 * The resulting {@code Lookup} can be used to do member lookup or teleport 844 * to another lookup class by calling {@link #in Lookup::in}. But 845 * it cannot be used to obtain another private {@code Lookup} by calling 846 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 847 * because it has no {@code MODULE} access. 848 * <p> 849 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 850 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 851 * of {@code T}. Extreme caution should be taken when opening a package 852 * to another module as such defined classes have the same full privilege 853 * access as other members in {@code M2}. 854 * 855 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 856 * 857 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 858 * allows cross-module access. The access checking is performed with respect 859 * to both the lookup class and the previous lookup class if present. 860 * <p> 861 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 862 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 863 * exported unconditionally}. 864 * <p> 865 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 866 * the lookup with {@link #PUBLIC} mode can access all public types in modules 867 * that are readable to {@code M1} and the type is in a package that is exported 868 * at least to {@code M1}. 869 * <p> 870 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 871 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 872 * the intersection of all public types that are accessible to {@code M1} 873 * with all public types that are accessible to {@code M0}. {@code M0} 874 * reads {@code M1} and hence the set of accessible types includes: 875 * 876 * <ul> 877 * <li>unconditional-exported packages from {@code M1}</li> 878 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 879 * <li> 880 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 881 * and {@code M1} read {@code M2} 882 * </li> 883 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 884 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 885 * <li> 886 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 887 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 888 * </li> 889 * </ul> 890 * 891 * <h2><a id="access-modes"></a>Access modes</h2> 892 * 893 * The table below shows the access modes of a {@code Lookup} produced by 894 * any of the following factory or transformation methods: 895 * <ul> 896 * <li>{@link #lookup() MethodHandles::lookup}</li> 897 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 898 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 899 * <li>{@link Lookup#in Lookup::in}</li> 900 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 901 * </ul> 902 * 903 * <table class="striped"> 904 * <caption style="display:none"> 905 * Access mode summary 906 * </caption> 907 * <thead> 908 * <tr> 909 * <th scope="col">Lookup object</th> 910 * <th style="text-align:center">original</th> 911 * <th style="text-align:center">protected</th> 912 * <th style="text-align:center">private</th> 913 * <th style="text-align:center">package</th> 914 * <th style="text-align:center">module</th> 915 * <th style="text-align:center">public</th> 916 * </tr> 917 * </thead> 918 * <tbody> 919 * <tr> 920 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 921 * <td style="text-align:center">ORI</td> 922 * <td style="text-align:center">PRO</td> 923 * <td style="text-align:center">PRI</td> 924 * <td style="text-align:center">PAC</td> 925 * <td style="text-align:center">MOD</td> 926 * <td style="text-align:center">1R</td> 927 * </tr> 928 * <tr> 929 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 930 * <td></td> 931 * <td></td> 932 * <td></td> 933 * <td style="text-align:center">PAC</td> 934 * <td style="text-align:center">MOD</td> 935 * <td style="text-align:center">1R</td> 936 * </tr> 937 * <tr> 938 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 939 * <td></td> 940 * <td></td> 941 * <td></td> 942 * <td></td> 943 * <td style="text-align:center">MOD</td> 944 * <td style="text-align:center">1R</td> 945 * </tr> 946 * <tr> 947 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 948 * <td></td> 949 * <td></td> 950 * <td></td> 951 * <td></td> 952 * <td></td> 953 * <td style="text-align:center">2R</td> 954 * </tr> 955 * <tr> 956 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 957 * <td></td> 958 * <td></td> 959 * <td></td> 960 * <td></td> 961 * <td></td> 962 * <td style="text-align:center">2R</td> 963 * </tr> 964 * <tr> 965 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 966 * <td></td> 967 * <td style="text-align:center">PRO</td> 968 * <td style="text-align:center">PRI</td> 969 * <td style="text-align:center">PAC</td> 970 * <td style="text-align:center">MOD</td> 971 * <td style="text-align:center">1R</td> 972 * </tr> 973 * <tr> 974 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 975 * <td></td> 976 * <td style="text-align:center">PRO</td> 977 * <td style="text-align:center">PRI</td> 978 * <td style="text-align:center">PAC</td> 979 * <td style="text-align:center">MOD</td> 980 * <td style="text-align:center">1R</td> 981 * </tr> 982 * <tr> 983 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 984 * <td></td> 985 * <td></td> 986 * <td></td> 987 * <td style="text-align:center">PAC</td> 988 * <td style="text-align:center">MOD</td> 989 * <td style="text-align:center">1R</td> 990 * </tr> 991 * <tr> 992 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 993 * <td></td> 994 * <td></td> 995 * <td></td> 996 * <td></td> 997 * <td style="text-align:center">MOD</td> 998 * <td style="text-align:center">1R</td> 999 * </tr> 1000 * <tr> 1001 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1002 * <td></td> 1003 * <td></td> 1004 * <td></td> 1005 * <td></td> 1006 * <td></td> 1007 * <td style="text-align:center">2R</td> 1008 * </tr> 1009 * <tr> 1010 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1011 * <td></td> 1012 * <td></td> 1013 * <td style="text-align:center">PRI</td> 1014 * <td style="text-align:center">PAC</td> 1015 * <td style="text-align:center">MOD</td> 1016 * <td style="text-align:center">1R</td> 1017 * </tr> 1018 * <tr> 1019 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1020 * <td></td> 1021 * <td></td> 1022 * <td></td> 1023 * <td style="text-align:center">PAC</td> 1024 * <td style="text-align:center">MOD</td> 1025 * <td style="text-align:center">1R</td> 1026 * </tr> 1027 * <tr> 1028 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1029 * <td></td> 1030 * <td></td> 1031 * <td></td> 1032 * <td></td> 1033 * <td style="text-align:center">MOD</td> 1034 * <td style="text-align:center">1R</td> 1035 * </tr> 1036 * <tr> 1037 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1038 * <td></td> 1039 * <td></td> 1040 * <td></td> 1041 * <td></td> 1042 * <td></td> 1043 * <td style="text-align:center">1R</td> 1044 * </tr> 1045 * <tr> 1046 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1047 * <td></td> 1048 * <td></td> 1049 * <td></td> 1050 * <td></td> 1051 * <td></td> 1052 * <td style="text-align:center">none</td> 1053 * <tr> 1054 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1055 * <td></td> 1056 * <td style="text-align:center">PRO</td> 1057 * <td style="text-align:center">PRI</td> 1058 * <td style="text-align:center">PAC</td> 1059 * <td></td> 1060 * <td style="text-align:center">2R</td> 1061 * </tr> 1062 * <tr> 1063 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1064 * <td></td> 1065 * <td style="text-align:center">PRO</td> 1066 * <td style="text-align:center">PRI</td> 1067 * <td style="text-align:center">PAC</td> 1068 * <td></td> 1069 * <td style="text-align:center">2R</td> 1070 * </tr> 1071 * <tr> 1072 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1073 * <td></td> 1074 * <td></td> 1075 * <td></td> 1076 * <td></td> 1077 * <td></td> 1078 * <td style="text-align:center">IAE</td> 1079 * </tr> 1080 * <tr> 1081 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1082 * <td></td> 1083 * <td></td> 1084 * <td></td> 1085 * <td style="text-align:center">PAC</td> 1086 * <td></td> 1087 * <td style="text-align:center">2R</td> 1088 * </tr> 1089 * <tr> 1090 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1091 * <td></td> 1092 * <td></td> 1093 * <td></td> 1094 * <td></td> 1095 * <td></td> 1096 * <td style="text-align:center">2R</td> 1097 * </tr> 1098 * <tr> 1099 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1100 * <td></td> 1101 * <td></td> 1102 * <td></td> 1103 * <td></td> 1104 * <td></td> 1105 * <td style="text-align:center">2R</td> 1106 * </tr> 1107 * <tr> 1108 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1109 * <td></td> 1110 * <td></td> 1111 * <td></td> 1112 * <td></td> 1113 * <td></td> 1114 * <td style="text-align:center">none</td> 1115 * </tr> 1116 * <tr> 1117 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1118 * <td></td> 1119 * <td></td> 1120 * <td style="text-align:center">PRI</td> 1121 * <td style="text-align:center">PAC</td> 1122 * <td></td> 1123 * <td style="text-align:center">2R</td> 1124 * </tr> 1125 * <tr> 1126 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1127 * <td></td> 1128 * <td></td> 1129 * <td></td> 1130 * <td style="text-align:center">PAC</td> 1131 * <td></td> 1132 * <td style="text-align:center">2R</td> 1133 * </tr> 1134 * <tr> 1135 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1136 * <td></td> 1137 * <td></td> 1138 * <td></td> 1139 * <td></td> 1140 * <td></td> 1141 * <td style="text-align:center">2R</td> 1142 * </tr> 1143 * <tr> 1144 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1145 * <td></td> 1146 * <td></td> 1147 * <td></td> 1148 * <td></td> 1149 * <td></td> 1150 * <td style="text-align:center">2R</td> 1151 * </tr> 1152 * <tr> 1153 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1154 * <td></td> 1155 * <td></td> 1156 * <td></td> 1157 * <td></td> 1158 * <td></td> 1159 * <td style="text-align:center">none</td> 1160 * </tr> 1161 * <tr> 1162 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1163 * <td></td> 1164 * <td></td> 1165 * <td style="text-align:center">PRI</td> 1166 * <td style="text-align:center">PAC</td> 1167 * <td style="text-align:center">MOD</td> 1168 * <td style="text-align:center">1R</td> 1169 * </tr> 1170 * <tr> 1171 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1172 * <td></td> 1173 * <td></td> 1174 * <td></td> 1175 * <td style="text-align:center">PAC</td> 1176 * <td style="text-align:center">MOD</td> 1177 * <td style="text-align:center">1R</td> 1178 * </tr> 1179 * <tr> 1180 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1181 * <td></td> 1182 * <td></td> 1183 * <td></td> 1184 * <td></td> 1185 * <td style="text-align:center">MOD</td> 1186 * <td style="text-align:center">1R</td> 1187 * </tr> 1188 * <tr> 1189 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1190 * <td></td> 1191 * <td></td> 1192 * <td></td> 1193 * <td></td> 1194 * <td></td> 1195 * <td style="text-align:center">1R</td> 1196 * </tr> 1197 * <tr> 1198 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1199 * <td></td> 1200 * <td></td> 1201 * <td></td> 1202 * <td></td> 1203 * <td></td> 1204 * <td style="text-align:center">none</td> 1205 * </tr> 1206 * <tr> 1207 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1208 * <td></td> 1209 * <td></td> 1210 * <td></td> 1211 * <td></td> 1212 * <td></td> 1213 * <td style="text-align:center">U</td> 1214 * </tr> 1215 * <tr> 1216 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1217 * <td></td> 1218 * <td></td> 1219 * <td></td> 1220 * <td></td> 1221 * <td></td> 1222 * <td style="text-align:center">U</td> 1223 * </tr> 1224 * <tr> 1225 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1226 * <td></td> 1227 * <td></td> 1228 * <td></td> 1229 * <td></td> 1230 * <td></td> 1231 * <td style="text-align:center">U</td> 1232 * </tr> 1233 * <tr> 1234 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1235 * <td></td> 1236 * <td></td> 1237 * <td></td> 1238 * <td></td> 1239 * <td></td> 1240 * <td style="text-align:center">none</td> 1241 * </tr> 1242 * <tr> 1243 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1244 * <td></td> 1245 * <td></td> 1246 * <td></td> 1247 * <td></td> 1248 * <td></td> 1249 * <td style="text-align:center">IAE</td> 1250 * </tr> 1251 * <tr> 1252 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1253 * <td></td> 1254 * <td></td> 1255 * <td></td> 1256 * <td></td> 1257 * <td></td> 1258 * <td style="text-align:center">none</td> 1259 * </tr> 1260 * </tbody> 1261 * </table> 1262 * 1263 * <p> 1264 * Notes: 1265 * <ul> 1266 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1267 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1268 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1269 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1270 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1271 * {@code PRO} indicates {@link #PROTECTED} bit set, 1272 * {@code PRI} indicates {@link #PRIVATE} bit set, 1273 * {@code PAC} indicates {@link #PACKAGE} bit set, 1274 * {@code MOD} indicates {@link #MODULE} bit set, 1275 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1276 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1277 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1278 * <li>Public access comes in three kinds: 1279 * <ul> 1280 * <li>unconditional ({@code U}): the lookup assumes readability. 1281 * The lookup has {@code null} previous lookup class. 1282 * <li>one-module-reads ({@code 1R}): the module access checking is 1283 * performed with respect to the lookup class. The lookup has {@code null} 1284 * previous lookup class. 1285 * <li>two-module-reads ({@code 2R}): the module access checking is 1286 * performed with respect to the lookup class and the previous lookup class. 1287 * The lookup has a non-null previous lookup class which is in a 1288 * different module from the current lookup class. 1289 * </ul> 1290 * <li>Any attempt to reach a third module loses all access.</li> 1291 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1292 * all access modes are dropped.</li> 1293 * </ul> 1294 * 1295 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1296 * A small number of Java methods have a special property called caller sensitivity. 1297 * A <em>caller-sensitive</em> method can behave differently depending on the 1298 * identity of its immediate caller. 1299 * <p> 1300 * If a method handle for a caller-sensitive method is requested, 1301 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1302 * but they take account of the lookup class in a special way. 1303 * The resulting method handle behaves as if it were called 1304 * from an instruction contained in the lookup class, 1305 * so that the caller-sensitive method detects the lookup class. 1306 * (By contrast, the invoker of the method handle is disregarded.) 1307 * Thus, in the case of caller-sensitive methods, 1308 * different lookup classes may give rise to 1309 * differently behaving method handles. 1310 * <p> 1311 * In cases where the lookup object is 1312 * {@link MethodHandles#publicLookup() publicLookup()}, 1313 * or some other lookup object without the 1314 * {@linkplain #ORIGINAL original access}, 1315 * the lookup class is disregarded. 1316 * In such cases, no caller-sensitive method handle can be created, 1317 * access is forbidden, and the lookup fails with an 1318 * {@code IllegalAccessException}. 1319 * <p style="font-size:smaller;"> 1320 * <em>Discussion:</em> 1321 * For example, the caller-sensitive method 1322 * {@link java.lang.Class#forName(String) Class.forName(x)} 1323 * can return varying classes or throw varying exceptions, 1324 * depending on the class loader of the class that calls it. 1325 * A public lookup of {@code Class.forName} will fail, because 1326 * there is no reasonable way to determine its bytecode behavior. 1327 * <p style="font-size:smaller;"> 1328 * If an application caches method handles for broad sharing, 1329 * it should use {@code publicLookup()} to create them. 1330 * If there is a lookup of {@code Class.forName}, it will fail, 1331 * and the application must take appropriate action in that case. 1332 * It may be that a later lookup, perhaps during the invocation of a 1333 * bootstrap method, can incorporate the specific identity 1334 * of the caller, making the method accessible. 1335 * <p style="font-size:smaller;"> 1336 * The function {@code MethodHandles.lookup} is caller sensitive 1337 * so that there can be a secure foundation for lookups. 1338 * Nearly all other methods in the JSR 292 API rely on lookup 1339 * objects to check access requests. 1340 */ 1341 public static final 1342 class Lookup { 1343 /** The class on behalf of whom the lookup is being performed. */ 1344 private final Class<?> lookupClass; 1345 1346 /** previous lookup class */ 1347 private final Class<?> prevLookupClass; 1348 1349 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1350 private final int allowedModes; 1351 1352 static { 1353 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1354 } 1355 1356 /** A single-bit mask representing {@code public} access, 1357 * which may contribute to the result of {@link #lookupModes lookupModes}. 1358 * The value, {@code 0x01}, happens to be the same as the value of the 1359 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1360 * <p> 1361 * A {@code Lookup} with this lookup mode performs cross-module access check 1362 * with respect to the {@linkplain #lookupClass() lookup class} and 1363 * {@linkplain #previousLookupClass() previous lookup class} if present. 1364 */ 1365 public static final int PUBLIC = Modifier.PUBLIC; 1366 1367 /** A single-bit mask representing {@code private} access, 1368 * which may contribute to the result of {@link #lookupModes lookupModes}. 1369 * The value, {@code 0x02}, happens to be the same as the value of the 1370 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1371 */ 1372 public static final int PRIVATE = Modifier.PRIVATE; 1373 1374 /** A single-bit mask representing {@code protected} access, 1375 * which may contribute to the result of {@link #lookupModes lookupModes}. 1376 * The value, {@code 0x04}, happens to be the same as the value of the 1377 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1378 */ 1379 public static final int PROTECTED = Modifier.PROTECTED; 1380 1381 /** A single-bit mask representing {@code package} access (default access), 1382 * which may contribute to the result of {@link #lookupModes lookupModes}. 1383 * The value is {@code 0x08}, which does not correspond meaningfully to 1384 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1385 */ 1386 public static final int PACKAGE = Modifier.STATIC; 1387 1388 /** A single-bit mask representing {@code module} access, 1389 * which may contribute to the result of {@link #lookupModes lookupModes}. 1390 * The value is {@code 0x10}, which does not correspond meaningfully to 1391 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1392 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1393 * with this lookup mode can access all public types in the module of the 1394 * lookup class and public types in packages exported by other modules 1395 * to the module of the lookup class. 1396 * <p> 1397 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1398 * previous lookup class} is always {@code null}. 1399 * 1400 * @since 9 1401 */ 1402 public static final int MODULE = PACKAGE << 1; 1403 1404 /** A single-bit mask representing {@code unconditional} access 1405 * which may contribute to the result of {@link #lookupModes lookupModes}. 1406 * The value is {@code 0x20}, which does not correspond meaningfully to 1407 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1408 * A {@code Lookup} with this lookup mode assumes {@linkplain 1409 * java.lang.Module#canRead(java.lang.Module) readability}. 1410 * This lookup mode can access all public members of public types 1411 * of all modules when the type is in a package that is {@link 1412 * java.lang.Module#isExported(String) exported unconditionally}. 1413 * 1414 * <p> 1415 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1416 * previous lookup class} is always {@code null}. 1417 * 1418 * @since 9 1419 * @see #publicLookup() 1420 */ 1421 public static final int UNCONDITIONAL = PACKAGE << 2; 1422 1423 /** A single-bit mask representing {@code original} access 1424 * which may contribute to the result of {@link #lookupModes lookupModes}. 1425 * The value is {@code 0x40}, which does not correspond meaningfully to 1426 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1427 * 1428 * <p> 1429 * If this lookup mode is set, the {@code Lookup} object must be 1430 * created by the original lookup class by calling 1431 * {@link MethodHandles#lookup()} method or by a bootstrap method 1432 * invoked by the VM. The {@code Lookup} object with this lookup 1433 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1434 * 1435 * @since 16 1436 */ 1437 public static final int ORIGINAL = PACKAGE << 3; 1438 1439 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1440 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1441 private static final int TRUSTED = -1; 1442 1443 /* 1444 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1445 * Adjust 0 => PACKAGE 1446 */ 1447 private static int fixmods(int mods) { 1448 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1449 if (Modifier.isPublic(mods)) 1450 mods |= UNCONDITIONAL; 1451 return (mods != 0) ? mods : PACKAGE; 1452 } 1453 1454 /** Tells which class is performing the lookup. It is this class against 1455 * which checks are performed for visibility and access permissions. 1456 * <p> 1457 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1458 * access checks are performed against both the lookup class and the previous lookup class. 1459 * <p> 1460 * The class implies a maximum level of access permission, 1461 * but the permissions may be additionally limited by the bitmask 1462 * {@link #lookupModes lookupModes}, which controls whether non-public members 1463 * can be accessed. 1464 * @return the lookup class, on behalf of which this lookup object finds members 1465 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1466 */ 1467 public Class<?> lookupClass() { 1468 return lookupClass; 1469 } 1470 1471 /** Reports a lookup class in another module that this lookup object 1472 * was previously teleported from, or {@code null}. 1473 * <p> 1474 * A {@code Lookup} object produced by the factory methods, such as the 1475 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1476 * has {@code null} previous lookup class. 1477 * A {@code Lookup} object has a non-null previous lookup class 1478 * when this lookup was teleported from an old lookup class 1479 * in one module to a new lookup class in another module. 1480 * 1481 * @return the lookup class in another module that this lookup object was 1482 * previously teleported from, or {@code null} 1483 * @since 14 1484 * @see #in(Class) 1485 * @see MethodHandles#privateLookupIn(Class, Lookup) 1486 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1487 */ 1488 public Class<?> previousLookupClass() { 1489 return prevLookupClass; 1490 } 1491 1492 // This is just for calling out to MethodHandleImpl. 1493 private Class<?> lookupClassOrNull() { 1494 return (allowedModes == TRUSTED) ? null : lookupClass; 1495 } 1496 1497 /** Tells which access-protection classes of members this lookup object can produce. 1498 * The result is a bit-mask of the bits 1499 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1500 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1501 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1502 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1503 * {@linkplain #MODULE MODULE (0x10)}, 1504 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1505 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1506 * <p> 1507 * A freshly-created lookup object 1508 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1509 * all possible bits set, except {@code UNCONDITIONAL}. 1510 * A lookup object on a new lookup class 1511 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1512 * may have some mode bits set to zero. 1513 * Mode bits can also be 1514 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1515 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1516 * The purpose of this is to restrict access via the new lookup object, 1517 * so that it can access only names which can be reached by the original 1518 * lookup object, and also by the new lookup class. 1519 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1520 * @see #in 1521 * @see #dropLookupMode 1522 */ 1523 public int lookupModes() { 1524 return allowedModes & ALL_MODES; 1525 } 1526 1527 /** Embody the current class (the lookupClass) as a lookup class 1528 * for method handle creation. 1529 * Must be called by from a method in this package, 1530 * which in turn is called by a method not in this package. 1531 */ 1532 Lookup(Class<?> lookupClass) { 1533 this(lookupClass, null, FULL_POWER_MODES); 1534 } 1535 1536 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1537 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1538 && prevLookupClass.getModule() != lookupClass.getModule()); 1539 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1540 this.lookupClass = lookupClass; 1541 this.prevLookupClass = prevLookupClass; 1542 this.allowedModes = allowedModes; 1543 } 1544 1545 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1546 // make sure we haven't accidentally picked up a privileged class: 1547 checkUnprivilegedlookupClass(lookupClass); 1548 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1549 } 1550 1551 /** 1552 * Creates a lookup on the specified new lookup class. 1553 * The resulting object will report the specified 1554 * class as its own {@link #lookupClass() lookupClass}. 1555 * 1556 * <p> 1557 * However, the resulting {@code Lookup} object is guaranteed 1558 * to have no more access capabilities than the original. 1559 * In particular, access capabilities can be lost as follows:<ul> 1560 * <li>If the new lookup class is different from the old lookup class, 1561 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1562 * <li>If the new lookup class is in a different module from the old one, 1563 * i.e. {@link #MODULE MODULE} access is lost. 1564 * <li>If the new lookup class is in a different package 1565 * than the old one, protected and default (package) members will not be accessible, 1566 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1567 * <li>If the new lookup class is not within the same package member 1568 * as the old one, private members will not be accessible, and protected members 1569 * will not be accessible by virtue of inheritance, 1570 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1571 * (Protected members may continue to be accessible because of package sharing.) 1572 * <li>If the new lookup class is not 1573 * {@linkplain #accessClass(Class) accessible} to this lookup, 1574 * then no members, not even public members, will be accessible 1575 * i.e. all access modes are lost. 1576 * <li>If the new lookup class, the old lookup class and the previous lookup class 1577 * are all in different modules i.e. teleporting to a third module, 1578 * all access modes are lost. 1579 * </ul> 1580 * <p> 1581 * The new previous lookup class is chosen as follows: 1582 * <ul> 1583 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1584 * the new previous lookup class is {@code null}. 1585 * <li>If the new lookup class is in the same module as the old lookup class, 1586 * the new previous lookup class is the old previous lookup class. 1587 * <li>If the new lookup class is in a different module from the old lookup class, 1588 * the new previous lookup class is the old lookup class. 1589 *</ul> 1590 * <p> 1591 * The resulting lookup's capabilities for loading classes 1592 * (used during {@link #findClass} invocations) 1593 * are determined by the lookup class' loader, 1594 * which may change due to this operation. 1595 * 1596 * @param requestedLookupClass the desired lookup class for the new lookup object 1597 * @return a lookup object which reports the desired lookup class, or the same object 1598 * if there is no change 1599 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1600 * @throws NullPointerException if the argument is null 1601 * 1602 * @see #accessClass(Class) 1603 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1604 */ 1605 public Lookup in(Class<?> requestedLookupClass) { 1606 Objects.requireNonNull(requestedLookupClass); 1607 if (requestedLookupClass.isPrimitive()) 1608 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1609 if (requestedLookupClass.isArray()) 1610 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1611 1612 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1613 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1614 if (requestedLookupClass == this.lookupClass) 1615 return this; // keep same capabilities 1616 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1617 Module fromModule = this.lookupClass.getModule(); 1618 Module targetModule = requestedLookupClass.getModule(); 1619 Class<?> plc = this.previousLookupClass(); 1620 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1621 assert plc == null; 1622 newModes = UNCONDITIONAL; 1623 } else if (fromModule != targetModule) { 1624 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1625 // allow hopping back and forth between fromModule and plc's module 1626 // but not the third module 1627 newModes = 0; 1628 } 1629 // drop MODULE access 1630 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1631 // teleport from this lookup class 1632 plc = this.lookupClass; 1633 } 1634 if ((newModes & PACKAGE) != 0 1635 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1636 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1637 } 1638 // Allow nestmate lookups to be created without special privilege: 1639 if ((newModes & PRIVATE) != 0 1640 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1641 newModes &= ~(PRIVATE|PROTECTED); 1642 } 1643 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1644 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1645 // The requested class it not accessible from the lookup class. 1646 // No permissions. 1647 newModes = 0; 1648 } 1649 return newLookup(requestedLookupClass, plc, newModes); 1650 } 1651 1652 /** 1653 * Creates a lookup on the same lookup class which this lookup object 1654 * finds members, but with a lookup mode that has lost the given lookup mode. 1655 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1656 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1657 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1658 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1659 * 1660 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1661 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1662 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1663 * lookup has no access. 1664 * 1665 * <p> If this lookup is not a public lookup, then the following applies 1666 * regardless of its {@linkplain #lookupModes() lookup modes}. 1667 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1668 * dropped and so the resulting lookup mode will never have these access 1669 * capabilities. When dropping {@code PACKAGE} 1670 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1671 * access. When dropping {@code MODULE} then the resulting lookup will not 1672 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1673 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1674 * 1675 * @apiNote 1676 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1677 * delegate non-public access within the package of the lookup class without 1678 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1679 * A lookup with {@code MODULE} but not 1680 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1681 * the module of the lookup class without conferring package access. 1682 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1683 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1684 * to public classes accessible to both the module of the lookup class 1685 * and the module of the previous lookup class. 1686 * 1687 * @param modeToDrop the lookup mode to drop 1688 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1689 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1690 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1691 * or {@code UNCONDITIONAL} 1692 * @see MethodHandles#privateLookupIn 1693 * @since 9 1694 */ 1695 public Lookup dropLookupMode(int modeToDrop) { 1696 int oldModes = lookupModes(); 1697 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1698 switch (modeToDrop) { 1699 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1700 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1701 case PACKAGE: newModes &= ~(PRIVATE); break; 1702 case PROTECTED: 1703 case PRIVATE: 1704 case ORIGINAL: 1705 case UNCONDITIONAL: break; 1706 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1707 } 1708 if (newModes == oldModes) return this; // return self if no change 1709 return newLookup(lookupClass(), previousLookupClass(), newModes); 1710 } 1711 1712 /** 1713 * Creates and links a class or interface from {@code bytes} 1714 * with the same class loader and in the same runtime package and 1715 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1716 * {@linkplain #lookupClass() lookup class} as if calling 1717 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1718 * ClassLoader::defineClass}. 1719 * 1720 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1721 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1722 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1723 * that the lookup object was created by a caller in the runtime package (or derived 1724 * from a lookup originally created by suitably privileged code to a target class in 1725 * the runtime package). </p> 1726 * 1727 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1728 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1729 * same package as the lookup class. </p> 1730 * 1731 * <p> This method does not run the class initializer. The class initializer may 1732 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1733 * Specification</em>. </p> 1734 * 1735 * @param bytes the class bytes 1736 * @return the {@code Class} object for the class 1737 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1738 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1739 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1740 * than the lookup class or {@code bytes} is not a class or interface 1741 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1742 * @throws VerifyError if the newly created class cannot be verified 1743 * @throws LinkageError if the newly created class cannot be linked for any other reason 1744 * @throws NullPointerException if {@code bytes} is {@code null} 1745 * @since 9 1746 * @see MethodHandles#privateLookupIn 1747 * @see Lookup#dropLookupMode 1748 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1749 */ 1750 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1751 if ((lookupModes() & PACKAGE) == 0) 1752 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1753 return makeClassDefiner(bytes.clone()).defineClass(false); 1754 } 1755 1756 /** 1757 * The set of class options that specify whether a hidden class created by 1758 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1759 * Lookup::defineHiddenClass} method is dynamically added as a new member 1760 * to the nest of a lookup class and/or whether a hidden class has 1761 * a strong relationship with the class loader marked as its defining loader. 1762 * 1763 * @since 15 1764 */ 1765 public enum ClassOption { 1766 /** 1767 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1768 * of a lookup class as a nestmate. 1769 * 1770 * <p> A hidden nestmate class has access to the private members of all 1771 * classes and interfaces in the same nest. 1772 * 1773 * @see Class#getNestHost() 1774 */ 1775 NESTMATE(NESTMATE_CLASS), 1776 1777 /** 1778 * Specifies that a hidden class has a <em>strong</em> 1779 * relationship with the class loader marked as its defining loader, 1780 * as a normal class or interface has with its own defining loader. 1781 * This means that the hidden class may be unloaded if and only if 1782 * its defining loader is not reachable and thus may be reclaimed 1783 * by a garbage collector (JLS {@jls 12.7}). 1784 * 1785 * <p> By default, a hidden class or interface may be unloaded 1786 * even if the class loader that is marked as its defining loader is 1787 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1788 1789 * 1790 * @jls 12.7 Unloading of Classes and Interfaces 1791 */ 1792 STRONG(STRONG_LOADER_LINK); 1793 1794 /* the flag value is used by VM at define class time */ 1795 private final int flag; 1796 ClassOption(int flag) { 1797 this.flag = flag; 1798 } 1799 1800 static int optionsToFlag(ClassOption[] options) { 1801 int flags = 0; 1802 for (ClassOption cp : options) { 1803 if ((flags & cp.flag) != 0) { 1804 throw new IllegalArgumentException("Duplicate ClassOption " + cp); 1805 } 1806 flags |= cp.flag; 1807 } 1808 return flags; 1809 } 1810 } 1811 1812 /** 1813 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1814 * returning a {@code Lookup} on the newly created class or interface. 1815 * 1816 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1817 * which either defines {@code C} directly or delegates to another class loader. 1818 * A class loader defines {@code C} directly by invoking 1819 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1820 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1821 * to derive {@code C} from a purported representation in {@code class} file format. 1822 * In situations where use of a class loader is undesirable, a class or interface 1823 * {@code C} can be created by this method instead. This method is capable of 1824 * defining {@code C}, and thereby creating it, without invoking 1825 * {@code ClassLoader::defineClass}. 1826 * Instead, this method defines {@code C} as if by arranging for 1827 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1828 * from a purported representation in {@code class} file format 1829 * using the following rules: 1830 * 1831 * <ol> 1832 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1833 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1834 * This level of access is needed to create {@code C} in the module 1835 * of the lookup class of this {@code Lookup}.</li> 1836 * 1837 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1838 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1839 * The major and minor version may differ from the {@code class} file version 1840 * of the lookup class of this {@code Lookup}.</li> 1841 * 1842 * <li> The value of {@code this_class} must be a valid index in the 1843 * {@code constant_pool} table, and the entry at that index must be a valid 1844 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1845 * encoded in internal form that is specified by this structure. {@code N} must 1846 * denote a class or interface in the same package as the lookup class.</li> 1847 * 1848 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1849 * where {@code <suffix>} is an unqualified name. 1850 * 1851 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1852 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1853 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1854 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1855 * refers to the new {@code CONSTANT_Utf8_info} structure. 1856 * 1857 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1858 * 1859 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1860 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1861 * with the following adjustments: 1862 * <ul> 1863 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1864 * that includes a single {@code "."} character, even though this is not a valid 1865 * binary class or interface name in internal form.</li> 1866 * 1867 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1868 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1869 * 1870 * <li> {@code C} is considered to have the same runtime 1871 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1872 * and {@linkplain java.security.ProtectionDomain protection domain} 1873 * as the lookup class of this {@code Lookup}. 1874 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1875 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1876 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1877 * <ul> 1878 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1879 * even though this is not a valid binary class or interface name.</li> 1880 * <li> {@link Class#descriptorString()} returns the string 1881 * {@code "L" + N + "." + <suffix> + ";"}, 1882 * even though this is not a valid type descriptor name.</li> 1883 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1884 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1885 * </ul> 1886 * </ul> 1887 * </li> 1888 * </ol> 1889 * 1890 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1891 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1892 * <ul> 1893 * <li> During verification, whenever it is necessary to load the class named 1894 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 1895 * made of any class loader.</li> 1896 * 1897 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 1898 * by {@code this_class}, the symbolic reference is considered to be resolved to 1899 * {@code C} and resolution always succeeds immediately.</li> 1900 * </ul> 1901 * 1902 * <p> If the {@code initialize} parameter is {@code true}, 1903 * then {@code C} is initialized by the Java Virtual Machine. 1904 * 1905 * <p> The newly created class or interface {@code C} serves as the 1906 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 1907 * returned by this method. {@code C} is <em>hidden</em> in the sense that 1908 * no other class or interface can refer to {@code C} via a constant pool entry. 1909 * That is, a hidden class or interface cannot be named as a supertype, a field type, 1910 * a method parameter type, or a method return type by any other class. 1911 * This is because a hidden class or interface does not have a binary name, so 1912 * there is no internal form available to record in any class's constant pool. 1913 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 1914 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 1915 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 1916 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 1917 * JVM Tool Interface</a>. 1918 * 1919 * <p> A class or interface created by 1920 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1921 * a class loader} has a strong relationship with that class loader. 1922 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 1923 * that {@linkplain Class#getClassLoader() defined it}. 1924 * This means that a class created by a class loader may be unloaded if and 1925 * only if its defining loader is not reachable and thus may be reclaimed 1926 * by a garbage collector (JLS {@jls 12.7}). 1927 * 1928 * By default, however, a hidden class or interface may be unloaded even if 1929 * the class loader that is marked as its defining loader is 1930 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1931 * This behavior is useful when a hidden class or interface serves multiple 1932 * classes defined by arbitrary class loaders. In other cases, a hidden 1933 * class or interface may be linked to a single class (or a small number of classes) 1934 * with the same defining loader as the hidden class or interface. 1935 * In such cases, where the hidden class or interface must be coterminous 1936 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 1937 * option may be passed in {@code options}. 1938 * This arranges for a hidden class to have the same strong relationship 1939 * with the class loader marked as its defining loader, 1940 * as a normal class or interface has with its own defining loader. 1941 * 1942 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 1943 * may still prevent a hidden class or interface from being 1944 * unloaded by ensuring that the {@code Class} object is reachable. 1945 * 1946 * <p> The unloading characteristics are set for each hidden class when it is 1947 * defined, and cannot be changed later. An advantage of allowing hidden classes 1948 * to be unloaded independently of the class loader marked as their defining loader 1949 * is that a very large number of hidden classes may be created by an application. 1950 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 1951 * just as if normal classes were created by class loaders. 1952 * 1953 * <p> Classes and interfaces in a nest are allowed to have mutual access to 1954 * their private members. The nest relationship is determined by 1955 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 1956 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 1957 * By default, a hidden class belongs to a nest consisting only of itself 1958 * because a hidden class has no binary name. 1959 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 1960 * to create a hidden class or interface {@code C} as a member of a nest. 1961 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 1962 * in the {@code ClassFile} structure from which {@code C} was derived. 1963 * Instead, the following rules determine the nest host of {@code C}: 1964 * <ul> 1965 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 1966 * been determined, then let {@code H} be the nest host of the lookup class. 1967 * Otherwise, the nest host of the lookup class is determined using the 1968 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 1969 * <li>The nest host of {@code C} is determined to be {@code H}, 1970 * the nest host of the lookup class.</li> 1971 * </ul> 1972 * 1973 * <p> A hidden class or interface may be serializable, but this requires a custom 1974 * serialization mechanism in order to ensure that instances are properly serialized 1975 * and deserialized. The default serialization mechanism supports only classes and 1976 * interfaces that are discoverable by their class name. 1977 * 1978 * @param bytes the bytes that make up the class data, 1979 * in the format of a valid {@code class} file as defined by 1980 * <cite>The Java Virtual Machine Specification</cite>. 1981 * @param initialize if {@code true} the class will be initialized. 1982 * @param options {@linkplain ClassOption class options} 1983 * @return the {@code Lookup} object on the hidden class, 1984 * with {@linkplain #ORIGINAL original} and 1985 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 1986 * 1987 * @throws IllegalAccessException if this {@code Lookup} does not have 1988 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 1989 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1990 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 1991 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1992 * than the lookup class or {@code bytes} is not a class or interface 1993 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1994 * @throws IncompatibleClassChangeError if the class or interface named as 1995 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 1996 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 1997 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 1998 * {@code C} is {@code C} itself 1999 * @throws VerifyError if the newly created class cannot be verified 2000 * @throws LinkageError if the newly created class cannot be linked for any other reason 2001 * @throws NullPointerException if any parameter is {@code null} 2002 * 2003 * @since 15 2004 * @see Class#isHidden() 2005 * @jvms 4.2.1 Binary Class and Interface Names 2006 * @jvms 4.2.2 Unqualified Names 2007 * @jvms 4.7.28 The {@code NestHost} Attribute 2008 * @jvms 4.7.29 The {@code NestMembers} Attribute 2009 * @jvms 5.4.3.1 Class and Interface Resolution 2010 * @jvms 5.4.4 Access Control 2011 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2012 * @jvms 5.4 Linking 2013 * @jvms 5.5 Initialization 2014 * @jls 12.7 Unloading of Classes and Interfaces 2015 */ 2016 @SuppressWarnings("doclint:reference") // cross-module links 2017 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2018 throws IllegalAccessException 2019 { 2020 Objects.requireNonNull(bytes); 2021 int flags = ClassOption.optionsToFlag(options); 2022 if (!hasFullPrivilegeAccess()) { 2023 throw new IllegalAccessException(this + " does not have full privilege access"); 2024 } 2025 2026 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize); 2027 } 2028 2029 /** 2030 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2031 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2032 * returning a {@code Lookup} on the newly created class or interface. 2033 * 2034 * <p> This method is equivalent to calling 2035 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2036 * as if the hidden class is injected with a private static final <i>unnamed</i> 2037 * field which is initialized with the given {@code classData} at 2038 * the first instruction of the class initializer. 2039 * The newly created class is linked by the Java Virtual Machine. 2040 * 2041 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2042 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2043 * methods can be used to retrieve the {@code classData}. 2044 * 2045 * @apiNote 2046 * A framework can create a hidden class with class data with one or more 2047 * objects and load the class data as dynamically-computed constant(s) 2048 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2049 * Class data} is accessible only to the lookup object created by the newly 2050 * defined hidden class but inaccessible to other members in the same nest 2051 * (unlike private static fields that are accessible to nestmates). 2052 * Care should be taken w.r.t. mutability for example when passing 2053 * an array or other mutable structure through the class data. 2054 * Changing any value stored in the class data at runtime may lead to 2055 * unpredictable behavior. 2056 * If the class data is a {@code List}, it is good practice to make it 2057 * unmodifiable for example via {@link List#of List::of}. 2058 * 2059 * @param bytes the class bytes 2060 * @param classData pre-initialized class data 2061 * @param initialize if {@code true} the class will be initialized. 2062 * @param options {@linkplain ClassOption class options} 2063 * @return the {@code Lookup} object on the hidden class, 2064 * with {@linkplain #ORIGINAL original} and 2065 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2066 * 2067 * @throws IllegalAccessException if this {@code Lookup} does not have 2068 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2069 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2070 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2071 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2072 * than the lookup class or {@code bytes} is not a class or interface 2073 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2074 * @throws IncompatibleClassChangeError if the class or interface named as 2075 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2076 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2077 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2078 * {@code C} is {@code C} itself 2079 * @throws VerifyError if the newly created class cannot be verified 2080 * @throws LinkageError if the newly created class cannot be linked for any other reason 2081 * @throws NullPointerException if any parameter is {@code null} 2082 * 2083 * @since 16 2084 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2085 * @see Class#isHidden() 2086 * @see MethodHandles#classData(Lookup, String, Class) 2087 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2088 * @jvms 4.2.1 Binary Class and Interface Names 2089 * @jvms 4.2.2 Unqualified Names 2090 * @jvms 4.7.28 The {@code NestHost} Attribute 2091 * @jvms 4.7.29 The {@code NestMembers} Attribute 2092 * @jvms 5.4.3.1 Class and Interface Resolution 2093 * @jvms 5.4.4 Access Control 2094 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2095 * @jvms 5.4 Linking 2096 * @jvms 5.5 Initialization 2097 * @jls 12.7 Unloading of Classes and Interfaces 2098 */ 2099 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2100 throws IllegalAccessException 2101 { 2102 Objects.requireNonNull(bytes); 2103 Objects.requireNonNull(classData); 2104 2105 int flags = ClassOption.optionsToFlag(options); 2106 2107 if (!hasFullPrivilegeAccess()) { 2108 throw new IllegalAccessException(this + " does not have full privilege access"); 2109 } 2110 2111 return makeHiddenClassDefiner(bytes.clone(), false, flags) 2112 .defineClassAsLookup(initialize, classData); 2113 } 2114 2115 // A default dumper for writing class files passed to Lookup::defineClass 2116 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2117 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2118 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2119 // 2120 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2121 // and LambdaForms and method handle internals. They are dumped via 2122 // different ClassFileDumpers. 2123 private static ClassFileDumper defaultDumper() { 2124 return DEFAULT_DUMPER; 2125 } 2126 2127 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2128 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2129 2130 /** 2131 * This method checks the class file version and the structure of `this_class`. 2132 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2133 * that is in the named package. 2134 * 2135 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2136 * or the class is not in the given package name. 2137 */ 2138 static String validateAndFindInternalName(byte[] bytes, String pkgName) { 2139 int magic = readInt(bytes, 0); 2140 if (magic != ClassFile.MAGIC_NUMBER) { 2141 throw new ClassFormatError("Incompatible magic value: " + magic); 2142 } 2143 // We have to read major and minor this way as ClassFile API throws IAE 2144 // yet we want distinct ClassFormatError and UnsupportedClassVersionError 2145 int minor = readUnsignedShort(bytes, 4); 2146 int major = readUnsignedShort(bytes, 6); 2147 2148 if (!VM.isSupportedClassFileVersion(major, minor)) { 2149 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2150 } 2151 2152 String name; 2153 ClassDesc sym; 2154 int accessFlags; 2155 try { 2156 ClassModel cm = ClassFile.of().parse(bytes); 2157 var thisClass = cm.thisClass(); 2158 name = thisClass.asInternalName(); 2159 sym = thisClass.asSymbol(); 2160 accessFlags = cm.flags().flagsMask(); 2161 } catch (IllegalArgumentException e) { 2162 ClassFormatError cfe = new ClassFormatError(); 2163 cfe.initCause(e); 2164 throw cfe; 2165 } 2166 // must be a class or interface 2167 if ((accessFlags & ACC_MODULE) != 0) { 2168 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2169 } 2170 2171 String pn = sym.packageName(); 2172 if (!pn.equals(pkgName)) { 2173 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2174 } 2175 2176 return name; 2177 } 2178 2179 private static int readInt(byte[] bytes, int offset) { 2180 if ((offset + 4) > bytes.length) { 2181 throw new ClassFormatError("Invalid ClassFile structure"); 2182 } 2183 return ((bytes[offset] & 0xFF) << 24) 2184 | ((bytes[offset + 1] & 0xFF) << 16) 2185 | ((bytes[offset + 2] & 0xFF) << 8) 2186 | (bytes[offset + 3] & 0xFF); 2187 } 2188 2189 private static int readUnsignedShort(byte[] bytes, int offset) { 2190 if ((offset+2) > bytes.length) { 2191 throw new ClassFormatError("Invalid ClassFile structure"); 2192 } 2193 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2194 } 2195 2196 /* 2197 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2198 * from the given bytes. 2199 * 2200 * Caller should make a defensive copy of the arguments if needed 2201 * before calling this factory method. 2202 * 2203 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2204 * {@code bytes} denotes a class in a different package than the lookup class 2205 */ 2206 private ClassDefiner makeClassDefiner(byte[] bytes) { 2207 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2208 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper()); 2209 } 2210 2211 /** 2212 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2213 * from the given bytes. No package name check on the given bytes. 2214 * 2215 * @param internalName internal name 2216 * @param bytes class bytes 2217 * @param dumper dumper to write the given bytes to the dumper's output directory 2218 * @return ClassDefiner that defines a normal class of the given bytes. 2219 */ 2220 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2221 // skip package name validation 2222 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper); 2223 } 2224 2225 /** 2226 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2227 * from the given bytes. The name must be in the same package as the lookup class. 2228 * 2229 * Caller should make a defensive copy of the arguments if needed 2230 * before calling this factory method. 2231 * 2232 * @param bytes class bytes 2233 * @param dumper dumper to write the given bytes to the dumper's output directory 2234 * @return ClassDefiner that defines a hidden class of the given bytes. 2235 * 2236 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2237 * {@code bytes} denotes a class in a different package than the lookup class 2238 */ 2239 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2240 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2241 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2242 } 2243 2244 /** 2245 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2246 * from the given bytes and options. 2247 * The name must be in the same package as the lookup class. 2248 * 2249 * Caller should make a defensive copy of the arguments if needed 2250 * before calling this factory method. 2251 * 2252 * @param bytes class bytes 2253 * @param flags class option flag mask 2254 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2255 * @return ClassDefiner that defines a hidden class of the given bytes and options 2256 * 2257 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2258 * {@code bytes} denotes a class in a different package than the lookup class 2259 */ 2260 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2261 boolean accessVmAnnotations, 2262 int flags) { 2263 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2264 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags); 2265 } 2266 2267 /** 2268 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2269 * from the given bytes and the given options. No package name check on the given bytes. 2270 * 2271 * @param internalName internal name that specifies the prefix of the hidden class 2272 * @param bytes class bytes 2273 * @param dumper dumper to write the given bytes to the dumper's output directory 2274 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2275 */ 2276 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2277 Objects.requireNonNull(dumper); 2278 // skip name and access flags validation 2279 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2280 } 2281 2282 /** 2283 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2284 * from the given bytes and the given options. No package name check on the given bytes. 2285 * 2286 * @param internalName internal name that specifies the prefix of the hidden class 2287 * @param bytes class bytes 2288 * @param flags class options flag mask 2289 * @param dumper dumper to write the given bytes to the dumper's output directory 2290 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2291 */ 2292 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) { 2293 Objects.requireNonNull(dumper); 2294 // skip name and access flags validation 2295 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags); 2296 } 2297 2298 /** 2299 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2300 * from the given class file and options. 2301 * 2302 * @param internalName internal name 2303 * @param bytes Class byte array 2304 * @param flags class option flag mask 2305 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2306 * @param dumper dumper to write the given bytes to the dumper's output directory 2307 */ 2308 private ClassDefiner makeHiddenClassDefiner(String internalName, 2309 byte[] bytes, 2310 boolean accessVmAnnotations, 2311 ClassFileDumper dumper, 2312 int flags) { 2313 flags |= HIDDEN_CLASS; 2314 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2315 // jdk.internal.vm.annotations are permitted for classes 2316 // defined to boot loader and platform loader 2317 flags |= ACCESS_VM_ANNOTATIONS; 2318 } 2319 2320 return new ClassDefiner(this, internalName, bytes, flags, dumper); 2321 } 2322 2323 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) { 2324 ClassDefiner { 2325 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2326 } 2327 2328 Class<?> defineClass(boolean initialize) { 2329 return defineClass(initialize, null); 2330 } 2331 2332 Lookup defineClassAsLookup(boolean initialize) { 2333 Class<?> c = defineClass(initialize, null); 2334 return new Lookup(c, null, FULL_POWER_MODES); 2335 } 2336 2337 /** 2338 * Defines the class of the given bytes and the given classData. 2339 * If {@code initialize} parameter is true, then the class will be initialized. 2340 * 2341 * @param initialize true if the class to be initialized 2342 * @param classData classData or null 2343 * @return the class 2344 * 2345 * @throws LinkageError linkage error 2346 */ 2347 Class<?> defineClass(boolean initialize, Object classData) { 2348 Class<?> lookupClass = lookup.lookupClass(); 2349 ClassLoader loader = lookupClass.getClassLoader(); 2350 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2351 Class<?> c = null; 2352 try { 2353 c = SharedSecrets.getJavaLangAccess() 2354 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData); 2355 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2356 return c; 2357 } finally { 2358 // dump the classfile for debugging 2359 if (dumper.isEnabled()) { 2360 String name = internalName(); 2361 if (c != null) { 2362 dumper.dumpClass(name, c, bytes); 2363 } else { 2364 dumper.dumpFailedClass(name, bytes); 2365 } 2366 } 2367 } 2368 } 2369 2370 /** 2371 * Defines the class of the given bytes and the given classData. 2372 * If {@code initialize} parameter is true, then the class will be initialized. 2373 * 2374 * @param initialize true if the class to be initialized 2375 * @param classData classData or null 2376 * @return a Lookup for the defined class 2377 * 2378 * @throws LinkageError linkage error 2379 */ 2380 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2381 Class<?> c = defineClass(initialize, classData); 2382 return new Lookup(c, null, FULL_POWER_MODES); 2383 } 2384 2385 private boolean isNestmate() { 2386 return (classFlags & NESTMATE_CLASS) != 0; 2387 } 2388 } 2389 2390 private ProtectionDomain lookupClassProtectionDomain() { 2391 ProtectionDomain pd = cachedProtectionDomain; 2392 if (pd == null) { 2393 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2394 } 2395 return pd; 2396 } 2397 2398 // cached protection domain 2399 private volatile ProtectionDomain cachedProtectionDomain; 2400 2401 // Make sure outer class is initialized first. 2402 static { IMPL_NAMES.getClass(); } 2403 2404 /** Package-private version of lookup which is trusted. */ 2405 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2406 2407 /** Version of lookup which is trusted minimally. 2408 * It can only be used to create method handles to publicly accessible 2409 * members in packages that are exported unconditionally. 2410 */ 2411 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2412 2413 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2414 String name = lookupClass.getName(); 2415 if (name.startsWith("java.lang.invoke.")) 2416 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2417 } 2418 2419 /** 2420 * Displays the name of the class from which lookups are to be made, 2421 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2422 * previous lookup class} if present. 2423 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2424 * If there are restrictions on the access permitted to this lookup, 2425 * this is indicated by adding a suffix to the class name, consisting 2426 * of a slash and a keyword. The keyword represents the strongest 2427 * allowed access, and is chosen as follows: 2428 * <ul> 2429 * <li>If no access is allowed, the suffix is "/noaccess". 2430 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2431 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2432 * <li>If only public and module access are allowed, the suffix is "/module". 2433 * <li>If public and package access are allowed, the suffix is "/package". 2434 * <li>If public, package, and private access are allowed, the suffix is "/private". 2435 * </ul> 2436 * If none of the above cases apply, it is the case that 2437 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2438 * (public, module, package, private, and protected) is allowed. 2439 * In this case, no suffix is added. 2440 * This is true only of an object obtained originally from 2441 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2442 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2443 * always have restricted access, and will display a suffix. 2444 * <p> 2445 * (It may seem strange that protected access should be 2446 * stronger than private access. Viewed independently from 2447 * package access, protected access is the first to be lost, 2448 * because it requires a direct subclass relationship between 2449 * caller and callee.) 2450 * @see #in 2451 */ 2452 @Override 2453 public String toString() { 2454 String cname = lookupClass.getName(); 2455 if (prevLookupClass != null) 2456 cname += "/" + prevLookupClass.getName(); 2457 switch (allowedModes) { 2458 case 0: // no privileges 2459 return cname + "/noaccess"; 2460 case UNCONDITIONAL: 2461 return cname + "/publicLookup"; 2462 case PUBLIC: 2463 return cname + "/public"; 2464 case PUBLIC|MODULE: 2465 return cname + "/module"; 2466 case PUBLIC|PACKAGE: 2467 case PUBLIC|MODULE|PACKAGE: 2468 return cname + "/package"; 2469 case PUBLIC|PACKAGE|PRIVATE: 2470 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2471 return cname + "/private"; 2472 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2473 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2474 case FULL_POWER_MODES: 2475 return cname; 2476 case TRUSTED: 2477 return "/trusted"; // internal only; not exported 2478 default: // Should not happen, but it's a bitfield... 2479 cname = cname + "/" + Integer.toHexString(allowedModes); 2480 assert(false) : cname; 2481 return cname; 2482 } 2483 } 2484 2485 /** 2486 * Produces a method handle for a static method. 2487 * The type of the method handle will be that of the method. 2488 * (Since static methods do not take receivers, there is no 2489 * additional receiver argument inserted into the method handle type, 2490 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2491 * The method and all its argument types must be accessible to the lookup object. 2492 * <p> 2493 * The returned method handle will have 2494 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2495 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2496 * <p> 2497 * If the returned method handle is invoked, the method's class will 2498 * be initialized, if it has not already been initialized. 2499 * <p><b>Example:</b> 2500 * {@snippet lang="java" : 2501 import static java.lang.invoke.MethodHandles.*; 2502 import static java.lang.invoke.MethodType.*; 2503 ... 2504 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2505 "asList", methodType(List.class, Object[].class)); 2506 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2507 * } 2508 * @param refc the class from which the method is accessed 2509 * @param name the name of the method 2510 * @param type the type of the method 2511 * @return the desired method handle 2512 * @throws NoSuchMethodException if the method does not exist 2513 * @throws IllegalAccessException if access checking fails, 2514 * or if the method is not {@code static}, 2515 * or if the method's variable arity modifier bit 2516 * is set and {@code asVarargsCollector} fails 2517 * @throws NullPointerException if any argument is null 2518 */ 2519 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2520 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2521 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2522 } 2523 2524 /** 2525 * Produces a method handle for a virtual method. 2526 * The type of the method handle will be that of the method, 2527 * with the receiver type (usually {@code refc}) prepended. 2528 * The method and all its argument types must be accessible to the lookup object. 2529 * <p> 2530 * When called, the handle will treat the first argument as a receiver 2531 * and, for non-private methods, dispatch on the receiver's type to determine which method 2532 * implementation to enter. 2533 * For private methods the named method in {@code refc} will be invoked on the receiver. 2534 * (The dispatching action is identical with that performed by an 2535 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2536 * <p> 2537 * The first argument will be of type {@code refc} if the lookup 2538 * class has full privileges to access the member. Otherwise 2539 * the member must be {@code protected} and the first argument 2540 * will be restricted in type to the lookup class. 2541 * <p> 2542 * The returned method handle will have 2543 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2544 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2545 * <p> 2546 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2547 * instructions and method handles produced by {@code findVirtual}, 2548 * if the class is {@code MethodHandle} and the name string is 2549 * {@code invokeExact} or {@code invoke}, the resulting 2550 * method handle is equivalent to one produced by 2551 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2552 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2553 * with the same {@code type} argument. 2554 * <p> 2555 * If the class is {@code VarHandle} and the name string corresponds to 2556 * the name of a signature-polymorphic access mode method, the resulting 2557 * method handle is equivalent to one produced by 2558 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2559 * the access mode corresponding to the name string and with the same 2560 * {@code type} arguments. 2561 * <p> 2562 * <b>Example:</b> 2563 * {@snippet lang="java" : 2564 import static java.lang.invoke.MethodHandles.*; 2565 import static java.lang.invoke.MethodType.*; 2566 ... 2567 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2568 "concat", methodType(String.class, String.class)); 2569 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2570 "hashCode", methodType(int.class)); 2571 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2572 "hashCode", methodType(int.class)); 2573 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2574 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2575 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2576 // interface method: 2577 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2578 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2579 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2580 // constructor "internal method" must be accessed differently: 2581 MethodType MT_newString = methodType(void.class); //()V for new String() 2582 try { assertEquals("impossible", lookup() 2583 .findVirtual(String.class, "<init>", MT_newString)); 2584 } catch (NoSuchMethodException ex) { } // OK 2585 MethodHandle MH_newString = publicLookup() 2586 .findConstructor(String.class, MT_newString); 2587 assertEquals("", (String) MH_newString.invokeExact()); 2588 * } 2589 * 2590 * @param refc the class or interface from which the method is accessed 2591 * @param name the name of the method 2592 * @param type the type of the method, with the receiver argument omitted 2593 * @return the desired method handle 2594 * @throws NoSuchMethodException if the method does not exist 2595 * @throws IllegalAccessException if access checking fails, 2596 * or if the method is {@code static}, 2597 * or if the method's variable arity modifier bit 2598 * is set and {@code asVarargsCollector} fails 2599 * @throws NullPointerException if any argument is null 2600 */ 2601 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2602 if (refc == MethodHandle.class) { 2603 MethodHandle mh = findVirtualForMH(name, type); 2604 if (mh != null) return mh; 2605 } else if (refc == VarHandle.class) { 2606 MethodHandle mh = findVirtualForVH(name, type); 2607 if (mh != null) return mh; 2608 } 2609 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2610 MemberName method = resolveOrFail(refKind, refc, name, type); 2611 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2612 } 2613 private MethodHandle findVirtualForMH(String name, MethodType type) { 2614 // these names require special lookups because of the implicit MethodType argument 2615 if ("invoke".equals(name)) 2616 return invoker(type); 2617 if ("invokeExact".equals(name)) 2618 return exactInvoker(type); 2619 assert(!MemberName.isMethodHandleInvokeName(name)); 2620 return null; 2621 } 2622 private MethodHandle findVirtualForVH(String name, MethodType type) { 2623 try { 2624 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2625 } catch (IllegalArgumentException e) { 2626 return null; 2627 } 2628 } 2629 2630 /** 2631 * Produces a method handle which creates an object and initializes it, using 2632 * the constructor of the specified type. 2633 * The parameter types of the method handle will be those of the constructor, 2634 * while the return type will be a reference to the constructor's class. 2635 * The constructor and all its argument types must be accessible to the lookup object. 2636 * <p> 2637 * The requested type must have a return type of {@code void}. 2638 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2639 * <p> 2640 * The returned method handle will have 2641 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2642 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2643 * <p> 2644 * If the returned method handle is invoked, the constructor's class will 2645 * be initialized, if it has not already been initialized. 2646 * <p><b>Example:</b> 2647 * {@snippet lang="java" : 2648 import static java.lang.invoke.MethodHandles.*; 2649 import static java.lang.invoke.MethodType.*; 2650 ... 2651 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2652 ArrayList.class, methodType(void.class, Collection.class)); 2653 Collection orig = Arrays.asList("x", "y"); 2654 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2655 assert(orig != copy); 2656 assertEquals(orig, copy); 2657 // a variable-arity constructor: 2658 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2659 ProcessBuilder.class, methodType(void.class, String[].class)); 2660 ProcessBuilder pb = (ProcessBuilder) 2661 MH_newProcessBuilder.invoke("x", "y", "z"); 2662 assertEquals("[x, y, z]", pb.command().toString()); 2663 * } 2664 * 2665 * 2666 * @param refc the class or interface from which the method is accessed 2667 * @param type the type of the method, with the receiver argument omitted, and a void return type 2668 * @return the desired method handle 2669 * @throws NoSuchMethodException if the constructor does not exist 2670 * @throws IllegalAccessException if access checking fails 2671 * or if the method's variable arity modifier bit 2672 * is set and {@code asVarargsCollector} fails 2673 * @throws NullPointerException if any argument is null 2674 */ 2675 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2676 if (refc.isArray()) { 2677 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2678 } 2679 if (type.returnType() != void.class) { 2680 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName()); 2681 } 2682 String name = ConstantDescs.INIT_NAME; 2683 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2684 return getDirectConstructor(refc, ctor); 2685 } 2686 2687 /** 2688 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2689 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2690 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2691 * and then determines whether the class is accessible to this lookup object. 2692 * <p> 2693 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2694 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2695 * of {@code '['} and followed by the element type as encoded in the 2696 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2697 * <p> 2698 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2699 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2700 * 2701 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2702 * or the string representing an array class 2703 * @return the requested class. 2704 * @throws LinkageError if the linkage fails 2705 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2706 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2707 * modes. 2708 * @throws NullPointerException if {@code targetName} is null 2709 * @since 9 2710 * @jvms 5.4.3.1 Class and Interface Resolution 2711 */ 2712 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2713 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2714 return accessClass(targetClass); 2715 } 2716 2717 /** 2718 * Ensures that {@code targetClass} has been initialized. The class 2719 * to be initialized must be {@linkplain #accessClass accessible} 2720 * to this {@code Lookup} object. This method causes {@code targetClass} 2721 * to be initialized if it has not been already initialized, 2722 * as specified in JVMS {@jvms 5.5}. 2723 * 2724 * <p> 2725 * This method returns when {@code targetClass} is fully initialized, or 2726 * when {@code targetClass} is being initialized by the current thread. 2727 * 2728 * @param <T> the type of the class to be initialized 2729 * @param targetClass the class to be initialized 2730 * @return {@code targetClass} that has been initialized, or that is being 2731 * initialized by the current thread. 2732 * 2733 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2734 * or array class 2735 * @throws IllegalAccessException if {@code targetClass} is not 2736 * {@linkplain #accessClass accessible} to this lookup 2737 * @throws ExceptionInInitializerError if the class initialization provoked 2738 * by this method fails 2739 * @since 15 2740 * @jvms 5.5 Initialization 2741 */ 2742 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2743 if (targetClass.isPrimitive()) 2744 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2745 if (targetClass.isArray()) 2746 throw new IllegalArgumentException(targetClass + " is an array class"); 2747 2748 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2749 throw makeAccessException(targetClass); 2750 } 2751 2752 // ensure class initialization 2753 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2754 return targetClass; 2755 } 2756 2757 /* 2758 * Returns IllegalAccessException due to access violation to the given targetClass. 2759 * 2760 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2761 * which verifies access to a class rather a member. 2762 */ 2763 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2764 String message = "access violation: "+ targetClass; 2765 if (this == MethodHandles.publicLookup()) { 2766 message += ", from public Lookup"; 2767 } else { 2768 Module m = lookupClass().getModule(); 2769 message += ", from " + lookupClass() + " (" + m + ")"; 2770 if (prevLookupClass != null) { 2771 message += ", previous lookup " + 2772 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2773 } 2774 } 2775 return new IllegalAccessException(message); 2776 } 2777 2778 /** 2779 * Determines if a class can be accessed from the lookup context defined by 2780 * this {@code Lookup} object. The static initializer of the class is not run. 2781 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2782 * if the element type of the array class is accessible. Otherwise, 2783 * {@code targetClass} is determined as accessible as follows. 2784 * 2785 * <p> 2786 * If {@code targetClass} is in the same module as the lookup class, 2787 * the lookup class is {@code LC} in module {@code M1} and 2788 * the previous lookup class is in module {@code M0} or 2789 * {@code null} if not present, 2790 * {@code targetClass} is accessible if and only if one of the following is true: 2791 * <ul> 2792 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2793 * {@code LC} or other class in the same nest of {@code LC}.</li> 2794 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2795 * in the same runtime package of {@code LC}.</li> 2796 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2797 * a public type in {@code M1}.</li> 2798 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2799 * a public type in a package exported by {@code M1} to at least {@code M0} 2800 * if the previous lookup class is present; otherwise, {@code targetClass} 2801 * is a public type in a package exported by {@code M1} unconditionally.</li> 2802 * </ul> 2803 * 2804 * <p> 2805 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2806 * can access public types in all modules when the type is in a package 2807 * that is exported unconditionally. 2808 * <p> 2809 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2810 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2811 * is inaccessible. 2812 * <p> 2813 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2814 * {@code M1} is the module containing {@code lookupClass} and 2815 * {@code M2} is the module containing {@code targetClass}, 2816 * then {@code targetClass} is accessible if and only if 2817 * <ul> 2818 * <li>{@code M1} reads {@code M2}, and 2819 * <li>{@code targetClass} is public and in a package exported by 2820 * {@code M2} at least to {@code M1}. 2821 * </ul> 2822 * <p> 2823 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2824 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2825 * containing the previous lookup class, then {@code targetClass} is accessible 2826 * if and only if one of the following is true: 2827 * <ul> 2828 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2829 * {@linkplain Module#reads reads} {@code M0} and the type is 2830 * in a package that is exported to at least {@code M1}. 2831 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2832 * {@linkplain Module#reads reads} {@code M1} and the type is 2833 * in a package that is exported to at least {@code M0}. 2834 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2835 * and {@code M1} reads {@code M2} and the type is in a package 2836 * that is exported to at least both {@code M0} and {@code M2}. 2837 * </ul> 2838 * <p> 2839 * Otherwise, {@code targetClass} is not accessible. 2840 * 2841 * @param <T> the type of the class to be access-checked 2842 * @param targetClass the class to be access-checked 2843 * @return {@code targetClass} that has been access-checked 2844 * @throws IllegalAccessException if the class is not accessible from the lookup class 2845 * and previous lookup class, if present, using the allowed access modes. 2846 * @throws NullPointerException if {@code targetClass} is {@code null} 2847 * @since 9 2848 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2849 */ 2850 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2851 if (!isClassAccessible(targetClass)) { 2852 throw makeAccessException(targetClass); 2853 } 2854 return targetClass; 2855 } 2856 2857 /** 2858 * Produces an early-bound method handle for a virtual method. 2859 * It will bypass checks for overriding methods on the receiver, 2860 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2861 * instruction from within the explicitly specified {@code specialCaller}. 2862 * The type of the method handle will be that of the method, 2863 * with a suitably restricted receiver type prepended. 2864 * (The receiver type will be {@code specialCaller} or a subtype.) 2865 * The method and all its argument types must be accessible 2866 * to the lookup object. 2867 * <p> 2868 * Before method resolution, 2869 * if the explicitly specified caller class is not identical with the 2870 * lookup class, or if this lookup object does not have 2871 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2872 * privileges, the access fails. 2873 * <p> 2874 * The returned method handle will have 2875 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2876 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2877 * <p style="font-size:smaller;"> 2878 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 2879 * are not visible to this API, 2880 * even though the {@code invokespecial} instruction can refer to them 2881 * in special circumstances. Use {@link #findConstructor findConstructor} 2882 * to access instance initialization methods in a safe manner.)</em> 2883 * <p><b>Example:</b> 2884 * {@snippet lang="java" : 2885 import static java.lang.invoke.MethodHandles.*; 2886 import static java.lang.invoke.MethodType.*; 2887 ... 2888 static class Listie extends ArrayList { 2889 public String toString() { return "[wee Listie]"; } 2890 static Lookup lookup() { return MethodHandles.lookup(); } 2891 } 2892 ... 2893 // no access to constructor via invokeSpecial: 2894 MethodHandle MH_newListie = Listie.lookup() 2895 .findConstructor(Listie.class, methodType(void.class)); 2896 Listie l = (Listie) MH_newListie.invokeExact(); 2897 try { assertEquals("impossible", Listie.lookup().findSpecial( 2898 Listie.class, "<init>", methodType(void.class), Listie.class)); 2899 } catch (NoSuchMethodException ex) { } // OK 2900 // access to super and self methods via invokeSpecial: 2901 MethodHandle MH_super = Listie.lookup().findSpecial( 2902 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2903 MethodHandle MH_this = Listie.lookup().findSpecial( 2904 Listie.class, "toString" , methodType(String.class), Listie.class); 2905 MethodHandle MH_duper = Listie.lookup().findSpecial( 2906 Object.class, "toString" , methodType(String.class), Listie.class); 2907 assertEquals("[]", (String) MH_super.invokeExact(l)); 2908 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2909 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2910 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2911 String.class, "toString", methodType(String.class), Listie.class)); 2912 } catch (IllegalAccessException ex) { } // OK 2913 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2914 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2915 * } 2916 * 2917 * @param refc the class or interface from which the method is accessed 2918 * @param name the name of the method (which must not be "<init>") 2919 * @param type the type of the method, with the receiver argument omitted 2920 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2921 * @return the desired method handle 2922 * @throws NoSuchMethodException if the method does not exist 2923 * @throws IllegalAccessException if access checking fails, 2924 * or if the method is {@code static}, 2925 * or if the method's variable arity modifier bit 2926 * is set and {@code asVarargsCollector} fails 2927 * @throws NullPointerException if any argument is null 2928 */ 2929 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 2930 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 2931 checkSpecialCaller(specialCaller, refc); 2932 Lookup specialLookup = this.in(specialCaller); 2933 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 2934 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 2935 } 2936 2937 /** 2938 * Produces a method handle giving read access to a non-static field. 2939 * The type of the method handle will have a return type of the field's 2940 * value type. 2941 * The method handle's single argument will be the instance containing 2942 * the field. 2943 * Access checking is performed immediately on behalf of the lookup class. 2944 * @param refc the class or interface from which the method is accessed 2945 * @param name the field's name 2946 * @param type the field's type 2947 * @return a method handle which can load values from the field 2948 * @throws NoSuchFieldException if the field does not exist 2949 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2950 * @throws NullPointerException if any argument is null 2951 * @see #findVarHandle(Class, String, Class) 2952 */ 2953 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2954 MemberName field = resolveOrFail(REF_getField, refc, name, type); 2955 return getDirectField(REF_getField, refc, field); 2956 } 2957 2958 /** 2959 * Produces a method handle giving write access to a non-static field. 2960 * The type of the method handle will have a void return type. 2961 * The method handle will take two arguments, the instance containing 2962 * the field, and the value to be stored. 2963 * The second argument will be of the field's value type. 2964 * Access checking is performed immediately on behalf of the lookup class. 2965 * @param refc the class or interface from which the method is accessed 2966 * @param name the field's name 2967 * @param type the field's type 2968 * @return a method handle which can store values into the field 2969 * @throws NoSuchFieldException if the field does not exist 2970 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2971 * or {@code final} 2972 * @throws NullPointerException if any argument is null 2973 * @see #findVarHandle(Class, String, Class) 2974 */ 2975 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2976 MemberName field = resolveOrFail(REF_putField, refc, name, type); 2977 return getDirectField(REF_putField, refc, field); 2978 } 2979 2980 /** 2981 * Produces a VarHandle giving access to a non-static field {@code name} 2982 * of type {@code type} declared in a class of type {@code recv}. 2983 * The VarHandle's variable type is {@code type} and it has one 2984 * coordinate type, {@code recv}. 2985 * <p> 2986 * Access checking is performed immediately on behalf of the lookup 2987 * class. 2988 * <p> 2989 * Certain access modes of the returned VarHandle are unsupported under 2990 * the following conditions: 2991 * <ul> 2992 * <li>if the field is declared {@code final}, then the write, atomic 2993 * update, numeric atomic update, and bitwise atomic update access 2994 * modes are unsupported. 2995 * <li>if the field type is anything other than {@code byte}, 2996 * {@code short}, {@code char}, {@code int}, {@code long}, 2997 * {@code float}, or {@code double} then numeric atomic update 2998 * access modes are unsupported. 2999 * <li>if the field type is anything other than {@code boolean}, 3000 * {@code byte}, {@code short}, {@code char}, {@code int} or 3001 * {@code long} then bitwise atomic update access modes are 3002 * unsupported. 3003 * </ul> 3004 * <p> 3005 * If the field is declared {@code volatile} then the returned VarHandle 3006 * will override access to the field (effectively ignore the 3007 * {@code volatile} declaration) in accordance to its specified 3008 * access modes. 3009 * <p> 3010 * If the field type is {@code float} or {@code double} then numeric 3011 * and atomic update access modes compare values using their bitwise 3012 * representation (see {@link Float#floatToRawIntBits} and 3013 * {@link Double#doubleToRawLongBits}, respectively). 3014 * @apiNote 3015 * Bitwise comparison of {@code float} values or {@code double} values, 3016 * as performed by the numeric and atomic update access modes, differ 3017 * from the primitive {@code ==} operator and the {@link Float#equals} 3018 * and {@link Double#equals} methods, specifically with respect to 3019 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3020 * Care should be taken when performing a compare and set or a compare 3021 * and exchange operation with such values since the operation may 3022 * unexpectedly fail. 3023 * There are many possible NaN values that are considered to be 3024 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3025 * provided by Java can distinguish between them. Operation failure can 3026 * occur if the expected or witness value is a NaN value and it is 3027 * transformed (perhaps in a platform specific manner) into another NaN 3028 * value, and thus has a different bitwise representation (see 3029 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3030 * details). 3031 * The values {@code -0.0} and {@code +0.0} have different bitwise 3032 * representations but are considered equal when using the primitive 3033 * {@code ==} operator. Operation failure can occur if, for example, a 3034 * numeric algorithm computes an expected value to be say {@code -0.0} 3035 * and previously computed the witness value to be say {@code +0.0}. 3036 * @param recv the receiver class, of type {@code R}, that declares the 3037 * non-static field 3038 * @param name the field's name 3039 * @param type the field's type, of type {@code T} 3040 * @return a VarHandle giving access to non-static fields. 3041 * @throws NoSuchFieldException if the field does not exist 3042 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3043 * @throws NullPointerException if any argument is null 3044 * @since 9 3045 */ 3046 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3047 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3048 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3049 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3050 } 3051 3052 /** 3053 * Produces a method handle giving read access to a static field. 3054 * The type of the method handle will have a return type of the field's 3055 * value type. 3056 * The method handle will take no arguments. 3057 * Access checking is performed immediately on behalf of the lookup class. 3058 * <p> 3059 * If the returned method handle is invoked, the field's class will 3060 * be initialized, if it has not already been initialized. 3061 * @param refc the class or interface from which the method is accessed 3062 * @param name the field's name 3063 * @param type the field's type 3064 * @return a method handle which can load values from the field 3065 * @throws NoSuchFieldException if the field does not exist 3066 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3067 * @throws NullPointerException if any argument is null 3068 */ 3069 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3070 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3071 return getDirectField(REF_getStatic, refc, field); 3072 } 3073 3074 /** 3075 * Produces a method handle giving write access to a static field. 3076 * The type of the method handle will have a void return type. 3077 * The method handle will take a single 3078 * argument, of the field's value type, the value to be stored. 3079 * Access checking is performed immediately on behalf of the lookup class. 3080 * <p> 3081 * If the returned method handle is invoked, the field's class will 3082 * be initialized, if it has not already been initialized. 3083 * @param refc the class or interface from which the method is accessed 3084 * @param name the field's name 3085 * @param type the field's type 3086 * @return a method handle which can store values into the field 3087 * @throws NoSuchFieldException if the field does not exist 3088 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3089 * or is {@code final} 3090 * @throws NullPointerException if any argument is null 3091 */ 3092 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3093 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3094 return getDirectField(REF_putStatic, refc, field); 3095 } 3096 3097 /** 3098 * Produces a VarHandle giving access to a static field {@code name} of 3099 * type {@code type} declared in a class of type {@code decl}. 3100 * The VarHandle's variable type is {@code type} and it has no 3101 * coordinate types. 3102 * <p> 3103 * Access checking is performed immediately on behalf of the lookup 3104 * class. 3105 * <p> 3106 * If the returned VarHandle is operated on, the declaring class will be 3107 * initialized, if it has not already been initialized. 3108 * <p> 3109 * Certain access modes of the returned VarHandle are unsupported under 3110 * the following conditions: 3111 * <ul> 3112 * <li>if the field is declared {@code final}, then the write, atomic 3113 * update, numeric atomic update, and bitwise atomic update access 3114 * modes are unsupported. 3115 * <li>if the field type is anything other than {@code byte}, 3116 * {@code short}, {@code char}, {@code int}, {@code long}, 3117 * {@code float}, or {@code double}, then numeric atomic update 3118 * access modes are unsupported. 3119 * <li>if the field type is anything other than {@code boolean}, 3120 * {@code byte}, {@code short}, {@code char}, {@code int} or 3121 * {@code long} then bitwise atomic update access modes are 3122 * unsupported. 3123 * </ul> 3124 * <p> 3125 * If the field is declared {@code volatile} then the returned VarHandle 3126 * will override access to the field (effectively ignore the 3127 * {@code volatile} declaration) in accordance to its specified 3128 * access modes. 3129 * <p> 3130 * If the field type is {@code float} or {@code double} then numeric 3131 * and atomic update access modes compare values using their bitwise 3132 * representation (see {@link Float#floatToRawIntBits} and 3133 * {@link Double#doubleToRawLongBits}, respectively). 3134 * @apiNote 3135 * Bitwise comparison of {@code float} values or {@code double} values, 3136 * as performed by the numeric and atomic update access modes, differ 3137 * from the primitive {@code ==} operator and the {@link Float#equals} 3138 * and {@link Double#equals} methods, specifically with respect to 3139 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3140 * Care should be taken when performing a compare and set or a compare 3141 * and exchange operation with such values since the operation may 3142 * unexpectedly fail. 3143 * There are many possible NaN values that are considered to be 3144 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3145 * provided by Java can distinguish between them. Operation failure can 3146 * occur if the expected or witness value is a NaN value and it is 3147 * transformed (perhaps in a platform specific manner) into another NaN 3148 * value, and thus has a different bitwise representation (see 3149 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3150 * details). 3151 * The values {@code -0.0} and {@code +0.0} have different bitwise 3152 * representations but are considered equal when using the primitive 3153 * {@code ==} operator. Operation failure can occur if, for example, a 3154 * numeric algorithm computes an expected value to be say {@code -0.0} 3155 * and previously computed the witness value to be say {@code +0.0}. 3156 * @param decl the class that declares the static field 3157 * @param name the field's name 3158 * @param type the field's type, of type {@code T} 3159 * @return a VarHandle giving access to a static field 3160 * @throws NoSuchFieldException if the field does not exist 3161 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3162 * @throws NullPointerException if any argument is null 3163 * @since 9 3164 */ 3165 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3166 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3167 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3168 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3169 } 3170 3171 /** 3172 * Produces an early-bound method handle for a non-static method. 3173 * The receiver must have a supertype {@code defc} in which a method 3174 * of the given name and type is accessible to the lookup class. 3175 * The method and all its argument types must be accessible to the lookup object. 3176 * The type of the method handle will be that of the method, 3177 * without any insertion of an additional receiver parameter. 3178 * The given receiver will be bound into the method handle, 3179 * so that every call to the method handle will invoke the 3180 * requested method on the given receiver. 3181 * <p> 3182 * The returned method handle will have 3183 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3184 * the method's variable arity modifier bit ({@code 0x0080}) is set 3185 * <em>and</em> the trailing array argument is not the only argument. 3186 * (If the trailing array argument is the only argument, 3187 * the given receiver value will be bound to it.) 3188 * <p> 3189 * This is almost equivalent to the following code, with some differences noted below: 3190 * {@snippet lang="java" : 3191 import static java.lang.invoke.MethodHandles.*; 3192 import static java.lang.invoke.MethodType.*; 3193 ... 3194 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3195 MethodHandle mh1 = mh0.bindTo(receiver); 3196 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3197 return mh1; 3198 * } 3199 * where {@code defc} is either {@code receiver.getClass()} or a super 3200 * type of that class, in which the requested method is accessible 3201 * to the lookup class. 3202 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3203 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3204 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3205 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3206 * @param receiver the object from which the method is accessed 3207 * @param name the name of the method 3208 * @param type the type of the method, with the receiver argument omitted 3209 * @return the desired method handle 3210 * @throws NoSuchMethodException if the method does not exist 3211 * @throws IllegalAccessException if access checking fails 3212 * or if the method's variable arity modifier bit 3213 * is set and {@code asVarargsCollector} fails 3214 * @throws NullPointerException if any argument is null 3215 * @see MethodHandle#bindTo 3216 * @see #findVirtual 3217 */ 3218 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3219 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3220 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3221 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3222 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3223 throw new IllegalAccessException("The restricted defining class " + 3224 mh.type().leadingReferenceParameter().getName() + 3225 " is not assignable from receiver class " + 3226 receiver.getClass().getName()); 3227 } 3228 return mh.bindArgumentL(0, receiver).setVarargs(method); 3229 } 3230 3231 /** 3232 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3233 * to <i>m</i>, if the lookup class has permission. 3234 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3235 * If <i>m</i> is virtual, overriding is respected on every call. 3236 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3237 * The type of the method handle will be that of the method, 3238 * with the receiver type prepended (but only if it is non-static). 3239 * If the method's {@code accessible} flag is not set, 3240 * access checking is performed immediately on behalf of the lookup class. 3241 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3242 * <p> 3243 * The returned method handle will have 3244 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3245 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3246 * <p> 3247 * If <i>m</i> is static, and 3248 * if the returned method handle is invoked, the method's class will 3249 * be initialized, if it has not already been initialized. 3250 * @param m the reflected method 3251 * @return a method handle which can invoke the reflected method 3252 * @throws IllegalAccessException if access checking fails 3253 * or if the method's variable arity modifier bit 3254 * is set and {@code asVarargsCollector} fails 3255 * @throws NullPointerException if the argument is null 3256 */ 3257 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3258 if (m.getDeclaringClass() == MethodHandle.class) { 3259 MethodHandle mh = unreflectForMH(m); 3260 if (mh != null) return mh; 3261 } 3262 if (m.getDeclaringClass() == VarHandle.class) { 3263 MethodHandle mh = unreflectForVH(m); 3264 if (mh != null) return mh; 3265 } 3266 MemberName method = new MemberName(m); 3267 byte refKind = method.getReferenceKind(); 3268 if (refKind == REF_invokeSpecial) 3269 refKind = REF_invokeVirtual; 3270 assert(method.isMethod()); 3271 @SuppressWarnings("deprecation") 3272 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3273 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3274 } 3275 private MethodHandle unreflectForMH(Method m) { 3276 // these names require special lookups because they throw UnsupportedOperationException 3277 if (MemberName.isMethodHandleInvokeName(m.getName())) 3278 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3279 return null; 3280 } 3281 private MethodHandle unreflectForVH(Method m) { 3282 // these names require special lookups because they throw UnsupportedOperationException 3283 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3284 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3285 return null; 3286 } 3287 3288 /** 3289 * Produces a method handle for a reflected method. 3290 * It will bypass checks for overriding methods on the receiver, 3291 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3292 * instruction from within the explicitly specified {@code specialCaller}. 3293 * The type of the method handle will be that of the method, 3294 * with a suitably restricted receiver type prepended. 3295 * (The receiver type will be {@code specialCaller} or a subtype.) 3296 * If the method's {@code accessible} flag is not set, 3297 * access checking is performed immediately on behalf of the lookup class, 3298 * as if {@code invokespecial} instruction were being linked. 3299 * <p> 3300 * Before method resolution, 3301 * if the explicitly specified caller class is not identical with the 3302 * lookup class, or if this lookup object does not have 3303 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3304 * privileges, the access fails. 3305 * <p> 3306 * The returned method handle will have 3307 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3308 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3309 * @param m the reflected method 3310 * @param specialCaller the class nominally calling the method 3311 * @return a method handle which can invoke the reflected method 3312 * @throws IllegalAccessException if access checking fails, 3313 * or if the method is {@code static}, 3314 * or if the method's variable arity modifier bit 3315 * is set and {@code asVarargsCollector} fails 3316 * @throws NullPointerException if any argument is null 3317 */ 3318 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3319 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3320 Lookup specialLookup = this.in(specialCaller); 3321 MemberName method = new MemberName(m, true); 3322 assert(method.isMethod()); 3323 // ignore m.isAccessible: this is a new kind of access 3324 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3325 } 3326 3327 /** 3328 * Produces a method handle for a reflected constructor. 3329 * The type of the method handle will be that of the constructor, 3330 * with the return type changed to the declaring class. 3331 * The method handle will perform a {@code newInstance} operation, 3332 * creating a new instance of the constructor's class on the 3333 * arguments passed to the method handle. 3334 * <p> 3335 * If the constructor's {@code accessible} flag is not set, 3336 * access checking is performed immediately on behalf of the lookup class. 3337 * <p> 3338 * The returned method handle will have 3339 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3340 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3341 * <p> 3342 * If the returned method handle is invoked, the constructor's class will 3343 * be initialized, if it has not already been initialized. 3344 * @param c the reflected constructor 3345 * @return a method handle which can invoke the reflected constructor 3346 * @throws IllegalAccessException if access checking fails 3347 * or if the method's variable arity modifier bit 3348 * is set and {@code asVarargsCollector} fails 3349 * @throws NullPointerException if the argument is null 3350 */ 3351 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3352 MemberName ctor = new MemberName(c); 3353 assert(ctor.isConstructor()); 3354 @SuppressWarnings("deprecation") 3355 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3356 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor); 3357 } 3358 3359 /* 3360 * Produces a method handle that is capable of creating instances of the given class 3361 * and instantiated by the given constructor. 3362 * 3363 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3364 */ 3365 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3366 MemberName ctor = new MemberName(c); 3367 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3368 checkAccess(REF_newInvokeSpecial, decl, ctor); 3369 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3370 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3371 } 3372 3373 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3374 if (decl == ctor.getDeclaringClass()) 3375 return true; 3376 3377 Class<?> cl = decl; 3378 while ((cl = cl.getSuperclass()) != null) { 3379 if (cl == ctor.getDeclaringClass()) { 3380 return true; 3381 } 3382 } 3383 return false; 3384 } 3385 3386 /** 3387 * Produces a method handle giving read access to a reflected field. 3388 * The type of the method handle will have a return type of the field's 3389 * value type. 3390 * If the field is {@code static}, the method handle will take no arguments. 3391 * Otherwise, its single argument will be the instance containing 3392 * the field. 3393 * If the {@code Field} object's {@code accessible} flag is not set, 3394 * access checking is performed immediately on behalf of the lookup class. 3395 * <p> 3396 * If the field is static, and 3397 * if the returned method handle is invoked, the field's class will 3398 * be initialized, if it has not already been initialized. 3399 * @param f the reflected field 3400 * @return a method handle which can load values from the reflected field 3401 * @throws IllegalAccessException if access checking fails 3402 * @throws NullPointerException if the argument is null 3403 */ 3404 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3405 return unreflectField(f, false); 3406 } 3407 3408 /** 3409 * Produces a method handle giving write access to a reflected field. 3410 * The type of the method handle will have a void return type. 3411 * If the field is {@code static}, the method handle will take a single 3412 * argument, of the field's value type, the value to be stored. 3413 * Otherwise, the two arguments will be the instance containing 3414 * the field, and the value to be stored. 3415 * If the {@code Field} object's {@code accessible} flag is not set, 3416 * access checking is performed immediately on behalf of the lookup class. 3417 * <p> 3418 * If the field is {@code final}, write access will not be 3419 * allowed and access checking will fail, except under certain 3420 * narrow circumstances documented for {@link Field#set Field.set}. 3421 * A method handle is returned only if a corresponding call to 3422 * the {@code Field} object's {@code set} method could return 3423 * normally. In particular, fields which are both {@code static} 3424 * and {@code final} may never be set. 3425 * <p> 3426 * If the field is {@code static}, and 3427 * if the returned method handle is invoked, the field's class will 3428 * be initialized, if it has not already been initialized. 3429 * @param f the reflected field 3430 * @return a method handle which can store values into the reflected field 3431 * @throws IllegalAccessException if access checking fails, 3432 * or if the field is {@code final} and write access 3433 * is not enabled on the {@code Field} object 3434 * @throws NullPointerException if the argument is null 3435 */ 3436 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3437 return unreflectField(f, true); 3438 } 3439 3440 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3441 MemberName field = new MemberName(f, isSetter); 3442 if (isSetter && field.isFinal()) { 3443 if (field.isTrustedFinalField()) { 3444 String msg = field.isStatic() ? "static final field has no write access" 3445 : "final field has no write access"; 3446 throw field.makeAccessException(msg, this); 3447 } 3448 } 3449 assert(isSetter 3450 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3451 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3452 @SuppressWarnings("deprecation") 3453 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3454 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field); 3455 } 3456 3457 /** 3458 * Produces a VarHandle giving access to a reflected field {@code f} 3459 * of type {@code T} declared in a class of type {@code R}. 3460 * The VarHandle's variable type is {@code T}. 3461 * If the field is non-static the VarHandle has one coordinate type, 3462 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3463 * coordinate types. 3464 * <p> 3465 * Access checking is performed immediately on behalf of the lookup 3466 * class, regardless of the value of the field's {@code accessible} 3467 * flag. 3468 * <p> 3469 * If the field is static, and if the returned VarHandle is operated 3470 * on, the field's declaring class will be initialized, if it has not 3471 * already been initialized. 3472 * <p> 3473 * Certain access modes of the returned VarHandle are unsupported under 3474 * the following conditions: 3475 * <ul> 3476 * <li>if the field is declared {@code final}, then the write, atomic 3477 * update, numeric atomic update, and bitwise atomic update access 3478 * modes are unsupported. 3479 * <li>if the field type is anything other than {@code byte}, 3480 * {@code short}, {@code char}, {@code int}, {@code long}, 3481 * {@code float}, or {@code double} then numeric atomic update 3482 * access modes are unsupported. 3483 * <li>if the field type is anything other than {@code boolean}, 3484 * {@code byte}, {@code short}, {@code char}, {@code int} or 3485 * {@code long} then bitwise atomic update access modes are 3486 * unsupported. 3487 * </ul> 3488 * <p> 3489 * If the field is declared {@code volatile} then the returned VarHandle 3490 * will override access to the field (effectively ignore the 3491 * {@code volatile} declaration) in accordance to its specified 3492 * access modes. 3493 * <p> 3494 * If the field type is {@code float} or {@code double} then numeric 3495 * and atomic update access modes compare values using their bitwise 3496 * representation (see {@link Float#floatToRawIntBits} and 3497 * {@link Double#doubleToRawLongBits}, respectively). 3498 * @apiNote 3499 * Bitwise comparison of {@code float} values or {@code double} values, 3500 * as performed by the numeric and atomic update access modes, differ 3501 * from the primitive {@code ==} operator and the {@link Float#equals} 3502 * and {@link Double#equals} methods, specifically with respect to 3503 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3504 * Care should be taken when performing a compare and set or a compare 3505 * and exchange operation with such values since the operation may 3506 * unexpectedly fail. 3507 * There are many possible NaN values that are considered to be 3508 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3509 * provided by Java can distinguish between them. Operation failure can 3510 * occur if the expected or witness value is a NaN value and it is 3511 * transformed (perhaps in a platform specific manner) into another NaN 3512 * value, and thus has a different bitwise representation (see 3513 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3514 * details). 3515 * The values {@code -0.0} and {@code +0.0} have different bitwise 3516 * representations but are considered equal when using the primitive 3517 * {@code ==} operator. Operation failure can occur if, for example, a 3518 * numeric algorithm computes an expected value to be say {@code -0.0} 3519 * and previously computed the witness value to be say {@code +0.0}. 3520 * @param f the reflected field, with a field of type {@code T}, and 3521 * a declaring class of type {@code R} 3522 * @return a VarHandle giving access to non-static fields or a static 3523 * field 3524 * @throws IllegalAccessException if access checking fails 3525 * @throws NullPointerException if the argument is null 3526 * @since 9 3527 */ 3528 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3529 MemberName getField = new MemberName(f, false); 3530 MemberName putField = new MemberName(f, true); 3531 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(), 3532 f.getDeclaringClass(), getField, putField); 3533 } 3534 3535 /** 3536 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3537 * created by this lookup object or a similar one. 3538 * Security and access checks are performed to ensure that this lookup object 3539 * is capable of reproducing the target method handle. 3540 * This means that the cracking may fail if target is a direct method handle 3541 * but was created by an unrelated lookup object. 3542 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3543 * and was created by a lookup object for a different class. 3544 * @param target a direct method handle to crack into symbolic reference components 3545 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3546 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3547 * @throws NullPointerException if the target is {@code null} 3548 * @see MethodHandleInfo 3549 * @since 1.8 3550 */ 3551 public MethodHandleInfo revealDirect(MethodHandle target) { 3552 if (!target.isCrackable()) { 3553 throw newIllegalArgumentException("not a direct method handle"); 3554 } 3555 MemberName member = target.internalMemberName(); 3556 Class<?> defc = member.getDeclaringClass(); 3557 byte refKind = member.getReferenceKind(); 3558 assert(MethodHandleNatives.refKindIsValid(refKind)); 3559 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3560 // Devirtualized method invocation is usually formally virtual. 3561 // To avoid creating extra MemberName objects for this common case, 3562 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3563 refKind = REF_invokeVirtual; 3564 if (refKind == REF_invokeVirtual && defc.isInterface()) 3565 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3566 refKind = REF_invokeInterface; 3567 // Check member access before cracking. 3568 try { 3569 checkAccess(refKind, defc, member); 3570 } catch (IllegalAccessException ex) { 3571 throw new IllegalArgumentException(ex); 3572 } 3573 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3574 Class<?> callerClass = target.internalCallerClass(); 3575 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3576 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3577 } 3578 // Produce the handle to the results. 3579 return new InfoFromMemberName(this, member, refKind); 3580 } 3581 3582 //--- Helper methods, all package-private. 3583 3584 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3585 checkSymbolicClass(refc); // do this before attempting to resolve 3586 Objects.requireNonNull(name); 3587 Objects.requireNonNull(type); 3588 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3589 NoSuchFieldException.class); 3590 } 3591 3592 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3593 checkSymbolicClass(refc); // do this before attempting to resolve 3594 Objects.requireNonNull(type); 3595 checkMethodName(refKind, name); // implicit null-check of name 3596 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3597 NoSuchMethodException.class); 3598 } 3599 3600 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3601 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3602 Objects.requireNonNull(member.getName()); 3603 Objects.requireNonNull(member.getType()); 3604 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3605 ReflectiveOperationException.class); 3606 } 3607 3608 MemberName resolveOrNull(byte refKind, MemberName member) { 3609 // do this before attempting to resolve 3610 if (!isClassAccessible(member.getDeclaringClass())) { 3611 return null; 3612 } 3613 Objects.requireNonNull(member.getName()); 3614 Objects.requireNonNull(member.getType()); 3615 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3616 } 3617 3618 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3619 // do this before attempting to resolve 3620 if (!isClassAccessible(refc)) { 3621 return null; 3622 } 3623 Objects.requireNonNull(type); 3624 // implicit null-check of name 3625 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3626 return null; 3627 } 3628 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3629 } 3630 3631 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3632 if (!isClassAccessible(refc)) { 3633 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3634 } 3635 } 3636 3637 boolean isClassAccessible(Class<?> refc) { 3638 Objects.requireNonNull(refc); 3639 Class<?> caller = lookupClassOrNull(); 3640 Class<?> type = refc; 3641 while (type.isArray()) { 3642 type = type.getComponentType(); 3643 } 3644 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3645 } 3646 3647 /** Check name for an illegal leading "<" character. */ 3648 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3649 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3650 throw new NoSuchMethodException("illegal method name: "+name); 3651 } 3652 3653 /** 3654 * Find my trustable caller class if m is a caller sensitive method. 3655 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3656 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3657 */ 3658 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3659 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3660 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3661 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3662 } 3663 return this; 3664 } 3665 3666 /** 3667 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3668 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3669 * 3670 * @deprecated This method was originally designed to test {@code PRIVATE} access 3671 * that implies full privilege access but {@code MODULE} access has since become 3672 * independent of {@code PRIVATE} access. It is recommended to call 3673 * {@link #hasFullPrivilegeAccess()} instead. 3674 * @since 9 3675 */ 3676 @Deprecated(since="14") 3677 public boolean hasPrivateAccess() { 3678 return hasFullPrivilegeAccess(); 3679 } 3680 3681 /** 3682 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3683 * i.e. {@code PRIVATE} and {@code MODULE} access. 3684 * A {@code Lookup} object must have full privilege access in order to 3685 * access all members that are allowed to the 3686 * {@linkplain #lookupClass() lookup class}. 3687 * 3688 * @return {@code true} if this lookup has full privilege access. 3689 * @since 14 3690 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3691 */ 3692 public boolean hasFullPrivilegeAccess() { 3693 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3694 } 3695 3696 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3697 boolean wantStatic = (refKind == REF_invokeStatic); 3698 String message; 3699 if (m.isConstructor()) 3700 message = "expected a method, not a constructor"; 3701 else if (!m.isMethod()) 3702 message = "expected a method"; 3703 else if (wantStatic != m.isStatic()) 3704 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3705 else 3706 { checkAccess(refKind, refc, m); return; } 3707 throw m.makeAccessException(message, this); 3708 } 3709 3710 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3711 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3712 String message; 3713 if (wantStatic != m.isStatic()) 3714 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3715 else 3716 { checkAccess(refKind, refc, m); return; } 3717 throw m.makeAccessException(message, this); 3718 } 3719 3720 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3721 return Modifier.isProtected(m.getModifiers()) && 3722 refKind == REF_invokeVirtual && 3723 m.getDeclaringClass() == Object.class && 3724 m.getName().equals("clone") && 3725 refc.isArray(); 3726 } 3727 3728 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3729 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3730 assert(m.referenceKindIsConsistentWith(refKind) && 3731 MethodHandleNatives.refKindIsValid(refKind) && 3732 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3733 int allowedModes = this.allowedModes; 3734 if (allowedModes == TRUSTED) return; 3735 int mods = m.getModifiers(); 3736 if (isArrayClone(refKind, refc, m)) { 3737 // The JVM does this hack also. 3738 // (See ClassVerifier::verify_invoke_instructions 3739 // and LinkResolver::check_method_accessability.) 3740 // Because the JVM does not allow separate methods on array types, 3741 // there is no separate method for int[].clone. 3742 // All arrays simply inherit Object.clone. 3743 // But for access checking logic, we make Object.clone 3744 // (normally protected) appear to be public. 3745 // Later on, when the DirectMethodHandle is created, 3746 // its leading argument will be restricted to the 3747 // requested array type. 3748 // N.B. The return type is not adjusted, because 3749 // that is *not* the bytecode behavior. 3750 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3751 } 3752 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3753 // cannot "new" a protected ctor in a different package 3754 mods ^= Modifier.PROTECTED; 3755 } 3756 if (Modifier.isFinal(mods) && 3757 MethodHandleNatives.refKindIsSetter(refKind)) 3758 throw m.makeAccessException("unexpected set of a final field", this); 3759 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3760 if ((requestedModes & allowedModes) != 0) { 3761 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3762 mods, lookupClass(), previousLookupClass(), allowedModes)) 3763 return; 3764 } else { 3765 // Protected members can also be checked as if they were package-private. 3766 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3767 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3768 return; 3769 } 3770 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3771 } 3772 3773 String accessFailedMessage(Class<?> refc, MemberName m) { 3774 Class<?> defc = m.getDeclaringClass(); 3775 int mods = m.getModifiers(); 3776 // check the class first: 3777 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3778 (defc == refc || 3779 Modifier.isPublic(refc.getModifiers()))); 3780 if (!classOK && (allowedModes & PACKAGE) != 0) { 3781 // ignore previous lookup class to check if default package access 3782 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3783 (defc == refc || 3784 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3785 } 3786 if (!classOK) 3787 return "class is not public"; 3788 if (Modifier.isPublic(mods)) 3789 return "access to public member failed"; // (how?, module not readable?) 3790 if (Modifier.isPrivate(mods)) 3791 return "member is private"; 3792 if (Modifier.isProtected(mods)) 3793 return "member is protected"; 3794 return "member is private to package"; 3795 } 3796 3797 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3798 int allowedModes = this.allowedModes; 3799 if (allowedModes == TRUSTED) return; 3800 if ((lookupModes() & PRIVATE) == 0 3801 || (specialCaller != lookupClass() 3802 // ensure non-abstract methods in superinterfaces can be special-invoked 3803 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3804 throw new MemberName(specialCaller). 3805 makeAccessException("no private access for invokespecial", this); 3806 } 3807 3808 private boolean restrictProtectedReceiver(MemberName method) { 3809 // The accessing class only has the right to use a protected member 3810 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3811 if (!method.isProtected() || method.isStatic() 3812 || allowedModes == TRUSTED 3813 || method.getDeclaringClass() == lookupClass() 3814 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3815 return false; 3816 return true; 3817 } 3818 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3819 assert(!method.isStatic()); 3820 // receiver type of mh is too wide; narrow to caller 3821 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3822 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3823 } 3824 MethodType rawType = mh.type(); 3825 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3826 MethodType narrowType = rawType.changeParameterType(0, caller); 3827 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3828 assert(mh.viewAsTypeChecks(narrowType, true)); 3829 return mh.copyWith(narrowType, mh.form); 3830 } 3831 3832 /** Check access and get the requested method. */ 3833 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3834 final boolean doRestrict = true; 3835 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup); 3836 } 3837 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3838 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3839 final boolean doRestrict = false; 3840 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup); 3841 } 3842 /** Common code for all methods; do not call directly except from immediately above. */ 3843 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3844 boolean doRestrict, 3845 Lookup boundCaller) throws IllegalAccessException { 3846 checkMethod(refKind, refc, method); 3847 assert(!method.isMethodHandleInvoke()); 3848 if (refKind == REF_invokeSpecial && 3849 refc != lookupClass() && 3850 !refc.isInterface() && !lookupClass().isInterface() && 3851 refc != lookupClass().getSuperclass() && 3852 refc.isAssignableFrom(lookupClass())) { 3853 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 3854 3855 // Per JVMS 6.5, desc. of invokespecial instruction: 3856 // If the method is in a superclass of the LC, 3857 // and if our original search was above LC.super, 3858 // repeat the search (symbolic lookup) from LC.super 3859 // and continue with the direct superclass of that class, 3860 // and so forth, until a match is found or no further superclasses exist. 3861 // FIXME: MemberName.resolve should handle this instead. 3862 Class<?> refcAsSuper = lookupClass(); 3863 MemberName m2; 3864 do { 3865 refcAsSuper = refcAsSuper.getSuperclass(); 3866 m2 = new MemberName(refcAsSuper, 3867 method.getName(), 3868 method.getMethodType(), 3869 REF_invokeSpecial); 3870 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 3871 } while (m2 == null && // no method is found yet 3872 refc != refcAsSuper); // search up to refc 3873 if (m2 == null) throw new InternalError(method.toString()); 3874 method = m2; 3875 refc = refcAsSuper; 3876 // redo basic checks 3877 checkMethod(refKind, refc, method); 3878 } 3879 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 3880 MethodHandle mh = dmh; 3881 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 3882 if ((doRestrict && refKind == REF_invokeSpecial) || 3883 (MethodHandleNatives.refKindHasReceiver(refKind) && 3884 restrictProtectedReceiver(method) && 3885 // All arrays simply inherit the protected Object.clone method. 3886 // The leading argument is already restricted to the requested 3887 // array type (not the lookup class). 3888 !isArrayClone(refKind, refc, method))) { 3889 mh = restrictReceiver(method, dmh, lookupClass()); 3890 } 3891 mh = maybeBindCaller(method, mh, boundCaller); 3892 mh = mh.setVarargs(method); 3893 return mh; 3894 } 3895 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 3896 throws IllegalAccessException { 3897 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 3898 return mh; 3899 3900 // boundCaller must have full privilege access. 3901 // It should have been checked by findBoundCallerLookup. Safe to check this again. 3902 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 3903 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3904 3905 assert boundCaller.hasFullPrivilegeAccess(); 3906 3907 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 3908 // Note: caller will apply varargs after this step happens. 3909 return cbmh; 3910 } 3911 3912 /** Check access and get the requested field. */ 3913 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3914 return getDirectFieldCommon(refKind, refc, field); 3915 } 3916 /** Common code for all fields; do not call directly except from immediately above. */ 3917 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3918 checkField(refKind, refc, field); 3919 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 3920 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 3921 restrictProtectedReceiver(field)); 3922 if (doRestrict) 3923 return restrictReceiver(field, dmh, lookupClass()); 3924 return dmh; 3925 } 3926 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 3927 Class<?> refc, MemberName getField, MemberName putField) 3928 throws IllegalAccessException { 3929 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField); 3930 } 3931 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 3932 Class<?> refc, MemberName getField, 3933 MemberName putField) throws IllegalAccessException { 3934 assert getField.isStatic() == putField.isStatic(); 3935 assert getField.isGetter() && putField.isSetter(); 3936 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 3937 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 3938 3939 checkField(getRefKind, refc, getField); 3940 3941 if (!putField.isFinal()) { 3942 // A VarHandle does not support updates to final fields, any 3943 // such VarHandle to a final field will be read-only and 3944 // therefore the following write-based accessibility checks are 3945 // only required for non-final fields 3946 checkField(putRefKind, refc, putField); 3947 } 3948 3949 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 3950 restrictProtectedReceiver(getField)); 3951 if (doRestrict) { 3952 assert !getField.isStatic(); 3953 // receiver type of VarHandle is too wide; narrow to caller 3954 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 3955 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 3956 } 3957 refc = lookupClass(); 3958 } 3959 return VarHandles.makeFieldHandle(getField, refc, 3960 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 3961 } 3962 /** Check access and get the requested constructor. */ 3963 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3964 return getDirectConstructorCommon(refc, ctor); 3965 } 3966 /** Common code for all constructors; do not call directly except from immediately above. */ 3967 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3968 assert(ctor.isConstructor()); 3969 checkAccess(REF_newInvokeSpecial, refc, ctor); 3970 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3971 return DirectMethodHandle.make(ctor).setVarargs(ctor); 3972 } 3973 3974 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 3975 */ 3976 /*non-public*/ 3977 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 3978 throws ReflectiveOperationException { 3979 if (!(type instanceof Class || type instanceof MethodType)) 3980 throw new InternalError("unresolved MemberName"); 3981 MemberName member = new MemberName(refKind, defc, name, type); 3982 MethodHandle mh = LOOKASIDE_TABLE.get(member); 3983 if (mh != null) { 3984 checkSymbolicClass(defc); 3985 return mh; 3986 } 3987 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 3988 // Treat MethodHandle.invoke and invokeExact specially. 3989 mh = findVirtualForMH(member.getName(), member.getMethodType()); 3990 if (mh != null) { 3991 return mh; 3992 } 3993 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 3994 // Treat signature-polymorphic methods on VarHandle specially. 3995 mh = findVirtualForVH(member.getName(), member.getMethodType()); 3996 if (mh != null) { 3997 return mh; 3998 } 3999 } 4000 MemberName resolved = resolveOrFail(refKind, member); 4001 mh = getDirectMethodForConstant(refKind, defc, resolved); 4002 if (mh instanceof DirectMethodHandle dmh 4003 && canBeCached(refKind, defc, resolved)) { 4004 MemberName key = mh.internalMemberName(); 4005 if (key != null) { 4006 key = key.asNormalOriginal(); 4007 } 4008 if (member.equals(key)) { // better safe than sorry 4009 LOOKASIDE_TABLE.put(key, dmh); 4010 } 4011 } 4012 return mh; 4013 } 4014 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4015 if (refKind == REF_invokeSpecial) { 4016 return false; 4017 } 4018 if (!Modifier.isPublic(defc.getModifiers()) || 4019 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4020 !member.isPublic() || 4021 member.isCallerSensitive()) { 4022 return false; 4023 } 4024 ClassLoader loader = defc.getClassLoader(); 4025 if (loader != null) { 4026 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4027 boolean found = false; 4028 while (sysl != null) { 4029 if (loader == sysl) { found = true; break; } 4030 sysl = sysl.getParent(); 4031 } 4032 if (!found) { 4033 return false; 4034 } 4035 } 4036 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4037 new MemberName(refKind, defc, member.getName(), member.getType())); 4038 if (resolved2 == null) { 4039 return false; 4040 } 4041 return true; 4042 } 4043 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4044 throws ReflectiveOperationException { 4045 if (MethodHandleNatives.refKindIsField(refKind)) { 4046 return getDirectField(refKind, defc, member); 4047 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4048 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member)); 4049 } else if (refKind == REF_newInvokeSpecial) { 4050 return getDirectConstructor(defc, member); 4051 } 4052 // oops 4053 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4054 } 4055 4056 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4057 } 4058 4059 /** 4060 * Produces a method handle constructing arrays of a desired type, 4061 * as if by the {@code anewarray} bytecode. 4062 * The return type of the method handle will be the array type. 4063 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4064 * 4065 * <p> If the returned method handle is invoked with a negative 4066 * array size, a {@code NegativeArraySizeException} will be thrown. 4067 * 4068 * @param arrayClass an array type 4069 * @return a method handle which can create arrays of the given type 4070 * @throws NullPointerException if the argument is {@code null} 4071 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4072 * @see java.lang.reflect.Array#newInstance(Class, int) 4073 * @jvms 6.5 {@code anewarray} Instruction 4074 * @since 9 4075 */ 4076 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4077 if (!arrayClass.isArray()) { 4078 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4079 } 4080 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4081 bindTo(arrayClass.getComponentType()); 4082 return ani.asType(ani.type().changeReturnType(arrayClass)); 4083 } 4084 4085 /** 4086 * Produces a method handle returning the length of an array, 4087 * as if by the {@code arraylength} bytecode. 4088 * The type of the method handle will have {@code int} as return type, 4089 * and its sole argument will be the array type. 4090 * 4091 * <p> If the returned method handle is invoked with a {@code null} 4092 * array reference, a {@code NullPointerException} will be thrown. 4093 * 4094 * @param arrayClass an array type 4095 * @return a method handle which can retrieve the length of an array of the given array type 4096 * @throws NullPointerException if the argument is {@code null} 4097 * @throws IllegalArgumentException if arrayClass is not an array type 4098 * @jvms 6.5 {@code arraylength} Instruction 4099 * @since 9 4100 */ 4101 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4102 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4103 } 4104 4105 /** 4106 * Produces a method handle giving read access to elements of an array, 4107 * as if by the {@code aaload} bytecode. 4108 * The type of the method handle will have a return type of the array's 4109 * element type. Its first argument will be the array type, 4110 * and the second will be {@code int}. 4111 * 4112 * <p> When the returned method handle is invoked, 4113 * the array reference and array index are checked. 4114 * A {@code NullPointerException} will be thrown if the array reference 4115 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4116 * thrown if the index is negative or if it is greater than or equal to 4117 * the length of the array. 4118 * 4119 * @param arrayClass an array type 4120 * @return a method handle which can load values from the given array type 4121 * @throws NullPointerException if the argument is null 4122 * @throws IllegalArgumentException if arrayClass is not an array type 4123 * @jvms 6.5 {@code aaload} Instruction 4124 */ 4125 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4126 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4127 } 4128 4129 /** 4130 * Produces a method handle giving write access to elements of an array, 4131 * as if by the {@code astore} bytecode. 4132 * The type of the method handle will have a void return type. 4133 * Its last argument will be the array's element type. 4134 * The first and second arguments will be the array type and int. 4135 * 4136 * <p> When the returned method handle is invoked, 4137 * the array reference and array index are checked. 4138 * A {@code NullPointerException} will be thrown if the array reference 4139 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4140 * thrown if the index is negative or if it is greater than or equal to 4141 * the length of the array. 4142 * 4143 * @param arrayClass the class of an array 4144 * @return a method handle which can store values into the array type 4145 * @throws NullPointerException if the argument is null 4146 * @throws IllegalArgumentException if arrayClass is not an array type 4147 * @jvms 6.5 {@code aastore} Instruction 4148 */ 4149 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4150 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4151 } 4152 4153 /** 4154 * Produces a VarHandle giving access to elements of an array of type 4155 * {@code arrayClass}. The VarHandle's variable type is the component type 4156 * of {@code arrayClass} and the list of coordinate types is 4157 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4158 * corresponds to an argument that is an index into an array. 4159 * <p> 4160 * Certain access modes of the returned VarHandle are unsupported under 4161 * the following conditions: 4162 * <ul> 4163 * <li>if the component type is anything other than {@code byte}, 4164 * {@code short}, {@code char}, {@code int}, {@code long}, 4165 * {@code float}, or {@code double} then numeric atomic update access 4166 * modes are unsupported. 4167 * <li>if the component type is anything other than {@code boolean}, 4168 * {@code byte}, {@code short}, {@code char}, {@code int} or 4169 * {@code long} then bitwise atomic update access modes are 4170 * unsupported. 4171 * </ul> 4172 * <p> 4173 * If the component type is {@code float} or {@code double} then numeric 4174 * and atomic update access modes compare values using their bitwise 4175 * representation (see {@link Float#floatToRawIntBits} and 4176 * {@link Double#doubleToRawLongBits}, respectively). 4177 * 4178 * <p> When the returned {@code VarHandle} is invoked, 4179 * the array reference and array index are checked. 4180 * A {@code NullPointerException} will be thrown if the array reference 4181 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4182 * thrown if the index is negative or if it is greater than or equal to 4183 * the length of the array. 4184 * 4185 * @apiNote 4186 * Bitwise comparison of {@code float} values or {@code double} values, 4187 * as performed by the numeric and atomic update access modes, differ 4188 * from the primitive {@code ==} operator and the {@link Float#equals} 4189 * and {@link Double#equals} methods, specifically with respect to 4190 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4191 * Care should be taken when performing a compare and set or a compare 4192 * and exchange operation with such values since the operation may 4193 * unexpectedly fail. 4194 * There are many possible NaN values that are considered to be 4195 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4196 * provided by Java can distinguish between them. Operation failure can 4197 * occur if the expected or witness value is a NaN value and it is 4198 * transformed (perhaps in a platform specific manner) into another NaN 4199 * value, and thus has a different bitwise representation (see 4200 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4201 * details). 4202 * The values {@code -0.0} and {@code +0.0} have different bitwise 4203 * representations but are considered equal when using the primitive 4204 * {@code ==} operator. Operation failure can occur if, for example, a 4205 * numeric algorithm computes an expected value to be say {@code -0.0} 4206 * and previously computed the witness value to be say {@code +0.0}. 4207 * @param arrayClass the class of an array, of type {@code T[]} 4208 * @return a VarHandle giving access to elements of an array 4209 * @throws NullPointerException if the arrayClass is null 4210 * @throws IllegalArgumentException if arrayClass is not an array type 4211 * @since 9 4212 */ 4213 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4214 return VarHandles.makeArrayElementHandle(arrayClass); 4215 } 4216 4217 /** 4218 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4219 * viewed as if it were a different primitive array type, such as 4220 * {@code int[]} or {@code long[]}. 4221 * The VarHandle's variable type is the component type of 4222 * {@code viewArrayClass} and the list of coordinate types is 4223 * {@code (byte[], int)}, where the {@code int} coordinate type 4224 * corresponds to an argument that is an index into a {@code byte[]} array. 4225 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4226 * array, composing bytes to or from a value of the component type of 4227 * {@code viewArrayClass} according to the given endianness. 4228 * <p> 4229 * The supported component types (variables types) are {@code short}, 4230 * {@code char}, {@code int}, {@code long}, {@code float} and 4231 * {@code double}. 4232 * <p> 4233 * Access of bytes at a given index will result in an 4234 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4235 * or greater than the {@code byte[]} array length minus the size (in bytes) 4236 * of {@code T}. 4237 * <p> 4238 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4239 * access modes are supported by the returned var handle. For all other access modes, an 4240 * {@link UnsupportedOperationException} will be thrown. 4241 * 4242 * @apiNote if access modes other than plain access are required, clients should 4243 * consider using off-heap memory through 4244 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4245 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4246 * or memory segments backed by a 4247 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4248 * for which stronger alignment guarantees can be made. 4249 * 4250 * @param viewArrayClass the view array class, with a component type of 4251 * type {@code T} 4252 * @param byteOrder the endianness of the view array elements, as 4253 * stored in the underlying {@code byte} array 4254 * @return a VarHandle giving access to elements of a {@code byte[]} array 4255 * viewed as if elements corresponding to the components type of the view 4256 * array class 4257 * @throws NullPointerException if viewArrayClass or byteOrder is null 4258 * @throws IllegalArgumentException if viewArrayClass is not an array type 4259 * @throws UnsupportedOperationException if the component type of 4260 * viewArrayClass is not supported as a variable type 4261 * @since 9 4262 */ 4263 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4264 ByteOrder byteOrder) throws IllegalArgumentException { 4265 Objects.requireNonNull(byteOrder); 4266 return VarHandles.byteArrayViewHandle(viewArrayClass, 4267 byteOrder == ByteOrder.BIG_ENDIAN); 4268 } 4269 4270 /** 4271 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4272 * viewed as if it were an array of elements of a different primitive 4273 * component type to that of {@code byte}, such as {@code int[]} or 4274 * {@code long[]}. 4275 * The VarHandle's variable type is the component type of 4276 * {@code viewArrayClass} and the list of coordinate types is 4277 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4278 * corresponds to an argument that is an index into a {@code byte[]} array. 4279 * The returned VarHandle accesses bytes at an index in a 4280 * {@code ByteBuffer}, composing bytes to or from a value of the component 4281 * type of {@code viewArrayClass} according to the given endianness. 4282 * <p> 4283 * The supported component types (variables types) are {@code short}, 4284 * {@code char}, {@code int}, {@code long}, {@code float} and 4285 * {@code double}. 4286 * <p> 4287 * Access will result in a {@code ReadOnlyBufferException} for anything 4288 * other than the read access modes if the {@code ByteBuffer} is read-only. 4289 * <p> 4290 * Access of bytes at a given index will result in an 4291 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4292 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4293 * {@code T}. 4294 * <p> 4295 * For heap byte buffers, access is always unaligned. As a result, only the plain 4296 * {@linkplain VarHandle.AccessMode#GET get} 4297 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4298 * returned var handle. For all other access modes, an {@link IllegalStateException} 4299 * will be thrown. 4300 * <p> 4301 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4302 * with respect to the underlying memory address, {@code A} say, associated 4303 * with the {@code ByteBuffer} and index. 4304 * If access is misaligned then access for anything other than the 4305 * {@code get} and {@code set} access modes will result in an 4306 * {@code IllegalStateException}. In such cases atomic access is only 4307 * guaranteed with respect to the largest power of two that divides the GCD 4308 * of {@code A} and the size (in bytes) of {@code T}. 4309 * If access is aligned then following access modes are supported and are 4310 * guaranteed to support atomic access: 4311 * <ul> 4312 * <li>read write access modes for all {@code T}, with the exception of 4313 * access modes {@code get} and {@code set} for {@code long} and 4314 * {@code double} on 32-bit platforms. 4315 * <li>atomic update access modes for {@code int}, {@code long}, 4316 * {@code float} or {@code double}. 4317 * (Future major platform releases of the JDK may support additional 4318 * types for certain currently unsupported access modes.) 4319 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4320 * (Future major platform releases of the JDK may support additional 4321 * numeric types for certain currently unsupported access modes.) 4322 * <li>bitwise 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 * </ul> 4326 * <p> 4327 * Misaligned access, and therefore atomicity guarantees, may be determined 4328 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4329 * {@code index}, {@code T} and its corresponding boxed type, 4330 * {@code T_BOX}, as follows: 4331 * <pre>{@code 4332 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4333 * ByteBuffer bb = ... 4334 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4335 * boolean isMisaligned = misalignedAtIndex != 0; 4336 * }</pre> 4337 * <p> 4338 * If the variable type is {@code float} or {@code double} then atomic 4339 * update access modes compare values using their bitwise representation 4340 * (see {@link Float#floatToRawIntBits} and 4341 * {@link Double#doubleToRawLongBits}, respectively). 4342 * @param viewArrayClass the view array class, with a component type of 4343 * type {@code T} 4344 * @param byteOrder the endianness of the view array elements, as 4345 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4346 * endianness of a {@code ByteBuffer}) 4347 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4348 * viewed as if elements corresponding to the components type of the view 4349 * array class 4350 * @throws NullPointerException if viewArrayClass or byteOrder is null 4351 * @throws IllegalArgumentException if viewArrayClass is not an array type 4352 * @throws UnsupportedOperationException if the component type of 4353 * viewArrayClass is not supported as a variable type 4354 * @since 9 4355 */ 4356 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4357 ByteOrder byteOrder) throws IllegalArgumentException { 4358 Objects.requireNonNull(byteOrder); 4359 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4360 byteOrder == ByteOrder.BIG_ENDIAN); 4361 } 4362 4363 4364 //--- method handle invocation (reflective style) 4365 4366 /** 4367 * Produces a method handle which will invoke any method handle of the 4368 * given {@code type}, with a given number of trailing arguments replaced by 4369 * a single trailing {@code Object[]} array. 4370 * The resulting invoker will be a method handle with the following 4371 * arguments: 4372 * <ul> 4373 * <li>a single {@code MethodHandle} target 4374 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4375 * <li>an {@code Object[]} array containing trailing arguments 4376 * </ul> 4377 * <p> 4378 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4379 * the indicated {@code type}. 4380 * That is, if the target is exactly of the given {@code type}, it will behave 4381 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4382 * is used to convert the target to the required {@code type}. 4383 * <p> 4384 * The type of the returned invoker will not be the given {@code type}, but rather 4385 * will have all parameters except the first {@code leadingArgCount} 4386 * replaced by a single array of type {@code Object[]}, which will be 4387 * the final parameter. 4388 * <p> 4389 * Before invoking its target, the invoker will spread the final array, apply 4390 * reference casts as necessary, and unbox and widen primitive arguments. 4391 * If, when the invoker is called, the supplied array argument does 4392 * not have the correct number of elements, the invoker will throw 4393 * an {@link IllegalArgumentException} instead of invoking the target. 4394 * <p> 4395 * This method is equivalent to the following code (though it may be more efficient): 4396 * {@snippet lang="java" : 4397 MethodHandle invoker = MethodHandles.invoker(type); 4398 int spreadArgCount = type.parameterCount() - leadingArgCount; 4399 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4400 return invoker; 4401 * } 4402 * This method throws no reflective exceptions. 4403 * @param type the desired target type 4404 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4405 * @return a method handle suitable for invoking any method handle of the given type 4406 * @throws NullPointerException if {@code type} is null 4407 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4408 * the range from 0 to {@code type.parameterCount()} inclusive, 4409 * or if the resulting method handle's type would have 4410 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4411 */ 4412 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4413 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4414 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4415 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4416 return type.invokers().spreadInvoker(leadingArgCount); 4417 } 4418 4419 /** 4420 * Produces a special <em>invoker method handle</em> which can be used to 4421 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4422 * The resulting invoker will have a type which is 4423 * exactly equal to the desired type, except that it will accept 4424 * an additional leading argument of type {@code MethodHandle}. 4425 * <p> 4426 * This method is equivalent to the following code (though it may be more efficient): 4427 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4428 * 4429 * <p style="font-size:smaller;"> 4430 * <em>Discussion:</em> 4431 * Invoker method handles can be useful when working with variable method handles 4432 * of unknown types. 4433 * For example, to emulate an {@code invokeExact} call to a variable method 4434 * handle {@code M}, extract its type {@code T}, 4435 * look up the invoker method {@code X} for {@code T}, 4436 * and call the invoker method, as {@code X.invoke(T, A...)}. 4437 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4438 * is unknown.) 4439 * If spreading, collecting, or other argument transformations are required, 4440 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4441 * method handle values, as long as they are compatible with the type of {@code X}. 4442 * <p style="font-size:smaller;"> 4443 * <em>(Note: The invoker method is not available via the Core Reflection API. 4444 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4445 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4446 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4447 * <p> 4448 * This method throws no reflective exceptions. 4449 * @param type the desired target type 4450 * @return a method handle suitable for invoking any method handle of the given type 4451 * @throws IllegalArgumentException if the resulting method handle's type would have 4452 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4453 */ 4454 public static MethodHandle exactInvoker(MethodType type) { 4455 return type.invokers().exactInvoker(); 4456 } 4457 4458 /** 4459 * Produces a special <em>invoker method handle</em> which can be used to 4460 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4461 * The resulting invoker will have a type which is 4462 * exactly equal to the desired type, except that it will accept 4463 * an additional leading argument of type {@code MethodHandle}. 4464 * <p> 4465 * Before invoking its target, if the target differs from the expected type, 4466 * the invoker will apply reference casts as 4467 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4468 * Similarly, the return value will be converted as necessary. 4469 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4470 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4471 * <p> 4472 * This method is equivalent to the following code (though it may be more efficient): 4473 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4474 * <p style="font-size:smaller;"> 4475 * <em>Discussion:</em> 4476 * A {@linkplain MethodType#genericMethodType general method type} is one which 4477 * mentions only {@code Object} arguments and return values. 4478 * An invoker for such a type is capable of calling any method handle 4479 * of the same arity as the general type. 4480 * <p style="font-size:smaller;"> 4481 * <em>(Note: The invoker method is not available via the Core Reflection API. 4482 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4483 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4484 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4485 * <p> 4486 * This method throws no reflective exceptions. 4487 * @param type the desired target type 4488 * @return a method handle suitable for invoking any method handle convertible to the given type 4489 * @throws IllegalArgumentException if the resulting method handle's type would have 4490 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4491 */ 4492 public static MethodHandle invoker(MethodType type) { 4493 return type.invokers().genericInvoker(); 4494 } 4495 4496 /** 4497 * Produces a special <em>invoker method handle</em> which can be used to 4498 * invoke a signature-polymorphic access mode method on any VarHandle whose 4499 * associated access mode type is compatible with the given type. 4500 * The resulting invoker will have a type which is exactly equal to the 4501 * desired given type, except that it will accept an additional leading 4502 * argument of type {@code VarHandle}. 4503 * 4504 * @param accessMode the VarHandle access mode 4505 * @param type the desired target type 4506 * @return a method handle suitable for invoking an access mode method of 4507 * any VarHandle whose access mode type is of the given type. 4508 * @since 9 4509 */ 4510 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4511 return type.invokers().varHandleMethodExactInvoker(accessMode); 4512 } 4513 4514 /** 4515 * Produces a special <em>invoker method handle</em> which can be used to 4516 * invoke a signature-polymorphic access mode method on any VarHandle whose 4517 * associated access mode type is compatible with the given type. 4518 * The resulting invoker will have a type which is exactly equal to the 4519 * desired given type, except that it will accept an additional leading 4520 * argument of type {@code VarHandle}. 4521 * <p> 4522 * Before invoking its target, if the access mode type differs from the 4523 * desired given type, the invoker will apply reference casts as necessary 4524 * and box, unbox, or widen primitive values, as if by 4525 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4526 * converted as necessary. 4527 * <p> 4528 * This method is equivalent to the following code (though it may be more 4529 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4530 * 4531 * @param accessMode the VarHandle access mode 4532 * @param type the desired target type 4533 * @return a method handle suitable for invoking an access mode method of 4534 * any VarHandle whose access mode type is convertible to the given 4535 * type. 4536 * @since 9 4537 */ 4538 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4539 return type.invokers().varHandleMethodInvoker(accessMode); 4540 } 4541 4542 /*non-public*/ 4543 static MethodHandle basicInvoker(MethodType type) { 4544 return type.invokers().basicInvoker(); 4545 } 4546 4547 //--- method handle modification (creation from other method handles) 4548 4549 /** 4550 * Produces a method handle which adapts the type of the 4551 * given method handle to a new type by pairwise argument and return type conversion. 4552 * The original type and new type must have the same number of arguments. 4553 * The resulting method handle is guaranteed to report a type 4554 * which is equal to the desired new type. 4555 * <p> 4556 * If the original type and new type are equal, returns target. 4557 * <p> 4558 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4559 * and some additional conversions are also applied if those conversions fail. 4560 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4561 * if possible, before or instead of any conversions done by {@code asType}: 4562 * <ul> 4563 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4564 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4565 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4566 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4567 * the boolean is converted to a byte value, 1 for true, 0 for false. 4568 * (This treatment follows the usage of the bytecode verifier.) 4569 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4570 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4571 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4572 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4573 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4574 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4575 * widening and/or narrowing.) 4576 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4577 * conversion will be applied at runtime, possibly followed 4578 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4579 * possibly followed by a conversion from byte to boolean by testing 4580 * the low-order bit. 4581 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4582 * and if the reference is null at runtime, a zero value is introduced. 4583 * </ul> 4584 * @param target the method handle to invoke after arguments are retyped 4585 * @param newType the expected type of the new method handle 4586 * @return a method handle which delegates to the target after performing 4587 * any necessary argument conversions, and arranges for any 4588 * necessary return value conversions 4589 * @throws NullPointerException if either argument is null 4590 * @throws WrongMethodTypeException if the conversion cannot be made 4591 * @see MethodHandle#asType 4592 */ 4593 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4594 explicitCastArgumentsChecks(target, newType); 4595 // use the asTypeCache when possible: 4596 MethodType oldType = target.type(); 4597 if (oldType == newType) return target; 4598 if (oldType.explicitCastEquivalentToAsType(newType)) { 4599 return target.asFixedArity().asType(newType); 4600 } 4601 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4602 } 4603 4604 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4605 if (target.type().parameterCount() != newType.parameterCount()) { 4606 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4607 } 4608 } 4609 4610 /** 4611 * Produces a method handle which adapts the calling sequence of the 4612 * given method handle to a new type, by reordering the arguments. 4613 * The resulting method handle is guaranteed to report a type 4614 * which is equal to the desired new type. 4615 * <p> 4616 * The given array controls the reordering. 4617 * Call {@code #I} the number of incoming parameters (the value 4618 * {@code newType.parameterCount()}, and call {@code #O} the number 4619 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4620 * Then the length of the reordering array must be {@code #O}, 4621 * and each element must be a non-negative number less than {@code #I}. 4622 * For every {@code N} less than {@code #O}, the {@code N}-th 4623 * outgoing argument will be taken from the {@code I}-th incoming 4624 * argument, where {@code I} is {@code reorder[N]}. 4625 * <p> 4626 * No argument or return value conversions are applied. 4627 * The type of each incoming argument, as determined by {@code newType}, 4628 * must be identical to the type of the corresponding outgoing parameter 4629 * or parameters in the target method handle. 4630 * The return type of {@code newType} must be identical to the return 4631 * type of the original target. 4632 * <p> 4633 * The reordering array need not specify an actual permutation. 4634 * An incoming argument will be duplicated if its index appears 4635 * more than once in the array, and an incoming argument will be dropped 4636 * if its index does not appear in the array. 4637 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4638 * incoming arguments which are not mentioned in the reordering array 4639 * may be of any type, as determined only by {@code newType}. 4640 * {@snippet lang="java" : 4641 import static java.lang.invoke.MethodHandles.*; 4642 import static java.lang.invoke.MethodType.*; 4643 ... 4644 MethodType intfn1 = methodType(int.class, int.class); 4645 MethodType intfn2 = methodType(int.class, int.class, int.class); 4646 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4647 assert(sub.type().equals(intfn2)); 4648 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4649 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4650 assert((int)rsub.invokeExact(1, 100) == 99); 4651 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4652 assert(add.type().equals(intfn2)); 4653 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4654 assert(twice.type().equals(intfn1)); 4655 assert((int)twice.invokeExact(21) == 42); 4656 * } 4657 * <p> 4658 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4659 * variable-arity method handle}, even if the original target method handle was. 4660 * @param target the method handle to invoke after arguments are reordered 4661 * @param newType the expected type of the new method handle 4662 * @param reorder an index array which controls the reordering 4663 * @return a method handle which delegates to the target after it 4664 * drops unused arguments and moves and/or duplicates the other arguments 4665 * @throws NullPointerException if any argument is null 4666 * @throws IllegalArgumentException if the index array length is not equal to 4667 * the arity of the target, or if any index array element 4668 * not a valid index for a parameter of {@code newType}, 4669 * or if two corresponding parameter types in 4670 * {@code target.type()} and {@code newType} are not identical, 4671 */ 4672 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4673 reorder = reorder.clone(); // get a private copy 4674 MethodType oldType = target.type(); 4675 permuteArgumentChecks(reorder, newType, oldType); 4676 // first detect dropped arguments and handle them separately 4677 int[] originalReorder = reorder; 4678 BoundMethodHandle result = target.rebind(); 4679 LambdaForm form = result.form; 4680 int newArity = newType.parameterCount(); 4681 // Normalize the reordering into a real permutation, 4682 // by removing duplicates and adding dropped elements. 4683 // This somewhat improves lambda form caching, as well 4684 // as simplifying the transform by breaking it up into steps. 4685 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4686 if (ddIdx > 0) { 4687 // We found a duplicated entry at reorder[ddIdx]. 4688 // Example: (x,y,z)->asList(x,y,z) 4689 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4690 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4691 // The starred element corresponds to the argument 4692 // deleted by the dupArgumentForm transform. 4693 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4694 boolean killFirst = false; 4695 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4696 // Set killFirst if the dup is larger than an intervening position. 4697 // This will remove at least one inversion from the permutation. 4698 if (dupVal > val) killFirst = true; 4699 } 4700 if (!killFirst) { 4701 srcPos = dstPos; 4702 dstPos = ddIdx; 4703 } 4704 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4705 assert (reorder[srcPos] == reorder[dstPos]); 4706 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4707 // contract the reordering by removing the element at dstPos 4708 int tailPos = dstPos + 1; 4709 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4710 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4711 } else { 4712 int dropVal = ~ddIdx, insPos = 0; 4713 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4714 // Find first element of reorder larger than dropVal. 4715 // This is where we will insert the dropVal. 4716 insPos += 1; 4717 } 4718 Class<?> ptype = newType.parameterType(dropVal); 4719 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4720 oldType = oldType.insertParameterTypes(insPos, ptype); 4721 // expand the reordering by inserting an element at insPos 4722 int tailPos = insPos + 1; 4723 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4724 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4725 reorder[insPos] = dropVal; 4726 } 4727 assert (permuteArgumentChecks(reorder, newType, oldType)); 4728 } 4729 assert (reorder.length == newArity); // a perfect permutation 4730 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4731 form = form.editor().permuteArgumentsForm(1, reorder); 4732 if (newType == result.type() && form == result.internalForm()) 4733 return result; 4734 return result.copyWith(newType, form); 4735 } 4736 4737 /** 4738 * Return an indication of any duplicate or omission in reorder. 4739 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4740 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4741 * Otherwise, return zero. 4742 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4743 */ 4744 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4745 final int BIT_LIMIT = 63; // max number of bits in bit mask 4746 if (newArity < BIT_LIMIT) { 4747 long mask = 0; 4748 for (int i = 0; i < reorder.length; i++) { 4749 int arg = reorder[i]; 4750 if (arg >= newArity) { 4751 return reorder.length; 4752 } 4753 long bit = 1L << arg; 4754 if ((mask & bit) != 0) { 4755 return i; // >0 indicates a dup 4756 } 4757 mask |= bit; 4758 } 4759 if (mask == (1L << newArity) - 1) { 4760 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4761 return 0; 4762 } 4763 // find first zero 4764 long zeroBit = Long.lowestOneBit(~mask); 4765 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4766 assert(zeroPos <= newArity); 4767 if (zeroPos == newArity) { 4768 return 0; 4769 } 4770 return ~zeroPos; 4771 } else { 4772 // same algorithm, different bit set 4773 BitSet mask = new BitSet(newArity); 4774 for (int i = 0; i < reorder.length; i++) { 4775 int arg = reorder[i]; 4776 if (arg >= newArity) { 4777 return reorder.length; 4778 } 4779 if (mask.get(arg)) { 4780 return i; // >0 indicates a dup 4781 } 4782 mask.set(arg); 4783 } 4784 int zeroPos = mask.nextClearBit(0); 4785 assert(zeroPos <= newArity); 4786 if (zeroPos == newArity) { 4787 return 0; 4788 } 4789 return ~zeroPos; 4790 } 4791 } 4792 4793 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4794 if (newType.returnType() != oldType.returnType()) 4795 throw newIllegalArgumentException("return types do not match", 4796 oldType, newType); 4797 if (reorder.length != oldType.parameterCount()) 4798 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 4799 oldType, Arrays.toString(reorder)); 4800 4801 int limit = newType.parameterCount(); 4802 for (int j = 0; j < reorder.length; j++) { 4803 int i = reorder[j]; 4804 if (i < 0 || i >= limit) { 4805 throw newIllegalArgumentException("index is out of bounds for new type", 4806 i, newType); 4807 } 4808 Class<?> src = newType.parameterType(i); 4809 Class<?> dst = oldType.parameterType(j); 4810 if (src != dst) 4811 throw newIllegalArgumentException("parameter types do not match after reorder", 4812 oldType, newType); 4813 } 4814 return true; 4815 } 4816 4817 /** 4818 * Produces a method handle of the requested return type which returns the given 4819 * constant value every time it is invoked. 4820 * <p> 4821 * Before the method handle is returned, the passed-in value is converted to the requested type. 4822 * If the requested type is primitive, widening primitive conversions are attempted, 4823 * else reference conversions are attempted. 4824 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 4825 * @param type the return type of the desired method handle 4826 * @param value the value to return 4827 * @return a method handle of the given return type and no arguments, which always returns the given value 4828 * @throws NullPointerException if the {@code type} argument is null 4829 * @throws ClassCastException if the value cannot be converted to the required return type 4830 * @throws IllegalArgumentException if the given type is {@code void.class} 4831 */ 4832 public static MethodHandle constant(Class<?> type, Object value) { 4833 if (Objects.requireNonNull(type) == void.class) 4834 throw newIllegalArgumentException("void type"); 4835 return MethodHandleImpl.makeConstantReturning(type, value); 4836 } 4837 4838 /** 4839 * Produces a method handle which returns its sole argument when invoked. 4840 * @param type the type of the sole parameter and return value of the desired method handle 4841 * @return a unary method handle which accepts and returns the given type 4842 * @throws NullPointerException if the argument is null 4843 * @throws IllegalArgumentException if the given type is {@code void.class} 4844 */ 4845 public static MethodHandle identity(Class<?> type) { 4846 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 4847 int pos = btw.ordinal(); 4848 MethodHandle ident = IDENTITY_MHS[pos]; 4849 if (ident == null) { 4850 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 4851 } 4852 if (ident.type().returnType() == type) 4853 return ident; 4854 // something like identity(Foo.class); do not bother to intern these 4855 assert (btw == Wrapper.OBJECT); 4856 return makeIdentity(type); 4857 } 4858 4859 /** 4860 * Produces a constant method handle of the requested return type which 4861 * returns the default value for that type every time it is invoked. 4862 * The resulting constant method handle will have no side effects. 4863 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 4864 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 4865 * since {@code explicitCastArguments} converts {@code null} to default values. 4866 * @param type the expected return type of the desired method handle 4867 * @return a constant method handle that takes no arguments 4868 * and returns the default value of the given type (or void, if the type is void) 4869 * @throws NullPointerException if the argument is null 4870 * @see MethodHandles#constant 4871 * @see MethodHandles#empty 4872 * @see MethodHandles#explicitCastArguments 4873 * @since 9 4874 */ 4875 public static MethodHandle zero(Class<?> type) { 4876 Objects.requireNonNull(type); 4877 return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type)) 4878 : MethodHandleImpl.makeConstantReturning(type, null); 4879 } 4880 4881 private static MethodHandle identityOrVoid(Class<?> type) { 4882 return type == void.class ? zero(type) : identity(type); 4883 } 4884 4885 /** 4886 * Produces a method handle of the requested type which ignores any arguments, does nothing, 4887 * and returns a suitable default depending on the return type. 4888 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 4889 * <p>The returned method handle is equivalent to 4890 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 4891 * 4892 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 4893 * {@code guardWithTest(pred, target, empty(target.type())}. 4894 * @param type the type of the desired method handle 4895 * @return a constant method handle of the given type, which returns a default value of the given return type 4896 * @throws NullPointerException if the argument is null 4897 * @see MethodHandles#primitiveZero 4898 * @see MethodHandles#constant 4899 * @since 9 4900 */ 4901 public static MethodHandle empty(MethodType type) { 4902 Objects.requireNonNull(type); 4903 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 4904 } 4905 4906 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 4907 private static MethodHandle makeIdentity(Class<?> ptype) { 4908 MethodType mtype = methodType(ptype, ptype); // throws IAE for void 4909 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 4910 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 4911 } 4912 4913 private static MethodHandle primitiveZero(Wrapper w) { 4914 assert w != Wrapper.OBJECT : w; 4915 int pos = w.ordinal(); 4916 MethodHandle mh = PRIMITIVE_ZERO_MHS[pos]; 4917 if (mh == null) { 4918 mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w)); 4919 } 4920 assert (mh.type().returnType() == w.primitiveType()) : mh; 4921 return mh; 4922 } 4923 4924 private static MethodHandle makePrimitiveZero(Wrapper w) { 4925 if (w == Wrapper.VOID) { 4926 var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized 4927 return SimpleMethodHandle.make(MethodType.methodType(void.class), lf); 4928 } else { 4929 return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero()); 4930 } 4931 } 4932 4933 private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 4934 4935 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 4936 // Simulate a CAS, to avoid racy duplication of results. 4937 MethodHandle prev = cache[pos]; 4938 if (prev != null) return prev; 4939 return cache[pos] = value; 4940 } 4941 4942 /** 4943 * Provides a target method handle with one or more <em>bound arguments</em> 4944 * in advance of the method handle's invocation. 4945 * The formal parameters to the target corresponding to the bound 4946 * arguments are called <em>bound parameters</em>. 4947 * Returns a new method handle which saves away the bound arguments. 4948 * When it is invoked, it receives arguments for any non-bound parameters, 4949 * binds the saved arguments to their corresponding parameters, 4950 * and calls the original target. 4951 * <p> 4952 * The type of the new method handle will drop the types for the bound 4953 * parameters from the original target type, since the new method handle 4954 * will no longer require those arguments to be supplied by its callers. 4955 * <p> 4956 * Each given argument object must match the corresponding bound parameter type. 4957 * If a bound parameter type is a primitive, the argument object 4958 * must be a wrapper, and will be unboxed to produce the primitive value. 4959 * <p> 4960 * The {@code pos} argument selects which parameters are to be bound. 4961 * It may range between zero and <i>N-L</i> (inclusively), 4962 * where <i>N</i> is the arity of the target method handle 4963 * and <i>L</i> is the length of the values array. 4964 * <p> 4965 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4966 * variable-arity method handle}, even if the original target method handle was. 4967 * @param target the method handle to invoke after the argument is inserted 4968 * @param pos where to insert the argument (zero for the first) 4969 * @param values the series of arguments to insert 4970 * @return a method handle which inserts an additional argument, 4971 * before calling the original method handle 4972 * @throws NullPointerException if the target or the {@code values} array is null 4973 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 4974 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 4975 * is the length of the values array. 4976 * @throws ClassCastException if an argument does not match the corresponding bound parameter 4977 * type. 4978 * @see MethodHandle#bindTo 4979 */ 4980 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 4981 int insCount = values.length; 4982 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 4983 if (insCount == 0) return target; 4984 BoundMethodHandle result = target.rebind(); 4985 for (int i = 0; i < insCount; i++) { 4986 Object value = values[i]; 4987 Class<?> ptype = ptypes[pos+i]; 4988 if (ptype.isPrimitive()) { 4989 result = insertArgumentPrimitive(result, pos, ptype, value); 4990 } else { 4991 value = ptype.cast(value); // throw CCE if needed 4992 result = result.bindArgumentL(pos, value); 4993 } 4994 } 4995 return result; 4996 } 4997 4998 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 4999 Class<?> ptype, Object value) { 5000 Wrapper w = Wrapper.forPrimitiveType(ptype); 5001 // perform unboxing and/or primitive conversion 5002 value = w.convert(value, ptype); 5003 return switch (w) { 5004 case INT -> result.bindArgumentI(pos, (int) value); 5005 case LONG -> result.bindArgumentJ(pos, (long) value); 5006 case FLOAT -> result.bindArgumentF(pos, (float) value); 5007 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5008 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5009 }; 5010 } 5011 5012 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5013 MethodType oldType = target.type(); 5014 int outargs = oldType.parameterCount(); 5015 int inargs = outargs - insCount; 5016 if (inargs < 0) 5017 throw newIllegalArgumentException("too many values to insert"); 5018 if (pos < 0 || pos > inargs) 5019 throw newIllegalArgumentException("no argument type to append"); 5020 return oldType.ptypes(); 5021 } 5022 5023 /** 5024 * Produces a method handle which will discard some dummy arguments 5025 * before calling some other specified <i>target</i> method handle. 5026 * The type of the new method handle will be the same as the target's type, 5027 * except it will also include the dummy argument types, 5028 * at some given position. 5029 * <p> 5030 * The {@code pos} argument may range between zero and <i>N</i>, 5031 * where <i>N</i> is the arity of the target. 5032 * If {@code pos} is zero, the dummy arguments will precede 5033 * the target's real arguments; if {@code pos} is <i>N</i> 5034 * they will come after. 5035 * <p> 5036 * <b>Example:</b> 5037 * {@snippet lang="java" : 5038 import static java.lang.invoke.MethodHandles.*; 5039 import static java.lang.invoke.MethodType.*; 5040 ... 5041 MethodHandle cat = lookup().findVirtual(String.class, 5042 "concat", methodType(String.class, String.class)); 5043 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5044 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5045 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5046 assertEquals(bigType, d0.type()); 5047 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5048 * } 5049 * <p> 5050 * This method is also equivalent to the following code: 5051 * <blockquote><pre> 5052 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5053 * </pre></blockquote> 5054 * @param target the method handle to invoke after the arguments are dropped 5055 * @param pos position of first argument to drop (zero for the leftmost) 5056 * @param valueTypes the type(s) of the argument(s) to drop 5057 * @return a method handle which drops arguments of the given types, 5058 * before calling the original method handle 5059 * @throws NullPointerException if the target is null, 5060 * or if the {@code valueTypes} list or any of its elements is null 5061 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5062 * or if {@code pos} is negative or greater than the arity of the target, 5063 * or if the new method handle's type would have too many parameters 5064 */ 5065 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5066 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5067 } 5068 5069 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5070 MethodType oldType = target.type(); // get NPE 5071 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5072 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5073 if (dropped == 0) return target; 5074 BoundMethodHandle result = target.rebind(); 5075 LambdaForm lform = result.form; 5076 int insertFormArg = 1 + pos; 5077 for (Class<?> ptype : valueTypes) { 5078 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5079 } 5080 result = result.copyWith(newType, lform); 5081 return result; 5082 } 5083 5084 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5085 int dropped = valueTypes.length; 5086 MethodType.checkSlotCount(dropped); 5087 int outargs = oldType.parameterCount(); 5088 int inargs = outargs + dropped; 5089 if (pos < 0 || pos > outargs) 5090 throw newIllegalArgumentException("no argument type to remove" 5091 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5092 ); 5093 return dropped; 5094 } 5095 5096 /** 5097 * Produces a method handle which will discard some dummy arguments 5098 * before calling some other specified <i>target</i> method handle. 5099 * The type of the new method handle will be the same as the target's type, 5100 * except it will also include the dummy argument types, 5101 * at some given position. 5102 * <p> 5103 * The {@code pos} argument may range between zero and <i>N</i>, 5104 * where <i>N</i> is the arity of the target. 5105 * If {@code pos} is zero, the dummy arguments will precede 5106 * the target's real arguments; if {@code pos} is <i>N</i> 5107 * they will come after. 5108 * @apiNote 5109 * {@snippet lang="java" : 5110 import static java.lang.invoke.MethodHandles.*; 5111 import static java.lang.invoke.MethodType.*; 5112 ... 5113 MethodHandle cat = lookup().findVirtual(String.class, 5114 "concat", methodType(String.class, String.class)); 5115 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5116 MethodHandle d0 = dropArguments(cat, 0, String.class); 5117 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5118 MethodHandle d1 = dropArguments(cat, 1, String.class); 5119 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5120 MethodHandle d2 = dropArguments(cat, 2, String.class); 5121 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5122 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5123 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5124 * } 5125 * <p> 5126 * This method is also equivalent to the following code: 5127 * <blockquote><pre> 5128 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5129 * </pre></blockquote> 5130 * @param target the method handle to invoke after the arguments are dropped 5131 * @param pos position of first argument to drop (zero for the leftmost) 5132 * @param valueTypes the type(s) of the argument(s) to drop 5133 * @return a method handle which drops arguments of the given types, 5134 * before calling the original method handle 5135 * @throws NullPointerException if the target is null, 5136 * or if the {@code valueTypes} array or any of its elements is null 5137 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5138 * or if {@code pos} is negative or greater than the arity of the target, 5139 * or if the new method handle's type would have 5140 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5141 */ 5142 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5143 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5144 } 5145 5146 /* Convenience overloads for trusting internal low-arity call-sites */ 5147 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5148 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5149 } 5150 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5151 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5152 } 5153 5154 // private version which allows caller some freedom with error handling 5155 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5156 boolean nullOnFailure) { 5157 Class<?>[] oldTypes = target.type().ptypes(); 5158 int match = oldTypes.length; 5159 if (skip != 0) { 5160 if (skip < 0 || skip > match) { 5161 throw newIllegalArgumentException("illegal skip", skip, target); 5162 } 5163 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5164 match -= skip; 5165 } 5166 Class<?>[] addTypes = newTypes; 5167 int add = addTypes.length; 5168 if (pos != 0) { 5169 if (pos < 0 || pos > add) { 5170 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5171 } 5172 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5173 add -= pos; 5174 assert(addTypes.length == add); 5175 } 5176 // Do not add types which already match the existing arguments. 5177 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5178 if (nullOnFailure) { 5179 return null; 5180 } 5181 throw newIllegalArgumentException("argument lists do not match", 5182 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5183 } 5184 addTypes = Arrays.copyOfRange(addTypes, match, add); 5185 add -= match; 5186 assert(addTypes.length == add); 5187 // newTypes: ( P*[pos], M*[match], A*[add] ) 5188 // target: ( S*[skip], M*[match] ) 5189 MethodHandle adapter = target; 5190 if (add > 0) { 5191 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5192 } 5193 // adapter: (S*[skip], M*[match], A*[add] ) 5194 if (pos > 0) { 5195 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5196 } 5197 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5198 return adapter; 5199 } 5200 5201 /** 5202 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5203 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5204 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5205 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5206 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5207 * {@link #dropArguments(MethodHandle, int, Class[])}. 5208 * <p> 5209 * The resulting handle will have the same return type as the target handle. 5210 * <p> 5211 * In more formal terms, assume these two type lists:<ul> 5212 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5213 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5214 * {@code newTypes}. 5215 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5216 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5217 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5218 * sub-list. 5219 * </ul> 5220 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5221 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5222 * {@link #dropArguments(MethodHandle, int, Class[])}. 5223 * 5224 * @apiNote 5225 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5226 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5227 * {@snippet lang="java" : 5228 import static java.lang.invoke.MethodHandles.*; 5229 import static java.lang.invoke.MethodType.*; 5230 ... 5231 ... 5232 MethodHandle h0 = constant(boolean.class, true); 5233 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5234 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5235 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5236 if (h1.type().parameterCount() < h2.type().parameterCount()) 5237 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5238 else 5239 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5240 MethodHandle h3 = guardWithTest(h0, h1, h2); 5241 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5242 * } 5243 * @param target the method handle to adapt 5244 * @param skip number of targets parameters to disregard (they will be unchanged) 5245 * @param newTypes the list of types to match {@code target}'s parameter type list to 5246 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5247 * @return a possibly adapted method handle 5248 * @throws NullPointerException if either argument is null 5249 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5250 * or if {@code skip} is negative or greater than the arity of the target, 5251 * or if {@code pos} is negative or greater than the newTypes list size, 5252 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5253 * {@code pos}. 5254 * @since 9 5255 */ 5256 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5257 Objects.requireNonNull(target); 5258 Objects.requireNonNull(newTypes); 5259 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5260 } 5261 5262 /** 5263 * Drop the return value of the target handle (if any). 5264 * The returned method handle will have a {@code void} return type. 5265 * 5266 * @param target the method handle to adapt 5267 * @return a possibly adapted method handle 5268 * @throws NullPointerException if {@code target} is null 5269 * @since 16 5270 */ 5271 public static MethodHandle dropReturn(MethodHandle target) { 5272 Objects.requireNonNull(target); 5273 MethodType oldType = target.type(); 5274 Class<?> oldReturnType = oldType.returnType(); 5275 if (oldReturnType == void.class) 5276 return target; 5277 MethodType newType = oldType.changeReturnType(void.class); 5278 BoundMethodHandle result = target.rebind(); 5279 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5280 result = result.copyWith(newType, lform); 5281 return result; 5282 } 5283 5284 /** 5285 * Adapts a target method handle by pre-processing 5286 * one or more of its arguments, each with its own unary filter function, 5287 * and then calling the target with each pre-processed argument 5288 * replaced by the result of its corresponding filter function. 5289 * <p> 5290 * The pre-processing is performed by one or more method handles, 5291 * specified in the elements of the {@code filters} array. 5292 * The first element of the filter array corresponds to the {@code pos} 5293 * argument of the target, and so on in sequence. 5294 * The filter functions are invoked in left to right order. 5295 * <p> 5296 * Null arguments in the array are treated as identity functions, 5297 * and the corresponding arguments left unchanged. 5298 * (If there are no non-null elements in the array, the original target is returned.) 5299 * Each filter is applied to the corresponding argument of the adapter. 5300 * <p> 5301 * If a filter {@code F} applies to the {@code N}th argument of 5302 * the target, then {@code F} must be a method handle which 5303 * takes exactly one argument. The type of {@code F}'s sole argument 5304 * replaces the corresponding argument type of the target 5305 * in the resulting adapted method handle. 5306 * The return type of {@code F} must be identical to the corresponding 5307 * parameter type of the target. 5308 * <p> 5309 * It is an error if there are elements of {@code filters} 5310 * (null or not) 5311 * which do not correspond to argument positions in the target. 5312 * <p><b>Example:</b> 5313 * {@snippet lang="java" : 5314 import static java.lang.invoke.MethodHandles.*; 5315 import static java.lang.invoke.MethodType.*; 5316 ... 5317 MethodHandle cat = lookup().findVirtual(String.class, 5318 "concat", methodType(String.class, String.class)); 5319 MethodHandle upcase = lookup().findVirtual(String.class, 5320 "toUpperCase", methodType(String.class)); 5321 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5322 MethodHandle f0 = filterArguments(cat, 0, upcase); 5323 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5324 MethodHandle f1 = filterArguments(cat, 1, upcase); 5325 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5326 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5327 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5328 * } 5329 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5330 * denotes the return type of both the {@code target} and resulting adapter. 5331 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5332 * of the parameters and arguments that precede and follow the filter position 5333 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5334 * values of the filtered parameters and arguments; they also represent the 5335 * return types of the {@code filter[i]} handles. The latter accept arguments 5336 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5337 * the resulting adapter. 5338 * {@snippet lang="java" : 5339 * T target(P... p, A[i]... a[i], B... b); 5340 * A[i] filter[i](V[i]); 5341 * T adapter(P... p, V[i]... v[i], B... b) { 5342 * return target(p..., filter[i](v[i])..., b...); 5343 * } 5344 * } 5345 * <p> 5346 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5347 * variable-arity method handle}, even if the original target method handle was. 5348 * 5349 * @param target the method handle to invoke after arguments are filtered 5350 * @param pos the position of the first argument to filter 5351 * @param filters method handles to call initially on filtered arguments 5352 * @return method handle which incorporates the specified argument filtering logic 5353 * @throws NullPointerException if the target is null 5354 * or if the {@code filters} array is null 5355 * @throws IllegalArgumentException if a non-null element of {@code filters} 5356 * does not match a corresponding argument type of target as described above, 5357 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5358 * or if the resulting method handle's type would have 5359 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5360 */ 5361 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5362 // In method types arguments start at index 0, while the LF 5363 // editor have the MH receiver at position 0 - adjust appropriately. 5364 final int MH_RECEIVER_OFFSET = 1; 5365 filterArgumentsCheckArity(target, pos, filters); 5366 MethodHandle adapter = target; 5367 5368 // keep track of currently matched filters, as to optimize repeated filters 5369 int index = 0; 5370 int[] positions = new int[filters.length]; 5371 MethodHandle filter = null; 5372 5373 // process filters in reverse order so that the invocation of 5374 // the resulting adapter will invoke the filters in left-to-right order 5375 for (int i = filters.length - 1; i >= 0; --i) { 5376 MethodHandle newFilter = filters[i]; 5377 if (newFilter == null) continue; // ignore null elements of filters 5378 5379 // flush changes on update 5380 if (filter != newFilter) { 5381 if (filter != null) { 5382 if (index > 1) { 5383 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5384 } else { 5385 adapter = filterArgument(adapter, positions[0] - 1, filter); 5386 } 5387 } 5388 filter = newFilter; 5389 index = 0; 5390 } 5391 5392 filterArgumentChecks(target, pos + i, newFilter); 5393 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5394 } 5395 if (index > 1) { 5396 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5397 } else if (index == 1) { 5398 adapter = filterArgument(adapter, positions[0] - 1, filter); 5399 } 5400 return adapter; 5401 } 5402 5403 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5404 MethodType targetType = adapter.type(); 5405 MethodType filterType = filter.type(); 5406 BoundMethodHandle result = adapter.rebind(); 5407 Class<?> newParamType = filterType.parameterType(0); 5408 5409 Class<?>[] ptypes = targetType.ptypes().clone(); 5410 for (int pos : positions) { 5411 ptypes[pos - 1] = newParamType; 5412 } 5413 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5414 5415 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5416 return result.copyWithExtendL(newType, lform, filter); 5417 } 5418 5419 /*non-public*/ 5420 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5421 filterArgumentChecks(target, pos, filter); 5422 MethodType targetType = target.type(); 5423 MethodType filterType = filter.type(); 5424 BoundMethodHandle result = target.rebind(); 5425 Class<?> newParamType = filterType.parameterType(0); 5426 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5427 MethodType newType = targetType.changeParameterType(pos, newParamType); 5428 result = result.copyWithExtendL(newType, lform, filter); 5429 return result; 5430 } 5431 5432 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5433 MethodType targetType = target.type(); 5434 int maxPos = targetType.parameterCount(); 5435 if (pos + filters.length > maxPos) 5436 throw newIllegalArgumentException("too many filters"); 5437 } 5438 5439 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5440 MethodType targetType = target.type(); 5441 MethodType filterType = filter.type(); 5442 if (filterType.parameterCount() != 1 5443 || filterType.returnType() != targetType.parameterType(pos)) 5444 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5445 } 5446 5447 /** 5448 * Adapts a target method handle by pre-processing 5449 * a sub-sequence of its arguments with a filter (another method handle). 5450 * The pre-processed arguments are replaced by the result (if any) of the 5451 * filter function. 5452 * The target is then called on the modified (usually shortened) argument list. 5453 * <p> 5454 * If the filter returns a value, the target must accept that value as 5455 * its argument in position {@code pos}, preceded and/or followed by 5456 * any arguments not passed to the filter. 5457 * If the filter returns void, the target must accept all arguments 5458 * not passed to the filter. 5459 * No arguments are reordered, and a result returned from the filter 5460 * replaces (in order) the whole subsequence of arguments originally 5461 * passed to the adapter. 5462 * <p> 5463 * The argument types (if any) of the filter 5464 * replace zero or one argument types of the target, at position {@code pos}, 5465 * in the resulting adapted method handle. 5466 * The return type of the filter (if any) must be identical to the 5467 * argument type of the target at position {@code pos}, and that target argument 5468 * is supplied by the return value of the filter. 5469 * <p> 5470 * In all cases, {@code pos} must be greater than or equal to zero, and 5471 * {@code pos} must also be less than or equal to the target's arity. 5472 * <p><b>Example:</b> 5473 * {@snippet lang="java" : 5474 import static java.lang.invoke.MethodHandles.*; 5475 import static java.lang.invoke.MethodType.*; 5476 ... 5477 MethodHandle deepToString = publicLookup() 5478 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5479 5480 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5481 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5482 5483 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5484 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5485 5486 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5487 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5488 assertEquals("[top, [up, down], strange]", 5489 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5490 5491 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5492 assertEquals("[top, [up, down], [strange]]", 5493 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5494 5495 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5496 assertEquals("[top, [[up, down, strange], charm], bottom]", 5497 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5498 * } 5499 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5500 * represents the return type of the {@code target} and resulting adapter. 5501 * {@code V}/{@code v} stand for the return type and value of the 5502 * {@code filter}, which are also found in the signature and arguments of 5503 * the {@code target}, respectively, unless {@code V} is {@code void}. 5504 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5505 * and values preceding and following the collection position, {@code pos}, 5506 * in the {@code target}'s signature. They also turn up in the resulting 5507 * adapter's signature and arguments, where they surround 5508 * {@code B}/{@code b}, which represent the parameter types and arguments 5509 * to the {@code filter} (if any). 5510 * {@snippet lang="java" : 5511 * T target(A...,V,C...); 5512 * V filter(B...); 5513 * T adapter(A... a,B... b,C... c) { 5514 * V v = filter(b...); 5515 * return target(a...,v,c...); 5516 * } 5517 * // and if the filter has no arguments: 5518 * T target2(A...,V,C...); 5519 * V filter2(); 5520 * T adapter2(A... a,C... c) { 5521 * V v = filter2(); 5522 * return target2(a...,v,c...); 5523 * } 5524 * // and if the filter has a void return: 5525 * T target3(A...,C...); 5526 * void filter3(B...); 5527 * T adapter3(A... a,B... b,C... c) { 5528 * filter3(b...); 5529 * return target3(a...,c...); 5530 * } 5531 * } 5532 * <p> 5533 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5534 * one which first "folds" the affected arguments, and then drops them, in separate 5535 * steps as follows: 5536 * {@snippet lang="java" : 5537 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5538 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5539 * } 5540 * If the target method handle consumes no arguments besides than the result 5541 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5542 * is equivalent to {@code filterReturnValue(coll, mh)}. 5543 * If the filter method handle {@code coll} consumes one argument and produces 5544 * a non-void result, then {@code collectArguments(mh, N, coll)} 5545 * is equivalent to {@code filterArguments(mh, N, coll)}. 5546 * Other equivalences are possible but would require argument permutation. 5547 * <p> 5548 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5549 * variable-arity method handle}, even if the original target method handle was. 5550 * 5551 * @param target the method handle to invoke after filtering the subsequence of arguments 5552 * @param pos the position of the first adapter argument to pass to the filter, 5553 * and/or the target argument which receives the result of the filter 5554 * @param filter method handle to call on the subsequence of arguments 5555 * @return method handle which incorporates the specified argument subsequence filtering logic 5556 * @throws NullPointerException if either argument is null 5557 * @throws IllegalArgumentException if the return type of {@code filter} 5558 * is non-void and is not the same as the {@code pos} argument of the target, 5559 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5560 * or if the resulting method handle's type would have 5561 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5562 * @see MethodHandles#foldArguments 5563 * @see MethodHandles#filterArguments 5564 * @see MethodHandles#filterReturnValue 5565 */ 5566 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5567 MethodType newType = collectArgumentsChecks(target, pos, filter); 5568 MethodType collectorType = filter.type(); 5569 BoundMethodHandle result = target.rebind(); 5570 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5571 return result.copyWithExtendL(newType, lform, filter); 5572 } 5573 5574 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5575 MethodType targetType = target.type(); 5576 MethodType filterType = filter.type(); 5577 Class<?> rtype = filterType.returnType(); 5578 Class<?>[] filterArgs = filterType.ptypes(); 5579 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5580 (rtype != void.class && pos >= targetType.parameterCount())) { 5581 throw newIllegalArgumentException("position is out of range for target", target, pos); 5582 } 5583 if (rtype == void.class) { 5584 return targetType.insertParameterTypes(pos, filterArgs); 5585 } 5586 if (rtype != targetType.parameterType(pos)) { 5587 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5588 } 5589 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5590 } 5591 5592 /** 5593 * Adapts a target method handle by post-processing 5594 * its return value (if any) with a filter (another method handle). 5595 * The result of the filter is returned from the adapter. 5596 * <p> 5597 * If the target returns a value, the filter must accept that value as 5598 * its only argument. 5599 * If the target returns void, the filter must accept no arguments. 5600 * <p> 5601 * The return type of the filter 5602 * replaces the return type of the target 5603 * in the resulting adapted method handle. 5604 * The argument type of the filter (if any) must be identical to the 5605 * return type of the target. 5606 * <p><b>Example:</b> 5607 * {@snippet lang="java" : 5608 import static java.lang.invoke.MethodHandles.*; 5609 import static java.lang.invoke.MethodType.*; 5610 ... 5611 MethodHandle cat = lookup().findVirtual(String.class, 5612 "concat", methodType(String.class, String.class)); 5613 MethodHandle length = lookup().findVirtual(String.class, 5614 "length", methodType(int.class)); 5615 System.out.println((String) cat.invokeExact("x", "y")); // xy 5616 MethodHandle f0 = filterReturnValue(cat, length); 5617 System.out.println((int) f0.invokeExact("x", "y")); // 2 5618 * } 5619 * <p>Here is pseudocode for the resulting adapter. In the code, 5620 * {@code T}/{@code t} represent the result type and value of the 5621 * {@code target}; {@code V}, the result type of the {@code filter}; and 5622 * {@code A}/{@code a}, the types and values of the parameters and arguments 5623 * of the {@code target} as well as the resulting adapter. 5624 * {@snippet lang="java" : 5625 * T target(A...); 5626 * V filter(T); 5627 * V adapter(A... a) { 5628 * T t = target(a...); 5629 * return filter(t); 5630 * } 5631 * // and if the target has a void return: 5632 * void target2(A...); 5633 * V filter2(); 5634 * V adapter2(A... a) { 5635 * target2(a...); 5636 * return filter2(); 5637 * } 5638 * // and if the filter has a void return: 5639 * T target3(A...); 5640 * void filter3(V); 5641 * void adapter3(A... a) { 5642 * T t = target3(a...); 5643 * filter3(t); 5644 * } 5645 * } 5646 * <p> 5647 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5648 * variable-arity method handle}, even if the original target method handle was. 5649 * @param target the method handle to invoke before filtering the return value 5650 * @param filter method handle to call on the return value 5651 * @return method handle which incorporates the specified return value filtering logic 5652 * @throws NullPointerException if either argument is null 5653 * @throws IllegalArgumentException if the argument list of {@code filter} 5654 * does not match the return type of target as described above 5655 */ 5656 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5657 MethodType targetType = target.type(); 5658 MethodType filterType = filter.type(); 5659 filterReturnValueChecks(targetType, filterType); 5660 BoundMethodHandle result = target.rebind(); 5661 BasicType rtype = BasicType.basicType(filterType.returnType()); 5662 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5663 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5664 result = result.copyWithExtendL(newType, lform, filter); 5665 return result; 5666 } 5667 5668 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5669 Class<?> rtype = targetType.returnType(); 5670 int filterValues = filterType.parameterCount(); 5671 if (filterValues == 0 5672 ? (rtype != void.class) 5673 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5674 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5675 } 5676 5677 /** 5678 * Filter the return value of a target method handle with a filter function. The filter function is 5679 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5680 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5681 * as follows: 5682 * {@snippet lang="java" : 5683 * T target(A...) 5684 * V filter(B... , T) 5685 * V adapter(A... a, B... b) { 5686 * T t = target(a...); 5687 * return filter(b..., t); 5688 * } 5689 * } 5690 * <p> 5691 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5692 * 5693 * @param target the target method handle 5694 * @param filter the filter method handle 5695 * @return the adapter method handle 5696 */ 5697 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5698 MethodType targetType = target.type(); 5699 MethodType filterType = filter.type(); 5700 BoundMethodHandle result = target.rebind(); 5701 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5702 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5703 if (filterType.parameterCount() > 1) { 5704 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5705 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5706 } 5707 } 5708 result = result.copyWithExtendL(newType, lform, filter); 5709 return result; 5710 } 5711 5712 /** 5713 * Adapts a target method handle by pre-processing 5714 * some of its arguments, and then calling the target with 5715 * the result of the pre-processing, inserted into the original 5716 * sequence of arguments. 5717 * <p> 5718 * The pre-processing is performed by {@code combiner}, a second method handle. 5719 * Of the arguments passed to the adapter, the first {@code N} arguments 5720 * are copied to the combiner, which is then called. 5721 * (Here, {@code N} is defined as the parameter count of the combiner.) 5722 * After this, control passes to the target, with any result 5723 * from the combiner inserted before the original {@code N} incoming 5724 * arguments. 5725 * <p> 5726 * If the combiner returns a value, the first parameter type of the target 5727 * must be identical with the return type of the combiner, and the next 5728 * {@code N} parameter types of the target must exactly match the parameters 5729 * of the combiner. 5730 * <p> 5731 * If the combiner has a void return, no result will be inserted, 5732 * and the first {@code N} parameter types of the target 5733 * must exactly match the parameters of the combiner. 5734 * <p> 5735 * The resulting adapter is the same type as the target, except that the 5736 * first parameter type is dropped, 5737 * if it corresponds to the result of the combiner. 5738 * <p> 5739 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5740 * that either the combiner or the target does not wish to receive. 5741 * If some of the incoming arguments are destined only for the combiner, 5742 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5743 * arguments will not need to be live on the stack on entry to the 5744 * target.) 5745 * <p><b>Example:</b> 5746 * {@snippet lang="java" : 5747 import static java.lang.invoke.MethodHandles.*; 5748 import static java.lang.invoke.MethodType.*; 5749 ... 5750 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5751 "println", methodType(void.class, String.class)) 5752 .bindTo(System.out); 5753 MethodHandle cat = lookup().findVirtual(String.class, 5754 "concat", methodType(String.class, String.class)); 5755 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5756 MethodHandle catTrace = foldArguments(cat, trace); 5757 // also prints "boo": 5758 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5759 * } 5760 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5761 * represents the result type of the {@code target} and resulting adapter. 5762 * {@code V}/{@code v} represent the type and value of the parameter and argument 5763 * of {@code target} that precedes the folding position; {@code V} also is 5764 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5765 * types and values of the {@code N} parameters and arguments at the folding 5766 * position. {@code B}/{@code b} represent the types and values of the 5767 * {@code target} parameters and arguments that follow the folded parameters 5768 * and arguments. 5769 * {@snippet lang="java" : 5770 * // there are N arguments in A... 5771 * T target(V, A[N]..., B...); 5772 * V combiner(A...); 5773 * T adapter(A... a, B... b) { 5774 * V v = combiner(a...); 5775 * return target(v, a..., b...); 5776 * } 5777 * // and if the combiner has a void return: 5778 * T target2(A[N]..., B...); 5779 * void combiner2(A...); 5780 * T adapter2(A... a, B... b) { 5781 * combiner2(a...); 5782 * return target2(a..., b...); 5783 * } 5784 * } 5785 * <p> 5786 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5787 * variable-arity method handle}, even if the original target method handle was. 5788 * @param target the method handle to invoke after arguments are combined 5789 * @param combiner method handle to call initially on the incoming arguments 5790 * @return method handle which incorporates the specified argument folding logic 5791 * @throws NullPointerException if either argument is null 5792 * @throws IllegalArgumentException if {@code combiner}'s return type 5793 * is non-void and not the same as the first argument type of 5794 * the target, or if the initial {@code N} argument types 5795 * of the target 5796 * (skipping one matching the {@code combiner}'s return type) 5797 * are not identical with the argument types of {@code combiner} 5798 */ 5799 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5800 return foldArguments(target, 0, combiner); 5801 } 5802 5803 /** 5804 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 5805 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 5806 * before the folded arguments. 5807 * <p> 5808 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 5809 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 5810 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 5811 * 0. 5812 * 5813 * @apiNote Example: 5814 * {@snippet lang="java" : 5815 import static java.lang.invoke.MethodHandles.*; 5816 import static java.lang.invoke.MethodType.*; 5817 ... 5818 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5819 "println", methodType(void.class, String.class)) 5820 .bindTo(System.out); 5821 MethodHandle cat = lookup().findVirtual(String.class, 5822 "concat", methodType(String.class, String.class)); 5823 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5824 MethodHandle catTrace = foldArguments(cat, 1, trace); 5825 // also prints "jum": 5826 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5827 * } 5828 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5829 * represents the result type of the {@code target} and resulting adapter. 5830 * {@code V}/{@code v} represent the type and value of the parameter and argument 5831 * of {@code target} that precedes the folding position; {@code V} also is 5832 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5833 * types and values of the {@code N} parameters and arguments at the folding 5834 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 5835 * and values of the {@code target} parameters and arguments that precede and 5836 * follow the folded parameters and arguments starting at {@code pos}, 5837 * respectively. 5838 * {@snippet lang="java" : 5839 * // there are N arguments in A... 5840 * T target(Z..., V, A[N]..., B...); 5841 * V combiner(A...); 5842 * T adapter(Z... z, A... a, B... b) { 5843 * V v = combiner(a...); 5844 * return target(z..., v, a..., b...); 5845 * } 5846 * // and if the combiner has a void return: 5847 * T target2(Z..., A[N]..., B...); 5848 * void combiner2(A...); 5849 * T adapter2(Z... z, A... a, B... b) { 5850 * combiner2(a...); 5851 * return target2(z..., a..., b...); 5852 * } 5853 * } 5854 * <p> 5855 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5856 * variable-arity method handle}, even if the original target method handle was. 5857 * 5858 * @param target the method handle to invoke after arguments are combined 5859 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 5860 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5861 * @param combiner method handle to call initially on the incoming arguments 5862 * @return method handle which incorporates the specified argument folding logic 5863 * @throws NullPointerException if either argument is null 5864 * @throws IllegalArgumentException if either of the following two conditions holds: 5865 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5866 * {@code pos} of the target signature; 5867 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 5868 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 5869 * 5870 * @see #foldArguments(MethodHandle, MethodHandle) 5871 * @since 9 5872 */ 5873 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 5874 MethodType targetType = target.type(); 5875 MethodType combinerType = combiner.type(); 5876 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 5877 BoundMethodHandle result = target.rebind(); 5878 boolean dropResult = rtype == void.class; 5879 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 5880 MethodType newType = targetType; 5881 if (!dropResult) { 5882 newType = newType.dropParameterTypes(pos, pos + 1); 5883 } 5884 result = result.copyWithExtendL(newType, lform, combiner); 5885 return result; 5886 } 5887 5888 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 5889 int foldArgs = combinerType.parameterCount(); 5890 Class<?> rtype = combinerType.returnType(); 5891 int foldVals = rtype == void.class ? 0 : 1; 5892 int afterInsertPos = foldPos + foldVals; 5893 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 5894 if (ok) { 5895 for (int i = 0; i < foldArgs; i++) { 5896 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 5897 ok = false; 5898 break; 5899 } 5900 } 5901 } 5902 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 5903 ok = false; 5904 if (!ok) 5905 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5906 return rtype; 5907 } 5908 5909 /** 5910 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 5911 * of the pre-processing replacing the argument at the given position. 5912 * 5913 * @param target the method handle to invoke after arguments are combined 5914 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5915 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5916 * @param combiner method handle to call initially on the incoming arguments 5917 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5918 * @return method handle which incorporates the specified argument folding logic 5919 * @throws NullPointerException if either argument is null 5920 * @throws IllegalArgumentException if either of the following two conditions holds: 5921 * (1) {@code combiner}'s return type is not the same as the argument type at position 5922 * {@code pos} of the target signature; 5923 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 5924 * not identical with the argument types of {@code combiner}. 5925 */ 5926 /*non-public*/ 5927 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5928 return argumentsWithCombiner(true, target, position, combiner, argPositions); 5929 } 5930 5931 /** 5932 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 5933 * the pre-processing inserted into the original sequence of arguments at the given position. 5934 * 5935 * @param target the method handle to invoke after arguments are combined 5936 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5937 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5938 * @param combiner method handle to call initially on the incoming arguments 5939 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5940 * @return method handle which incorporates the specified argument folding logic 5941 * @throws NullPointerException if either argument is null 5942 * @throws IllegalArgumentException if either of the following two conditions holds: 5943 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5944 * {@code pos} of the target signature; 5945 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 5946 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 5947 * with the argument types of {@code combiner}. 5948 */ 5949 /*non-public*/ 5950 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5951 return argumentsWithCombiner(false, target, position, combiner, argPositions); 5952 } 5953 5954 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5955 MethodType targetType = target.type(); 5956 MethodType combinerType = combiner.type(); 5957 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 5958 BoundMethodHandle result = target.rebind(); 5959 5960 MethodType newType = targetType; 5961 LambdaForm lform; 5962 if (filter) { 5963 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 5964 } else { 5965 boolean dropResult = rtype == void.class; 5966 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 5967 if (!dropResult) { 5968 newType = newType.dropParameterTypes(position, position + 1); 5969 } 5970 } 5971 result = result.copyWithExtendL(newType, lform, combiner); 5972 return result; 5973 } 5974 5975 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 5976 int combinerArgs = combinerType.parameterCount(); 5977 if (argPos.length != combinerArgs) { 5978 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 5979 } 5980 Class<?> rtype = combinerType.returnType(); 5981 5982 for (int i = 0; i < combinerArgs; i++) { 5983 int arg = argPos[i]; 5984 if (arg < 0 || arg > targetType.parameterCount()) { 5985 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 5986 } 5987 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 5988 throw newIllegalArgumentException("target argument type at position " + arg 5989 + " must match combiner argument type at index " + i + ": " + targetType 5990 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 5991 } 5992 } 5993 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 5994 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5995 } 5996 return rtype; 5997 } 5998 5999 /** 6000 * Makes a method handle which adapts a target method handle, 6001 * by guarding it with a test, a boolean-valued method handle. 6002 * If the guard fails, a fallback handle is called instead. 6003 * All three method handles must have the same corresponding 6004 * argument and return types, except that the return type 6005 * of the test must be boolean, and the test is allowed 6006 * to have fewer arguments than the other two method handles. 6007 * <p> 6008 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6009 * represents the uniform result type of the three involved handles; 6010 * {@code A}/{@code a}, the types and values of the {@code target} 6011 * parameters and arguments that are consumed by the {@code test}; and 6012 * {@code B}/{@code b}, those types and values of the {@code target} 6013 * parameters and arguments that are not consumed by the {@code test}. 6014 * {@snippet lang="java" : 6015 * boolean test(A...); 6016 * T target(A...,B...); 6017 * T fallback(A...,B...); 6018 * T adapter(A... a,B... b) { 6019 * if (test(a...)) 6020 * return target(a..., b...); 6021 * else 6022 * return fallback(a..., b...); 6023 * } 6024 * } 6025 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6026 * be modified by execution of the test, and so are passed unchanged 6027 * from the caller to the target or fallback as appropriate. 6028 * @param test method handle used for test, must return boolean 6029 * @param target method handle to call if test passes 6030 * @param fallback method handle to call if test fails 6031 * @return method handle which incorporates the specified if/then/else logic 6032 * @throws NullPointerException if any argument is null 6033 * @throws IllegalArgumentException if {@code test} does not return boolean, 6034 * or if all three method types do not match (with the return 6035 * type of {@code test} changed to match that of the target). 6036 */ 6037 public static MethodHandle guardWithTest(MethodHandle test, 6038 MethodHandle target, 6039 MethodHandle fallback) { 6040 MethodType gtype = test.type(); 6041 MethodType ttype = target.type(); 6042 MethodType ftype = fallback.type(); 6043 if (!ttype.equals(ftype)) 6044 throw misMatchedTypes("target and fallback types", ttype, ftype); 6045 if (gtype.returnType() != boolean.class) 6046 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6047 6048 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6049 if (test == null) { 6050 throw misMatchedTypes("target and test types", ttype, gtype); 6051 } 6052 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6053 } 6054 6055 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6056 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6057 } 6058 6059 /** 6060 * Makes a method handle which adapts a target method handle, 6061 * by running it inside an exception handler. 6062 * If the target returns normally, the adapter returns that value. 6063 * If an exception matching the specified type is thrown, the fallback 6064 * handle is called instead on the exception, plus the original arguments. 6065 * <p> 6066 * The target and handler must have the same corresponding 6067 * argument and return types, except that handler may omit trailing arguments 6068 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6069 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6070 * <p> 6071 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6072 * represents the return type of the {@code target} and {@code handler}, 6073 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6074 * the types and values of arguments to the resulting handle consumed by 6075 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6076 * resulting handle discarded by {@code handler}. 6077 * {@snippet lang="java" : 6078 * T target(A..., B...); 6079 * T handler(ExType, A...); 6080 * T adapter(A... a, B... b) { 6081 * try { 6082 * return target(a..., b...); 6083 * } catch (ExType ex) { 6084 * return handler(ex, a...); 6085 * } 6086 * } 6087 * } 6088 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6089 * be modified by execution of the target, and so are passed unchanged 6090 * from the caller to the handler, if the handler is invoked. 6091 * <p> 6092 * The target and handler must return the same type, even if the handler 6093 * always throws. (This might happen, for instance, because the handler 6094 * is simulating a {@code finally} clause). 6095 * To create such a throwing handler, compose the handler creation logic 6096 * with {@link #throwException throwException}, 6097 * in order to create a method handle of the correct return type. 6098 * @param target method handle to call 6099 * @param exType the type of exception which the handler will catch 6100 * @param handler method handle to call if a matching exception is thrown 6101 * @return method handle which incorporates the specified try/catch logic 6102 * @throws NullPointerException if any argument is null 6103 * @throws IllegalArgumentException if {@code handler} does not accept 6104 * the given exception type, or if the method handle types do 6105 * not match in their return types and their 6106 * corresponding parameters 6107 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6108 */ 6109 public static MethodHandle catchException(MethodHandle target, 6110 Class<? extends Throwable> exType, 6111 MethodHandle handler) { 6112 MethodType ttype = target.type(); 6113 MethodType htype = handler.type(); 6114 if (!Throwable.class.isAssignableFrom(exType)) 6115 throw new ClassCastException(exType.getName()); 6116 if (htype.parameterCount() < 1 || 6117 !htype.parameterType(0).isAssignableFrom(exType)) 6118 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6119 if (htype.returnType() != ttype.returnType()) 6120 throw misMatchedTypes("target and handler return types", ttype, htype); 6121 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6122 if (handler == null) { 6123 throw misMatchedTypes("target and handler types", ttype, htype); 6124 } 6125 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6126 } 6127 6128 /** 6129 * Produces a method handle which will throw exceptions of the given {@code exType}. 6130 * The method handle will accept a single argument of {@code exType}, 6131 * and immediately throw it as an exception. 6132 * The method type will nominally specify a return of {@code returnType}. 6133 * The return type may be anything convenient: It doesn't matter to the 6134 * method handle's behavior, since it will never return normally. 6135 * @param returnType the return type of the desired method handle 6136 * @param exType the parameter type of the desired method handle 6137 * @return method handle which can throw the given exceptions 6138 * @throws NullPointerException if either argument is null 6139 */ 6140 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6141 if (!Throwable.class.isAssignableFrom(exType)) 6142 throw new ClassCastException(exType.getName()); 6143 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6144 } 6145 6146 /** 6147 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6148 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6149 * delivers the loop's result, which is the return value of the resulting handle. 6150 * <p> 6151 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6152 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6153 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6154 * terms of method handles, each clause will specify up to four independent actions:<ul> 6155 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6156 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6157 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6158 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6159 * </ul> 6160 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6161 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6162 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6163 * <p> 6164 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6165 * this case. See below for a detailed description. 6166 * <p> 6167 * <em>Parameters optional everywhere:</em> 6168 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6169 * As an exception, the init functions cannot take any {@code v} parameters, 6170 * because those values are not yet computed when the init functions are executed. 6171 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6172 * In fact, any clause function may take no arguments at all. 6173 * <p> 6174 * <em>Loop parameters:</em> 6175 * A clause function may take all the iteration variable values it is entitled to, in which case 6176 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6177 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6178 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6179 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6180 * init function is automatically a loop parameter {@code a}.) 6181 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6182 * These loop parameters act as loop-invariant values visible across the whole loop. 6183 * <p> 6184 * <em>Parameters visible everywhere:</em> 6185 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6186 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6187 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6188 * Most clause functions will not need all of this information, but they will be formally connected to it 6189 * as if by {@link #dropArguments}. 6190 * <a id="astar"></a> 6191 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6192 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6193 * In that notation, the general form of an init function parameter list 6194 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6195 * <p> 6196 * <em>Checking clause structure:</em> 6197 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6198 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6199 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6200 * met by the inputs to the loop combinator. 6201 * <p> 6202 * <em>Effectively identical sequences:</em> 6203 * <a id="effid"></a> 6204 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6205 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6206 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6207 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6208 * that longest list. 6209 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6210 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6211 * <p> 6212 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6213 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6214 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6215 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6216 * four. Padding takes place by appending elements to the array. 6217 * <li>Clauses with all {@code null}s are disregarded. 6218 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6219 * </ol> 6220 * <p> 6221 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6222 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6223 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6224 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6225 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6226 * iteration variable type. 6227 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6228 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6229 * </ol> 6230 * <p> 6231 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6232 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6233 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6234 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6235 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6236 * (These types will be checked in step 2, along with all the clause function types.) 6237 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6238 * <li>All of the collected parameter lists must be effectively identical. 6239 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6240 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6241 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6242 * the "internal parameter list". 6243 * </ul> 6244 * <p> 6245 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6246 * <li>Examine fini function return types, disregarding omitted fini functions. 6247 * <li>If there are no fini functions, the loop return type is {@code void}. 6248 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6249 * type. 6250 * </ol> 6251 * <p> 6252 * <em>Step 1D: Check other types.</em><ol type="a"> 6253 * <li>There must be at least one non-omitted pred function. 6254 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6255 * </ol> 6256 * <p> 6257 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6258 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6259 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6260 * (Note that their parameter lists are already effectively identical to this list.) 6261 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6262 * effectively identical to the internal parameter list {@code (V... A...)}. 6263 * </ol> 6264 * <p> 6265 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6266 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6267 * type. 6268 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6269 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6270 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6271 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6272 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6273 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6274 * loop return type. 6275 * </ol> 6276 * <p> 6277 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6278 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6279 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6280 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6281 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6282 * pad out the end of the list. 6283 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6284 * </ol> 6285 * <p> 6286 * <em>Final observations.</em><ol type="a"> 6287 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6288 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6289 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6290 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6291 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6292 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6293 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6294 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6295 * </ol> 6296 * <p> 6297 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6298 * <ul> 6299 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6300 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6301 * (Only one {@code Pn} has to be non-{@code null}.) 6302 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6303 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6304 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6305 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6306 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6307 * the resulting loop handle's parameter types {@code (A...)}. 6308 * </ul> 6309 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6310 * which is natural if most of the loop computation happens in the steps. For some loops, 6311 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6312 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6313 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6314 * where the init functions will need the extra parameters. For such reasons, the rules for 6315 * determining these parameters are as symmetric as possible, across all clause parts. 6316 * In general, the loop parameters function as common invariant values across the whole 6317 * loop, while the iteration variables function as common variant values, or (if there is 6318 * no step function) as internal loop invariant temporaries. 6319 * <p> 6320 * <em>Loop execution.</em><ol type="a"> 6321 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6322 * every clause function. These locals are loop invariant. 6323 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6324 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6325 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6326 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6327 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6328 * (in argument order). 6329 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6330 * returns {@code false}. 6331 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6332 * sequence {@code (v...)} of loop variables. 6333 * The updated value is immediately visible to all subsequent function calls. 6334 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6335 * (of type {@code R}) is returned from the loop as a whole. 6336 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6337 * except by throwing an exception. 6338 * </ol> 6339 * <p> 6340 * <em>Usage tips.</em> 6341 * <ul> 6342 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6343 * sometimes a step function only needs to observe the current value of its own variable. 6344 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6345 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6346 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6347 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6348 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6349 * <li>If some of the clause functions are virtual methods on an instance, the instance 6350 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6351 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6352 * will be the first iteration variable value, and it will be easy to use virtual 6353 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6354 * </ul> 6355 * <p> 6356 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6357 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6358 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6359 * {@snippet lang="java" : 6360 * V... init...(A...); 6361 * boolean pred...(V..., A...); 6362 * V... step...(V..., A...); 6363 * R fini...(V..., A...); 6364 * R loop(A... a) { 6365 * V... v... = init...(a...); 6366 * for (;;) { 6367 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6368 * v = s(v..., a...); 6369 * if (!p(v..., a...)) { 6370 * return f(v..., a...); 6371 * } 6372 * } 6373 * } 6374 * } 6375 * } 6376 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6377 * to their full length, even though individual clause functions may neglect to take them all. 6378 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6379 * 6380 * @apiNote Example: 6381 * {@snippet lang="java" : 6382 * // iterative implementation of the factorial function as a loop handle 6383 * static int one(int k) { return 1; } 6384 * static int inc(int i, int acc, int k) { return i + 1; } 6385 * static int mult(int i, int acc, int k) { return i * acc; } 6386 * static boolean pred(int i, int acc, int k) { return i < k; } 6387 * static int fin(int i, int acc, int k) { return acc; } 6388 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6389 * // null initializer for counter, should initialize to 0 6390 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6391 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6392 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6393 * assertEquals(120, loop.invoke(5)); 6394 * } 6395 * The same example, dropping arguments and using combinators: 6396 * {@snippet lang="java" : 6397 * // simplified implementation of the factorial function as a loop handle 6398 * static int inc(int i) { return i + 1; } // drop acc, k 6399 * static int mult(int i, int acc) { return i * acc; } //drop k 6400 * static boolean cmp(int i, int k) { return i < k; } 6401 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6402 * // null initializer for counter, should initialize to 0 6403 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6404 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6405 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6406 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6407 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6408 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6409 * assertEquals(720, loop.invoke(6)); 6410 * } 6411 * A similar example, using a helper object to hold a loop parameter: 6412 * {@snippet lang="java" : 6413 * // instance-based implementation of the factorial function as a loop handle 6414 * static class FacLoop { 6415 * final int k; 6416 * FacLoop(int k) { this.k = k; } 6417 * int inc(int i) { return i + 1; } 6418 * int mult(int i, int acc) { return i * acc; } 6419 * boolean pred(int i) { return i < k; } 6420 * int fin(int i, int acc) { return acc; } 6421 * } 6422 * // assume MH_FacLoop is a handle to the constructor 6423 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6424 * // null initializer for counter, should initialize to 0 6425 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6426 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6427 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6428 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6429 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6430 * assertEquals(5040, loop.invoke(7)); 6431 * } 6432 * 6433 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6434 * 6435 * @return a method handle embodying the looping behavior as defined by the arguments. 6436 * 6437 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6438 * 6439 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6440 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6441 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6442 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6443 * @since 9 6444 */ 6445 public static MethodHandle loop(MethodHandle[]... clauses) { 6446 // Step 0: determine clause structure. 6447 loopChecks0(clauses); 6448 6449 List<MethodHandle> init = new ArrayList<>(); 6450 List<MethodHandle> step = new ArrayList<>(); 6451 List<MethodHandle> pred = new ArrayList<>(); 6452 List<MethodHandle> fini = new ArrayList<>(); 6453 6454 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6455 init.add(clause[0]); // all clauses have at least length 1 6456 step.add(clause.length <= 1 ? null : clause[1]); 6457 pred.add(clause.length <= 2 ? null : clause[2]); 6458 fini.add(clause.length <= 3 ? null : clause[3]); 6459 }); 6460 6461 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6462 final int nclauses = init.size(); 6463 6464 // Step 1A: determine iteration variables (V...). 6465 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6466 for (int i = 0; i < nclauses; ++i) { 6467 MethodHandle in = init.get(i); 6468 MethodHandle st = step.get(i); 6469 if (in == null && st == null) { 6470 iterationVariableTypes.add(void.class); 6471 } else if (in != null && st != null) { 6472 loopChecks1a(i, in, st); 6473 iterationVariableTypes.add(in.type().returnType()); 6474 } else { 6475 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6476 } 6477 } 6478 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6479 6480 // Step 1B: determine loop parameters (A...). 6481 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6482 loopChecks1b(init, commonSuffix); 6483 6484 // Step 1C: determine loop return type. 6485 // Step 1D: check other types. 6486 // local variable required here; see JDK-8223553 6487 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6488 .map(MethodType::returnType); 6489 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6490 loopChecks1cd(pred, fini, loopReturnType); 6491 6492 // Step 2: determine parameter lists. 6493 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6494 commonParameterSequence.addAll(commonSuffix); 6495 loopChecks2(step, pred, fini, commonParameterSequence); 6496 // Step 3: fill in omitted functions. 6497 for (int i = 0; i < nclauses; ++i) { 6498 Class<?> t = iterationVariableTypes.get(i); 6499 if (init.get(i) == null) { 6500 init.set(i, empty(methodType(t, commonSuffix))); 6501 } 6502 if (step.get(i) == null) { 6503 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6504 } 6505 if (pred.get(i) == null) { 6506 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6507 } 6508 if (fini.get(i) == null) { 6509 fini.set(i, empty(methodType(t, commonParameterSequence))); 6510 } 6511 } 6512 6513 // Step 4: fill in missing parameter types. 6514 // Also convert all handles to fixed-arity handles. 6515 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6516 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6517 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6518 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6519 6520 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6521 allMatch(pl -> pl.equals(commonSuffix)); 6522 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6523 allMatch(pl -> pl.equals(commonParameterSequence)); 6524 6525 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6526 } 6527 6528 private static void loopChecks0(MethodHandle[][] clauses) { 6529 if (clauses == null || clauses.length == 0) { 6530 throw newIllegalArgumentException("null or no clauses passed"); 6531 } 6532 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6533 throw newIllegalArgumentException("null clauses are not allowed"); 6534 } 6535 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6536 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6537 } 6538 } 6539 6540 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6541 if (in.type().returnType() != st.type().returnType()) { 6542 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6543 st.type().returnType()); 6544 } 6545 } 6546 6547 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6548 return mhs.filter(Objects::nonNull) 6549 // take only those that can contribute to a common suffix because they are longer than the prefix 6550 .map(MethodHandle::type) 6551 .filter(t -> t.parameterCount() > skipSize) 6552 .max(Comparator.comparingInt(MethodType::parameterCount)) 6553 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6554 .orElse(List.of()); 6555 } 6556 6557 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6558 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6559 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6560 return longest1.size() >= longest2.size() ? longest1 : longest2; 6561 } 6562 6563 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6564 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6565 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6566 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6567 " (common suffix: " + commonSuffix + ")"); 6568 } 6569 } 6570 6571 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6572 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6573 anyMatch(t -> t != loopReturnType)) { 6574 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6575 loopReturnType + ")"); 6576 } 6577 6578 if (pred.stream().noneMatch(Objects::nonNull)) { 6579 throw newIllegalArgumentException("no predicate found", pred); 6580 } 6581 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6582 anyMatch(t -> t != boolean.class)) { 6583 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6584 } 6585 } 6586 6587 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6588 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6589 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6590 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6591 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6592 } 6593 } 6594 6595 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6596 return hs.stream().map(h -> { 6597 int pc = h.type().parameterCount(); 6598 int tpsize = targetParams.size(); 6599 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6600 }).toList(); 6601 } 6602 6603 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6604 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6605 } 6606 6607 /** 6608 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6609 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6610 * <p> 6611 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6612 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6613 * evaluates to {@code true}). 6614 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6615 * <p> 6616 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6617 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6618 * and updated with the value returned from its invocation. The result of loop execution will be 6619 * the final value of the additional loop-local variable (if present). 6620 * <p> 6621 * The following rules hold for these argument handles:<ul> 6622 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6623 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6624 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6625 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6626 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6627 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6628 * It will constrain the parameter lists of the other loop parts. 6629 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6630 * list {@code (A...)} is called the <em>external parameter list</em>. 6631 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6632 * additional state variable of the loop. 6633 * The body must both accept and return a value of this type {@code V}. 6634 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6635 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6636 * <a href="MethodHandles.html#effid">effectively identical</a> 6637 * to the external parameter list {@code (A...)}. 6638 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6639 * {@linkplain #empty default value}. 6640 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6641 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6642 * effectively identical to the internal parameter list. 6643 * </ul> 6644 * <p> 6645 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6646 * <li>The loop handle's result type is the result type {@code V} of the body. 6647 * <li>The loop handle's parameter types are the types {@code (A...)}, 6648 * from the external parameter list. 6649 * </ul> 6650 * <p> 6651 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6652 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6653 * passed to the loop. 6654 * {@snippet lang="java" : 6655 * V init(A...); 6656 * boolean pred(V, A...); 6657 * V body(V, A...); 6658 * V whileLoop(A... a...) { 6659 * V v = init(a...); 6660 * while (pred(v, a...)) { 6661 * v = body(v, a...); 6662 * } 6663 * return v; 6664 * } 6665 * } 6666 * 6667 * @apiNote Example: 6668 * {@snippet lang="java" : 6669 * // implement the zip function for lists as a loop handle 6670 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6671 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6672 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6673 * zip.add(a.next()); 6674 * zip.add(b.next()); 6675 * return zip; 6676 * } 6677 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6678 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6679 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6680 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6681 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6682 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6683 * } 6684 * 6685 * 6686 * @apiNote The implementation of this method can be expressed as follows: 6687 * {@snippet lang="java" : 6688 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6689 * MethodHandle fini = (body.type().returnType() == void.class 6690 * ? null : identity(body.type().returnType())); 6691 * MethodHandle[] 6692 * checkExit = { null, null, pred, fini }, 6693 * varBody = { init, body }; 6694 * return loop(checkExit, varBody); 6695 * } 6696 * } 6697 * 6698 * @param init optional initializer, providing the initial value of the loop variable. 6699 * May be {@code null}, implying a default initial value. See above for other constraints. 6700 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6701 * above for other constraints. 6702 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6703 * See above for other constraints. 6704 * 6705 * @return a method handle implementing the {@code while} loop as described by the arguments. 6706 * @throws IllegalArgumentException if the rules for the arguments are violated. 6707 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6708 * 6709 * @see #loop(MethodHandle[][]) 6710 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6711 * @since 9 6712 */ 6713 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6714 whileLoopChecks(init, pred, body); 6715 MethodHandle fini = identityOrVoid(body.type().returnType()); 6716 MethodHandle[] checkExit = { null, null, pred, fini }; 6717 MethodHandle[] varBody = { init, body }; 6718 return loop(checkExit, varBody); 6719 } 6720 6721 /** 6722 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6723 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6724 * <p> 6725 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6726 * method will, in each iteration, first execute its body and then evaluate the predicate. 6727 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6728 * <p> 6729 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6730 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6731 * and updated with the value returned from its invocation. The result of loop execution will be 6732 * the final value of the additional loop-local variable (if present). 6733 * <p> 6734 * The following rules hold for these argument handles:<ul> 6735 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6736 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6737 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6738 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6739 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6740 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6741 * It will constrain the parameter lists of the other loop parts. 6742 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6743 * list {@code (A...)} is called the <em>external parameter list</em>. 6744 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6745 * additional state variable of the loop. 6746 * The body must both accept and return a value of this type {@code V}. 6747 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6748 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6749 * <a href="MethodHandles.html#effid">effectively identical</a> 6750 * to the external parameter list {@code (A...)}. 6751 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6752 * {@linkplain #empty default value}. 6753 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6754 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6755 * effectively identical to the internal parameter list. 6756 * </ul> 6757 * <p> 6758 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6759 * <li>The loop handle's result type is the result type {@code V} of the body. 6760 * <li>The loop handle's parameter types are the types {@code (A...)}, 6761 * from the external parameter list. 6762 * </ul> 6763 * <p> 6764 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6765 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6766 * passed to the loop. 6767 * {@snippet lang="java" : 6768 * V init(A...); 6769 * boolean pred(V, A...); 6770 * V body(V, A...); 6771 * V doWhileLoop(A... a...) { 6772 * V v = init(a...); 6773 * do { 6774 * v = body(v, a...); 6775 * } while (pred(v, a...)); 6776 * return v; 6777 * } 6778 * } 6779 * 6780 * @apiNote Example: 6781 * {@snippet lang="java" : 6782 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6783 * static int zero(int limit) { return 0; } 6784 * static int step(int i, int limit) { return i + 1; } 6785 * static boolean pred(int i, int limit) { return i < limit; } 6786 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6787 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6788 * assertEquals(23, loop.invoke(23)); 6789 * } 6790 * 6791 * 6792 * @apiNote The implementation of this method can be expressed as follows: 6793 * {@snippet lang="java" : 6794 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6795 * MethodHandle fini = (body.type().returnType() == void.class 6796 * ? null : identity(body.type().returnType())); 6797 * MethodHandle[] clause = { init, body, pred, fini }; 6798 * return loop(clause); 6799 * } 6800 * } 6801 * 6802 * @param init optional initializer, providing the initial value of the loop variable. 6803 * May be {@code null}, implying a default initial value. See above for other constraints. 6804 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6805 * See above for other constraints. 6806 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6807 * above for other constraints. 6808 * 6809 * @return a method handle implementing the {@code while} loop as described by the arguments. 6810 * @throws IllegalArgumentException if the rules for the arguments are violated. 6811 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6812 * 6813 * @see #loop(MethodHandle[][]) 6814 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 6815 * @since 9 6816 */ 6817 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6818 whileLoopChecks(init, pred, body); 6819 MethodHandle fini = identityOrVoid(body.type().returnType()); 6820 MethodHandle[] clause = {init, body, pred, fini }; 6821 return loop(clause); 6822 } 6823 6824 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 6825 Objects.requireNonNull(pred); 6826 Objects.requireNonNull(body); 6827 MethodType bodyType = body.type(); 6828 Class<?> returnType = bodyType.returnType(); 6829 List<Class<?>> innerList = bodyType.parameterList(); 6830 List<Class<?>> outerList = innerList; 6831 if (returnType == void.class) { 6832 // OK 6833 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 6834 // leading V argument missing => error 6835 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6836 throw misMatchedTypes("body function", bodyType, expected); 6837 } else { 6838 outerList = innerList.subList(1, innerList.size()); 6839 } 6840 MethodType predType = pred.type(); 6841 if (predType.returnType() != boolean.class || 6842 !predType.effectivelyIdenticalParameters(0, innerList)) { 6843 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 6844 } 6845 if (init != null) { 6846 MethodType initType = init.type(); 6847 if (initType.returnType() != returnType || 6848 !initType.effectivelyIdenticalParameters(0, outerList)) { 6849 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6850 } 6851 } 6852 } 6853 6854 /** 6855 * Constructs a loop that runs a given number of iterations. 6856 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6857 * <p> 6858 * The number of iterations is determined by the {@code iterations} handle evaluation result. 6859 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 6860 * It will be initialized to 0 and incremented by 1 in each iteration. 6861 * <p> 6862 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6863 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6864 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6865 * <p> 6866 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6867 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6868 * iteration variable. 6869 * The result of the loop handle execution will be the final {@code V} value of that variable 6870 * (or {@code void} if there is no {@code V} variable). 6871 * <p> 6872 * The following rules hold for the argument handles:<ul> 6873 * <li>The {@code iterations} handle must not be {@code null}, and must return 6874 * the type {@code int}, referred to here as {@code I} in parameter type lists. 6875 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6876 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6877 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6878 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6879 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6880 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6881 * of types called the <em>internal parameter list</em>. 6882 * It will constrain the parameter lists of the other loop parts. 6883 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6884 * with no additional {@code A} types, then the internal parameter list is extended by 6885 * the argument types {@code A...} of the {@code iterations} handle. 6886 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6887 * list {@code (A...)} is called the <em>external parameter list</em>. 6888 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6889 * additional state variable of the loop. 6890 * The body must both accept a leading parameter and return a value of this type {@code V}. 6891 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6892 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6893 * <a href="MethodHandles.html#effid">effectively identical</a> 6894 * to the external parameter list {@code (A...)}. 6895 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6896 * {@linkplain #empty default value}. 6897 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 6898 * effectively identical to the external parameter list {@code (A...)}. 6899 * </ul> 6900 * <p> 6901 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6902 * <li>The loop handle's result type is the result type {@code V} of the body. 6903 * <li>The loop handle's parameter types are the types {@code (A...)}, 6904 * from the external parameter list. 6905 * </ul> 6906 * <p> 6907 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6908 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6909 * arguments passed to the loop. 6910 * {@snippet lang="java" : 6911 * int iterations(A...); 6912 * V init(A...); 6913 * V body(V, int, A...); 6914 * V countedLoop(A... a...) { 6915 * int end = iterations(a...); 6916 * V v = init(a...); 6917 * for (int i = 0; i < end; ++i) { 6918 * v = body(v, i, a...); 6919 * } 6920 * return v; 6921 * } 6922 * } 6923 * 6924 * @apiNote Example with a fully conformant body method: 6925 * {@snippet lang="java" : 6926 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6927 * // => a variation on a well known theme 6928 * static String step(String v, int counter, String init) { return "na " + v; } 6929 * // assume MH_step is a handle to the method above 6930 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 6931 * MethodHandle start = MethodHandles.identity(String.class); 6932 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 6933 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 6934 * } 6935 * 6936 * @apiNote Example with the simplest possible body method type, 6937 * and passing the number of iterations to the loop invocation: 6938 * {@snippet lang="java" : 6939 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6940 * // => a variation on a well known theme 6941 * static String step(String v, int counter ) { return "na " + v; } 6942 * // assume MH_step is a handle to the method above 6943 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 6944 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 6945 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 6946 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 6947 * } 6948 * 6949 * @apiNote Example that treats the number of iterations, string to append to, and string to append 6950 * as loop parameters: 6951 * {@snippet lang="java" : 6952 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6953 * // => a variation on a well known theme 6954 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 6955 * // assume MH_step is a handle to the method above 6956 * MethodHandle count = MethodHandles.identity(int.class); 6957 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 6958 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 6959 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 6960 * } 6961 * 6962 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 6963 * to enforce a loop type: 6964 * {@snippet lang="java" : 6965 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6966 * // => a variation on a well known theme 6967 * static String step(String v, int counter, String pre) { return pre + " " + v; } 6968 * // assume MH_step is a handle to the method above 6969 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 6970 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 6971 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 6972 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 6973 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 6974 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 6975 * } 6976 * 6977 * @apiNote The implementation of this method can be expressed as follows: 6978 * {@snippet lang="java" : 6979 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6980 * return countedLoop(empty(iterations.type()), iterations, init, body); 6981 * } 6982 * } 6983 * 6984 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 6985 * result type must be {@code int}. See above for other constraints. 6986 * @param init optional initializer, providing the initial value of the loop variable. 6987 * May be {@code null}, implying a default initial value. See above for other constraints. 6988 * @param body body of the loop, which may not be {@code null}. 6989 * It controls the loop parameters and result type in the standard case (see above for details). 6990 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6991 * and may accept any number of additional types. 6992 * See above for other constraints. 6993 * 6994 * @return a method handle representing the loop. 6995 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 6996 * @throws IllegalArgumentException if any argument violates the rules formulated above. 6997 * 6998 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 6999 * @since 9 7000 */ 7001 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7002 return countedLoop(empty(iterations.type()), iterations, init, body); 7003 } 7004 7005 /** 7006 * Constructs a loop that counts over a range of numbers. 7007 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7008 * <p> 7009 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7010 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7011 * values of the loop counter. 7012 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7013 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7014 * <p> 7015 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7016 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7017 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7018 * <p> 7019 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7020 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7021 * iteration variable. 7022 * The result of the loop handle execution will be the final {@code V} value of that variable 7023 * (or {@code void} if there is no {@code V} variable). 7024 * <p> 7025 * The following rules hold for the argument handles:<ul> 7026 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7027 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7028 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7029 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7030 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7031 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7032 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7033 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7034 * of types called the <em>internal parameter list</em>. 7035 * It will constrain the parameter lists of the other loop parts. 7036 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7037 * with no additional {@code A} types, then the internal parameter list is extended by 7038 * the argument types {@code A...} of the {@code end} handle. 7039 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7040 * list {@code (A...)} is called the <em>external parameter list</em>. 7041 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7042 * additional state variable of the loop. 7043 * The body must both accept a leading parameter and return a value of this type {@code V}. 7044 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7045 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7046 * <a href="MethodHandles.html#effid">effectively identical</a> 7047 * to the external parameter list {@code (A...)}. 7048 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7049 * {@linkplain #empty default value}. 7050 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7051 * effectively identical to the external parameter list {@code (A...)}. 7052 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7053 * to the external parameter list. 7054 * </ul> 7055 * <p> 7056 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7057 * <li>The loop handle's result type is the result type {@code V} of the body. 7058 * <li>The loop handle's parameter types are the types {@code (A...)}, 7059 * from the external parameter list. 7060 * </ul> 7061 * <p> 7062 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7063 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7064 * arguments passed to the loop. 7065 * {@snippet lang="java" : 7066 * int start(A...); 7067 * int end(A...); 7068 * V init(A...); 7069 * V body(V, int, A...); 7070 * V countedLoop(A... a...) { 7071 * int e = end(a...); 7072 * int s = start(a...); 7073 * V v = init(a...); 7074 * for (int i = s; i < e; ++i) { 7075 * v = body(v, i, a...); 7076 * } 7077 * return v; 7078 * } 7079 * } 7080 * 7081 * @apiNote The implementation of this method can be expressed as follows: 7082 * {@snippet lang="java" : 7083 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7084 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7085 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7086 * // the following semantics: 7087 * // MH_increment: (int limit, int counter) -> counter + 1 7088 * // MH_predicate: (int limit, int counter) -> counter < limit 7089 * Class<?> counterType = start.type().returnType(); // int 7090 * Class<?> returnType = body.type().returnType(); 7091 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7092 * if (returnType != void.class) { // ignore the V variable 7093 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7094 * pred = dropArguments(pred, 1, returnType); // ditto 7095 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7096 * } 7097 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7098 * MethodHandle[] 7099 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7100 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7101 * indexVar = { start, incr }; // i = start(); i = i + 1 7102 * return loop(loopLimit, bodyClause, indexVar); 7103 * } 7104 * } 7105 * 7106 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7107 * See above for other constraints. 7108 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7109 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7110 * @param init optional initializer, providing the initial value of the loop variable. 7111 * May be {@code null}, implying a default initial value. See above for other constraints. 7112 * @param body body of the loop, which may not be {@code null}. 7113 * It controls the loop parameters and result type in the standard case (see above for details). 7114 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7115 * and may accept any number of additional types. 7116 * See above for other constraints. 7117 * 7118 * @return a method handle representing the loop. 7119 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7120 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7121 * 7122 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7123 * @since 9 7124 */ 7125 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7126 countedLoopChecks(start, end, init, body); 7127 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7128 Class<?> limitType = end.type().returnType(); // yes, int again 7129 Class<?> returnType = body.type().returnType(); 7130 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7131 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7132 MethodHandle retv = null; 7133 if (returnType != void.class) { 7134 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7135 pred = dropArguments(pred, 1, returnType); // ditto 7136 retv = dropArguments(identity(returnType), 0, counterType); 7137 } 7138 body = dropArguments(body, 0, counterType); // ignore the limit variable 7139 MethodHandle[] 7140 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7141 bodyClause = { init, body }, // v = init(); v = body(v, i) 7142 indexVar = { start, incr }; // i = start(); i = i + 1 7143 return loop(loopLimit, bodyClause, indexVar); 7144 } 7145 7146 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7147 Objects.requireNonNull(start); 7148 Objects.requireNonNull(end); 7149 Objects.requireNonNull(body); 7150 Class<?> counterType = start.type().returnType(); 7151 if (counterType != int.class) { 7152 MethodType expected = start.type().changeReturnType(int.class); 7153 throw misMatchedTypes("start function", start.type(), expected); 7154 } else if (end.type().returnType() != counterType) { 7155 MethodType expected = end.type().changeReturnType(counterType); 7156 throw misMatchedTypes("end function", end.type(), expected); 7157 } 7158 MethodType bodyType = body.type(); 7159 Class<?> returnType = bodyType.returnType(); 7160 List<Class<?>> innerList = bodyType.parameterList(); 7161 // strip leading V value if present 7162 int vsize = (returnType == void.class ? 0 : 1); 7163 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7164 // argument list has no "V" => error 7165 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7166 throw misMatchedTypes("body function", bodyType, expected); 7167 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7168 // missing I type => error 7169 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7170 throw misMatchedTypes("body function", bodyType, expected); 7171 } 7172 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7173 if (outerList.isEmpty()) { 7174 // special case; take lists from end handle 7175 outerList = end.type().parameterList(); 7176 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7177 } 7178 MethodType expected = methodType(counterType, outerList); 7179 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7180 throw misMatchedTypes("start parameter types", start.type(), expected); 7181 } 7182 if (end.type() != start.type() && 7183 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7184 throw misMatchedTypes("end parameter types", end.type(), expected); 7185 } 7186 if (init != null) { 7187 MethodType initType = init.type(); 7188 if (initType.returnType() != returnType || 7189 !initType.effectivelyIdenticalParameters(0, outerList)) { 7190 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7191 } 7192 } 7193 } 7194 7195 /** 7196 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7197 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7198 * <p> 7199 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7200 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7201 * <p> 7202 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7203 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7204 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7205 * <p> 7206 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7207 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7208 * iteration variable. 7209 * The result of the loop handle execution will be the final {@code V} value of that variable 7210 * (or {@code void} if there is no {@code V} variable). 7211 * <p> 7212 * The following rules hold for the argument handles:<ul> 7213 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7214 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7215 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7216 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7217 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7218 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7219 * of types called the <em>internal parameter list</em>. 7220 * It will constrain the parameter lists of the other loop parts. 7221 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7222 * with no additional {@code A} types, then the internal parameter list is extended by 7223 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7224 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7225 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7226 * list {@code (A...)} is called the <em>external parameter list</em>. 7227 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7228 * additional state variable of the loop. 7229 * The body must both accept a leading parameter and return a value of this type {@code V}. 7230 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7231 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7232 * <a href="MethodHandles.html#effid">effectively identical</a> 7233 * to the external parameter list {@code (A...)}. 7234 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7235 * {@linkplain #empty default value}. 7236 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7237 * type {@code java.util.Iterator} or a subtype thereof. 7238 * The iterator it produces when the loop is executed will be assumed 7239 * to yield values which can be converted to type {@code T}. 7240 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7241 * effectively identical to the external parameter list {@code (A...)}. 7242 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7243 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7244 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7245 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7246 * the {@link MethodHandle#asType asType} conversion method. 7247 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7248 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7249 * </ul> 7250 * <p> 7251 * The type {@code T} may be either a primitive or reference. 7252 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7253 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7254 * as if by the {@link MethodHandle#asType asType} conversion method. 7255 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7256 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7257 * <p> 7258 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7259 * <li>The loop handle's result type is the result type {@code V} of the body. 7260 * <li>The loop handle's parameter types are the types {@code (A...)}, 7261 * from the external parameter list. 7262 * </ul> 7263 * <p> 7264 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7265 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7266 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7267 * {@snippet lang="java" : 7268 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7269 * V init(A...); 7270 * V body(V,T,A...); 7271 * V iteratedLoop(A... a...) { 7272 * Iterator<T> it = iterator(a...); 7273 * V v = init(a...); 7274 * while (it.hasNext()) { 7275 * T t = it.next(); 7276 * v = body(v, t, a...); 7277 * } 7278 * return v; 7279 * } 7280 * } 7281 * 7282 * @apiNote Example: 7283 * {@snippet lang="java" : 7284 * // get an iterator from a list 7285 * static List<String> reverseStep(List<String> r, String e) { 7286 * r.add(0, e); 7287 * return r; 7288 * } 7289 * static List<String> newArrayList() { return new ArrayList<>(); } 7290 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7291 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7292 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7293 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7294 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7295 * } 7296 * 7297 * @apiNote The implementation of this method can be expressed approximately as follows: 7298 * {@snippet lang="java" : 7299 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7300 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7301 * Class<?> returnType = body.type().returnType(); 7302 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7303 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7304 * MethodHandle retv = null, step = body, startIter = iterator; 7305 * if (returnType != void.class) { 7306 * // the simple thing first: in (I V A...), drop the I to get V 7307 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7308 * // body type signature (V T A...), internal loop types (I V A...) 7309 * step = swapArguments(body, 0, 1); // swap V <-> T 7310 * } 7311 * if (startIter == null) startIter = MH_getIter; 7312 * MethodHandle[] 7313 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7314 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7315 * return loop(iterVar, bodyClause); 7316 * } 7317 * } 7318 * 7319 * @param iterator an optional handle to return the iterator to start the loop. 7320 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7321 * See above for other constraints. 7322 * @param init optional initializer, providing the initial value of the loop variable. 7323 * May be {@code null}, implying a default initial value. See above for other constraints. 7324 * @param body body of the loop, which may not be {@code null}. 7325 * It controls the loop parameters and result type in the standard case (see above for details). 7326 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7327 * and may accept any number of additional types. 7328 * See above for other constraints. 7329 * 7330 * @return a method handle embodying the iteration loop functionality. 7331 * @throws NullPointerException if the {@code body} handle is {@code null}. 7332 * @throws IllegalArgumentException if any argument violates the above requirements. 7333 * 7334 * @since 9 7335 */ 7336 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7337 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7338 Class<?> returnType = body.type().returnType(); 7339 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7340 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7341 MethodHandle startIter; 7342 MethodHandle nextVal; 7343 { 7344 MethodType iteratorType; 7345 if (iterator == null) { 7346 // derive argument type from body, if available, else use Iterable 7347 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7348 iteratorType = startIter.type().changeParameterType(0, iterableType); 7349 } else { 7350 // force return type to the internal iterator class 7351 iteratorType = iterator.type().changeReturnType(Iterator.class); 7352 startIter = iterator; 7353 } 7354 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7355 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7356 7357 // perform the asType transforms under an exception transformer, as per spec.: 7358 try { 7359 startIter = startIter.asType(iteratorType); 7360 nextVal = nextRaw.asType(nextValType); 7361 } catch (WrongMethodTypeException ex) { 7362 throw new IllegalArgumentException(ex); 7363 } 7364 } 7365 7366 MethodHandle retv = null, step = body; 7367 if (returnType != void.class) { 7368 // the simple thing first: in (I V A...), drop the I to get V 7369 retv = dropArguments(identity(returnType), 0, Iterator.class); 7370 // body type signature (V T A...), internal loop types (I V A...) 7371 step = swapArguments(body, 0, 1); // swap V <-> T 7372 } 7373 7374 MethodHandle[] 7375 iterVar = { startIter, null, hasNext, retv }, 7376 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7377 return loop(iterVar, bodyClause); 7378 } 7379 7380 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7381 Objects.requireNonNull(body); 7382 MethodType bodyType = body.type(); 7383 Class<?> returnType = bodyType.returnType(); 7384 List<Class<?>> internalParamList = bodyType.parameterList(); 7385 // strip leading V value if present 7386 int vsize = (returnType == void.class ? 0 : 1); 7387 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7388 // argument list has no "V" => error 7389 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7390 throw misMatchedTypes("body function", bodyType, expected); 7391 } else if (internalParamList.size() <= vsize) { 7392 // missing T type => error 7393 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7394 throw misMatchedTypes("body function", bodyType, expected); 7395 } 7396 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7397 Class<?> iterableType = null; 7398 if (iterator != null) { 7399 // special case; if the body handle only declares V and T then 7400 // the external parameter list is obtained from iterator handle 7401 if (externalParamList.isEmpty()) { 7402 externalParamList = iterator.type().parameterList(); 7403 } 7404 MethodType itype = iterator.type(); 7405 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7406 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7407 } 7408 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7409 MethodType expected = methodType(itype.returnType(), externalParamList); 7410 throw misMatchedTypes("iterator parameters", itype, expected); 7411 } 7412 } else { 7413 if (externalParamList.isEmpty()) { 7414 // special case; if the iterator handle is null and the body handle 7415 // only declares V and T then the external parameter list consists 7416 // of Iterable 7417 externalParamList = List.of(Iterable.class); 7418 iterableType = Iterable.class; 7419 } else { 7420 // special case; if the iterator handle is null and the external 7421 // parameter list is not empty then the first parameter must be 7422 // assignable to Iterable 7423 iterableType = externalParamList.get(0); 7424 if (!Iterable.class.isAssignableFrom(iterableType)) { 7425 throw newIllegalArgumentException( 7426 "inferred first loop argument must inherit from Iterable: " + iterableType); 7427 } 7428 } 7429 } 7430 if (init != null) { 7431 MethodType initType = init.type(); 7432 if (initType.returnType() != returnType || 7433 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7434 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7435 } 7436 } 7437 return iterableType; // help the caller a bit 7438 } 7439 7440 /*non-public*/ 7441 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7442 // there should be a better way to uncross my wires 7443 int arity = mh.type().parameterCount(); 7444 int[] order = new int[arity]; 7445 for (int k = 0; k < arity; k++) order[k] = k; 7446 order[i] = j; order[j] = i; 7447 Class<?>[] types = mh.type().parameterArray(); 7448 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7449 MethodType swapType = methodType(mh.type().returnType(), types); 7450 return permuteArguments(mh, swapType, order); 7451 } 7452 7453 /** 7454 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7455 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7456 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7457 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7458 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7459 * {@code try-finally} handle. 7460 * <p> 7461 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7462 * The first is the exception thrown during the 7463 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7464 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7465 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7466 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7467 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7468 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7469 * <p> 7470 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7471 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7472 * two extra leading parameters:<ul> 7473 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7474 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7475 * the result from the execution of the {@code target} handle. 7476 * This parameter is not present if the {@code target} returns {@code void}. 7477 * </ul> 7478 * <p> 7479 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7480 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7481 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7482 * the cleanup. 7483 * {@snippet lang="java" : 7484 * V target(A..., B...); 7485 * V cleanup(Throwable, V, A...); 7486 * V adapter(A... a, B... b) { 7487 * V result = (zero value for V); 7488 * Throwable throwable = null; 7489 * try { 7490 * result = target(a..., b...); 7491 * } catch (Throwable t) { 7492 * throwable = t; 7493 * throw t; 7494 * } finally { 7495 * result = cleanup(throwable, result, a...); 7496 * } 7497 * return result; 7498 * } 7499 * } 7500 * <p> 7501 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7502 * be modified by execution of the target, and so are passed unchanged 7503 * from the caller to the cleanup, if it is invoked. 7504 * <p> 7505 * The target and cleanup must return the same type, even if the cleanup 7506 * always throws. 7507 * To create such a throwing cleanup, compose the cleanup logic 7508 * with {@link #throwException throwException}, 7509 * in order to create a method handle of the correct return type. 7510 * <p> 7511 * Note that {@code tryFinally} never converts exceptions into normal returns. 7512 * In rare cases where exceptions must be converted in that way, first wrap 7513 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7514 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7515 * <p> 7516 * It is recommended that the first parameter type of {@code cleanup} be 7517 * declared {@code Throwable} rather than a narrower subtype. This ensures 7518 * {@code cleanup} will always be invoked with whatever exception that 7519 * {@code target} throws. Declaring a narrower type may result in a 7520 * {@code ClassCastException} being thrown by the {@code try-finally} 7521 * handle if the type of the exception thrown by {@code target} is not 7522 * assignable to the first parameter type of {@code cleanup}. Note that 7523 * various exception types of {@code VirtualMachineError}, 7524 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7525 * thrown by almost any kind of Java code, and a finally clause that 7526 * catches (say) only {@code IOException} would mask any of the others 7527 * behind a {@code ClassCastException}. 7528 * 7529 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7530 * @param cleanup the handle that is invoked in the finally block. 7531 * 7532 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7533 * @throws NullPointerException if any argument is null 7534 * @throws IllegalArgumentException if {@code cleanup} does not accept 7535 * the required leading arguments, or if the method handle types do 7536 * not match in their return types and their 7537 * corresponding trailing parameters 7538 * 7539 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7540 * @since 9 7541 */ 7542 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7543 Class<?>[] targetParamTypes = target.type().ptypes(); 7544 Class<?> rtype = target.type().returnType(); 7545 7546 tryFinallyChecks(target, cleanup); 7547 7548 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7549 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7550 // target parameter list. 7551 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7552 7553 // Ensure that the intrinsic type checks the instance thrown by the 7554 // target against the first parameter of cleanup 7555 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7556 7557 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7558 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7559 } 7560 7561 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7562 Class<?> rtype = target.type().returnType(); 7563 if (rtype != cleanup.type().returnType()) { 7564 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7565 } 7566 MethodType cleanupType = cleanup.type(); 7567 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7568 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7569 } 7570 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7571 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7572 } 7573 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7574 // target parameter list. 7575 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7576 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7577 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7578 cleanup.type(), target.type()); 7579 } 7580 } 7581 7582 /** 7583 * Creates a table switch method handle, which can be used to switch over a set of target 7584 * method handles, based on a given target index, called selector. 7585 * <p> 7586 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7587 * and where {@code N} is the number of target method handles, the table switch method 7588 * handle will invoke the n-th target method handle from the list of target method handles. 7589 * <p> 7590 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7591 * method handle will invoke the given fallback method handle. 7592 * <p> 7593 * All method handles passed to this method must have the same type, with the additional 7594 * requirement that the leading parameter be of type {@code int}. The leading parameter 7595 * represents the selector. 7596 * <p> 7597 * Any trailing parameters present in the type will appear on the returned table switch 7598 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7599 * together with the selector value, to the selected method handle when invoking it. 7600 * 7601 * @apiNote Example: 7602 * The cases each drop the {@code selector} value they are given, and take an additional 7603 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7604 * to a specific constant label string for each case: 7605 * {@snippet lang="java" : 7606 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7607 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7608 * MethodType.methodType(String.class, String.class)); 7609 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7610 * 7611 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7612 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7613 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7614 * 7615 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7616 * caseDefault, 7617 * case0, 7618 * case1 7619 * ); 7620 * 7621 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7622 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7623 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7624 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7625 * } 7626 * 7627 * @param fallback the fallback method handle that is called when the selector is not 7628 * within the range {@code [0, N)}. 7629 * @param targets array of target method handles. 7630 * @return the table switch method handle. 7631 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7632 * any of the elements of the {@code targets} array are 7633 * {@code null}. 7634 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7635 * parameter of the fallback handle or any of the target 7636 * handles is not {@code int}, or if the types of 7637 * the fallback handle and all of target handles are 7638 * not the same. 7639 * 7640 * @since 17 7641 */ 7642 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7643 Objects.requireNonNull(fallback); 7644 Objects.requireNonNull(targets); 7645 targets = targets.clone(); 7646 MethodType type = tableSwitchChecks(fallback, targets); 7647 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7648 } 7649 7650 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7651 if (caseActions.length == 0) 7652 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7653 7654 MethodType expectedType = defaultCase.type(); 7655 7656 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7657 throw new IllegalArgumentException( 7658 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7659 7660 for (MethodHandle mh : caseActions) { 7661 Objects.requireNonNull(mh); 7662 if (mh.type() != expectedType) 7663 throw new IllegalArgumentException( 7664 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7665 } 7666 7667 return expectedType; 7668 } 7669 7670 /** 7671 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7672 * <p> 7673 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7674 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7675 * to the target var handle. 7676 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7677 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7678 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7679 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7680 * <p> 7681 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7682 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7683 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7684 * will be appended to the coordinates of the target var handle). 7685 * <p> 7686 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7687 * throw an {@link IllegalStateException}. 7688 * <p> 7689 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7690 * atomic access guarantees as those featured by the target var handle. 7691 * 7692 * @param target the target var handle 7693 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7694 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7695 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7696 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7697 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7698 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7699 * @throws NullPointerException if any of the arguments is {@code null}. 7700 * @since 22 7701 */ 7702 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7703 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7704 } 7705 7706 /** 7707 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7708 * <p> 7709 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7710 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7711 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7712 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7713 * by the adaptation) to the target var handle. 7714 * <p> 7715 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7716 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7717 * <p> 7718 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7719 * throw an {@link IllegalStateException}. 7720 * <p> 7721 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7722 * atomic access guarantees as those featured by the target var handle. 7723 * 7724 * @param target the target var handle 7725 * @param pos the position of the first coordinate to be transformed 7726 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7727 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7728 * to the new coordinate values. 7729 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7730 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7731 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7732 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7733 * or if it's determined that any of the filters throws any checked exceptions. 7734 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 7735 * @since 22 7736 */ 7737 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 7738 return VarHandles.filterCoordinates(target, pos, filters); 7739 } 7740 7741 /** 7742 * Provides a target var handle with one or more <em>bound coordinates</em> 7743 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 7744 * coordinate types than the target var handle. 7745 * <p> 7746 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 7747 * are joined with bound coordinate values, and then passed to the target var handle. 7748 * <p> 7749 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 7750 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7751 * <p> 7752 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7753 * atomic access guarantees as those featured by the target var handle. 7754 * 7755 * @param target the var handle to invoke after the bound coordinates are inserted 7756 * @param pos the position of the first coordinate to be inserted 7757 * @param values the series of bound coordinates to insert 7758 * @return an adapter var handle which inserts additional coordinates, 7759 * before calling the target var handle 7760 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7761 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 7762 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 7763 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 7764 * of the target var handle. 7765 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 7766 * @since 22 7767 */ 7768 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 7769 return VarHandles.insertCoordinates(target, pos, values); 7770 } 7771 7772 /** 7773 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 7774 * so that the new coordinates match the provided ones. 7775 * <p> 7776 * The given array controls the reordering. 7777 * Call {@code #I} the number of incoming coordinates (the value 7778 * {@code newCoordinates.size()}), and call {@code #O} the number 7779 * of outgoing coordinates (the number of coordinates associated with the target var handle). 7780 * Then the length of the reordering array must be {@code #O}, 7781 * and each element must be a non-negative number less than {@code #I}. 7782 * For every {@code N} less than {@code #O}, the {@code N}-th 7783 * outgoing coordinate will be taken from the {@code I}-th incoming 7784 * coordinate, where {@code I} is {@code reorder[N]}. 7785 * <p> 7786 * No coordinate value conversions are applied. 7787 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 7788 * must be identical to the type of the corresponding outgoing coordinate 7789 * in the target var handle. 7790 * <p> 7791 * The reordering array need not specify an actual permutation. 7792 * An incoming coordinate will be duplicated if its index appears 7793 * more than once in the array, and an incoming coordinate will be dropped 7794 * if its index does not appear in the array. 7795 * <p> 7796 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7797 * atomic access guarantees as those featured by the target var handle. 7798 * @param target the var handle to invoke after the coordinates have been reordered 7799 * @param newCoordinates the new coordinate types 7800 * @param reorder an index array which controls the reordering 7801 * @return an adapter var handle which re-arranges the incoming coordinate values, 7802 * before calling the target var handle 7803 * @throws IllegalArgumentException if the index array length is not equal to 7804 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 7805 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 7806 * the target var handle and in {@code newCoordinates} are not identical. 7807 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 7808 * @since 22 7809 */ 7810 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 7811 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 7812 } 7813 7814 /** 7815 * Adapts a target var handle by pre-processing 7816 * a sub-sequence of its coordinate values with a filter (a method handle). 7817 * The pre-processed coordinates are replaced by the result (if any) of the 7818 * filter function and the target var handle is then called on the modified (usually shortened) 7819 * coordinate list. 7820 * <p> 7821 * If {@code R} is the return type of the filter, then: 7822 * <ul> 7823 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 7824 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 7825 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 7826 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 7827 * target var handle.</li> 7828 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 7829 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 7830 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 7831 * downstream invocation of the target var handle.</li> 7832 * </ul> 7833 * <p> 7834 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7835 * throw an {@link IllegalStateException}. 7836 * <p> 7837 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7838 * atomic access guarantees as those featured by the target var handle. 7839 * 7840 * @param target the var handle to invoke after the coordinates have been filtered 7841 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 7842 * @param filter the filter method handle 7843 * @return an adapter var handle which filters the incoming coordinate values, 7844 * before calling the target var handle 7845 * @throws IllegalArgumentException if the return type of {@code filter} 7846 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 7847 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7848 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 7849 * or if it's determined that {@code filter} throws any checked exceptions. 7850 * @throws NullPointerException if any of the arguments is {@code null}. 7851 * @since 22 7852 */ 7853 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 7854 return VarHandles.collectCoordinates(target, pos, filter); 7855 } 7856 7857 /** 7858 * Returns a var handle which will discard some dummy coordinates before delegating to the 7859 * target var handle. As a consequence, the resulting var handle will feature more 7860 * coordinate types than the target var handle. 7861 * <p> 7862 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 7863 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 7864 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 7865 * <p> 7866 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7867 * atomic access guarantees as those featured by the target var handle. 7868 * 7869 * @param target the var handle to invoke after the dummy coordinates are dropped 7870 * @param pos position of the first coordinate to drop (zero for the leftmost) 7871 * @param valueTypes the type(s) of the coordinate(s) to drop 7872 * @return an adapter var handle which drops some dummy coordinates, 7873 * before calling the target var handle 7874 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 7875 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 7876 * @since 22 7877 */ 7878 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 7879 return VarHandles.dropCoordinates(target, pos, valueTypes); 7880 } 7881 }