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 sun.invoke.util.ValueConversions; 37 import sun.invoke.util.VerifyAccess; 38 import sun.invoke.util.Wrapper; 39 40 import java.lang.classfile.ClassFile; 41 import java.lang.classfile.ClassModel; 42 import java.lang.constant.ClassDesc; 43 import java.lang.constant.ConstantDescs; 44 import java.lang.invoke.LambdaForm.BasicType; 45 import java.lang.invoke.MethodHandleImpl.Intrinsic; 46 import java.lang.reflect.Constructor; 47 import java.lang.reflect.Field; 48 import java.lang.reflect.Member; 49 import java.lang.reflect.Method; 50 import java.lang.reflect.Modifier; 51 import java.nio.ByteOrder; 52 import java.security.ProtectionDomain; 53 import java.util.ArrayList; 54 import java.util.Arrays; 55 import java.util.BitSet; 56 import java.util.Comparator; 57 import java.util.Iterator; 58 import java.util.List; 59 import java.util.Objects; 60 import java.util.Set; 61 import java.util.concurrent.ConcurrentHashMap; 62 import java.util.stream.Stream; 63 64 import static java.lang.classfile.ClassFile.*; 65 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 66 import static java.lang.invoke.MethodHandleNatives.Constants.*; 67 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 68 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 69 import static java.lang.invoke.MethodHandleStatics.newInternalError; 70 import static java.lang.invoke.MethodType.methodType; 71 72 /** 73 * This class consists exclusively of static methods that operate on or return 74 * method handles. They fall into several categories: 75 * <ul> 76 * <li>Lookup methods which help create method handles for methods and fields. 77 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 78 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 79 * </ul> 80 * A lookup, combinator, or factory method will fail and throw an 81 * {@code IllegalArgumentException} if the created method handle's type 82 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 83 * 84 * @author John Rose, JSR 292 EG 85 * @since 1.7 86 */ 87 public final class MethodHandles { 88 89 private MethodHandles() { } // do not instantiate 90 91 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 92 93 // See IMPL_LOOKUP below. 94 95 //--- Method handle creation from ordinary methods. 96 97 /** 98 * Returns a {@link Lookup lookup object} with 99 * full capabilities to emulate all supported bytecode behaviors of the caller. 100 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 101 * Factory methods on the lookup object can create 102 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 103 * for any member that the caller has access to via bytecodes, 104 * including protected and private fields and methods. 105 * This lookup object is created by the original lookup class 106 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 107 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 108 * Do not store it in place where untrusted code can access it. 109 * <p> 110 * This method is caller sensitive, which means that it may return different 111 * values to different callers. 112 * In cases where {@code MethodHandles.lookup} is called from a context where 113 * there is no caller frame on the stack (e.g. when called directly 114 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 115 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 116 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 117 * to obtain a low-privileged lookup instead. 118 * @return a lookup object for the caller of this method, with 119 * {@linkplain Lookup#ORIGINAL original} and 120 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 121 * @throws IllegalCallerException if there is no caller frame on the stack. 122 */ 123 @CallerSensitive 124 @ForceInline // to ensure Reflection.getCallerClass optimization 125 public static Lookup lookup() { 126 final Class<?> c = Reflection.getCallerClass(); 127 if (c == null) { 128 throw new IllegalCallerException("no caller frame"); 129 } 130 return new Lookup(c); 131 } 132 133 /** 134 * This lookup method is the alternate implementation of 135 * the lookup method with a leading caller class argument which is 136 * non-caller-sensitive. This method is only invoked by reflection 137 * and method handle. 138 */ 139 @CallerSensitiveAdapter 140 private static Lookup lookup(Class<?> caller) { 141 if (caller.getClassLoader() == null) { 142 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 143 } 144 return new Lookup(caller); 145 } 146 147 /** 148 * Returns a {@link Lookup lookup object} which is trusted minimally. 149 * The lookup has the {@code UNCONDITIONAL} mode. 150 * It can only be used to create method handles to public members of 151 * public classes in packages that are exported unconditionally. 152 * <p> 153 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 154 * of this lookup object will be {@link java.lang.Object}. 155 * 156 * @apiNote The use of Object is conventional, and because the lookup modes are 157 * limited, there is no special access provided to the internals of Object, its package 158 * or its module. This public lookup object or other lookup object with 159 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 160 * is not used to determine the lookup context. 161 * 162 * <p style="font-size:smaller;"> 163 * <em>Discussion:</em> 164 * The lookup class can be changed to any other class {@code C} using an expression of the form 165 * {@link Lookup#in publicLookup().in(C.class)}. 166 * Also, it cannot access 167 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 168 * @return a lookup object which is trusted minimally 169 */ 170 public static Lookup publicLookup() { 171 return Lookup.PUBLIC_LOOKUP; 172 } 173 174 /** 175 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 176 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 177 * The returned lookup object can provide access to classes in modules and packages, 178 * and members of those classes, outside the normal rules of Java access control, 179 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 180 * <p> 181 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 182 * allowed to do deep reflection on module {@code M2} and package of the target class 183 * if and only if all of the following conditions are {@code true}: 184 * <ul> 185 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 186 * full privilege access}. Specifically: 187 * <ul> 188 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 189 * (This is because otherwise there would be no way to ensure the original lookup 190 * creator was a member of any particular module, and so any subsequent checks 191 * for readability and qualified exports would become ineffective.) 192 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 193 * (This is because an application intending to share intra-module access 194 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 195 * deep reflection to its own module.) 196 * </ul> 197 * <li>The target class must be a proper class, not a primitive or array class. 198 * (Thus, {@code M2} is well-defined.) 199 * <li>If the caller module {@code M1} differs from 200 * the target module {@code M2} then both of the following must be true: 201 * <ul> 202 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 203 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 204 * containing the target class to at least {@code M1}.</li> 205 * </ul> 206 * </ul> 207 * <p> 208 * If any of the above checks is violated, this method fails with an 209 * exception. 210 * <p> 211 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 212 * returns a {@code Lookup} on {@code targetClass} with 213 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 214 * with {@code null} previous lookup class. 215 * <p> 216 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 217 * returns a {@code Lookup} on {@code targetClass} that records 218 * the lookup class of the caller as the new previous lookup class with 219 * {@code PRIVATE} access but no {@code MODULE} access. 220 * <p> 221 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 222 * 223 * @apiNote The {@code Lookup} object returned by this method is allowed to 224 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 225 * of {@code targetClass}. Extreme caution should be taken when opening a package 226 * to another module as such defined classes have the same full privilege 227 * access as other members in {@code targetClass}'s module. 228 * 229 * @param targetClass the target class 230 * @param caller the caller lookup object 231 * @return a lookup object for the target class, with private access 232 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 233 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 234 * @throws IllegalAccessException if any of the other access checks specified above fails 235 * @since 9 236 * @see Lookup#dropLookupMode 237 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 238 */ 239 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 240 if (caller.allowedModes == Lookup.TRUSTED) { 241 return new Lookup(targetClass); 242 } 243 244 if (targetClass.isPrimitive()) 245 throw new IllegalArgumentException(targetClass + " is a primitive class"); 246 if (targetClass.isArray()) 247 throw new IllegalArgumentException(targetClass + " is an array class"); 248 // Ensure that we can reason accurately about private and module access. 249 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 250 if ((caller.lookupModes() & requireAccess) != requireAccess) 251 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 252 253 // previous lookup class is never set if it has MODULE access 254 assert caller.previousLookupClass() == null; 255 256 Class<?> callerClass = caller.lookupClass(); 257 Module callerModule = callerClass.getModule(); // M1 258 Module targetModule = targetClass.getModule(); // M2 259 Class<?> newPreviousClass = null; 260 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 261 262 if (targetModule != callerModule) { 263 if (!callerModule.canRead(targetModule)) 264 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 265 if (targetModule.isNamed()) { 266 String pn = targetClass.getPackageName(); 267 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 268 if (!targetModule.isOpen(pn, callerModule)) 269 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 270 } 271 272 // M2 != M1, set previous lookup class to M1 and drop MODULE access 273 newPreviousClass = callerClass; 274 newModes &= ~Lookup.MODULE; 275 } 276 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 277 } 278 279 /** 280 * Returns the <em>class data</em> associated with the lookup class 281 * of the given {@code caller} lookup object, or {@code null}. 282 * 283 * <p> A hidden class with class data can be created by calling 284 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 285 * Lookup::defineHiddenClassWithClassData}. 286 * This method will cause the static class initializer of the lookup 287 * class of the given {@code caller} lookup object be executed if 288 * it has not been initialized. 289 * 290 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 291 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 292 * {@code null} is returned if this method is called on the lookup object 293 * on these classes. 294 * 295 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 296 * must have {@linkplain Lookup#ORIGINAL original access} 297 * in order to retrieve the class data. 298 * 299 * @apiNote 300 * This method can be called as a bootstrap method for a dynamically computed 301 * constant. A framework can create a hidden class with class data, for 302 * example that can be {@code Class} or {@code MethodHandle} object. 303 * The class data is accessible only to the lookup object 304 * created by the original caller but inaccessible to other members 305 * in the same nest. If a framework passes security sensitive objects 306 * to a hidden class via class data, it is recommended to load the value 307 * of class data as a dynamically computed constant instead of storing 308 * the class data in private static field(s) which are accessible to 309 * other nestmates. 310 * 311 * @param <T> the type to cast the class data object to 312 * @param caller the lookup context describing the class performing the 313 * operation (normally stacked by the JVM) 314 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 315 * ({@code "_"}) 316 * @param type the type of the class data 317 * @return the value of the class data if present in the lookup class; 318 * otherwise {@code null} 319 * @throws IllegalArgumentException if name is not {@code "_"} 320 * @throws IllegalAccessException if the lookup context does not have 321 * {@linkplain Lookup#ORIGINAL original} access 322 * @throws ClassCastException if the class data cannot be converted to 323 * the given {@code type} 324 * @throws NullPointerException if {@code caller} or {@code type} argument 325 * is {@code null} 326 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 327 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 328 * @since 16 329 * @jvms 5.5 Initialization 330 */ 331 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 332 Objects.requireNonNull(caller); 333 Objects.requireNonNull(type); 334 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 335 throw new IllegalArgumentException("name must be \"_\": " + name); 336 } 337 338 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 339 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 340 } 341 342 Object classdata = classData(caller.lookupClass()); 343 if (classdata == null) return null; 344 345 try { 346 return BootstrapMethodInvoker.widenAndCast(classdata, type); 347 } catch (RuntimeException|Error e) { 348 throw e; // let CCE and other runtime exceptions through 349 } catch (Throwable e) { 350 throw new InternalError(e); 351 } 352 } 353 354 /* 355 * Returns the class data set by the VM in the Class::classData field. 356 * 357 * This is also invoked by LambdaForms as it cannot use condy via 358 * MethodHandles::classData due to bootstrapping issue. 359 */ 360 static Object classData(Class<?> c) { 361 UNSAFE.ensureClassInitialized(c); 362 return SharedSecrets.getJavaLangAccess().classData(c); 363 } 364 365 /** 366 * Returns the element at the specified index in the 367 * {@linkplain #classData(Lookup, String, Class) class data}, 368 * if the class data associated with the lookup class 369 * of the given {@code caller} lookup object is a {@code List}. 370 * If the class data is not present in this lookup class, this method 371 * returns {@code null}. 372 * 373 * <p> A hidden class with class data can be created by calling 374 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 375 * Lookup::defineHiddenClassWithClassData}. 376 * This method will cause the static class initializer of the lookup 377 * class of the given {@code caller} lookup object be executed if 378 * it has not been initialized. 379 * 380 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 381 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 382 * {@code null} is returned if this method is called on the lookup object 383 * on these classes. 384 * 385 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 386 * must have {@linkplain Lookup#ORIGINAL original access} 387 * in order to retrieve the class data. 388 * 389 * @apiNote 390 * This method can be called as a bootstrap method for a dynamically computed 391 * constant. A framework can create a hidden class with class data, for 392 * example that can be {@code List.of(o1, o2, o3....)} containing more than 393 * one object and use this method to load one element at a specific index. 394 * The class data is accessible only to the lookup object 395 * created by the original caller but inaccessible to other members 396 * in the same nest. If a framework passes security sensitive objects 397 * to a hidden class via class data, it is recommended to load the value 398 * of class data as a dynamically computed constant instead of storing 399 * the class data in private static field(s) which are accessible to other 400 * nestmates. 401 * 402 * @param <T> the type to cast the result object to 403 * @param caller the lookup context describing the class performing the 404 * operation (normally stacked by the JVM) 405 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 406 * ({@code "_"}) 407 * @param type the type of the element at the given index in the class data 408 * @param index index of the element in the class data 409 * @return the element at the given index in the class data 410 * if the class data is present; otherwise {@code null} 411 * @throws IllegalArgumentException if name is not {@code "_"} 412 * @throws IllegalAccessException if the lookup context does not have 413 * {@linkplain Lookup#ORIGINAL original} access 414 * @throws ClassCastException if the class data cannot be converted to {@code List} 415 * or the element at the specified index cannot be converted to the given type 416 * @throws IndexOutOfBoundsException if the index is out of range 417 * @throws NullPointerException if {@code caller} or {@code type} argument is 418 * {@code null}; or if unboxing operation fails because 419 * the element at the given index is {@code null} 420 * 421 * @since 16 422 * @see #classData(Lookup, String, Class) 423 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 424 */ 425 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 426 throws IllegalAccessException 427 { 428 @SuppressWarnings("unchecked") 429 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 430 if (classdata == null) return null; 431 432 try { 433 Object element = classdata.get(index); 434 return BootstrapMethodInvoker.widenAndCast(element, type); 435 } catch (RuntimeException|Error e) { 436 throw e; // let specified exceptions and other runtime exceptions/errors through 437 } catch (Throwable e) { 438 throw new InternalError(e); 439 } 440 } 441 442 /** 443 * Performs an unchecked "crack" of a 444 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 445 * The result is as if the user had obtained a lookup object capable enough 446 * to crack the target method handle, called 447 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 448 * on the target to obtain its symbolic reference, and then called 449 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 450 * to resolve the symbolic reference to a member. 451 * @param <T> the desired type of the result, either {@link Member} or a subtype 452 * @param expected a class object representing the desired result type {@code T} 453 * @param target a direct method handle to crack into symbolic reference components 454 * @return a reference to the method, constructor, or field object 455 * @throws NullPointerException if either argument is {@code null} 456 * @throws IllegalArgumentException if the target is not a direct method handle 457 * @throws ClassCastException if the member is not of the expected type 458 * @since 1.8 459 */ 460 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 461 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 462 return lookup.revealDirect(target).reflectAs(expected, lookup); 463 } 464 465 /** 466 * A <em>lookup object</em> is a factory for creating method handles, 467 * when the creation requires access checking. 468 * Method handles do not perform 469 * access checks when they are called, but rather when they are created. 470 * Therefore, method handle access 471 * restrictions must be enforced when a method handle is created. 472 * The caller class against which those restrictions are enforced 473 * is known as the {@linkplain #lookupClass() lookup class}. 474 * <p> 475 * A lookup class which needs to create method handles will call 476 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 477 * When the {@code Lookup} factory object is created, the identity of the lookup class is 478 * determined, and securely stored in the {@code Lookup} object. 479 * The lookup class (or its delegates) may then use factory methods 480 * on the {@code Lookup} object to create method handles for access-checked members. 481 * This includes all methods, constructors, and fields which are allowed to the lookup class, 482 * even private ones. 483 * 484 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 485 * The factory methods on a {@code Lookup} object correspond to all major 486 * use cases for methods, constructors, and fields. 487 * Each method handle created by a factory method is the functional 488 * equivalent of a particular <em>bytecode behavior</em>. 489 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 490 * the Java Virtual Machine Specification.) 491 * Here is a summary of the correspondence between these factory methods and 492 * the behavior of the resulting method handles: 493 * <table class="striped"> 494 * <caption style="display:none">lookup method behaviors</caption> 495 * <thead> 496 * <tr> 497 * <th scope="col"><a id="equiv"></a>lookup expression</th> 498 * <th scope="col">member</th> 499 * <th scope="col">bytecode behavior</th> 500 * </tr> 501 * </thead> 502 * <tbody> 503 * <tr> 504 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 505 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 506 * </tr> 507 * <tr> 508 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 509 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 510 * </tr> 511 * <tr> 512 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 513 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 514 * </tr> 515 * <tr> 516 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 517 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 518 * </tr> 519 * <tr> 520 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 521 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 522 * </tr> 523 * <tr> 524 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 525 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 526 * </tr> 527 * <tr> 528 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 529 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 530 * </tr> 531 * <tr> 532 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 533 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 534 * </tr> 535 * <tr> 536 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 537 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 538 * </tr> 539 * <tr> 540 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 541 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 542 * </tr> 543 * <tr> 544 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 545 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 546 * </tr> 547 * <tr> 548 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 549 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 550 * </tr> 551 * <tr> 552 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 553 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 554 * </tr> 555 * <tr> 556 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 557 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 558 * </tr> 559 * </tbody> 560 * </table> 561 * 562 * Here, the type {@code C} is the class or interface being searched for a member, 563 * documented as a parameter named {@code refc} in the lookup methods. 564 * The method type {@code MT} is composed from the return type {@code T} 565 * and the sequence of argument types {@code A*}. 566 * The constructor also has a sequence of argument types {@code A*} and 567 * is deemed to return the newly-created object of type {@code C}. 568 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 569 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 570 * if it is present, it is always the leading argument to the method handle invocation. 571 * (In the case of some {@code protected} members, {@code this} may be 572 * restricted in type to the lookup class; see below.) 573 * The name {@code arg} stands for all the other method handle arguments. 574 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 575 * stands for a null reference if the accessed method or field is static, 576 * and {@code this} otherwise. 577 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 578 * for reflective objects corresponding to the given members declared in type {@code C}. 579 * <p> 580 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 581 * as if by {@code ldc CONSTANT_Class}. 582 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 583 * <p> 584 * In cases where the given member is of variable arity (i.e., a method or constructor) 585 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 586 * In all other cases, the returned method handle will be of fixed arity. 587 * <p style="font-size:smaller;"> 588 * <em>Discussion:</em> 589 * The equivalence between looked-up method handles and underlying 590 * class members and bytecode behaviors 591 * can break down in a few ways: 592 * <ul style="font-size:smaller;"> 593 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 594 * the lookup can still succeed, even when there is no equivalent 595 * Java expression or bytecoded constant. 596 * <li>Likewise, if {@code T} or {@code MT} 597 * is not symbolically accessible from the lookup class's loader, 598 * the lookup can still succeed. 599 * For example, lookups for {@code MethodHandle.invokeExact} and 600 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 601 * <li>If the looked-up method has a 602 * <a href="MethodHandle.html#maxarity">very large arity</a>, 603 * the method handle creation may fail with an 604 * {@code IllegalArgumentException}, due to the method handle type having 605 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 606 * </ul> 607 * 608 * <h2><a id="access"></a>Access checking</h2> 609 * Access checks are applied in the factory methods of {@code Lookup}, 610 * when a method handle is created. 611 * This is a key difference from the Core Reflection API, since 612 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 613 * performs access checking against every caller, on every call. 614 * <p> 615 * All access checks start from a {@code Lookup} object, which 616 * compares its recorded lookup class against all requests to 617 * create method handles. 618 * A single {@code Lookup} object can be used to create any number 619 * of access-checked method handles, all checked against a single 620 * lookup class. 621 * <p> 622 * A {@code Lookup} object can be shared with other trusted code, 623 * such as a metaobject protocol. 624 * A shared {@code Lookup} object delegates the capability 625 * to create method handles on private members of the lookup class. 626 * Even if privileged code uses the {@code Lookup} object, 627 * the access checking is confined to the privileges of the 628 * original lookup class. 629 * <p> 630 * A lookup can fail, because 631 * the containing class is not accessible to the lookup class, or 632 * because the desired class member is missing, or because the 633 * desired class member is not accessible to the lookup class, or 634 * because the lookup object is not trusted enough to access the member. 635 * In the case of a field setter function on a {@code final} field, 636 * finality enforcement is treated as a kind of access control, 637 * and the lookup will fail, except in special cases of 638 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 639 * In any of these cases, a {@code ReflectiveOperationException} will be 640 * thrown from the attempted lookup. The exact class will be one of 641 * the following: 642 * <ul> 643 * <li>NoSuchMethodException — if a method is requested but does not exist 644 * <li>NoSuchFieldException — if a field is requested but does not exist 645 * <li>IllegalAccessException — if the member exists but an access check fails 646 * </ul> 647 * <p> 648 * In general, the conditions under which a method handle may be 649 * looked up for a method {@code M} are no more restrictive than the conditions 650 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 651 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 652 * a method handle lookup will generally raise a corresponding 653 * checked exception, such as {@code NoSuchMethodException}. 654 * And the effect of invoking the method handle resulting from the lookup 655 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 656 * to executing the compiled, verified, and resolved call to {@code M}. 657 * The same point is true of fields and constructors. 658 * <p style="font-size:smaller;"> 659 * <em>Discussion:</em> 660 * Access checks only apply to named and reflected methods, 661 * constructors, and fields. 662 * Other method handle creation methods, such as 663 * {@link MethodHandle#asType MethodHandle.asType}, 664 * do not require any access checks, and are used 665 * independently of any {@code Lookup} object. 666 * <p> 667 * If the desired member is {@code protected}, the usual JVM rules apply, 668 * including the requirement that the lookup class must either be in the 669 * same package as the desired member, or must inherit that member. 670 * (See the Java Virtual Machine Specification, sections {@jvms 671 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 672 * In addition, if the desired member is a non-static field or method 673 * in a different package, the resulting method handle may only be applied 674 * to objects of the lookup class or one of its subclasses. 675 * This requirement is enforced by narrowing the type of the leading 676 * {@code this} parameter from {@code C} 677 * (which will necessarily be a superclass of the lookup class) 678 * to the lookup class itself. 679 * <p> 680 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 681 * that the receiver argument must match both the resolved method <em>and</em> 682 * the current class. Again, this requirement is enforced by narrowing the 683 * type of the leading parameter to the resulting method handle. 684 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 685 * <p> 686 * The JVM represents constructors and static initializer blocks as internal methods 687 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 688 * ConstantDescs#CLASS_INIT_NAME}). 689 * The internal syntax of invocation instructions allows them to refer to such internal 690 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 691 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 692 * <p> 693 * If the relationship between nested types is expressed directly through the 694 * {@code NestHost} and {@code NestMembers} attributes 695 * (see the Java Virtual Machine Specification, sections {@jvms 696 * 4.7.28} and {@jvms 4.7.29}), 697 * then the associated {@code Lookup} object provides direct access to 698 * the lookup class and all of its nestmates 699 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 700 * Otherwise, access between nested classes is obtained by the Java compiler creating 701 * a wrapper method to access a private method of another class in the same nest. 702 * For example, a nested class {@code C.D} 703 * can access private members within other related classes such as 704 * {@code C}, {@code C.D.E}, or {@code C.B}, 705 * but the Java compiler may need to generate wrapper methods in 706 * those related classes. In such cases, a {@code Lookup} object on 707 * {@code C.E} would be unable to access those private members. 708 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 709 * which can transform a lookup on {@code C.E} into one on any of those other 710 * classes, without special elevation of privilege. 711 * <p> 712 * The accesses permitted to a given lookup object may be limited, 713 * according to its set of {@link #lookupModes lookupModes}, 714 * to a subset of members normally accessible to the lookup class. 715 * For example, the {@link MethodHandles#publicLookup publicLookup} 716 * method produces a lookup object which is only allowed to access 717 * public members in public classes of exported packages. 718 * The caller sensitive method {@link MethodHandles#lookup lookup} 719 * produces a lookup object with full capabilities relative to 720 * its caller class, to emulate all supported bytecode behaviors. 721 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 722 * with fewer access modes than the original lookup object. 723 * 724 * <p style="font-size:smaller;"> 725 * <a id="privacc"></a> 726 * <em>Discussion of private and module access:</em> 727 * We say that a lookup has <em>private access</em> 728 * if its {@linkplain #lookupModes lookup modes} 729 * include the possibility of accessing {@code private} members 730 * (which includes the private members of nestmates). 731 * As documented in the relevant methods elsewhere, 732 * only lookups with private access possess the following capabilities: 733 * <ul style="font-size:smaller;"> 734 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 735 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 736 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 737 * within the same package member 738 * </ul> 739 * <p style="font-size:smaller;"> 740 * Similarly, a lookup with module access ensures that the original lookup creator was 741 * a member in the same module as the lookup class. 742 * <p style="font-size:smaller;"> 743 * Private and module access are independently determined modes; a lookup may have 744 * either or both or neither. A lookup which possesses both access modes is said to 745 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 746 * <p style="font-size:smaller;"> 747 * A lookup with <em>original access</em> ensures that this lookup is created by 748 * the original lookup class and the bootstrap method invoked by the VM. 749 * Such a lookup with original access also has private and module access 750 * which has the following additional capability: 751 * <ul style="font-size:smaller;"> 752 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 753 * such as {@code Class.forName} 754 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 755 * class data} associated with the lookup class</li> 756 * </ul> 757 * <p style="font-size:smaller;"> 758 * Each of these permissions is a consequence of the fact that a lookup object 759 * with private access can be securely traced back to an originating class, 760 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 761 * can be reliably determined and emulated by method handles. 762 * 763 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 764 * When a lookup class in one module {@code M1} accesses a class in another module 765 * {@code M2}, extra access checking is performed beyond the access mode bits. 766 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 767 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 768 * and when the type is in a package of {@code M2} that is exported to 769 * at least {@code M1}. 770 * <p> 771 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 772 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 773 * MethodHandles.privateLookupIn} methods. 774 * Teleporting across modules will always record the original lookup class as 775 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 776 * and drops {@link Lookup#MODULE MODULE} access. 777 * If the target class is in the same module as the lookup class {@code C}, 778 * then the target class becomes the new lookup class 779 * and there is no change to the previous lookup class. 780 * If the target class is in a different module from {@code M1} ({@code C}'s module), 781 * {@code C} becomes the new previous lookup class 782 * and the target class becomes the new lookup class. 783 * In that case, if there was already a previous lookup class in {@code M0}, 784 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 785 * drops all privileges. 786 * For example, 787 * {@snippet lang="java" : 788 * Lookup lookup = MethodHandles.lookup(); // in class C 789 * Lookup lookup2 = lookup.in(D.class); 790 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 791 * } 792 * <p> 793 * The {@link #lookup()} factory method produces a {@code Lookup} object 794 * with {@code null} previous lookup class. 795 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 796 * to class {@code D} without elevation of privileges. 797 * If {@code C} and {@code D} are in the same module, 798 * {@code lookup2} records {@code D} as the new lookup class and keeps the 799 * same previous lookup class as the original {@code lookup}, or 800 * {@code null} if not present. 801 * <p> 802 * When a {@code Lookup} teleports from a class 803 * in one nest to another nest, {@code PRIVATE} access is dropped. 804 * When a {@code Lookup} teleports from a class in one package to 805 * another package, {@code PACKAGE} access is dropped. 806 * When a {@code Lookup} teleports from a class in one module to another module, 807 * {@code MODULE} access is dropped. 808 * Teleporting across modules drops the ability to access non-exported classes 809 * in both the module of the new lookup class and the module of the old lookup class 810 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 811 * A {@code Lookup} can teleport back and forth to a class in the module of 812 * the lookup class and the module of the previous class lookup. 813 * Teleporting across modules can only decrease access but cannot increase it. 814 * Teleporting to some third module drops all accesses. 815 * <p> 816 * In the above example, if {@code C} and {@code D} are in different modules, 817 * {@code lookup2} records {@code D} as its lookup class and 818 * {@code C} as its previous lookup class and {@code lookup2} has only 819 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 820 * {@code C}'s module and {@code D}'s module. 821 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 822 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 823 * class {@code D} is recorded as its previous lookup class. 824 * <p> 825 * Teleporting across modules restricts access to the public types that 826 * both the lookup class and the previous lookup class can equally access 827 * (see below). 828 * <p> 829 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 830 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 831 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 832 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 833 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 834 * to call {@code privateLookupIn}. 835 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 836 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 837 * produces a new {@code Lookup} on {@code T} with full capabilities. 838 * A {@code lookup} on {@code C} is also allowed 839 * to do deep reflection on {@code T} in another module {@code M2} if 840 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 841 * the package containing {@code T} to at least {@code M1}. 842 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 843 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 844 * The resulting {@code Lookup} can be used to do member lookup or teleport 845 * to another lookup class by calling {@link #in Lookup::in}. But 846 * it cannot be used to obtain another private {@code Lookup} by calling 847 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 848 * because it has no {@code MODULE} access. 849 * <p> 850 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 851 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 852 * of {@code T}. Extreme caution should be taken when opening a package 853 * to another module as such defined classes have the same full privilege 854 * access as other members in {@code M2}. 855 * 856 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 857 * 858 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 859 * allows cross-module access. The access checking is performed with respect 860 * to both the lookup class and the previous lookup class if present. 861 * <p> 862 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 863 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 864 * exported unconditionally}. 865 * <p> 866 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 867 * the lookup with {@link #PUBLIC} mode can access all public types in modules 868 * that are readable to {@code M1} and the type is in a package that is exported 869 * at least to {@code M1}. 870 * <p> 871 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 872 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 873 * the intersection of all public types that are accessible to {@code M1} 874 * with all public types that are accessible to {@code M0}. {@code M0} 875 * reads {@code M1} and hence the set of accessible types includes: 876 * 877 * <ul> 878 * <li>unconditional-exported packages from {@code M1}</li> 879 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 880 * <li> 881 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 882 * and {@code M1} read {@code M2} 883 * </li> 884 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 885 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 886 * <li> 887 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 888 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 889 * </li> 890 * </ul> 891 * 892 * <h2><a id="access-modes"></a>Access modes</h2> 893 * 894 * The table below shows the access modes of a {@code Lookup} produced by 895 * any of the following factory or transformation methods: 896 * <ul> 897 * <li>{@link #lookup() MethodHandles::lookup}</li> 898 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 899 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 900 * <li>{@link Lookup#in Lookup::in}</li> 901 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 902 * </ul> 903 * 904 * <table class="striped"> 905 * <caption style="display:none"> 906 * Access mode summary 907 * </caption> 908 * <thead> 909 * <tr> 910 * <th scope="col">Lookup object</th> 911 * <th style="text-align:center">original</th> 912 * <th style="text-align:center">protected</th> 913 * <th style="text-align:center">private</th> 914 * <th style="text-align:center">package</th> 915 * <th style="text-align:center">module</th> 916 * <th style="text-align:center">public</th> 917 * </tr> 918 * </thead> 919 * <tbody> 920 * <tr> 921 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 922 * <td style="text-align:center">ORI</td> 923 * <td style="text-align:center">PRO</td> 924 * <td style="text-align:center">PRI</td> 925 * <td style="text-align:center">PAC</td> 926 * <td style="text-align:center">MOD</td> 927 * <td style="text-align:center">1R</td> 928 * </tr> 929 * <tr> 930 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 931 * <td></td> 932 * <td></td> 933 * <td></td> 934 * <td style="text-align:center">PAC</td> 935 * <td style="text-align:center">MOD</td> 936 * <td style="text-align:center">1R</td> 937 * </tr> 938 * <tr> 939 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 940 * <td></td> 941 * <td></td> 942 * <td></td> 943 * <td></td> 944 * <td style="text-align:center">MOD</td> 945 * <td style="text-align:center">1R</td> 946 * </tr> 947 * <tr> 948 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 949 * <td></td> 950 * <td></td> 951 * <td></td> 952 * <td></td> 953 * <td></td> 954 * <td style="text-align:center">2R</td> 955 * </tr> 956 * <tr> 957 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 958 * <td></td> 959 * <td></td> 960 * <td></td> 961 * <td></td> 962 * <td></td> 963 * <td style="text-align:center">2R</td> 964 * </tr> 965 * <tr> 966 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 967 * <td></td> 968 * <td style="text-align:center">PRO</td> 969 * <td style="text-align:center">PRI</td> 970 * <td style="text-align:center">PAC</td> 971 * <td style="text-align:center">MOD</td> 972 * <td style="text-align:center">1R</td> 973 * </tr> 974 * <tr> 975 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 976 * <td></td> 977 * <td style="text-align:center">PRO</td> 978 * <td style="text-align:center">PRI</td> 979 * <td style="text-align:center">PAC</td> 980 * <td style="text-align:center">MOD</td> 981 * <td style="text-align:center">1R</td> 982 * </tr> 983 * <tr> 984 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 985 * <td></td> 986 * <td></td> 987 * <td></td> 988 * <td style="text-align:center">PAC</td> 989 * <td style="text-align:center">MOD</td> 990 * <td style="text-align:center">1R</td> 991 * </tr> 992 * <tr> 993 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 994 * <td></td> 995 * <td></td> 996 * <td></td> 997 * <td></td> 998 * <td style="text-align:center">MOD</td> 999 * <td style="text-align:center">1R</td> 1000 * </tr> 1001 * <tr> 1002 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1003 * <td></td> 1004 * <td></td> 1005 * <td></td> 1006 * <td></td> 1007 * <td></td> 1008 * <td style="text-align:center">2R</td> 1009 * </tr> 1010 * <tr> 1011 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1012 * <td></td> 1013 * <td></td> 1014 * <td style="text-align:center">PRI</td> 1015 * <td style="text-align:center">PAC</td> 1016 * <td style="text-align:center">MOD</td> 1017 * <td style="text-align:center">1R</td> 1018 * </tr> 1019 * <tr> 1020 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1021 * <td></td> 1022 * <td></td> 1023 * <td></td> 1024 * <td style="text-align:center">PAC</td> 1025 * <td style="text-align:center">MOD</td> 1026 * <td style="text-align:center">1R</td> 1027 * </tr> 1028 * <tr> 1029 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1030 * <td></td> 1031 * <td></td> 1032 * <td></td> 1033 * <td></td> 1034 * <td style="text-align:center">MOD</td> 1035 * <td style="text-align:center">1R</td> 1036 * </tr> 1037 * <tr> 1038 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1039 * <td></td> 1040 * <td></td> 1041 * <td></td> 1042 * <td></td> 1043 * <td></td> 1044 * <td style="text-align:center">1R</td> 1045 * </tr> 1046 * <tr> 1047 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1048 * <td></td> 1049 * <td></td> 1050 * <td></td> 1051 * <td></td> 1052 * <td></td> 1053 * <td style="text-align:center">none</td> 1054 * <tr> 1055 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1056 * <td></td> 1057 * <td style="text-align:center">PRO</td> 1058 * <td style="text-align:center">PRI</td> 1059 * <td style="text-align:center">PAC</td> 1060 * <td></td> 1061 * <td style="text-align:center">2R</td> 1062 * </tr> 1063 * <tr> 1064 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1065 * <td></td> 1066 * <td style="text-align:center">PRO</td> 1067 * <td style="text-align:center">PRI</td> 1068 * <td style="text-align:center">PAC</td> 1069 * <td></td> 1070 * <td style="text-align:center">2R</td> 1071 * </tr> 1072 * <tr> 1073 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1074 * <td></td> 1075 * <td></td> 1076 * <td></td> 1077 * <td></td> 1078 * <td></td> 1079 * <td style="text-align:center">IAE</td> 1080 * </tr> 1081 * <tr> 1082 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1083 * <td></td> 1084 * <td></td> 1085 * <td></td> 1086 * <td style="text-align:center">PAC</td> 1087 * <td></td> 1088 * <td style="text-align:center">2R</td> 1089 * </tr> 1090 * <tr> 1091 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1092 * <td></td> 1093 * <td></td> 1094 * <td></td> 1095 * <td></td> 1096 * <td></td> 1097 * <td style="text-align:center">2R</td> 1098 * </tr> 1099 * <tr> 1100 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1101 * <td></td> 1102 * <td></td> 1103 * <td></td> 1104 * <td></td> 1105 * <td></td> 1106 * <td style="text-align:center">2R</td> 1107 * </tr> 1108 * <tr> 1109 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1110 * <td></td> 1111 * <td></td> 1112 * <td></td> 1113 * <td></td> 1114 * <td></td> 1115 * <td style="text-align:center">none</td> 1116 * </tr> 1117 * <tr> 1118 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1119 * <td></td> 1120 * <td></td> 1121 * <td style="text-align:center">PRI</td> 1122 * <td style="text-align:center">PAC</td> 1123 * <td></td> 1124 * <td style="text-align:center">2R</td> 1125 * </tr> 1126 * <tr> 1127 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1128 * <td></td> 1129 * <td></td> 1130 * <td></td> 1131 * <td style="text-align:center">PAC</td> 1132 * <td></td> 1133 * <td style="text-align:center">2R</td> 1134 * </tr> 1135 * <tr> 1136 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1137 * <td></td> 1138 * <td></td> 1139 * <td></td> 1140 * <td></td> 1141 * <td></td> 1142 * <td style="text-align:center">2R</td> 1143 * </tr> 1144 * <tr> 1145 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1146 * <td></td> 1147 * <td></td> 1148 * <td></td> 1149 * <td></td> 1150 * <td></td> 1151 * <td style="text-align:center">2R</td> 1152 * </tr> 1153 * <tr> 1154 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1155 * <td></td> 1156 * <td></td> 1157 * <td></td> 1158 * <td></td> 1159 * <td></td> 1160 * <td style="text-align:center">none</td> 1161 * </tr> 1162 * <tr> 1163 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1164 * <td></td> 1165 * <td></td> 1166 * <td style="text-align:center">PRI</td> 1167 * <td style="text-align:center">PAC</td> 1168 * <td style="text-align:center">MOD</td> 1169 * <td style="text-align:center">1R</td> 1170 * </tr> 1171 * <tr> 1172 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1173 * <td></td> 1174 * <td></td> 1175 * <td></td> 1176 * <td style="text-align:center">PAC</td> 1177 * <td style="text-align:center">MOD</td> 1178 * <td style="text-align:center">1R</td> 1179 * </tr> 1180 * <tr> 1181 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1182 * <td></td> 1183 * <td></td> 1184 * <td></td> 1185 * <td></td> 1186 * <td style="text-align:center">MOD</td> 1187 * <td style="text-align:center">1R</td> 1188 * </tr> 1189 * <tr> 1190 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1191 * <td></td> 1192 * <td></td> 1193 * <td></td> 1194 * <td></td> 1195 * <td></td> 1196 * <td style="text-align:center">1R</td> 1197 * </tr> 1198 * <tr> 1199 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1200 * <td></td> 1201 * <td></td> 1202 * <td></td> 1203 * <td></td> 1204 * <td></td> 1205 * <td style="text-align:center">none</td> 1206 * </tr> 1207 * <tr> 1208 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1209 * <td></td> 1210 * <td></td> 1211 * <td></td> 1212 * <td></td> 1213 * <td></td> 1214 * <td style="text-align:center">U</td> 1215 * </tr> 1216 * <tr> 1217 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1218 * <td></td> 1219 * <td></td> 1220 * <td></td> 1221 * <td></td> 1222 * <td></td> 1223 * <td style="text-align:center">U</td> 1224 * </tr> 1225 * <tr> 1226 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1227 * <td></td> 1228 * <td></td> 1229 * <td></td> 1230 * <td></td> 1231 * <td></td> 1232 * <td style="text-align:center">U</td> 1233 * </tr> 1234 * <tr> 1235 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1236 * <td></td> 1237 * <td></td> 1238 * <td></td> 1239 * <td></td> 1240 * <td></td> 1241 * <td style="text-align:center">none</td> 1242 * </tr> 1243 * <tr> 1244 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1245 * <td></td> 1246 * <td></td> 1247 * <td></td> 1248 * <td></td> 1249 * <td></td> 1250 * <td style="text-align:center">IAE</td> 1251 * </tr> 1252 * <tr> 1253 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1254 * <td></td> 1255 * <td></td> 1256 * <td></td> 1257 * <td></td> 1258 * <td></td> 1259 * <td style="text-align:center">none</td> 1260 * </tr> 1261 * </tbody> 1262 * </table> 1263 * 1264 * <p> 1265 * Notes: 1266 * <ul> 1267 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1268 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1269 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1270 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1271 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1272 * {@code PRO} indicates {@link #PROTECTED} bit set, 1273 * {@code PRI} indicates {@link #PRIVATE} bit set, 1274 * {@code PAC} indicates {@link #PACKAGE} bit set, 1275 * {@code MOD} indicates {@link #MODULE} bit set, 1276 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1277 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1278 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1279 * <li>Public access comes in three kinds: 1280 * <ul> 1281 * <li>unconditional ({@code U}): the lookup assumes readability. 1282 * The lookup has {@code null} previous lookup class. 1283 * <li>one-module-reads ({@code 1R}): the module access checking is 1284 * performed with respect to the lookup class. The lookup has {@code null} 1285 * previous lookup class. 1286 * <li>two-module-reads ({@code 2R}): the module access checking is 1287 * performed with respect to the lookup class and the previous lookup class. 1288 * The lookup has a non-null previous lookup class which is in a 1289 * different module from the current lookup class. 1290 * </ul> 1291 * <li>Any attempt to reach a third module loses all access.</li> 1292 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1293 * all access modes are dropped.</li> 1294 * </ul> 1295 * 1296 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1297 * A small number of Java methods have a special property called caller sensitivity. 1298 * A <em>caller-sensitive</em> method can behave differently depending on the 1299 * identity of its immediate caller. 1300 * <p> 1301 * If a method handle for a caller-sensitive method is requested, 1302 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1303 * but they take account of the lookup class in a special way. 1304 * The resulting method handle behaves as if it were called 1305 * from an instruction contained in the lookup class, 1306 * so that the caller-sensitive method detects the lookup class. 1307 * (By contrast, the invoker of the method handle is disregarded.) 1308 * Thus, in the case of caller-sensitive methods, 1309 * different lookup classes may give rise to 1310 * differently behaving method handles. 1311 * <p> 1312 * In cases where the lookup object is 1313 * {@link MethodHandles#publicLookup() publicLookup()}, 1314 * or some other lookup object without the 1315 * {@linkplain #ORIGINAL original access}, 1316 * the lookup class is disregarded. 1317 * In such cases, no caller-sensitive method handle can be created, 1318 * access is forbidden, and the lookup fails with an 1319 * {@code IllegalAccessException}. 1320 * <p style="font-size:smaller;"> 1321 * <em>Discussion:</em> 1322 * For example, the caller-sensitive method 1323 * {@link java.lang.Class#forName(String) Class.forName(x)} 1324 * can return varying classes or throw varying exceptions, 1325 * depending on the class loader of the class that calls it. 1326 * A public lookup of {@code Class.forName} will fail, because 1327 * there is no reasonable way to determine its bytecode behavior. 1328 * <p style="font-size:smaller;"> 1329 * If an application caches method handles for broad sharing, 1330 * it should use {@code publicLookup()} to create them. 1331 * If there is a lookup of {@code Class.forName}, it will fail, 1332 * and the application must take appropriate action in that case. 1333 * It may be that a later lookup, perhaps during the invocation of a 1334 * bootstrap method, can incorporate the specific identity 1335 * of the caller, making the method accessible. 1336 * <p style="font-size:smaller;"> 1337 * The function {@code MethodHandles.lookup} is caller sensitive 1338 * so that there can be a secure foundation for lookups. 1339 * Nearly all other methods in the JSR 292 API rely on lookup 1340 * objects to check access requests. 1341 */ 1342 public static final 1343 class Lookup { 1344 /** The class on behalf of whom the lookup is being performed. */ 1345 private final Class<?> lookupClass; 1346 1347 /** previous lookup class */ 1348 private final Class<?> prevLookupClass; 1349 1350 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1351 private final int allowedModes; 1352 1353 static { 1354 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1355 } 1356 1357 /** A single-bit mask representing {@code public} access, 1358 * which may contribute to the result of {@link #lookupModes lookupModes}. 1359 * The value, {@code 0x01}, happens to be the same as the value of the 1360 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1361 * <p> 1362 * A {@code Lookup} with this lookup mode performs cross-module access check 1363 * with respect to the {@linkplain #lookupClass() lookup class} and 1364 * {@linkplain #previousLookupClass() previous lookup class} if present. 1365 */ 1366 public static final int PUBLIC = Modifier.PUBLIC; 1367 1368 /** A single-bit mask representing {@code private} access, 1369 * which may contribute to the result of {@link #lookupModes lookupModes}. 1370 * The value, {@code 0x02}, happens to be the same as the value of the 1371 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1372 */ 1373 public static final int PRIVATE = Modifier.PRIVATE; 1374 1375 /** A single-bit mask representing {@code protected} access, 1376 * which may contribute to the result of {@link #lookupModes lookupModes}. 1377 * The value, {@code 0x04}, happens to be the same as the value of the 1378 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1379 */ 1380 public static final int PROTECTED = Modifier.PROTECTED; 1381 1382 /** A single-bit mask representing {@code package} access (default access), 1383 * which may contribute to the result of {@link #lookupModes lookupModes}. 1384 * The value is {@code 0x08}, which does not correspond meaningfully to 1385 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1386 */ 1387 public static final int PACKAGE = Modifier.STATIC; 1388 1389 /** A single-bit mask representing {@code module} access, 1390 * which may contribute to the result of {@link #lookupModes lookupModes}. 1391 * The value is {@code 0x10}, which does not correspond meaningfully to 1392 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1393 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1394 * with this lookup mode can access all public types in the module of the 1395 * lookup class and public types in packages exported by other modules 1396 * to the module of the lookup class. 1397 * <p> 1398 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1399 * previous lookup class} is always {@code null}. 1400 * 1401 * @since 9 1402 */ 1403 public static final int MODULE = PACKAGE << 1; 1404 1405 /** A single-bit mask representing {@code unconditional} access 1406 * which may contribute to the result of {@link #lookupModes lookupModes}. 1407 * The value is {@code 0x20}, which does not correspond meaningfully to 1408 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1409 * A {@code Lookup} with this lookup mode assumes {@linkplain 1410 * java.lang.Module#canRead(java.lang.Module) readability}. 1411 * This lookup mode can access all public members of public types 1412 * of all modules when the type is in a package that is {@link 1413 * java.lang.Module#isExported(String) exported unconditionally}. 1414 * 1415 * <p> 1416 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1417 * previous lookup class} is always {@code null}. 1418 * 1419 * @since 9 1420 * @see #publicLookup() 1421 */ 1422 public static final int UNCONDITIONAL = PACKAGE << 2; 1423 1424 /** A single-bit mask representing {@code original} access 1425 * which may contribute to the result of {@link #lookupModes lookupModes}. 1426 * The value is {@code 0x40}, which does not correspond meaningfully to 1427 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1428 * 1429 * <p> 1430 * If this lookup mode is set, the {@code Lookup} object must be 1431 * created by the original lookup class by calling 1432 * {@link MethodHandles#lookup()} method or by a bootstrap method 1433 * invoked by the VM. The {@code Lookup} object with this lookup 1434 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1435 * 1436 * @since 16 1437 */ 1438 public static final int ORIGINAL = PACKAGE << 3; 1439 1440 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1441 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1442 private static final int TRUSTED = -1; 1443 1444 /* 1445 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1446 * Adjust 0 => PACKAGE 1447 */ 1448 private static int fixmods(int mods) { 1449 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1450 if (Modifier.isPublic(mods)) 1451 mods |= UNCONDITIONAL; 1452 return (mods != 0) ? mods : PACKAGE; 1453 } 1454 1455 /** Tells which class is performing the lookup. It is this class against 1456 * which checks are performed for visibility and access permissions. 1457 * <p> 1458 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1459 * access checks are performed against both the lookup class and the previous lookup class. 1460 * <p> 1461 * The class implies a maximum level of access permission, 1462 * but the permissions may be additionally limited by the bitmask 1463 * {@link #lookupModes lookupModes}, which controls whether non-public members 1464 * can be accessed. 1465 * @return the lookup class, on behalf of which this lookup object finds members 1466 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1467 */ 1468 public Class<?> lookupClass() { 1469 return lookupClass; 1470 } 1471 1472 /** Reports a lookup class in another module that this lookup object 1473 * was previously teleported from, or {@code null}. 1474 * <p> 1475 * A {@code Lookup} object produced by the factory methods, such as the 1476 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1477 * has {@code null} previous lookup class. 1478 * A {@code Lookup} object has a non-null previous lookup class 1479 * when this lookup was teleported from an old lookup class 1480 * in one module to a new lookup class in another module. 1481 * 1482 * @return the lookup class in another module that this lookup object was 1483 * previously teleported from, or {@code null} 1484 * @since 14 1485 * @see #in(Class) 1486 * @see MethodHandles#privateLookupIn(Class, Lookup) 1487 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1488 */ 1489 public Class<?> previousLookupClass() { 1490 return prevLookupClass; 1491 } 1492 1493 // This is just for calling out to MethodHandleImpl. 1494 private Class<?> lookupClassOrNull() { 1495 return (allowedModes == TRUSTED) ? null : lookupClass; 1496 } 1497 1498 /** Tells which access-protection classes of members this lookup object can produce. 1499 * The result is a bit-mask of the bits 1500 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1501 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1502 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1503 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1504 * {@linkplain #MODULE MODULE (0x10)}, 1505 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1506 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1507 * <p> 1508 * A freshly-created lookup object 1509 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1510 * all possible bits set, except {@code UNCONDITIONAL}. 1511 * A lookup object on a new lookup class 1512 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1513 * may have some mode bits set to zero. 1514 * Mode bits can also be 1515 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1516 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1517 * The purpose of this is to restrict access via the new lookup object, 1518 * so that it can access only names which can be reached by the original 1519 * lookup object, and also by the new lookup class. 1520 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1521 * @see #in 1522 * @see #dropLookupMode 1523 */ 1524 public int lookupModes() { 1525 return allowedModes & ALL_MODES; 1526 } 1527 1528 /** Embody the current class (the lookupClass) as a lookup class 1529 * for method handle creation. 1530 * Must be called by from a method in this package, 1531 * which in turn is called by a method not in this package. 1532 */ 1533 Lookup(Class<?> lookupClass) { 1534 this(lookupClass, null, FULL_POWER_MODES); 1535 } 1536 1537 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1538 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1539 && prevLookupClass.getModule() != lookupClass.getModule()); 1540 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1541 this.lookupClass = lookupClass; 1542 this.prevLookupClass = prevLookupClass; 1543 this.allowedModes = allowedModes; 1544 } 1545 1546 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1547 // make sure we haven't accidentally picked up a privileged class: 1548 checkUnprivilegedlookupClass(lookupClass); 1549 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1550 } 1551 1552 /** 1553 * Creates a lookup on the specified new lookup class. 1554 * The resulting object will report the specified 1555 * class as its own {@link #lookupClass() lookupClass}. 1556 * 1557 * <p> 1558 * However, the resulting {@code Lookup} object is guaranteed 1559 * to have no more access capabilities than the original. 1560 * In particular, access capabilities can be lost as follows:<ul> 1561 * <li>If the new lookup class is different from the old lookup class, 1562 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1563 * <li>If the new lookup class is in a different module from the old one, 1564 * i.e. {@link #MODULE MODULE} access is lost. 1565 * <li>If the new lookup class is in a different package 1566 * than the old one, protected and default (package) members will not be accessible, 1567 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1568 * <li>If the new lookup class is not within the same package member 1569 * as the old one, private members will not be accessible, and protected members 1570 * will not be accessible by virtue of inheritance, 1571 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1572 * (Protected members may continue to be accessible because of package sharing.) 1573 * <li>If the new lookup class is not 1574 * {@linkplain #accessClass(Class) accessible} to this lookup, 1575 * then no members, not even public members, will be accessible 1576 * i.e. all access modes are lost. 1577 * <li>If the new lookup class, the old lookup class and the previous lookup class 1578 * are all in different modules i.e. teleporting to a third module, 1579 * all access modes are lost. 1580 * </ul> 1581 * <p> 1582 * The new previous lookup class is chosen as follows: 1583 * <ul> 1584 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1585 * the new previous lookup class is {@code null}. 1586 * <li>If the new lookup class is in the same module as the old lookup class, 1587 * the new previous lookup class is the old previous lookup class. 1588 * <li>If the new lookup class is in a different module from the old lookup class, 1589 * the new previous lookup class is the old lookup class. 1590 *</ul> 1591 * <p> 1592 * The resulting lookup's capabilities for loading classes 1593 * (used during {@link #findClass} invocations) 1594 * are determined by the lookup class' loader, 1595 * which may change due to this operation. 1596 * 1597 * @param requestedLookupClass the desired lookup class for the new lookup object 1598 * @return a lookup object which reports the desired lookup class, or the same object 1599 * if there is no change 1600 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1601 * @throws NullPointerException if the argument is null 1602 * 1603 * @see #accessClass(Class) 1604 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1605 */ 1606 public Lookup in(Class<?> requestedLookupClass) { 1607 Objects.requireNonNull(requestedLookupClass); 1608 if (requestedLookupClass.isPrimitive()) 1609 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1610 if (requestedLookupClass.isArray()) 1611 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1612 1613 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1614 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1615 if (requestedLookupClass == this.lookupClass) 1616 return this; // keep same capabilities 1617 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1618 Module fromModule = this.lookupClass.getModule(); 1619 Module targetModule = requestedLookupClass.getModule(); 1620 Class<?> plc = this.previousLookupClass(); 1621 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1622 assert plc == null; 1623 newModes = UNCONDITIONAL; 1624 } else if (fromModule != targetModule) { 1625 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1626 // allow hopping back and forth between fromModule and plc's module 1627 // but not the third module 1628 newModes = 0; 1629 } 1630 // drop MODULE access 1631 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1632 // teleport from this lookup class 1633 plc = this.lookupClass; 1634 } 1635 if ((newModes & PACKAGE) != 0 1636 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1637 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1638 } 1639 // Allow nestmate lookups to be created without special privilege: 1640 if ((newModes & PRIVATE) != 0 1641 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1642 newModes &= ~(PRIVATE|PROTECTED); 1643 } 1644 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1645 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1646 // The requested class it not accessible from the lookup class. 1647 // No permissions. 1648 newModes = 0; 1649 } 1650 return newLookup(requestedLookupClass, plc, newModes); 1651 } 1652 1653 /** 1654 * Creates a lookup on the same lookup class which this lookup object 1655 * finds members, but with a lookup mode that has lost the given lookup mode. 1656 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1657 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1658 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1659 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1660 * 1661 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1662 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1663 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1664 * lookup has no access. 1665 * 1666 * <p> If this lookup is not a public lookup, then the following applies 1667 * regardless of its {@linkplain #lookupModes() lookup modes}. 1668 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1669 * dropped and so the resulting lookup mode will never have these access 1670 * capabilities. When dropping {@code PACKAGE} 1671 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1672 * access. When dropping {@code MODULE} then the resulting lookup will not 1673 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1674 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1675 * 1676 * @apiNote 1677 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1678 * delegate non-public access within the package of the lookup class without 1679 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1680 * A lookup with {@code MODULE} but not 1681 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1682 * the module of the lookup class without conferring package access. 1683 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1684 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1685 * to public classes accessible to both the module of the lookup class 1686 * and the module of the previous lookup class. 1687 * 1688 * @param modeToDrop the lookup mode to drop 1689 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1690 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1691 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1692 * or {@code UNCONDITIONAL} 1693 * @see MethodHandles#privateLookupIn 1694 * @since 9 1695 */ 1696 public Lookup dropLookupMode(int modeToDrop) { 1697 int oldModes = lookupModes(); 1698 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1699 switch (modeToDrop) { 1700 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1701 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1702 case PACKAGE: newModes &= ~(PRIVATE); break; 1703 case PROTECTED: 1704 case PRIVATE: 1705 case ORIGINAL: 1706 case UNCONDITIONAL: break; 1707 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1708 } 1709 if (newModes == oldModes) return this; // return self if no change 1710 return newLookup(lookupClass(), previousLookupClass(), newModes); 1711 } 1712 1713 /** 1714 * Creates and links a class or interface from {@code bytes} 1715 * with the same class loader and in the same runtime package and 1716 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1717 * {@linkplain #lookupClass() lookup class} as if calling 1718 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1719 * ClassLoader::defineClass}. 1720 * 1721 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1722 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1723 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1724 * that the lookup object was created by a caller in the runtime package (or derived 1725 * from a lookup originally created by suitably privileged code to a target class in 1726 * the runtime package). </p> 1727 * 1728 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1729 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1730 * same package as the lookup class. </p> 1731 * 1732 * <p> This method does not run the class initializer. The class initializer may 1733 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1734 * Specification</em>. </p> 1735 * 1736 * @param bytes the class bytes 1737 * @return the {@code Class} object for the class 1738 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1739 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1740 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1741 * than the lookup class or {@code bytes} is not a class or interface 1742 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1743 * @throws VerifyError if the newly created class cannot be verified 1744 * @throws LinkageError if the newly created class cannot be linked for any other reason 1745 * @throws NullPointerException if {@code bytes} is {@code null} 1746 * @since 9 1747 * @see MethodHandles#privateLookupIn 1748 * @see Lookup#dropLookupMode 1749 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1750 */ 1751 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1752 if ((lookupModes() & PACKAGE) == 0) 1753 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1754 return makeClassDefiner(bytes.clone()).defineClass(false); 1755 } 1756 1757 /** 1758 * The set of class options that specify whether a hidden class created by 1759 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1760 * Lookup::defineHiddenClass} method is dynamically added as a new member 1761 * to the nest of a lookup class and/or whether a hidden class has 1762 * a strong relationship with the class loader marked as its defining loader. 1763 * 1764 * @since 15 1765 */ 1766 public enum ClassOption { 1767 /** 1768 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1769 * of a lookup class as a nestmate. 1770 * 1771 * <p> A hidden nestmate class has access to the private members of all 1772 * classes and interfaces in the same nest. 1773 * 1774 * @see Class#getNestHost() 1775 */ 1776 NESTMATE(NESTMATE_CLASS), 1777 1778 /** 1779 * Specifies that a hidden class has a <em>strong</em> 1780 * relationship with the class loader marked as its defining loader, 1781 * as a normal class or interface has with its own defining loader. 1782 * This means that the hidden class may be unloaded if and only if 1783 * its defining loader is not reachable and thus may be reclaimed 1784 * by a garbage collector (JLS {@jls 12.7}). 1785 * 1786 * <p> By default, a hidden class or interface may be unloaded 1787 * even if the class loader that is marked as its defining loader is 1788 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1789 1790 * 1791 * @jls 12.7 Unloading of Classes and Interfaces 1792 */ 1793 STRONG(STRONG_LOADER_LINK); 1794 1795 /* the flag value is used by VM at define class time */ 1796 private final int flag; 1797 ClassOption(int flag) { 1798 this.flag = flag; 1799 } 1800 1801 static int optionsToFlag(ClassOption[] options) { 1802 int flags = 0; 1803 for (ClassOption cp : options) { 1804 if ((flags & cp.flag) != 0) { 1805 throw new IllegalArgumentException("Duplicate ClassOption " + cp); 1806 } 1807 flags |= cp.flag; 1808 } 1809 return flags; 1810 } 1811 } 1812 1813 /** 1814 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1815 * returning a {@code Lookup} on the newly created class or interface. 1816 * 1817 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1818 * which either defines {@code C} directly or delegates to another class loader. 1819 * A class loader defines {@code C} directly by invoking 1820 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1821 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1822 * to derive {@code C} from a purported representation in {@code class} file format. 1823 * In situations where use of a class loader is undesirable, a class or interface 1824 * {@code C} can be created by this method instead. This method is capable of 1825 * defining {@code C}, and thereby creating it, without invoking 1826 * {@code ClassLoader::defineClass}. 1827 * Instead, this method defines {@code C} as if by arranging for 1828 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1829 * from a purported representation in {@code class} file format 1830 * using the following rules: 1831 * 1832 * <ol> 1833 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1834 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1835 * This level of access is needed to create {@code C} in the module 1836 * of the lookup class of this {@code Lookup}.</li> 1837 * 1838 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1839 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1840 * The major and minor version may differ from the {@code class} file version 1841 * of the lookup class of this {@code Lookup}.</li> 1842 * 1843 * <li> The value of {@code this_class} must be a valid index in the 1844 * {@code constant_pool} table, and the entry at that index must be a valid 1845 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1846 * encoded in internal form that is specified by this structure. {@code N} must 1847 * denote a class or interface in the same package as the lookup class.</li> 1848 * 1849 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1850 * where {@code <suffix>} is an unqualified name. 1851 * 1852 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1853 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1854 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1855 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1856 * refers to the new {@code CONSTANT_Utf8_info} structure. 1857 * 1858 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1859 * 1860 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1861 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1862 * with the following adjustments: 1863 * <ul> 1864 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1865 * that includes a single {@code "."} character, even though this is not a valid 1866 * binary class or interface name in internal form.</li> 1867 * 1868 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1869 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1870 * 1871 * <li> {@code C} is considered to have the same runtime 1872 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1873 * and {@linkplain java.security.ProtectionDomain protection domain} 1874 * as the lookup class of this {@code Lookup}. 1875 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1876 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1877 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1878 * <ul> 1879 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1880 * even though this is not a valid binary class or interface name.</li> 1881 * <li> {@link Class#descriptorString()} returns the string 1882 * {@code "L" + N + "." + <suffix> + ";"}, 1883 * even though this is not a valid type descriptor name.</li> 1884 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1885 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1886 * </ul> 1887 * </ul> 1888 * </li> 1889 * </ol> 1890 * 1891 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1892 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1893 * <ul> 1894 * <li> During verification, whenever it is necessary to load the class named 1895 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 1896 * made of any class loader.</li> 1897 * 1898 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 1899 * by {@code this_class}, the symbolic reference is considered to be resolved to 1900 * {@code C} and resolution always succeeds immediately.</li> 1901 * </ul> 1902 * 1903 * <p> If the {@code initialize} parameter is {@code true}, 1904 * then {@code C} is initialized by the Java Virtual Machine. 1905 * 1906 * <p> The newly created class or interface {@code C} serves as the 1907 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 1908 * returned by this method. {@code C} is <em>hidden</em> in the sense that 1909 * no other class or interface can refer to {@code C} via a constant pool entry. 1910 * That is, a hidden class or interface cannot be named as a supertype, a field type, 1911 * a method parameter type, or a method return type by any other class. 1912 * This is because a hidden class or interface does not have a binary name, so 1913 * there is no internal form available to record in any class's constant pool. 1914 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 1915 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 1916 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 1917 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 1918 * JVM Tool Interface</a>. 1919 * 1920 * <p> A class or interface created by 1921 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1922 * a class loader} has a strong relationship with that class loader. 1923 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 1924 * that {@linkplain Class#getClassLoader() defined it}. 1925 * This means that a class created by a class loader may be unloaded if and 1926 * only if its defining loader is not reachable and thus may be reclaimed 1927 * by a garbage collector (JLS {@jls 12.7}). 1928 * 1929 * By default, however, a hidden class or interface may be unloaded even if 1930 * the class loader that is marked as its defining loader is 1931 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1932 * This behavior is useful when a hidden class or interface serves multiple 1933 * classes defined by arbitrary class loaders. In other cases, a hidden 1934 * class or interface may be linked to a single class (or a small number of classes) 1935 * with the same defining loader as the hidden class or interface. 1936 * In such cases, where the hidden class or interface must be coterminous 1937 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 1938 * option may be passed in {@code options}. 1939 * This arranges for a hidden class to have the same strong relationship 1940 * with the class loader marked as its defining loader, 1941 * as a normal class or interface has with its own defining loader. 1942 * 1943 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 1944 * may still prevent a hidden class or interface from being 1945 * unloaded by ensuring that the {@code Class} object is reachable. 1946 * 1947 * <p> The unloading characteristics are set for each hidden class when it is 1948 * defined, and cannot be changed later. An advantage of allowing hidden classes 1949 * to be unloaded independently of the class loader marked as their defining loader 1950 * is that a very large number of hidden classes may be created by an application. 1951 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 1952 * just as if normal classes were created by class loaders. 1953 * 1954 * <p> Classes and interfaces in a nest are allowed to have mutual access to 1955 * their private members. The nest relationship is determined by 1956 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 1957 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 1958 * By default, a hidden class belongs to a nest consisting only of itself 1959 * because a hidden class has no binary name. 1960 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 1961 * to create a hidden class or interface {@code C} as a member of a nest. 1962 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 1963 * in the {@code ClassFile} structure from which {@code C} was derived. 1964 * Instead, the following rules determine the nest host of {@code C}: 1965 * <ul> 1966 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 1967 * been determined, then let {@code H} be the nest host of the lookup class. 1968 * Otherwise, the nest host of the lookup class is determined using the 1969 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 1970 * <li>The nest host of {@code C} is determined to be {@code H}, 1971 * the nest host of the lookup class.</li> 1972 * </ul> 1973 * 1974 * <p> A hidden class or interface may be serializable, but this requires a custom 1975 * serialization mechanism in order to ensure that instances are properly serialized 1976 * and deserialized. The default serialization mechanism supports only classes and 1977 * interfaces that are discoverable by their class name. 1978 * 1979 * @param bytes the bytes that make up the class data, 1980 * in the format of a valid {@code class} file as defined by 1981 * <cite>The Java Virtual Machine Specification</cite>. 1982 * @param initialize if {@code true} the class will be initialized. 1983 * @param options {@linkplain ClassOption class options} 1984 * @return the {@code Lookup} object on the hidden class, 1985 * with {@linkplain #ORIGINAL original} and 1986 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 1987 * 1988 * @throws IllegalAccessException if this {@code Lookup} does not have 1989 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 1990 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1991 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 1992 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1993 * than the lookup class or {@code bytes} is not a class or interface 1994 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1995 * @throws IncompatibleClassChangeError if the class or interface named as 1996 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 1997 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 1998 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 1999 * {@code C} is {@code C} itself 2000 * @throws VerifyError if the newly created class cannot be verified 2001 * @throws LinkageError if the newly created class cannot be linked for any other reason 2002 * @throws NullPointerException if any parameter is {@code null} 2003 * 2004 * @since 15 2005 * @see Class#isHidden() 2006 * @jvms 4.2.1 Binary Class and Interface Names 2007 * @jvms 4.2.2 Unqualified Names 2008 * @jvms 4.7.28 The {@code NestHost} Attribute 2009 * @jvms 4.7.29 The {@code NestMembers} Attribute 2010 * @jvms 5.4.3.1 Class and Interface Resolution 2011 * @jvms 5.4.4 Access Control 2012 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2013 * @jvms 5.4 Linking 2014 * @jvms 5.5 Initialization 2015 * @jls 12.7 Unloading of Classes and Interfaces 2016 */ 2017 @SuppressWarnings("doclint:reference") // cross-module links 2018 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2019 throws IllegalAccessException 2020 { 2021 Objects.requireNonNull(bytes); 2022 int flags = ClassOption.optionsToFlag(options); 2023 if (!hasFullPrivilegeAccess()) { 2024 throw new IllegalAccessException(this + " does not have full privilege access"); 2025 } 2026 2027 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize); 2028 } 2029 2030 /** 2031 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2032 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2033 * returning a {@code Lookup} on the newly created class or interface. 2034 * 2035 * <p> This method is equivalent to calling 2036 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2037 * as if the hidden class is injected with a private static final <i>unnamed</i> 2038 * field which is initialized with the given {@code classData} at 2039 * the first instruction of the class initializer. 2040 * The newly created class is linked by the Java Virtual Machine. 2041 * 2042 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2043 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2044 * methods can be used to retrieve the {@code classData}. 2045 * 2046 * @apiNote 2047 * A framework can create a hidden class with class data with one or more 2048 * objects and load the class data as dynamically-computed constant(s) 2049 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2050 * Class data} is accessible only to the lookup object created by the newly 2051 * defined hidden class but inaccessible to other members in the same nest 2052 * (unlike private static fields that are accessible to nestmates). 2053 * Care should be taken w.r.t. mutability for example when passing 2054 * an array or other mutable structure through the class data. 2055 * Changing any value stored in the class data at runtime may lead to 2056 * unpredictable behavior. 2057 * If the class data is a {@code List}, it is good practice to make it 2058 * unmodifiable for example via {@link List#of List::of}. 2059 * 2060 * @param bytes the class bytes 2061 * @param classData pre-initialized class data 2062 * @param initialize if {@code true} the class will be initialized. 2063 * @param options {@linkplain ClassOption class options} 2064 * @return the {@code Lookup} object on the hidden class, 2065 * with {@linkplain #ORIGINAL original} and 2066 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2067 * 2068 * @throws IllegalAccessException if this {@code Lookup} does not have 2069 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2070 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2071 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2072 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2073 * than the lookup class or {@code bytes} is not a class or interface 2074 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2075 * @throws IncompatibleClassChangeError if the class or interface named as 2076 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2077 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2078 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2079 * {@code C} is {@code C} itself 2080 * @throws VerifyError if the newly created class cannot be verified 2081 * @throws LinkageError if the newly created class cannot be linked for any other reason 2082 * @throws NullPointerException if any parameter is {@code null} 2083 * 2084 * @since 16 2085 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2086 * @see Class#isHidden() 2087 * @see MethodHandles#classData(Lookup, String, Class) 2088 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2089 * @jvms 4.2.1 Binary Class and Interface Names 2090 * @jvms 4.2.2 Unqualified Names 2091 * @jvms 4.7.28 The {@code NestHost} Attribute 2092 * @jvms 4.7.29 The {@code NestMembers} Attribute 2093 * @jvms 5.4.3.1 Class and Interface Resolution 2094 * @jvms 5.4.4 Access Control 2095 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2096 * @jvms 5.4 Linking 2097 * @jvms 5.5 Initialization 2098 * @jls 12.7 Unloading of Classes and Interfaces 2099 */ 2100 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2101 throws IllegalAccessException 2102 { 2103 Objects.requireNonNull(bytes); 2104 Objects.requireNonNull(classData); 2105 2106 int flags = ClassOption.optionsToFlag(options); 2107 2108 if (!hasFullPrivilegeAccess()) { 2109 throw new IllegalAccessException(this + " does not have full privilege access"); 2110 } 2111 2112 return makeHiddenClassDefiner(bytes.clone(), false, flags) 2113 .defineClassAsLookup(initialize, classData); 2114 } 2115 2116 // A default dumper for writing class files passed to Lookup::defineClass 2117 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2118 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2119 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2120 // 2121 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2122 // and LambdaForms and method handle internals. They are dumped via 2123 // different ClassFileDumpers. 2124 private static ClassFileDumper defaultDumper() { 2125 return DEFAULT_DUMPER; 2126 } 2127 2128 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2129 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2130 2131 /** 2132 * This method checks the class file version and the structure of `this_class`. 2133 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2134 * that is in the named package. 2135 * 2136 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2137 * or the class is not in the given package name. 2138 */ 2139 static String validateAndFindInternalName(byte[] bytes, String pkgName) { 2140 int magic = readInt(bytes, 0); 2141 if (magic != ClassFile.MAGIC_NUMBER) { 2142 throw new ClassFormatError("Incompatible magic value: " + magic); 2143 } 2144 // We have to read major and minor this way as ClassFile API throws IAE 2145 // yet we want distinct ClassFormatError and UnsupportedClassVersionError 2146 int minor = readUnsignedShort(bytes, 4); 2147 int major = readUnsignedShort(bytes, 6); 2148 2149 if (!VM.isSupportedClassFileVersion(major, minor)) { 2150 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2151 } 2152 2153 String name; 2154 ClassDesc sym; 2155 int accessFlags; 2156 try { 2157 ClassModel cm = ClassFile.of().parse(bytes); 2158 var thisClass = cm.thisClass(); 2159 name = thisClass.asInternalName(); 2160 sym = thisClass.asSymbol(); 2161 accessFlags = cm.flags().flagsMask(); 2162 } catch (IllegalArgumentException e) { 2163 ClassFormatError cfe = new ClassFormatError(); 2164 cfe.initCause(e); 2165 throw cfe; 2166 } 2167 // must be a class or interface 2168 if ((accessFlags & ACC_MODULE) != 0) { 2169 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2170 } 2171 2172 String pn = sym.packageName(); 2173 if (!pn.equals(pkgName)) { 2174 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2175 } 2176 2177 return name; 2178 } 2179 2180 private static int readInt(byte[] bytes, int offset) { 2181 if ((offset + 4) > bytes.length) { 2182 throw new ClassFormatError("Invalid ClassFile structure"); 2183 } 2184 return ((bytes[offset] & 0xFF) << 24) 2185 | ((bytes[offset + 1] & 0xFF) << 16) 2186 | ((bytes[offset + 2] & 0xFF) << 8) 2187 | (bytes[offset + 3] & 0xFF); 2188 } 2189 2190 private static int readUnsignedShort(byte[] bytes, int offset) { 2191 if ((offset+2) > bytes.length) { 2192 throw new ClassFormatError("Invalid ClassFile structure"); 2193 } 2194 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2195 } 2196 2197 /* 2198 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2199 * from the given bytes. 2200 * 2201 * Caller should make a defensive copy of the arguments if needed 2202 * before calling this factory method. 2203 * 2204 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2205 * {@code bytes} denotes a class in a different package than the lookup class 2206 */ 2207 private ClassDefiner makeClassDefiner(byte[] bytes) { 2208 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2209 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper()); 2210 } 2211 2212 /** 2213 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2214 * from the given bytes. No package name check on the given bytes. 2215 * 2216 * @param internalName internal name 2217 * @param bytes class bytes 2218 * @param dumper dumper to write the given bytes to the dumper's output directory 2219 * @return ClassDefiner that defines a normal class of the given bytes. 2220 */ 2221 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2222 // skip package name validation 2223 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper); 2224 } 2225 2226 /** 2227 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2228 * from the given bytes. The name must be in the same package as the lookup class. 2229 * 2230 * Caller should make a defensive copy of the arguments if needed 2231 * before calling this factory method. 2232 * 2233 * @param bytes class bytes 2234 * @param dumper dumper to write the given bytes to the dumper's output directory 2235 * @return ClassDefiner that defines a hidden class of the given bytes. 2236 * 2237 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2238 * {@code bytes} denotes a class in a different package than the lookup class 2239 */ 2240 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2241 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2242 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2243 } 2244 2245 /** 2246 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2247 * from the given bytes and options. 2248 * The name must be in the same package as the lookup class. 2249 * 2250 * Caller should make a defensive copy of the arguments if needed 2251 * before calling this factory method. 2252 * 2253 * @param bytes class bytes 2254 * @param flags class option flag mask 2255 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2256 * @return ClassDefiner that defines a hidden class of the given bytes and options 2257 * 2258 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2259 * {@code bytes} denotes a class in a different package than the lookup class 2260 */ 2261 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2262 boolean accessVmAnnotations, 2263 int flags) { 2264 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2265 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags); 2266 } 2267 2268 /** 2269 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2270 * from the given bytes and the given options. No package name check on the given bytes. 2271 * 2272 * @param internalName internal name that specifies the prefix of the hidden class 2273 * @param bytes class bytes 2274 * @param dumper dumper to write the given bytes to the dumper's output directory 2275 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2276 */ 2277 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2278 Objects.requireNonNull(dumper); 2279 // skip name and access flags validation 2280 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2281 } 2282 2283 /** 2284 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2285 * from the given bytes and the given options. No package name check on the given bytes. 2286 * 2287 * @param internalName internal name that specifies the prefix of the hidden class 2288 * @param bytes class bytes 2289 * @param flags class options flag mask 2290 * @param dumper dumper to write the given bytes to the dumper's output directory 2291 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2292 */ 2293 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) { 2294 Objects.requireNonNull(dumper); 2295 // skip name and access flags validation 2296 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags); 2297 } 2298 2299 /** 2300 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2301 * from the given class file and options. 2302 * 2303 * @param internalName internal name 2304 * @param bytes Class byte array 2305 * @param flags class option flag mask 2306 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2307 * @param dumper dumper to write the given bytes to the dumper's output directory 2308 */ 2309 private ClassDefiner makeHiddenClassDefiner(String internalName, 2310 byte[] bytes, 2311 boolean accessVmAnnotations, 2312 ClassFileDumper dumper, 2313 int flags) { 2314 flags |= HIDDEN_CLASS; 2315 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2316 // jdk.internal.vm.annotations are permitted for classes 2317 // defined to boot loader and platform loader 2318 flags |= ACCESS_VM_ANNOTATIONS; 2319 } 2320 2321 return new ClassDefiner(this, internalName, bytes, flags, dumper); 2322 } 2323 2324 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) { 2325 ClassDefiner { 2326 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2327 } 2328 2329 Class<?> defineClass(boolean initialize) { 2330 return defineClass(initialize, null); 2331 } 2332 2333 Lookup defineClassAsLookup(boolean initialize) { 2334 Class<?> c = defineClass(initialize, null); 2335 return new Lookup(c, null, FULL_POWER_MODES); 2336 } 2337 2338 /** 2339 * Defines the class of the given bytes and the given classData. 2340 * If {@code initialize} parameter is true, then the class will be initialized. 2341 * 2342 * @param initialize true if the class to be initialized 2343 * @param classData classData or null 2344 * @return the class 2345 * 2346 * @throws LinkageError linkage error 2347 */ 2348 Class<?> defineClass(boolean initialize, Object classData) { 2349 Class<?> lookupClass = lookup.lookupClass(); 2350 ClassLoader loader = lookupClass.getClassLoader(); 2351 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2352 Class<?> c = null; 2353 try { 2354 c = SharedSecrets.getJavaLangAccess() 2355 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData); 2356 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2357 return c; 2358 } finally { 2359 // dump the classfile for debugging 2360 if (dumper.isEnabled()) { 2361 String name = internalName(); 2362 if (c != null) { 2363 dumper.dumpClass(name, c, bytes); 2364 } else { 2365 dumper.dumpFailedClass(name, bytes); 2366 } 2367 } 2368 } 2369 } 2370 2371 /** 2372 * Defines the class of the given bytes and the given classData. 2373 * If {@code initialize} parameter is true, then the class will be initialized. 2374 * 2375 * @param initialize true if the class to be initialized 2376 * @param classData classData or null 2377 * @return a Lookup for the defined class 2378 * 2379 * @throws LinkageError linkage error 2380 */ 2381 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2382 Class<?> c = defineClass(initialize, classData); 2383 return new Lookup(c, null, FULL_POWER_MODES); 2384 } 2385 2386 private boolean isNestmate() { 2387 return (classFlags & NESTMATE_CLASS) != 0; 2388 } 2389 } 2390 2391 private ProtectionDomain lookupClassProtectionDomain() { 2392 ProtectionDomain pd = cachedProtectionDomain; 2393 if (pd == null) { 2394 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2395 } 2396 return pd; 2397 } 2398 2399 // cached protection domain 2400 private volatile ProtectionDomain cachedProtectionDomain; 2401 2402 // Make sure outer class is initialized first. 2403 static { IMPL_NAMES.getClass(); } 2404 2405 /** Package-private version of lookup which is trusted. */ 2406 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2407 2408 /** Version of lookup which is trusted minimally. 2409 * It can only be used to create method handles to publicly accessible 2410 * members in packages that are exported unconditionally. 2411 */ 2412 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2413 2414 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2415 String name = lookupClass.getName(); 2416 if (name.startsWith("java.lang.invoke.")) 2417 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2418 } 2419 2420 /** 2421 * Displays the name of the class from which lookups are to be made, 2422 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2423 * previous lookup class} if present. 2424 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2425 * If there are restrictions on the access permitted to this lookup, 2426 * this is indicated by adding a suffix to the class name, consisting 2427 * of a slash and a keyword. The keyword represents the strongest 2428 * allowed access, and is chosen as follows: 2429 * <ul> 2430 * <li>If no access is allowed, the suffix is "/noaccess". 2431 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2432 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2433 * <li>If only public and module access are allowed, the suffix is "/module". 2434 * <li>If public and package access are allowed, the suffix is "/package". 2435 * <li>If public, package, and private access are allowed, the suffix is "/private". 2436 * </ul> 2437 * If none of the above cases apply, it is the case that 2438 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2439 * (public, module, package, private, and protected) is allowed. 2440 * In this case, no suffix is added. 2441 * This is true only of an object obtained originally from 2442 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2443 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2444 * always have restricted access, and will display a suffix. 2445 * <p> 2446 * (It may seem strange that protected access should be 2447 * stronger than private access. Viewed independently from 2448 * package access, protected access is the first to be lost, 2449 * because it requires a direct subclass relationship between 2450 * caller and callee.) 2451 * @see #in 2452 */ 2453 @Override 2454 public String toString() { 2455 String cname = lookupClass.getName(); 2456 if (prevLookupClass != null) 2457 cname += "/" + prevLookupClass.getName(); 2458 switch (allowedModes) { 2459 case 0: // no privileges 2460 return cname + "/noaccess"; 2461 case UNCONDITIONAL: 2462 return cname + "/publicLookup"; 2463 case PUBLIC: 2464 return cname + "/public"; 2465 case PUBLIC|MODULE: 2466 return cname + "/module"; 2467 case PUBLIC|PACKAGE: 2468 case PUBLIC|MODULE|PACKAGE: 2469 return cname + "/package"; 2470 case PUBLIC|PACKAGE|PRIVATE: 2471 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2472 return cname + "/private"; 2473 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2474 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2475 case FULL_POWER_MODES: 2476 return cname; 2477 case TRUSTED: 2478 return "/trusted"; // internal only; not exported 2479 default: // Should not happen, but it's a bitfield... 2480 cname = cname + "/" + Integer.toHexString(allowedModes); 2481 assert(false) : cname; 2482 return cname; 2483 } 2484 } 2485 2486 /** 2487 * Produces a method handle for a static method. 2488 * The type of the method handle will be that of the method. 2489 * (Since static methods do not take receivers, there is no 2490 * additional receiver argument inserted into the method handle type, 2491 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2492 * The method and all its argument types must be accessible to the lookup object. 2493 * <p> 2494 * The returned method handle will have 2495 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2496 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2497 * <p> 2498 * If the returned method handle is invoked, the method's class will 2499 * be initialized, if it has not already been initialized. 2500 * <p><b>Example:</b> 2501 * {@snippet lang="java" : 2502 import static java.lang.invoke.MethodHandles.*; 2503 import static java.lang.invoke.MethodType.*; 2504 ... 2505 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2506 "asList", methodType(List.class, Object[].class)); 2507 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2508 * } 2509 * @param refc the class from which the method is accessed 2510 * @param name the name of the method 2511 * @param type the type of the method 2512 * @return the desired method handle 2513 * @throws NoSuchMethodException if the method does not exist 2514 * @throws IllegalAccessException if access checking fails, 2515 * or if the method is not {@code static}, 2516 * or if the method's variable arity modifier bit 2517 * is set and {@code asVarargsCollector} fails 2518 * @throws NullPointerException if any argument is null 2519 */ 2520 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2521 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2522 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2523 } 2524 2525 /** 2526 * Produces a method handle for a virtual method. 2527 * The type of the method handle will be that of the method, 2528 * with the receiver type (usually {@code refc}) prepended. 2529 * The method and all its argument types must be accessible to the lookup object. 2530 * <p> 2531 * When called, the handle will treat the first argument as a receiver 2532 * and, for non-private methods, dispatch on the receiver's type to determine which method 2533 * implementation to enter. 2534 * For private methods the named method in {@code refc} will be invoked on the receiver. 2535 * (The dispatching action is identical with that performed by an 2536 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2537 * <p> 2538 * The first argument will be of type {@code refc} if the lookup 2539 * class has full privileges to access the member. Otherwise 2540 * the member must be {@code protected} and the first argument 2541 * will be restricted in type to the lookup class. 2542 * <p> 2543 * The returned method handle will have 2544 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2545 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2546 * <p> 2547 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2548 * instructions and method handles produced by {@code findVirtual}, 2549 * if the class is {@code MethodHandle} and the name string is 2550 * {@code invokeExact} or {@code invoke}, the resulting 2551 * method handle is equivalent to one produced by 2552 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2553 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2554 * with the same {@code type} argument. 2555 * <p> 2556 * If the class is {@code VarHandle} and the name string corresponds to 2557 * the name of a signature-polymorphic access mode method, the resulting 2558 * method handle is equivalent to one produced by 2559 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2560 * the access mode corresponding to the name string and with the same 2561 * {@code type} arguments. 2562 * <p> 2563 * <b>Example:</b> 2564 * {@snippet lang="java" : 2565 import static java.lang.invoke.MethodHandles.*; 2566 import static java.lang.invoke.MethodType.*; 2567 ... 2568 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2569 "concat", methodType(String.class, String.class)); 2570 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2571 "hashCode", methodType(int.class)); 2572 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2573 "hashCode", methodType(int.class)); 2574 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2575 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2576 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2577 // interface method: 2578 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2579 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2580 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2581 // constructor "internal method" must be accessed differently: 2582 MethodType MT_newString = methodType(void.class); //()V for new String() 2583 try { assertEquals("impossible", lookup() 2584 .findVirtual(String.class, "<init>", MT_newString)); 2585 } catch (NoSuchMethodException ex) { } // OK 2586 MethodHandle MH_newString = publicLookup() 2587 .findConstructor(String.class, MT_newString); 2588 assertEquals("", (String) MH_newString.invokeExact()); 2589 * } 2590 * 2591 * @param refc the class or interface from which the method is accessed 2592 * @param name the name of the method 2593 * @param type the type of the method, with the receiver argument omitted 2594 * @return the desired method handle 2595 * @throws NoSuchMethodException if the method does not exist 2596 * @throws IllegalAccessException if access checking fails, 2597 * or if the method is {@code static}, 2598 * or if the method's variable arity modifier bit 2599 * is set and {@code asVarargsCollector} fails 2600 * @throws NullPointerException if any argument is null 2601 */ 2602 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2603 if (refc == MethodHandle.class) { 2604 MethodHandle mh = findVirtualForMH(name, type); 2605 if (mh != null) return mh; 2606 } else if (refc == VarHandle.class) { 2607 MethodHandle mh = findVirtualForVH(name, type); 2608 if (mh != null) return mh; 2609 } 2610 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2611 MemberName method = resolveOrFail(refKind, refc, name, type); 2612 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2613 } 2614 private MethodHandle findVirtualForMH(String name, MethodType type) { 2615 // these names require special lookups because of the implicit MethodType argument 2616 if ("invoke".equals(name)) 2617 return invoker(type); 2618 if ("invokeExact".equals(name)) 2619 return exactInvoker(type); 2620 assert(!MemberName.isMethodHandleInvokeName(name)); 2621 return null; 2622 } 2623 private MethodHandle findVirtualForVH(String name, MethodType type) { 2624 try { 2625 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2626 } catch (IllegalArgumentException e) { 2627 return null; 2628 } 2629 } 2630 2631 /** 2632 * Produces a method handle which creates an object and initializes it, using 2633 * the constructor of the specified type. 2634 * The parameter types of the method handle will be those of the constructor, 2635 * while the return type will be a reference to the constructor's class. 2636 * The constructor and all its argument types must be accessible to the lookup object. 2637 * <p> 2638 * The requested type must have a return type of {@code void}. 2639 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2640 * <p> 2641 * The returned method handle will have 2642 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2643 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2644 * <p> 2645 * If the returned method handle is invoked, the constructor's class will 2646 * be initialized, if it has not already been initialized. 2647 * <p><b>Example:</b> 2648 * {@snippet lang="java" : 2649 import static java.lang.invoke.MethodHandles.*; 2650 import static java.lang.invoke.MethodType.*; 2651 ... 2652 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2653 ArrayList.class, methodType(void.class, Collection.class)); 2654 Collection orig = Arrays.asList("x", "y"); 2655 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2656 assert(orig != copy); 2657 assertEquals(orig, copy); 2658 // a variable-arity constructor: 2659 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2660 ProcessBuilder.class, methodType(void.class, String[].class)); 2661 ProcessBuilder pb = (ProcessBuilder) 2662 MH_newProcessBuilder.invoke("x", "y", "z"); 2663 assertEquals("[x, y, z]", pb.command().toString()); 2664 * } 2665 * @param refc the class or interface from which the method is accessed 2666 * @param type the type of the method, with the receiver argument omitted, and a void return type 2667 * @return the desired method handle 2668 * @throws NoSuchMethodException if the constructor does not exist 2669 * @throws IllegalAccessException if access checking fails 2670 * or if the method's variable arity modifier bit 2671 * is set and {@code asVarargsCollector} fails 2672 * @throws NullPointerException if any argument is null 2673 */ 2674 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2675 if (refc.isArray()) { 2676 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2677 } 2678 String name = ConstantDescs.INIT_NAME; 2679 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2680 return getDirectConstructor(refc, ctor); 2681 } 2682 2683 /** 2684 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2685 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2686 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2687 * and then determines whether the class is accessible to this lookup object. 2688 * <p> 2689 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2690 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2691 * of {@code '['} and followed by the element type as encoded in the 2692 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2693 * <p> 2694 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2695 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2696 * 2697 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2698 * or the string representing an array class 2699 * @return the requested class. 2700 * @throws LinkageError if the linkage fails 2701 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2702 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2703 * modes. 2704 * @throws NullPointerException if {@code targetName} is null 2705 * @since 9 2706 * @jvms 5.4.3.1 Class and Interface Resolution 2707 */ 2708 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2709 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2710 return accessClass(targetClass); 2711 } 2712 2713 /** 2714 * Ensures that {@code targetClass} has been initialized. The class 2715 * to be initialized must be {@linkplain #accessClass accessible} 2716 * to this {@code Lookup} object. This method causes {@code targetClass} 2717 * to be initialized if it has not been already initialized, 2718 * as specified in JVMS {@jvms 5.5}. 2719 * 2720 * <p> 2721 * This method returns when {@code targetClass} is fully initialized, or 2722 * when {@code targetClass} is being initialized by the current thread. 2723 * 2724 * @param <T> the type of the class to be initialized 2725 * @param targetClass the class to be initialized 2726 * @return {@code targetClass} that has been initialized, or that is being 2727 * initialized by the current thread. 2728 * 2729 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2730 * or array class 2731 * @throws IllegalAccessException if {@code targetClass} is not 2732 * {@linkplain #accessClass accessible} to this lookup 2733 * @throws ExceptionInInitializerError if the class initialization provoked 2734 * by this method fails 2735 * @since 15 2736 * @jvms 5.5 Initialization 2737 */ 2738 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2739 if (targetClass.isPrimitive()) 2740 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2741 if (targetClass.isArray()) 2742 throw new IllegalArgumentException(targetClass + " is an array class"); 2743 2744 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2745 throw makeAccessException(targetClass); 2746 } 2747 2748 // ensure class initialization 2749 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2750 return targetClass; 2751 } 2752 2753 /* 2754 * Returns IllegalAccessException due to access violation to the given targetClass. 2755 * 2756 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2757 * which verifies access to a class rather a member. 2758 */ 2759 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2760 String message = "access violation: "+ targetClass; 2761 if (this == MethodHandles.publicLookup()) { 2762 message += ", from public Lookup"; 2763 } else { 2764 Module m = lookupClass().getModule(); 2765 message += ", from " + lookupClass() + " (" + m + ")"; 2766 if (prevLookupClass != null) { 2767 message += ", previous lookup " + 2768 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2769 } 2770 } 2771 return new IllegalAccessException(message); 2772 } 2773 2774 /** 2775 * Determines if a class can be accessed from the lookup context defined by 2776 * this {@code Lookup} object. The static initializer of the class is not run. 2777 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2778 * if the element type of the array class is accessible. Otherwise, 2779 * {@code targetClass} is determined as accessible as follows. 2780 * 2781 * <p> 2782 * If {@code targetClass} is in the same module as the lookup class, 2783 * the lookup class is {@code LC} in module {@code M1} and 2784 * the previous lookup class is in module {@code M0} or 2785 * {@code null} if not present, 2786 * {@code targetClass} is accessible if and only if one of the following is true: 2787 * <ul> 2788 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2789 * {@code LC} or other class in the same nest of {@code LC}.</li> 2790 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2791 * in the same runtime package of {@code LC}.</li> 2792 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2793 * a public type in {@code M1}.</li> 2794 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2795 * a public type in a package exported by {@code M1} to at least {@code M0} 2796 * if the previous lookup class is present; otherwise, {@code targetClass} 2797 * is a public type in a package exported by {@code M1} unconditionally.</li> 2798 * </ul> 2799 * 2800 * <p> 2801 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2802 * can access public types in all modules when the type is in a package 2803 * that is exported unconditionally. 2804 * <p> 2805 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2806 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2807 * is inaccessible. 2808 * <p> 2809 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2810 * {@code M1} is the module containing {@code lookupClass} and 2811 * {@code M2} is the module containing {@code targetClass}, 2812 * then {@code targetClass} is accessible if and only if 2813 * <ul> 2814 * <li>{@code M1} reads {@code M2}, and 2815 * <li>{@code targetClass} is public and in a package exported by 2816 * {@code M2} at least to {@code M1}. 2817 * </ul> 2818 * <p> 2819 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2820 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2821 * containing the previous lookup class, then {@code targetClass} is accessible 2822 * if and only if one of the following is true: 2823 * <ul> 2824 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2825 * {@linkplain Module#reads reads} {@code M0} and the type is 2826 * in a package that is exported to at least {@code M1}. 2827 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2828 * {@linkplain Module#reads reads} {@code M1} and the type is 2829 * in a package that is exported to at least {@code M0}. 2830 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2831 * and {@code M1} reads {@code M2} and the type is in a package 2832 * that is exported to at least both {@code M0} and {@code M2}. 2833 * </ul> 2834 * <p> 2835 * Otherwise, {@code targetClass} is not accessible. 2836 * 2837 * @param <T> the type of the class to be access-checked 2838 * @param targetClass the class to be access-checked 2839 * @return {@code targetClass} that has been access-checked 2840 * @throws IllegalAccessException if the class is not accessible from the lookup class 2841 * and previous lookup class, if present, using the allowed access modes. 2842 * @throws NullPointerException if {@code targetClass} is {@code null} 2843 * @since 9 2844 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2845 */ 2846 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2847 if (!isClassAccessible(targetClass)) { 2848 throw makeAccessException(targetClass); 2849 } 2850 return targetClass; 2851 } 2852 2853 /** 2854 * Produces an early-bound method handle for a virtual method. 2855 * It will bypass checks for overriding methods on the receiver, 2856 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2857 * instruction from within the explicitly specified {@code specialCaller}. 2858 * The type of the method handle will be that of the method, 2859 * with a suitably restricted receiver type prepended. 2860 * (The receiver type will be {@code specialCaller} or a subtype.) 2861 * The method and all its argument types must be accessible 2862 * to the lookup object. 2863 * <p> 2864 * Before method resolution, 2865 * if the explicitly specified caller class is not identical with the 2866 * lookup class, or if this lookup object does not have 2867 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2868 * privileges, the access fails. 2869 * <p> 2870 * The returned method handle will have 2871 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2872 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2873 * <p style="font-size:smaller;"> 2874 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 2875 * are not visible to this API, 2876 * even though the {@code invokespecial} instruction can refer to them 2877 * in special circumstances. Use {@link #findConstructor findConstructor} 2878 * to access instance initialization methods in a safe manner.)</em> 2879 * <p><b>Example:</b> 2880 * {@snippet lang="java" : 2881 import static java.lang.invoke.MethodHandles.*; 2882 import static java.lang.invoke.MethodType.*; 2883 ... 2884 static class Listie extends ArrayList { 2885 public String toString() { return "[wee Listie]"; } 2886 static Lookup lookup() { return MethodHandles.lookup(); } 2887 } 2888 ... 2889 // no access to constructor via invokeSpecial: 2890 MethodHandle MH_newListie = Listie.lookup() 2891 .findConstructor(Listie.class, methodType(void.class)); 2892 Listie l = (Listie) MH_newListie.invokeExact(); 2893 try { assertEquals("impossible", Listie.lookup().findSpecial( 2894 Listie.class, "<init>", methodType(void.class), Listie.class)); 2895 } catch (NoSuchMethodException ex) { } // OK 2896 // access to super and self methods via invokeSpecial: 2897 MethodHandle MH_super = Listie.lookup().findSpecial( 2898 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2899 MethodHandle MH_this = Listie.lookup().findSpecial( 2900 Listie.class, "toString" , methodType(String.class), Listie.class); 2901 MethodHandle MH_duper = Listie.lookup().findSpecial( 2902 Object.class, "toString" , methodType(String.class), Listie.class); 2903 assertEquals("[]", (String) MH_super.invokeExact(l)); 2904 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2905 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2906 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2907 String.class, "toString", methodType(String.class), Listie.class)); 2908 } catch (IllegalAccessException ex) { } // OK 2909 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2910 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2911 * } 2912 * 2913 * @param refc the class or interface from which the method is accessed 2914 * @param name the name of the method (which must not be "<init>") 2915 * @param type the type of the method, with the receiver argument omitted 2916 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2917 * @return the desired method handle 2918 * @throws NoSuchMethodException if the method does not exist 2919 * @throws IllegalAccessException if access checking fails, 2920 * or if the method is {@code static}, 2921 * or if the method's variable arity modifier bit 2922 * is set and {@code asVarargsCollector} fails 2923 * @throws NullPointerException if any argument is null 2924 */ 2925 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 2926 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 2927 checkSpecialCaller(specialCaller, refc); 2928 Lookup specialLookup = this.in(specialCaller); 2929 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 2930 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 2931 } 2932 2933 /** 2934 * Produces a method handle giving read access to a non-static field. 2935 * The type of the method handle will have a return type of the field's 2936 * value type. 2937 * The method handle's single argument will be the instance containing 2938 * the field. 2939 * Access checking is performed immediately on behalf of the lookup class. 2940 * @param refc the class or interface from which the method is accessed 2941 * @param name the field's name 2942 * @param type the field's type 2943 * @return a method handle which can load values from the field 2944 * @throws NoSuchFieldException if the field does not exist 2945 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2946 * @throws NullPointerException if any argument is null 2947 * @see #findVarHandle(Class, String, Class) 2948 */ 2949 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2950 MemberName field = resolveOrFail(REF_getField, refc, name, type); 2951 return getDirectField(REF_getField, refc, field); 2952 } 2953 2954 /** 2955 * Produces a method handle giving write access to a non-static field. 2956 * The type of the method handle will have a void return type. 2957 * The method handle will take two arguments, the instance containing 2958 * the field, and the value to be stored. 2959 * The second argument will be of the field's value type. 2960 * Access checking is performed immediately on behalf of the lookup class. 2961 * @param refc the class or interface from which the method is accessed 2962 * @param name the field's name 2963 * @param type the field's type 2964 * @return a method handle which can store values into the field 2965 * @throws NoSuchFieldException if the field does not exist 2966 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2967 * or {@code final} 2968 * @throws NullPointerException if any argument is null 2969 * @see #findVarHandle(Class, String, Class) 2970 */ 2971 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2972 MemberName field = resolveOrFail(REF_putField, refc, name, type); 2973 return getDirectField(REF_putField, refc, field); 2974 } 2975 2976 /** 2977 * Produces a VarHandle giving access to a non-static field {@code name} 2978 * of type {@code type} declared in a class of type {@code recv}. 2979 * The VarHandle's variable type is {@code type} and it has one 2980 * coordinate type, {@code recv}. 2981 * <p> 2982 * Access checking is performed immediately on behalf of the lookup 2983 * class. 2984 * <p> 2985 * Certain access modes of the returned VarHandle are unsupported under 2986 * the following conditions: 2987 * <ul> 2988 * <li>if the field is declared {@code final}, then the write, atomic 2989 * update, numeric atomic update, and bitwise atomic update access 2990 * modes are unsupported. 2991 * <li>if the field type is anything other than {@code byte}, 2992 * {@code short}, {@code char}, {@code int}, {@code long}, 2993 * {@code float}, or {@code double} then numeric atomic update 2994 * access modes are unsupported. 2995 * <li>if the field type is anything other than {@code boolean}, 2996 * {@code byte}, {@code short}, {@code char}, {@code int} or 2997 * {@code long} then bitwise atomic update access modes are 2998 * unsupported. 2999 * </ul> 3000 * <p> 3001 * If the field is declared {@code volatile} then the returned VarHandle 3002 * will override access to the field (effectively ignore the 3003 * {@code volatile} declaration) in accordance to its specified 3004 * access modes. 3005 * <p> 3006 * If the field type is {@code float} or {@code double} then numeric 3007 * and atomic update access modes compare values using their bitwise 3008 * representation (see {@link Float#floatToRawIntBits} and 3009 * {@link Double#doubleToRawLongBits}, respectively). 3010 * @apiNote 3011 * Bitwise comparison of {@code float} values or {@code double} values, 3012 * as performed by the numeric and atomic update access modes, differ 3013 * from the primitive {@code ==} operator and the {@link Float#equals} 3014 * and {@link Double#equals} methods, specifically with respect to 3015 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3016 * Care should be taken when performing a compare and set or a compare 3017 * and exchange operation with such values since the operation may 3018 * unexpectedly fail. 3019 * There are many possible NaN values that are considered to be 3020 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3021 * provided by Java can distinguish between them. Operation failure can 3022 * occur if the expected or witness value is a NaN value and it is 3023 * transformed (perhaps in a platform specific manner) into another NaN 3024 * value, and thus has a different bitwise representation (see 3025 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3026 * details). 3027 * The values {@code -0.0} and {@code +0.0} have different bitwise 3028 * representations but are considered equal when using the primitive 3029 * {@code ==} operator. Operation failure can occur if, for example, a 3030 * numeric algorithm computes an expected value to be say {@code -0.0} 3031 * and previously computed the witness value to be say {@code +0.0}. 3032 * @param recv the receiver class, of type {@code R}, that declares the 3033 * non-static field 3034 * @param name the field's name 3035 * @param type the field's type, of type {@code T} 3036 * @return a VarHandle giving access to non-static fields. 3037 * @throws NoSuchFieldException if the field does not exist 3038 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3039 * @throws NullPointerException if any argument is null 3040 * @since 9 3041 */ 3042 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3043 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3044 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3045 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3046 } 3047 3048 /** 3049 * Produces a method handle giving read access to a static field. 3050 * The type of the method handle will have a return type of the field's 3051 * value type. 3052 * The method handle will take no arguments. 3053 * Access checking is performed immediately on behalf of the lookup class. 3054 * <p> 3055 * If the returned method handle is invoked, the field's class will 3056 * be initialized, if it has not already been initialized. 3057 * @param refc the class or interface from which the method is accessed 3058 * @param name the field's name 3059 * @param type the field's type 3060 * @return a method handle which can load values from the field 3061 * @throws NoSuchFieldException if the field does not exist 3062 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3063 * @throws NullPointerException if any argument is null 3064 */ 3065 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3066 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3067 return getDirectField(REF_getStatic, refc, field); 3068 } 3069 3070 /** 3071 * Produces a method handle giving write access to a static field. 3072 * The type of the method handle will have a void return type. 3073 * The method handle will take a single 3074 * argument, of the field's value type, the value to be stored. 3075 * Access checking is performed immediately on behalf of the lookup class. 3076 * <p> 3077 * If the returned method handle is invoked, the field's class will 3078 * be initialized, if it has not already been initialized. 3079 * @param refc the class or interface from which the method is accessed 3080 * @param name the field's name 3081 * @param type the field's type 3082 * @return a method handle which can store values into the field 3083 * @throws NoSuchFieldException if the field does not exist 3084 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3085 * or is {@code final} 3086 * @throws NullPointerException if any argument is null 3087 */ 3088 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3089 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3090 return getDirectField(REF_putStatic, refc, field); 3091 } 3092 3093 /** 3094 * Produces a VarHandle giving access to a static field {@code name} of 3095 * type {@code type} declared in a class of type {@code decl}. 3096 * The VarHandle's variable type is {@code type} and it has no 3097 * coordinate types. 3098 * <p> 3099 * Access checking is performed immediately on behalf of the lookup 3100 * class. 3101 * <p> 3102 * If the returned VarHandle is operated on, the declaring class will be 3103 * initialized, if it has not already been initialized. 3104 * <p> 3105 * Certain access modes of the returned VarHandle are unsupported under 3106 * the following conditions: 3107 * <ul> 3108 * <li>if the field is declared {@code final}, then the write, atomic 3109 * update, numeric atomic update, and bitwise atomic update access 3110 * modes are unsupported. 3111 * <li>if the field type is anything other than {@code byte}, 3112 * {@code short}, {@code char}, {@code int}, {@code long}, 3113 * {@code float}, or {@code double}, then numeric atomic update 3114 * access modes are unsupported. 3115 * <li>if the field type is anything other than {@code boolean}, 3116 * {@code byte}, {@code short}, {@code char}, {@code int} or 3117 * {@code long} then bitwise atomic update access modes are 3118 * unsupported. 3119 * </ul> 3120 * <p> 3121 * If the field is declared {@code volatile} then the returned VarHandle 3122 * will override access to the field (effectively ignore the 3123 * {@code volatile} declaration) in accordance to its specified 3124 * access modes. 3125 * <p> 3126 * If the field type is {@code float} or {@code double} then numeric 3127 * and atomic update access modes compare values using their bitwise 3128 * representation (see {@link Float#floatToRawIntBits} and 3129 * {@link Double#doubleToRawLongBits}, respectively). 3130 * @apiNote 3131 * Bitwise comparison of {@code float} values or {@code double} values, 3132 * as performed by the numeric and atomic update access modes, differ 3133 * from the primitive {@code ==} operator and the {@link Float#equals} 3134 * and {@link Double#equals} methods, specifically with respect to 3135 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3136 * Care should be taken when performing a compare and set or a compare 3137 * and exchange operation with such values since the operation may 3138 * unexpectedly fail. 3139 * There are many possible NaN values that are considered to be 3140 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3141 * provided by Java can distinguish between them. Operation failure can 3142 * occur if the expected or witness value is a NaN value and it is 3143 * transformed (perhaps in a platform specific manner) into another NaN 3144 * value, and thus has a different bitwise representation (see 3145 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3146 * details). 3147 * The values {@code -0.0} and {@code +0.0} have different bitwise 3148 * representations but are considered equal when using the primitive 3149 * {@code ==} operator. Operation failure can occur if, for example, a 3150 * numeric algorithm computes an expected value to be say {@code -0.0} 3151 * and previously computed the witness value to be say {@code +0.0}. 3152 * @param decl the class that declares the static field 3153 * @param name the field's name 3154 * @param type the field's type, of type {@code T} 3155 * @return a VarHandle giving access to a static field 3156 * @throws NoSuchFieldException if the field does not exist 3157 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3158 * @throws NullPointerException if any argument is null 3159 * @since 9 3160 */ 3161 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3162 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3163 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3164 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3165 } 3166 3167 /** 3168 * Produces an early-bound method handle for a non-static method. 3169 * The receiver must have a supertype {@code defc} in which a method 3170 * of the given name and type is accessible to the lookup class. 3171 * The method and all its argument types must be accessible to the lookup object. 3172 * The type of the method handle will be that of the method, 3173 * without any insertion of an additional receiver parameter. 3174 * The given receiver will be bound into the method handle, 3175 * so that every call to the method handle will invoke the 3176 * requested method on the given receiver. 3177 * <p> 3178 * The returned method handle will have 3179 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3180 * the method's variable arity modifier bit ({@code 0x0080}) is set 3181 * <em>and</em> the trailing array argument is not the only argument. 3182 * (If the trailing array argument is the only argument, 3183 * the given receiver value will be bound to it.) 3184 * <p> 3185 * This is almost equivalent to the following code, with some differences noted below: 3186 * {@snippet lang="java" : 3187 import static java.lang.invoke.MethodHandles.*; 3188 import static java.lang.invoke.MethodType.*; 3189 ... 3190 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3191 MethodHandle mh1 = mh0.bindTo(receiver); 3192 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3193 return mh1; 3194 * } 3195 * where {@code defc} is either {@code receiver.getClass()} or a super 3196 * type of that class, in which the requested method is accessible 3197 * to the lookup class. 3198 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3199 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3200 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3201 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3202 * @param receiver the object from which the method is accessed 3203 * @param name the name of the method 3204 * @param type the type of the method, with the receiver argument omitted 3205 * @return the desired method handle 3206 * @throws NoSuchMethodException if the method does not exist 3207 * @throws IllegalAccessException if access checking fails 3208 * or if the method's variable arity modifier bit 3209 * is set and {@code asVarargsCollector} fails 3210 * @throws NullPointerException if any argument is null 3211 * @see MethodHandle#bindTo 3212 * @see #findVirtual 3213 */ 3214 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3215 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3216 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3217 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3218 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3219 throw new IllegalAccessException("The restricted defining class " + 3220 mh.type().leadingReferenceParameter().getName() + 3221 " is not assignable from receiver class " + 3222 receiver.getClass().getName()); 3223 } 3224 return mh.bindArgumentL(0, receiver).setVarargs(method); 3225 } 3226 3227 /** 3228 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3229 * to <i>m</i>, if the lookup class has permission. 3230 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3231 * If <i>m</i> is virtual, overriding is respected on every call. 3232 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3233 * The type of the method handle will be that of the method, 3234 * with the receiver type prepended (but only if it is non-static). 3235 * If the method's {@code accessible} flag is not set, 3236 * access checking is performed immediately on behalf of the lookup class. 3237 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3238 * <p> 3239 * The returned method handle will have 3240 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3241 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3242 * <p> 3243 * If <i>m</i> is static, and 3244 * if the returned method handle is invoked, the method's class will 3245 * be initialized, if it has not already been initialized. 3246 * @param m the reflected method 3247 * @return a method handle which can invoke the reflected method 3248 * @throws IllegalAccessException if access checking fails 3249 * or if the method's variable arity modifier bit 3250 * is set and {@code asVarargsCollector} fails 3251 * @throws NullPointerException if the argument is null 3252 */ 3253 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3254 if (m.getDeclaringClass() == MethodHandle.class) { 3255 MethodHandle mh = unreflectForMH(m); 3256 if (mh != null) return mh; 3257 } 3258 if (m.getDeclaringClass() == VarHandle.class) { 3259 MethodHandle mh = unreflectForVH(m); 3260 if (mh != null) return mh; 3261 } 3262 MemberName method = new MemberName(m); 3263 byte refKind = method.getReferenceKind(); 3264 if (refKind == REF_invokeSpecial) 3265 refKind = REF_invokeVirtual; 3266 assert(method.isMethod()); 3267 @SuppressWarnings("deprecation") 3268 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3269 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3270 } 3271 private MethodHandle unreflectForMH(Method m) { 3272 // these names require special lookups because they throw UnsupportedOperationException 3273 if (MemberName.isMethodHandleInvokeName(m.getName())) 3274 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3275 return null; 3276 } 3277 private MethodHandle unreflectForVH(Method m) { 3278 // these names require special lookups because they throw UnsupportedOperationException 3279 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3280 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3281 return null; 3282 } 3283 3284 /** 3285 * Produces a method handle for a reflected method. 3286 * It will bypass checks for overriding methods on the receiver, 3287 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3288 * instruction from within the explicitly specified {@code specialCaller}. 3289 * The type of the method handle will be that of the method, 3290 * with a suitably restricted receiver type prepended. 3291 * (The receiver type will be {@code specialCaller} or a subtype.) 3292 * If the method's {@code accessible} flag is not set, 3293 * access checking is performed immediately on behalf of the lookup class, 3294 * as if {@code invokespecial} instruction were being linked. 3295 * <p> 3296 * Before method resolution, 3297 * if the explicitly specified caller class is not identical with the 3298 * lookup class, or if this lookup object does not have 3299 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3300 * privileges, the access fails. 3301 * <p> 3302 * The returned method handle will have 3303 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3304 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3305 * @param m the reflected method 3306 * @param specialCaller the class nominally calling the method 3307 * @return a method handle which can invoke the reflected method 3308 * @throws IllegalAccessException if access checking fails, 3309 * or if the method is {@code static}, 3310 * or if the method's variable arity modifier bit 3311 * is set and {@code asVarargsCollector} fails 3312 * @throws NullPointerException if any argument is null 3313 */ 3314 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3315 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3316 Lookup specialLookup = this.in(specialCaller); 3317 MemberName method = new MemberName(m, true); 3318 assert(method.isMethod()); 3319 // ignore m.isAccessible: this is a new kind of access 3320 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3321 } 3322 3323 /** 3324 * Produces a method handle for a reflected constructor. 3325 * The type of the method handle will be that of the constructor, 3326 * with the return type changed to the declaring class. 3327 * The method handle will perform a {@code newInstance} operation, 3328 * creating a new instance of the constructor's class on the 3329 * arguments passed to the method handle. 3330 * <p> 3331 * If the constructor's {@code accessible} flag is not set, 3332 * access checking is performed immediately on behalf of the lookup class. 3333 * <p> 3334 * The returned method handle will have 3335 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3336 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3337 * <p> 3338 * If the returned method handle is invoked, the constructor's class will 3339 * be initialized, if it has not already been initialized. 3340 * @param c the reflected constructor 3341 * @return a method handle which can invoke the reflected constructor 3342 * @throws IllegalAccessException if access checking fails 3343 * or if the method's variable arity modifier bit 3344 * is set and {@code asVarargsCollector} fails 3345 * @throws NullPointerException if the argument is null 3346 */ 3347 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3348 MemberName ctor = new MemberName(c); 3349 assert(ctor.isConstructor()); 3350 @SuppressWarnings("deprecation") 3351 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3352 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor); 3353 } 3354 3355 /* 3356 * Produces a method handle that is capable of creating instances of the given class 3357 * and instantiated by the given constructor. 3358 * 3359 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3360 */ 3361 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3362 MemberName ctor = new MemberName(c); 3363 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3364 checkAccess(REF_newInvokeSpecial, decl, ctor); 3365 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3366 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3367 } 3368 3369 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3370 if (decl == ctor.getDeclaringClass()) 3371 return true; 3372 3373 Class<?> cl = decl; 3374 while ((cl = cl.getSuperclass()) != null) { 3375 if (cl == ctor.getDeclaringClass()) { 3376 return true; 3377 } 3378 } 3379 return false; 3380 } 3381 3382 /** 3383 * Produces a method handle giving read access to a reflected field. 3384 * The type of the method handle will have a return type of the field's 3385 * value type. 3386 * If the field is {@code static}, the method handle will take no arguments. 3387 * Otherwise, its single argument will be the instance containing 3388 * the field. 3389 * If the {@code Field} object's {@code accessible} flag is not set, 3390 * access checking is performed immediately on behalf of the lookup class. 3391 * <p> 3392 * If the field is static, and 3393 * if the returned method handle is invoked, the field's class will 3394 * be initialized, if it has not already been initialized. 3395 * @param f the reflected field 3396 * @return a method handle which can load values from the reflected field 3397 * @throws IllegalAccessException if access checking fails 3398 * @throws NullPointerException if the argument is null 3399 */ 3400 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3401 return unreflectField(f, false); 3402 } 3403 3404 /** 3405 * Produces a method handle giving write access to a reflected field. 3406 * The type of the method handle will have a void return type. 3407 * If the field is {@code static}, the method handle will take a single 3408 * argument, of the field's value type, the value to be stored. 3409 * Otherwise, the two arguments will be the instance containing 3410 * the field, and the value to be stored. 3411 * If the {@code Field} object's {@code accessible} flag is not set, 3412 * access checking is performed immediately on behalf of the lookup class. 3413 * <p> 3414 * If the field is {@code final}, write access will not be 3415 * allowed and access checking will fail, except under certain 3416 * narrow circumstances documented for {@link Field#set Field.set}. 3417 * A method handle is returned only if a corresponding call to 3418 * the {@code Field} object's {@code set} method could return 3419 * normally. In particular, fields which are both {@code static} 3420 * and {@code final} may never be set. 3421 * <p> 3422 * If the field is {@code static}, and 3423 * if the returned method handle is invoked, the field's class will 3424 * be initialized, if it has not already been initialized. 3425 * @param f the reflected field 3426 * @return a method handle which can store values into the reflected field 3427 * @throws IllegalAccessException if access checking fails, 3428 * or if the field is {@code final} and write access 3429 * is not enabled on the {@code Field} object 3430 * @throws NullPointerException if the argument is null 3431 */ 3432 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3433 return unreflectField(f, true); 3434 } 3435 3436 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3437 MemberName field = new MemberName(f, isSetter); 3438 if (isSetter && field.isFinal()) { 3439 if (field.isTrustedFinalField()) { 3440 String msg = field.isStatic() ? "static final field has no write access" 3441 : "final field has no write access"; 3442 throw field.makeAccessException(msg, this); 3443 } 3444 } 3445 assert(isSetter 3446 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3447 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3448 @SuppressWarnings("deprecation") 3449 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3450 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field); 3451 } 3452 3453 /** 3454 * Produces a VarHandle giving access to a reflected field {@code f} 3455 * of type {@code T} declared in a class of type {@code R}. 3456 * The VarHandle's variable type is {@code T}. 3457 * If the field is non-static the VarHandle has one coordinate type, 3458 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3459 * coordinate types. 3460 * <p> 3461 * Access checking is performed immediately on behalf of the lookup 3462 * class, regardless of the value of the field's {@code accessible} 3463 * flag. 3464 * <p> 3465 * If the field is static, and if the returned VarHandle is operated 3466 * on, the field's declaring class will be initialized, if it has not 3467 * already been initialized. 3468 * <p> 3469 * Certain access modes of the returned VarHandle are unsupported under 3470 * the following conditions: 3471 * <ul> 3472 * <li>if the field is declared {@code final}, then the write, atomic 3473 * update, numeric atomic update, and bitwise atomic update access 3474 * modes are unsupported. 3475 * <li>if the field type is anything other than {@code byte}, 3476 * {@code short}, {@code char}, {@code int}, {@code long}, 3477 * {@code float}, or {@code double} then numeric atomic update 3478 * access modes are unsupported. 3479 * <li>if the field type is anything other than {@code boolean}, 3480 * {@code byte}, {@code short}, {@code char}, {@code int} or 3481 * {@code long} then bitwise atomic update access modes are 3482 * unsupported. 3483 * </ul> 3484 * <p> 3485 * If the field is declared {@code volatile} then the returned VarHandle 3486 * will override access to the field (effectively ignore the 3487 * {@code volatile} declaration) in accordance to its specified 3488 * access modes. 3489 * <p> 3490 * If the field type is {@code float} or {@code double} then numeric 3491 * and atomic update access modes compare values using their bitwise 3492 * representation (see {@link Float#floatToRawIntBits} and 3493 * {@link Double#doubleToRawLongBits}, respectively). 3494 * @apiNote 3495 * Bitwise comparison of {@code float} values or {@code double} values, 3496 * as performed by the numeric and atomic update access modes, differ 3497 * from the primitive {@code ==} operator and the {@link Float#equals} 3498 * and {@link Double#equals} methods, specifically with respect to 3499 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3500 * Care should be taken when performing a compare and set or a compare 3501 * and exchange operation with such values since the operation may 3502 * unexpectedly fail. 3503 * There are many possible NaN values that are considered to be 3504 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3505 * provided by Java can distinguish between them. Operation failure can 3506 * occur if the expected or witness value is a NaN value and it is 3507 * transformed (perhaps in a platform specific manner) into another NaN 3508 * value, and thus has a different bitwise representation (see 3509 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3510 * details). 3511 * The values {@code -0.0} and {@code +0.0} have different bitwise 3512 * representations but are considered equal when using the primitive 3513 * {@code ==} operator. Operation failure can occur if, for example, a 3514 * numeric algorithm computes an expected value to be say {@code -0.0} 3515 * and previously computed the witness value to be say {@code +0.0}. 3516 * @param f the reflected field, with a field of type {@code T}, and 3517 * a declaring class of type {@code R} 3518 * @return a VarHandle giving access to non-static fields or a static 3519 * field 3520 * @throws IllegalAccessException if access checking fails 3521 * @throws NullPointerException if the argument is null 3522 * @since 9 3523 */ 3524 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3525 MemberName getField = new MemberName(f, false); 3526 MemberName putField = new MemberName(f, true); 3527 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(), 3528 f.getDeclaringClass(), getField, putField); 3529 } 3530 3531 /** 3532 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3533 * created by this lookup object or a similar one. 3534 * Security and access checks are performed to ensure that this lookup object 3535 * is capable of reproducing the target method handle. 3536 * This means that the cracking may fail if target is a direct method handle 3537 * but was created by an unrelated lookup object. 3538 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3539 * and was created by a lookup object for a different class. 3540 * @param target a direct method handle to crack into symbolic reference components 3541 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3542 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3543 * @throws NullPointerException if the target is {@code null} 3544 * @see MethodHandleInfo 3545 * @since 1.8 3546 */ 3547 public MethodHandleInfo revealDirect(MethodHandle target) { 3548 if (!target.isCrackable()) { 3549 throw newIllegalArgumentException("not a direct method handle"); 3550 } 3551 MemberName member = target.internalMemberName(); 3552 Class<?> defc = member.getDeclaringClass(); 3553 byte refKind = member.getReferenceKind(); 3554 assert(MethodHandleNatives.refKindIsValid(refKind)); 3555 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3556 // Devirtualized method invocation is usually formally virtual. 3557 // To avoid creating extra MemberName objects for this common case, 3558 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3559 refKind = REF_invokeVirtual; 3560 if (refKind == REF_invokeVirtual && defc.isInterface()) 3561 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3562 refKind = REF_invokeInterface; 3563 // Check member access before cracking. 3564 try { 3565 checkAccess(refKind, defc, member); 3566 } catch (IllegalAccessException ex) { 3567 throw new IllegalArgumentException(ex); 3568 } 3569 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3570 Class<?> callerClass = target.internalCallerClass(); 3571 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3572 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3573 } 3574 // Produce the handle to the results. 3575 return new InfoFromMemberName(this, member, refKind); 3576 } 3577 3578 //--- Helper methods, all package-private. 3579 3580 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3581 checkSymbolicClass(refc); // do this before attempting to resolve 3582 Objects.requireNonNull(name); 3583 Objects.requireNonNull(type); 3584 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3585 NoSuchFieldException.class); 3586 } 3587 3588 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3589 checkSymbolicClass(refc); // do this before attempting to resolve 3590 Objects.requireNonNull(type); 3591 checkMethodName(refKind, name); // implicit null-check of name 3592 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3593 NoSuchMethodException.class); 3594 } 3595 3596 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3597 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3598 Objects.requireNonNull(member.getName()); 3599 Objects.requireNonNull(member.getType()); 3600 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3601 ReflectiveOperationException.class); 3602 } 3603 3604 MemberName resolveOrNull(byte refKind, MemberName member) { 3605 // do this before attempting to resolve 3606 if (!isClassAccessible(member.getDeclaringClass())) { 3607 return null; 3608 } 3609 Objects.requireNonNull(member.getName()); 3610 Objects.requireNonNull(member.getType()); 3611 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3612 } 3613 3614 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3615 // do this before attempting to resolve 3616 if (!isClassAccessible(refc)) { 3617 return null; 3618 } 3619 Objects.requireNonNull(type); 3620 // implicit null-check of name 3621 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3622 return null; 3623 } 3624 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3625 } 3626 3627 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3628 if (!isClassAccessible(refc)) { 3629 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3630 } 3631 } 3632 3633 boolean isClassAccessible(Class<?> refc) { 3634 Objects.requireNonNull(refc); 3635 Class<?> caller = lookupClassOrNull(); 3636 Class<?> type = refc; 3637 while (type.isArray()) { 3638 type = type.getComponentType(); 3639 } 3640 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3641 } 3642 3643 /** Check name for an illegal leading "<" character. */ 3644 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3645 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3646 throw new NoSuchMethodException("illegal method name: "+name); 3647 } 3648 3649 /** 3650 * Find my trustable caller class if m is a caller sensitive method. 3651 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3652 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3653 */ 3654 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3655 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3656 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3657 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3658 } 3659 return this; 3660 } 3661 3662 /** 3663 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3664 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3665 * 3666 * @deprecated This method was originally designed to test {@code PRIVATE} access 3667 * that implies full privilege access but {@code MODULE} access has since become 3668 * independent of {@code PRIVATE} access. It is recommended to call 3669 * {@link #hasFullPrivilegeAccess()} instead. 3670 * @since 9 3671 */ 3672 @Deprecated(since="14") 3673 public boolean hasPrivateAccess() { 3674 return hasFullPrivilegeAccess(); 3675 } 3676 3677 /** 3678 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3679 * i.e. {@code PRIVATE} and {@code MODULE} access. 3680 * A {@code Lookup} object must have full privilege access in order to 3681 * access all members that are allowed to the 3682 * {@linkplain #lookupClass() lookup class}. 3683 * 3684 * @return {@code true} if this lookup has full privilege access. 3685 * @since 14 3686 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3687 */ 3688 public boolean hasFullPrivilegeAccess() { 3689 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3690 } 3691 3692 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3693 boolean wantStatic = (refKind == REF_invokeStatic); 3694 String message; 3695 if (m.isConstructor()) 3696 message = "expected a method, not a constructor"; 3697 else if (!m.isMethod()) 3698 message = "expected a method"; 3699 else if (wantStatic != m.isStatic()) 3700 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3701 else 3702 { checkAccess(refKind, refc, m); return; } 3703 throw m.makeAccessException(message, this); 3704 } 3705 3706 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3707 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3708 String message; 3709 if (wantStatic != m.isStatic()) 3710 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3711 else 3712 { checkAccess(refKind, refc, m); return; } 3713 throw m.makeAccessException(message, this); 3714 } 3715 3716 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3717 return Modifier.isProtected(m.getModifiers()) && 3718 refKind == REF_invokeVirtual && 3719 m.getDeclaringClass() == Object.class && 3720 m.getName().equals("clone") && 3721 refc.isArray(); 3722 } 3723 3724 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3725 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3726 assert(m.referenceKindIsConsistentWith(refKind) && 3727 MethodHandleNatives.refKindIsValid(refKind) && 3728 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3729 int allowedModes = this.allowedModes; 3730 if (allowedModes == TRUSTED) return; 3731 int mods = m.getModifiers(); 3732 if (isArrayClone(refKind, refc, m)) { 3733 // The JVM does this hack also. 3734 // (See ClassVerifier::verify_invoke_instructions 3735 // and LinkResolver::check_method_accessability.) 3736 // Because the JVM does not allow separate methods on array types, 3737 // there is no separate method for int[].clone. 3738 // All arrays simply inherit Object.clone. 3739 // But for access checking logic, we make Object.clone 3740 // (normally protected) appear to be public. 3741 // Later on, when the DirectMethodHandle is created, 3742 // its leading argument will be restricted to the 3743 // requested array type. 3744 // N.B. The return type is not adjusted, because 3745 // that is *not* the bytecode behavior. 3746 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3747 } 3748 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3749 // cannot "new" a protected ctor in a different package 3750 mods ^= Modifier.PROTECTED; 3751 } 3752 if (Modifier.isFinal(mods) && 3753 MethodHandleNatives.refKindIsSetter(refKind)) 3754 throw m.makeAccessException("unexpected set of a final field", this); 3755 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3756 if ((requestedModes & allowedModes) != 0) { 3757 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3758 mods, lookupClass(), previousLookupClass(), allowedModes)) 3759 return; 3760 } else { 3761 // Protected members can also be checked as if they were package-private. 3762 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3763 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3764 return; 3765 } 3766 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3767 } 3768 3769 String accessFailedMessage(Class<?> refc, MemberName m) { 3770 Class<?> defc = m.getDeclaringClass(); 3771 int mods = m.getModifiers(); 3772 // check the class first: 3773 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3774 (defc == refc || 3775 Modifier.isPublic(refc.getModifiers()))); 3776 if (!classOK && (allowedModes & PACKAGE) != 0) { 3777 // ignore previous lookup class to check if default package access 3778 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3779 (defc == refc || 3780 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3781 } 3782 if (!classOK) 3783 return "class is not public"; 3784 if (Modifier.isPublic(mods)) 3785 return "access to public member failed"; // (how?, module not readable?) 3786 if (Modifier.isPrivate(mods)) 3787 return "member is private"; 3788 if (Modifier.isProtected(mods)) 3789 return "member is protected"; 3790 return "member is private to package"; 3791 } 3792 3793 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3794 int allowedModes = this.allowedModes; 3795 if (allowedModes == TRUSTED) return; 3796 if ((lookupModes() & PRIVATE) == 0 3797 || (specialCaller != lookupClass() 3798 // ensure non-abstract methods in superinterfaces can be special-invoked 3799 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3800 throw new MemberName(specialCaller). 3801 makeAccessException("no private access for invokespecial", this); 3802 } 3803 3804 private boolean restrictProtectedReceiver(MemberName method) { 3805 // The accessing class only has the right to use a protected member 3806 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3807 if (!method.isProtected() || method.isStatic() 3808 || allowedModes == TRUSTED 3809 || method.getDeclaringClass() == lookupClass() 3810 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3811 return false; 3812 return true; 3813 } 3814 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3815 assert(!method.isStatic()); 3816 // receiver type of mh is too wide; narrow to caller 3817 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3818 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3819 } 3820 MethodType rawType = mh.type(); 3821 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3822 MethodType narrowType = rawType.changeParameterType(0, caller); 3823 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3824 assert(mh.viewAsTypeChecks(narrowType, true)); 3825 return mh.copyWith(narrowType, mh.form); 3826 } 3827 3828 /** Check access and get the requested method. */ 3829 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3830 final boolean doRestrict = true; 3831 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup); 3832 } 3833 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3834 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3835 final boolean doRestrict = false; 3836 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup); 3837 } 3838 /** Common code for all methods; do not call directly except from immediately above. */ 3839 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3840 boolean doRestrict, 3841 Lookup boundCaller) throws IllegalAccessException { 3842 checkMethod(refKind, refc, method); 3843 assert(!method.isMethodHandleInvoke()); 3844 3845 if (refKind == REF_invokeSpecial && 3846 refc != lookupClass() && 3847 !refc.isInterface() && !lookupClass().isInterface() && 3848 refc != lookupClass().getSuperclass() && 3849 refc.isAssignableFrom(lookupClass())) { 3850 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 3851 3852 // Per JVMS 6.5, desc. of invokespecial instruction: 3853 // If the method is in a superclass of the LC, 3854 // and if our original search was above LC.super, 3855 // repeat the search (symbolic lookup) from LC.super 3856 // and continue with the direct superclass of that class, 3857 // and so forth, until a match is found or no further superclasses exist. 3858 // FIXME: MemberName.resolve should handle this instead. 3859 Class<?> refcAsSuper = lookupClass(); 3860 MemberName m2; 3861 do { 3862 refcAsSuper = refcAsSuper.getSuperclass(); 3863 m2 = new MemberName(refcAsSuper, 3864 method.getName(), 3865 method.getMethodType(), 3866 REF_invokeSpecial); 3867 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 3868 } while (m2 == null && // no method is found yet 3869 refc != refcAsSuper); // search up to refc 3870 if (m2 == null) throw new InternalError(method.toString()); 3871 method = m2; 3872 refc = refcAsSuper; 3873 // redo basic checks 3874 checkMethod(refKind, refc, method); 3875 } 3876 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 3877 MethodHandle mh = dmh; 3878 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 3879 if ((doRestrict && refKind == REF_invokeSpecial) || 3880 (MethodHandleNatives.refKindHasReceiver(refKind) && 3881 restrictProtectedReceiver(method) && 3882 // All arrays simply inherit the protected Object.clone method. 3883 // The leading argument is already restricted to the requested 3884 // array type (not the lookup class). 3885 !isArrayClone(refKind, refc, method))) { 3886 mh = restrictReceiver(method, dmh, lookupClass()); 3887 } 3888 mh = maybeBindCaller(method, mh, boundCaller); 3889 mh = mh.setVarargs(method); 3890 return mh; 3891 } 3892 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 3893 throws IllegalAccessException { 3894 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 3895 return mh; 3896 3897 // boundCaller must have full privilege access. 3898 // It should have been checked by findBoundCallerLookup. Safe to check this again. 3899 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 3900 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3901 3902 assert boundCaller.hasFullPrivilegeAccess(); 3903 3904 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 3905 // Note: caller will apply varargs after this step happens. 3906 return cbmh; 3907 } 3908 3909 /** Check access and get the requested field. */ 3910 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3911 return getDirectFieldCommon(refKind, refc, field); 3912 } 3913 /** Common code for all fields; do not call directly except from immediately above. */ 3914 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3915 checkField(refKind, refc, field); 3916 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 3917 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 3918 restrictProtectedReceiver(field)); 3919 if (doRestrict) 3920 return restrictReceiver(field, dmh, lookupClass()); 3921 return dmh; 3922 } 3923 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 3924 Class<?> refc, MemberName getField, MemberName putField) 3925 throws IllegalAccessException { 3926 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField); 3927 } 3928 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 3929 Class<?> refc, MemberName getField, 3930 MemberName putField) throws IllegalAccessException { 3931 assert getField.isStatic() == putField.isStatic(); 3932 assert getField.isGetter() && putField.isSetter(); 3933 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 3934 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 3935 3936 checkField(getRefKind, refc, getField); 3937 3938 if (!putField.isFinal()) { 3939 // A VarHandle does not support updates to final fields, any 3940 // such VarHandle to a final field will be read-only and 3941 // therefore the following write-based accessibility checks are 3942 // only required for non-final fields 3943 checkField(putRefKind, refc, putField); 3944 } 3945 3946 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 3947 restrictProtectedReceiver(getField)); 3948 if (doRestrict) { 3949 assert !getField.isStatic(); 3950 // receiver type of VarHandle is too wide; narrow to caller 3951 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 3952 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 3953 } 3954 refc = lookupClass(); 3955 } 3956 return VarHandles.makeFieldHandle(getField, refc, 3957 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 3958 } 3959 /** Check access and get the requested constructor. */ 3960 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3961 return getDirectConstructorCommon(refc, ctor); 3962 } 3963 /** Common code for all constructors; do not call directly except from immediately above. */ 3964 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3965 assert(ctor.isConstructor()); 3966 checkAccess(REF_newInvokeSpecial, refc, ctor); 3967 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3968 return DirectMethodHandle.make(ctor).setVarargs(ctor); 3969 } 3970 3971 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 3972 */ 3973 /*non-public*/ 3974 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 3975 throws ReflectiveOperationException { 3976 if (!(type instanceof Class || type instanceof MethodType)) 3977 throw new InternalError("unresolved MemberName"); 3978 MemberName member = new MemberName(refKind, defc, name, type); 3979 MethodHandle mh = LOOKASIDE_TABLE.get(member); 3980 if (mh != null) { 3981 checkSymbolicClass(defc); 3982 return mh; 3983 } 3984 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 3985 // Treat MethodHandle.invoke and invokeExact specially. 3986 mh = findVirtualForMH(member.getName(), member.getMethodType()); 3987 if (mh != null) { 3988 return mh; 3989 } 3990 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 3991 // Treat signature-polymorphic methods on VarHandle specially. 3992 mh = findVirtualForVH(member.getName(), member.getMethodType()); 3993 if (mh != null) { 3994 return mh; 3995 } 3996 } 3997 MemberName resolved = resolveOrFail(refKind, member); 3998 mh = getDirectMethodForConstant(refKind, defc, resolved); 3999 if (mh instanceof DirectMethodHandle dmh 4000 && canBeCached(refKind, defc, resolved)) { 4001 MemberName key = mh.internalMemberName(); 4002 if (key != null) { 4003 key = key.asNormalOriginal(); 4004 } 4005 if (member.equals(key)) { // better safe than sorry 4006 LOOKASIDE_TABLE.put(key, dmh); 4007 } 4008 } 4009 return mh; 4010 } 4011 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4012 if (refKind == REF_invokeSpecial) { 4013 return false; 4014 } 4015 if (!Modifier.isPublic(defc.getModifiers()) || 4016 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4017 !member.isPublic() || 4018 member.isCallerSensitive()) { 4019 return false; 4020 } 4021 ClassLoader loader = defc.getClassLoader(); 4022 if (loader != null) { 4023 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4024 boolean found = false; 4025 while (sysl != null) { 4026 if (loader == sysl) { found = true; break; } 4027 sysl = sysl.getParent(); 4028 } 4029 if (!found) { 4030 return false; 4031 } 4032 } 4033 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4034 new MemberName(refKind, defc, member.getName(), member.getType())); 4035 if (resolved2 == null) { 4036 return false; 4037 } 4038 return true; 4039 } 4040 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4041 throws ReflectiveOperationException { 4042 if (MethodHandleNatives.refKindIsField(refKind)) { 4043 return getDirectField(refKind, defc, member); 4044 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4045 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member)); 4046 } else if (refKind == REF_newInvokeSpecial) { 4047 return getDirectConstructor(defc, member); 4048 } 4049 // oops 4050 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4051 } 4052 4053 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4054 } 4055 4056 /** 4057 * Produces a method handle constructing arrays of a desired type, 4058 * as if by the {@code anewarray} bytecode. 4059 * The return type of the method handle will be the array type. 4060 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4061 * 4062 * <p> If the returned method handle is invoked with a negative 4063 * array size, a {@code NegativeArraySizeException} will be thrown. 4064 * 4065 * @param arrayClass an array type 4066 * @return a method handle which can create arrays of the given type 4067 * @throws NullPointerException if the argument is {@code null} 4068 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4069 * @see java.lang.reflect.Array#newInstance(Class, int) 4070 * @jvms 6.5 {@code anewarray} Instruction 4071 * @since 9 4072 */ 4073 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4074 if (!arrayClass.isArray()) { 4075 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4076 } 4077 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4078 bindTo(arrayClass.getComponentType()); 4079 return ani.asType(ani.type().changeReturnType(arrayClass)); 4080 } 4081 4082 /** 4083 * Produces a method handle returning the length of an array, 4084 * as if by the {@code arraylength} bytecode. 4085 * The type of the method handle will have {@code int} as return type, 4086 * and its sole argument will be the array type. 4087 * 4088 * <p> If the returned method handle is invoked with a {@code null} 4089 * array reference, a {@code NullPointerException} will be thrown. 4090 * 4091 * @param arrayClass an array type 4092 * @return a method handle which can retrieve the length of an array of the given array type 4093 * @throws NullPointerException if the argument is {@code null} 4094 * @throws IllegalArgumentException if arrayClass is not an array type 4095 * @jvms 6.5 {@code arraylength} Instruction 4096 * @since 9 4097 */ 4098 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4099 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4100 } 4101 4102 /** 4103 * Produces a method handle giving read access to elements of an array, 4104 * as if by the {@code aaload} bytecode. 4105 * The type of the method handle will have a return type of the array's 4106 * element type. Its first argument will be the array type, 4107 * and the second will be {@code int}. 4108 * 4109 * <p> When the returned method handle is invoked, 4110 * the array reference and array index are checked. 4111 * A {@code NullPointerException} will be thrown if the array reference 4112 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4113 * thrown if the index is negative or if it is greater than or equal to 4114 * the length of the array. 4115 * 4116 * @param arrayClass an array type 4117 * @return a method handle which can load values from the given array type 4118 * @throws NullPointerException if the argument is null 4119 * @throws IllegalArgumentException if arrayClass is not an array type 4120 * @jvms 6.5 {@code aaload} Instruction 4121 */ 4122 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4123 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4124 } 4125 4126 /** 4127 * Produces a method handle giving write access to elements of an array, 4128 * as if by the {@code astore} bytecode. 4129 * The type of the method handle will have a void return type. 4130 * Its last argument will be the array's element type. 4131 * The first and second arguments will be the array type and int. 4132 * 4133 * <p> When the returned method handle is invoked, 4134 * the array reference and array index are checked. 4135 * A {@code NullPointerException} will be thrown if the array reference 4136 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4137 * thrown if the index is negative or if it is greater than or equal to 4138 * the length of the array. 4139 * 4140 * @param arrayClass the class of an array 4141 * @return a method handle which can store values into the array type 4142 * @throws NullPointerException if the argument is null 4143 * @throws IllegalArgumentException if arrayClass is not an array type 4144 * @jvms 6.5 {@code aastore} Instruction 4145 */ 4146 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4147 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4148 } 4149 4150 /** 4151 * Produces a VarHandle giving access to elements of an array of type 4152 * {@code arrayClass}. The VarHandle's variable type is the component type 4153 * of {@code arrayClass} and the list of coordinate types is 4154 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4155 * corresponds to an argument that is an index into an array. 4156 * <p> 4157 * Certain access modes of the returned VarHandle are unsupported under 4158 * the following conditions: 4159 * <ul> 4160 * <li>if the component type is anything other than {@code byte}, 4161 * {@code short}, {@code char}, {@code int}, {@code long}, 4162 * {@code float}, or {@code double} then numeric atomic update access 4163 * modes are unsupported. 4164 * <li>if the component type is anything other than {@code boolean}, 4165 * {@code byte}, {@code short}, {@code char}, {@code int} or 4166 * {@code long} then bitwise atomic update access modes are 4167 * unsupported. 4168 * </ul> 4169 * <p> 4170 * If the component type is {@code float} or {@code double} then numeric 4171 * and atomic update access modes compare values using their bitwise 4172 * representation (see {@link Float#floatToRawIntBits} and 4173 * {@link Double#doubleToRawLongBits}, respectively). 4174 * 4175 * <p> When the returned {@code VarHandle} is invoked, 4176 * the array reference and array index are checked. 4177 * A {@code NullPointerException} will be thrown if the array reference 4178 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4179 * thrown if the index is negative or if it is greater than or equal to 4180 * the length of the array. 4181 * 4182 * @apiNote 4183 * Bitwise comparison of {@code float} values or {@code double} values, 4184 * as performed by the numeric and atomic update access modes, differ 4185 * from the primitive {@code ==} operator and the {@link Float#equals} 4186 * and {@link Double#equals} methods, specifically with respect to 4187 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4188 * Care should be taken when performing a compare and set or a compare 4189 * and exchange operation with such values since the operation may 4190 * unexpectedly fail. 4191 * There are many possible NaN values that are considered to be 4192 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4193 * provided by Java can distinguish between them. Operation failure can 4194 * occur if the expected or witness value is a NaN value and it is 4195 * transformed (perhaps in a platform specific manner) into another NaN 4196 * value, and thus has a different bitwise representation (see 4197 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4198 * details). 4199 * The values {@code -0.0} and {@code +0.0} have different bitwise 4200 * representations but are considered equal when using the primitive 4201 * {@code ==} operator. Operation failure can occur if, for example, a 4202 * numeric algorithm computes an expected value to be say {@code -0.0} 4203 * and previously computed the witness value to be say {@code +0.0}. 4204 * @param arrayClass the class of an array, of type {@code T[]} 4205 * @return a VarHandle giving access to elements of an array 4206 * @throws NullPointerException if the arrayClass is null 4207 * @throws IllegalArgumentException if arrayClass is not an array type 4208 * @since 9 4209 */ 4210 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4211 return VarHandles.makeArrayElementHandle(arrayClass); 4212 } 4213 4214 /** 4215 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4216 * viewed as if it were a different primitive array type, such as 4217 * {@code int[]} or {@code long[]}. 4218 * The VarHandle's variable type is the component type of 4219 * {@code viewArrayClass} and the list of coordinate types is 4220 * {@code (byte[], int)}, where the {@code int} coordinate type 4221 * corresponds to an argument that is an index into a {@code byte[]} array. 4222 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4223 * array, composing bytes to or from a value of the component type of 4224 * {@code viewArrayClass} according to the given endianness. 4225 * <p> 4226 * The supported component types (variables types) are {@code short}, 4227 * {@code char}, {@code int}, {@code long}, {@code float} and 4228 * {@code double}. 4229 * <p> 4230 * Access of bytes at a given index will result in an 4231 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4232 * or greater than the {@code byte[]} array length minus the size (in bytes) 4233 * of {@code T}. 4234 * <p> 4235 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4236 * access modes are supported by the returned var handle. For all other access modes, an 4237 * {@link UnsupportedOperationException} will be thrown. 4238 * 4239 * @apiNote if access modes other than plain access are required, clients should 4240 * consider using off-heap memory through 4241 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4242 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4243 * or memory segments backed by a 4244 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4245 * for which stronger alignment guarantees can be made. 4246 * 4247 * @param viewArrayClass the view array class, with a component type of 4248 * type {@code T} 4249 * @param byteOrder the endianness of the view array elements, as 4250 * stored in the underlying {@code byte} array 4251 * @return a VarHandle giving access to elements of a {@code byte[]} array 4252 * viewed as if elements corresponding to the components type of the view 4253 * array class 4254 * @throws NullPointerException if viewArrayClass or byteOrder is null 4255 * @throws IllegalArgumentException if viewArrayClass is not an array type 4256 * @throws UnsupportedOperationException if the component type of 4257 * viewArrayClass is not supported as a variable type 4258 * @since 9 4259 */ 4260 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4261 ByteOrder byteOrder) throws IllegalArgumentException { 4262 Objects.requireNonNull(byteOrder); 4263 return VarHandles.byteArrayViewHandle(viewArrayClass, 4264 byteOrder == ByteOrder.BIG_ENDIAN); 4265 } 4266 4267 /** 4268 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4269 * viewed as if it were an array of elements of a different primitive 4270 * component type to that of {@code byte}, such as {@code int[]} or 4271 * {@code long[]}. 4272 * The VarHandle's variable type is the component type of 4273 * {@code viewArrayClass} and the list of coordinate types is 4274 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4275 * corresponds to an argument that is an index into a {@code byte[]} array. 4276 * The returned VarHandle accesses bytes at an index in a 4277 * {@code ByteBuffer}, composing bytes to or from a value of the component 4278 * type of {@code viewArrayClass} according to the given endianness. 4279 * <p> 4280 * The supported component types (variables types) are {@code short}, 4281 * {@code char}, {@code int}, {@code long}, {@code float} and 4282 * {@code double}. 4283 * <p> 4284 * Access will result in a {@code ReadOnlyBufferException} for anything 4285 * other than the read access modes if the {@code ByteBuffer} is read-only. 4286 * <p> 4287 * Access of bytes at a given index will result in an 4288 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4289 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4290 * {@code T}. 4291 * <p> 4292 * For heap byte buffers, access is always unaligned. As a result, only the plain 4293 * {@linkplain VarHandle.AccessMode#GET get} 4294 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4295 * returned var handle. For all other access modes, an {@link IllegalStateException} 4296 * will be thrown. 4297 * <p> 4298 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4299 * with respect to the underlying memory address, {@code A} say, associated 4300 * with the {@code ByteBuffer} and index. 4301 * If access is misaligned then access for anything other than the 4302 * {@code get} and {@code set} access modes will result in an 4303 * {@code IllegalStateException}. In such cases atomic access is only 4304 * guaranteed with respect to the largest power of two that divides the GCD 4305 * of {@code A} and the size (in bytes) of {@code T}. 4306 * If access is aligned then following access modes are supported and are 4307 * guaranteed to support atomic access: 4308 * <ul> 4309 * <li>read write access modes for all {@code T}, with the exception of 4310 * access modes {@code get} and {@code set} for {@code long} and 4311 * {@code double} on 32-bit platforms. 4312 * <li>atomic update access modes for {@code int}, {@code long}, 4313 * {@code float} or {@code double}. 4314 * (Future major platform releases of the JDK may support additional 4315 * types for certain currently unsupported access modes.) 4316 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4317 * (Future major platform releases of the JDK may support additional 4318 * numeric types for certain currently unsupported access modes.) 4319 * <li>bitwise 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 * </ul> 4323 * <p> 4324 * Misaligned access, and therefore atomicity guarantees, may be determined 4325 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4326 * {@code index}, {@code T} and its corresponding boxed type, 4327 * {@code T_BOX}, as follows: 4328 * <pre>{@code 4329 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4330 * ByteBuffer bb = ... 4331 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4332 * boolean isMisaligned = misalignedAtIndex != 0; 4333 * }</pre> 4334 * <p> 4335 * If the variable type is {@code float} or {@code double} then atomic 4336 * update access modes compare values using their bitwise representation 4337 * (see {@link Float#floatToRawIntBits} and 4338 * {@link Double#doubleToRawLongBits}, respectively). 4339 * @param viewArrayClass the view array class, with a component type of 4340 * type {@code T} 4341 * @param byteOrder the endianness of the view array elements, as 4342 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4343 * endianness of a {@code ByteBuffer}) 4344 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4345 * viewed as if elements corresponding to the components type of the view 4346 * array class 4347 * @throws NullPointerException if viewArrayClass or byteOrder is null 4348 * @throws IllegalArgumentException if viewArrayClass is not an array type 4349 * @throws UnsupportedOperationException if the component type of 4350 * viewArrayClass is not supported as a variable type 4351 * @since 9 4352 */ 4353 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4354 ByteOrder byteOrder) throws IllegalArgumentException { 4355 Objects.requireNonNull(byteOrder); 4356 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4357 byteOrder == ByteOrder.BIG_ENDIAN); 4358 } 4359 4360 4361 //--- method handle invocation (reflective style) 4362 4363 /** 4364 * Produces a method handle which will invoke any method handle of the 4365 * given {@code type}, with a given number of trailing arguments replaced by 4366 * a single trailing {@code Object[]} array. 4367 * The resulting invoker will be a method handle with the following 4368 * arguments: 4369 * <ul> 4370 * <li>a single {@code MethodHandle} target 4371 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4372 * <li>an {@code Object[]} array containing trailing arguments 4373 * </ul> 4374 * <p> 4375 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4376 * the indicated {@code type}. 4377 * That is, if the target is exactly of the given {@code type}, it will behave 4378 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4379 * is used to convert the target to the required {@code type}. 4380 * <p> 4381 * The type of the returned invoker will not be the given {@code type}, but rather 4382 * will have all parameters except the first {@code leadingArgCount} 4383 * replaced by a single array of type {@code Object[]}, which will be 4384 * the final parameter. 4385 * <p> 4386 * Before invoking its target, the invoker will spread the final array, apply 4387 * reference casts as necessary, and unbox and widen primitive arguments. 4388 * If, when the invoker is called, the supplied array argument does 4389 * not have the correct number of elements, the invoker will throw 4390 * an {@link IllegalArgumentException} instead of invoking the target. 4391 * <p> 4392 * This method is equivalent to the following code (though it may be more efficient): 4393 * {@snippet lang="java" : 4394 MethodHandle invoker = MethodHandles.invoker(type); 4395 int spreadArgCount = type.parameterCount() - leadingArgCount; 4396 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4397 return invoker; 4398 * } 4399 * This method throws no reflective exceptions. 4400 * @param type the desired target type 4401 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4402 * @return a method handle suitable for invoking any method handle of the given type 4403 * @throws NullPointerException if {@code type} is null 4404 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4405 * the range from 0 to {@code type.parameterCount()} inclusive, 4406 * or if the resulting method handle's type would have 4407 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4408 */ 4409 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4410 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4411 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4412 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4413 return type.invokers().spreadInvoker(leadingArgCount); 4414 } 4415 4416 /** 4417 * Produces a special <em>invoker method handle</em> which can be used to 4418 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4419 * The resulting invoker will have a type which is 4420 * exactly equal to the desired type, except that it will accept 4421 * an additional leading argument of type {@code MethodHandle}. 4422 * <p> 4423 * This method is equivalent to the following code (though it may be more efficient): 4424 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4425 * 4426 * <p style="font-size:smaller;"> 4427 * <em>Discussion:</em> 4428 * Invoker method handles can be useful when working with variable method handles 4429 * of unknown types. 4430 * For example, to emulate an {@code invokeExact} call to a variable method 4431 * handle {@code M}, extract its type {@code T}, 4432 * look up the invoker method {@code X} for {@code T}, 4433 * and call the invoker method, as {@code X.invoke(T, A...)}. 4434 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4435 * is unknown.) 4436 * If spreading, collecting, or other argument transformations are required, 4437 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4438 * method handle values, as long as they are compatible with the type of {@code X}. 4439 * <p style="font-size:smaller;"> 4440 * <em>(Note: The invoker method is not available via the Core Reflection API. 4441 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4442 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4443 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4444 * <p> 4445 * This method throws no reflective exceptions. 4446 * @param type the desired target type 4447 * @return a method handle suitable for invoking any method handle of the given type 4448 * @throws IllegalArgumentException if the resulting method handle's type would have 4449 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4450 */ 4451 public static MethodHandle exactInvoker(MethodType type) { 4452 return type.invokers().exactInvoker(); 4453 } 4454 4455 /** 4456 * Produces a special <em>invoker method handle</em> which can be used to 4457 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4458 * The resulting invoker will have a type which is 4459 * exactly equal to the desired type, except that it will accept 4460 * an additional leading argument of type {@code MethodHandle}. 4461 * <p> 4462 * Before invoking its target, if the target differs from the expected type, 4463 * the invoker will apply reference casts as 4464 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4465 * Similarly, the return value will be converted as necessary. 4466 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4467 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4468 * <p> 4469 * This method is equivalent to the following code (though it may be more efficient): 4470 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4471 * <p style="font-size:smaller;"> 4472 * <em>Discussion:</em> 4473 * A {@linkplain MethodType#genericMethodType general method type} is one which 4474 * mentions only {@code Object} arguments and return values. 4475 * An invoker for such a type is capable of calling any method handle 4476 * of the same arity as the general type. 4477 * <p style="font-size:smaller;"> 4478 * <em>(Note: The invoker method is not available via the Core Reflection API. 4479 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4480 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4481 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4482 * <p> 4483 * This method throws no reflective exceptions. 4484 * @param type the desired target type 4485 * @return a method handle suitable for invoking any method handle convertible to the given type 4486 * @throws IllegalArgumentException if the resulting method handle's type would have 4487 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4488 */ 4489 public static MethodHandle invoker(MethodType type) { 4490 return type.invokers().genericInvoker(); 4491 } 4492 4493 /** 4494 * Produces a special <em>invoker method handle</em> which can be used to 4495 * invoke a signature-polymorphic access mode method on any VarHandle whose 4496 * associated access mode type is compatible with the given type. 4497 * The resulting invoker will have a type which is exactly equal to the 4498 * desired given type, except that it will accept an additional leading 4499 * argument of type {@code VarHandle}. 4500 * 4501 * @param accessMode the VarHandle access mode 4502 * @param type the desired target type 4503 * @return a method handle suitable for invoking an access mode method of 4504 * any VarHandle whose access mode type is of the given type. 4505 * @since 9 4506 */ 4507 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4508 return type.invokers().varHandleMethodExactInvoker(accessMode); 4509 } 4510 4511 /** 4512 * Produces a special <em>invoker method handle</em> which can be used to 4513 * invoke a signature-polymorphic access mode method on any VarHandle whose 4514 * associated access mode type is compatible with the given type. 4515 * The resulting invoker will have a type which is exactly equal to the 4516 * desired given type, except that it will accept an additional leading 4517 * argument of type {@code VarHandle}. 4518 * <p> 4519 * Before invoking its target, if the access mode type differs from the 4520 * desired given type, the invoker will apply reference casts as necessary 4521 * and box, unbox, or widen primitive values, as if by 4522 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4523 * converted as necessary. 4524 * <p> 4525 * This method is equivalent to the following code (though it may be more 4526 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4527 * 4528 * @param accessMode the VarHandle access mode 4529 * @param type the desired target type 4530 * @return a method handle suitable for invoking an access mode method of 4531 * any VarHandle whose access mode type is convertible to the given 4532 * type. 4533 * @since 9 4534 */ 4535 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4536 return type.invokers().varHandleMethodInvoker(accessMode); 4537 } 4538 4539 /*non-public*/ 4540 static MethodHandle basicInvoker(MethodType type) { 4541 return type.invokers().basicInvoker(); 4542 } 4543 4544 //--- method handle modification (creation from other method handles) 4545 4546 /** 4547 * Produces a method handle which adapts the type of the 4548 * given method handle to a new type by pairwise argument and return type conversion. 4549 * The original type and new type must have the same number of arguments. 4550 * The resulting method handle is guaranteed to report a type 4551 * which is equal to the desired new type. 4552 * <p> 4553 * If the original type and new type are equal, returns target. 4554 * <p> 4555 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4556 * and some additional conversions are also applied if those conversions fail. 4557 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4558 * if possible, before or instead of any conversions done by {@code asType}: 4559 * <ul> 4560 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4561 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4562 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4563 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4564 * the boolean is converted to a byte value, 1 for true, 0 for false. 4565 * (This treatment follows the usage of the bytecode verifier.) 4566 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4567 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4568 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4569 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4570 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4571 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4572 * widening and/or narrowing.) 4573 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4574 * conversion will be applied at runtime, possibly followed 4575 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4576 * possibly followed by a conversion from byte to boolean by testing 4577 * the low-order bit. 4578 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4579 * and if the reference is null at runtime, a zero value is introduced. 4580 * </ul> 4581 * @param target the method handle to invoke after arguments are retyped 4582 * @param newType the expected type of the new method handle 4583 * @return a method handle which delegates to the target after performing 4584 * any necessary argument conversions, and arranges for any 4585 * necessary return value conversions 4586 * @throws NullPointerException if either argument is null 4587 * @throws WrongMethodTypeException if the conversion cannot be made 4588 * @see MethodHandle#asType 4589 */ 4590 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4591 explicitCastArgumentsChecks(target, newType); 4592 // use the asTypeCache when possible: 4593 MethodType oldType = target.type(); 4594 if (oldType == newType) return target; 4595 if (oldType.explicitCastEquivalentToAsType(newType)) { 4596 return target.asFixedArity().asType(newType); 4597 } 4598 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4599 } 4600 4601 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4602 if (target.type().parameterCount() != newType.parameterCount()) { 4603 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4604 } 4605 } 4606 4607 /** 4608 * Produces a method handle which adapts the calling sequence of the 4609 * given method handle to a new type, by reordering the arguments. 4610 * The resulting method handle is guaranteed to report a type 4611 * which is equal to the desired new type. 4612 * <p> 4613 * The given array controls the reordering. 4614 * Call {@code #I} the number of incoming parameters (the value 4615 * {@code newType.parameterCount()}, and call {@code #O} the number 4616 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4617 * Then the length of the reordering array must be {@code #O}, 4618 * and each element must be a non-negative number less than {@code #I}. 4619 * For every {@code N} less than {@code #O}, the {@code N}-th 4620 * outgoing argument will be taken from the {@code I}-th incoming 4621 * argument, where {@code I} is {@code reorder[N]}. 4622 * <p> 4623 * No argument or return value conversions are applied. 4624 * The type of each incoming argument, as determined by {@code newType}, 4625 * must be identical to the type of the corresponding outgoing parameter 4626 * or parameters in the target method handle. 4627 * The return type of {@code newType} must be identical to the return 4628 * type of the original target. 4629 * <p> 4630 * The reordering array need not specify an actual permutation. 4631 * An incoming argument will be duplicated if its index appears 4632 * more than once in the array, and an incoming argument will be dropped 4633 * if its index does not appear in the array. 4634 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4635 * incoming arguments which are not mentioned in the reordering array 4636 * may be of any type, as determined only by {@code newType}. 4637 * {@snippet lang="java" : 4638 import static java.lang.invoke.MethodHandles.*; 4639 import static java.lang.invoke.MethodType.*; 4640 ... 4641 MethodType intfn1 = methodType(int.class, int.class); 4642 MethodType intfn2 = methodType(int.class, int.class, int.class); 4643 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4644 assert(sub.type().equals(intfn2)); 4645 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4646 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4647 assert((int)rsub.invokeExact(1, 100) == 99); 4648 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4649 assert(add.type().equals(intfn2)); 4650 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4651 assert(twice.type().equals(intfn1)); 4652 assert((int)twice.invokeExact(21) == 42); 4653 * } 4654 * <p> 4655 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4656 * variable-arity method handle}, even if the original target method handle was. 4657 * @param target the method handle to invoke after arguments are reordered 4658 * @param newType the expected type of the new method handle 4659 * @param reorder an index array which controls the reordering 4660 * @return a method handle which delegates to the target after it 4661 * drops unused arguments and moves and/or duplicates the other arguments 4662 * @throws NullPointerException if any argument is null 4663 * @throws IllegalArgumentException if the index array length is not equal to 4664 * the arity of the target, or if any index array element 4665 * not a valid index for a parameter of {@code newType}, 4666 * or if two corresponding parameter types in 4667 * {@code target.type()} and {@code newType} are not identical, 4668 */ 4669 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4670 reorder = reorder.clone(); // get a private copy 4671 MethodType oldType = target.type(); 4672 permuteArgumentChecks(reorder, newType, oldType); 4673 // first detect dropped arguments and handle them separately 4674 int[] originalReorder = reorder; 4675 BoundMethodHandle result = target.rebind(); 4676 LambdaForm form = result.form; 4677 int newArity = newType.parameterCount(); 4678 // Normalize the reordering into a real permutation, 4679 // by removing duplicates and adding dropped elements. 4680 // This somewhat improves lambda form caching, as well 4681 // as simplifying the transform by breaking it up into steps. 4682 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4683 if (ddIdx > 0) { 4684 // We found a duplicated entry at reorder[ddIdx]. 4685 // Example: (x,y,z)->asList(x,y,z) 4686 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4687 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4688 // The starred element corresponds to the argument 4689 // deleted by the dupArgumentForm transform. 4690 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4691 boolean killFirst = false; 4692 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4693 // Set killFirst if the dup is larger than an intervening position. 4694 // This will remove at least one inversion from the permutation. 4695 if (dupVal > val) killFirst = true; 4696 } 4697 if (!killFirst) { 4698 srcPos = dstPos; 4699 dstPos = ddIdx; 4700 } 4701 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4702 assert (reorder[srcPos] == reorder[dstPos]); 4703 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4704 // contract the reordering by removing the element at dstPos 4705 int tailPos = dstPos + 1; 4706 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4707 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4708 } else { 4709 int dropVal = ~ddIdx, insPos = 0; 4710 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4711 // Find first element of reorder larger than dropVal. 4712 // This is where we will insert the dropVal. 4713 insPos += 1; 4714 } 4715 Class<?> ptype = newType.parameterType(dropVal); 4716 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4717 oldType = oldType.insertParameterTypes(insPos, ptype); 4718 // expand the reordering by inserting an element at insPos 4719 int tailPos = insPos + 1; 4720 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4721 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4722 reorder[insPos] = dropVal; 4723 } 4724 assert (permuteArgumentChecks(reorder, newType, oldType)); 4725 } 4726 assert (reorder.length == newArity); // a perfect permutation 4727 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4728 form = form.editor().permuteArgumentsForm(1, reorder); 4729 if (newType == result.type() && form == result.internalForm()) 4730 return result; 4731 return result.copyWith(newType, form); 4732 } 4733 4734 /** 4735 * Return an indication of any duplicate or omission in reorder. 4736 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4737 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4738 * Otherwise, return zero. 4739 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4740 */ 4741 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4742 final int BIT_LIMIT = 63; // max number of bits in bit mask 4743 if (newArity < BIT_LIMIT) { 4744 long mask = 0; 4745 for (int i = 0; i < reorder.length; i++) { 4746 int arg = reorder[i]; 4747 if (arg >= newArity) { 4748 return reorder.length; 4749 } 4750 long bit = 1L << arg; 4751 if ((mask & bit) != 0) { 4752 return i; // >0 indicates a dup 4753 } 4754 mask |= bit; 4755 } 4756 if (mask == (1L << newArity) - 1) { 4757 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4758 return 0; 4759 } 4760 // find first zero 4761 long zeroBit = Long.lowestOneBit(~mask); 4762 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4763 assert(zeroPos <= newArity); 4764 if (zeroPos == newArity) { 4765 return 0; 4766 } 4767 return ~zeroPos; 4768 } else { 4769 // same algorithm, different bit set 4770 BitSet mask = new BitSet(newArity); 4771 for (int i = 0; i < reorder.length; i++) { 4772 int arg = reorder[i]; 4773 if (arg >= newArity) { 4774 return reorder.length; 4775 } 4776 if (mask.get(arg)) { 4777 return i; // >0 indicates a dup 4778 } 4779 mask.set(arg); 4780 } 4781 int zeroPos = mask.nextClearBit(0); 4782 assert(zeroPos <= newArity); 4783 if (zeroPos == newArity) { 4784 return 0; 4785 } 4786 return ~zeroPos; 4787 } 4788 } 4789 4790 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4791 if (newType.returnType() != oldType.returnType()) 4792 throw newIllegalArgumentException("return types do not match", 4793 oldType, newType); 4794 if (reorder.length != oldType.parameterCount()) 4795 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 4796 oldType, Arrays.toString(reorder)); 4797 4798 int limit = newType.parameterCount(); 4799 for (int j = 0; j < reorder.length; j++) { 4800 int i = reorder[j]; 4801 if (i < 0 || i >= limit) { 4802 throw newIllegalArgumentException("index is out of bounds for new type", 4803 i, newType); 4804 } 4805 Class<?> src = newType.parameterType(i); 4806 Class<?> dst = oldType.parameterType(j); 4807 if (src != dst) 4808 throw newIllegalArgumentException("parameter types do not match after reorder", 4809 oldType, newType); 4810 } 4811 return true; 4812 } 4813 4814 /** 4815 * Produces a method handle of the requested return type which returns the given 4816 * constant value every time it is invoked. 4817 * <p> 4818 * Before the method handle is returned, the passed-in value is converted to the requested type. 4819 * If the requested type is primitive, widening primitive conversions are attempted, 4820 * else reference conversions are attempted. 4821 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 4822 * @param type the return type of the desired method handle 4823 * @param value the value to return 4824 * @return a method handle of the given return type and no arguments, which always returns the given value 4825 * @throws NullPointerException if the {@code type} argument is null 4826 * @throws ClassCastException if the value cannot be converted to the required return type 4827 * @throws IllegalArgumentException if the given type is {@code void.class} 4828 */ 4829 public static MethodHandle constant(Class<?> type, Object value) { 4830 if (type.isPrimitive()) { 4831 if (type == void.class) 4832 throw newIllegalArgumentException("void type"); 4833 Wrapper w = Wrapper.forPrimitiveType(type); 4834 value = w.convert(value, type); 4835 if (w.zero().equals(value)) 4836 return zero(w, type); 4837 return insertArguments(identity(type), 0, value); 4838 } else { 4839 if (value == null) 4840 return zero(Wrapper.OBJECT, type); 4841 return identity(type).bindTo(value); 4842 } 4843 } 4844 4845 /** 4846 * Produces a method handle which returns its sole argument when invoked. 4847 * @param type the type of the sole parameter and return value of the desired method handle 4848 * @return a unary method handle which accepts and returns the given type 4849 * @throws NullPointerException if the argument is null 4850 * @throws IllegalArgumentException if the given type is {@code void.class} 4851 */ 4852 public static MethodHandle identity(Class<?> type) { 4853 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 4854 int pos = btw.ordinal(); 4855 MethodHandle ident = IDENTITY_MHS[pos]; 4856 if (ident == null) { 4857 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 4858 } 4859 if (ident.type().returnType() == type) 4860 return ident; 4861 // something like identity(Foo.class); do not bother to intern these 4862 assert (btw == Wrapper.OBJECT); 4863 return makeIdentity(type); 4864 } 4865 4866 /** 4867 * Produces a constant method handle of the requested return type which 4868 * returns the default value for that type every time it is invoked. 4869 * The resulting constant method handle will have no side effects. 4870 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 4871 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 4872 * since {@code explicitCastArguments} converts {@code null} to default values. 4873 * @param type the expected return type of the desired method handle 4874 * @return a constant method handle that takes no arguments 4875 * and returns the default value of the given type (or void, if the type is void) 4876 * @throws NullPointerException if the argument is null 4877 * @see MethodHandles#constant 4878 * @see MethodHandles#empty 4879 * @see MethodHandles#explicitCastArguments 4880 * @since 9 4881 */ 4882 public static MethodHandle zero(Class<?> type) { 4883 Objects.requireNonNull(type); 4884 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 4885 } 4886 4887 private static MethodHandle identityOrVoid(Class<?> type) { 4888 return type == void.class ? zero(type) : identity(type); 4889 } 4890 4891 /** 4892 * Produces a method handle of the requested type which ignores any arguments, does nothing, 4893 * and returns a suitable default depending on the return type. 4894 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 4895 * <p>The returned method handle is equivalent to 4896 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 4897 * 4898 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 4899 * {@code guardWithTest(pred, target, empty(target.type())}. 4900 * @param type the type of the desired method handle 4901 * @return a constant method handle of the given type, which returns a default value of the given return type 4902 * @throws NullPointerException if the argument is null 4903 * @see MethodHandles#zero 4904 * @see MethodHandles#constant 4905 * @since 9 4906 */ 4907 public static MethodHandle empty(MethodType type) { 4908 Objects.requireNonNull(type); 4909 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 4910 } 4911 4912 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 4913 private static MethodHandle makeIdentity(Class<?> ptype) { 4914 MethodType mtype = methodType(ptype, ptype); 4915 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 4916 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 4917 } 4918 4919 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 4920 int pos = btw.ordinal(); 4921 MethodHandle zero = ZERO_MHS[pos]; 4922 if (zero == null) { 4923 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 4924 } 4925 if (zero.type().returnType() == rtype) 4926 return zero; 4927 assert(btw == Wrapper.OBJECT); 4928 return makeZero(rtype); 4929 } 4930 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 4931 private static MethodHandle makeZero(Class<?> rtype) { 4932 MethodType mtype = methodType(rtype); 4933 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 4934 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 4935 } 4936 4937 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 4938 // Simulate a CAS, to avoid racy duplication of results. 4939 MethodHandle prev = cache[pos]; 4940 if (prev != null) return prev; 4941 return cache[pos] = value; 4942 } 4943 4944 /** 4945 * Provides a target method handle with one or more <em>bound arguments</em> 4946 * in advance of the method handle's invocation. 4947 * The formal parameters to the target corresponding to the bound 4948 * arguments are called <em>bound parameters</em>. 4949 * Returns a new method handle which saves away the bound arguments. 4950 * When it is invoked, it receives arguments for any non-bound parameters, 4951 * binds the saved arguments to their corresponding parameters, 4952 * and calls the original target. 4953 * <p> 4954 * The type of the new method handle will drop the types for the bound 4955 * parameters from the original target type, since the new method handle 4956 * will no longer require those arguments to be supplied by its callers. 4957 * <p> 4958 * Each given argument object must match the corresponding bound parameter type. 4959 * If a bound parameter type is a primitive, the argument object 4960 * must be a wrapper, and will be unboxed to produce the primitive value. 4961 * <p> 4962 * The {@code pos} argument selects which parameters are to be bound. 4963 * It may range between zero and <i>N-L</i> (inclusively), 4964 * where <i>N</i> is the arity of the target method handle 4965 * and <i>L</i> is the length of the values array. 4966 * <p> 4967 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4968 * variable-arity method handle}, even if the original target method handle was. 4969 * @param target the method handle to invoke after the argument is inserted 4970 * @param pos where to insert the argument (zero for the first) 4971 * @param values the series of arguments to insert 4972 * @return a method handle which inserts an additional argument, 4973 * before calling the original method handle 4974 * @throws NullPointerException if the target or the {@code values} array is null 4975 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 4976 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 4977 * is the length of the values array. 4978 * @throws ClassCastException if an argument does not match the corresponding bound parameter 4979 * type. 4980 * @see MethodHandle#bindTo 4981 */ 4982 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 4983 int insCount = values.length; 4984 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 4985 if (insCount == 0) return target; 4986 BoundMethodHandle result = target.rebind(); 4987 for (int i = 0; i < insCount; i++) { 4988 Object value = values[i]; 4989 Class<?> ptype = ptypes[pos+i]; 4990 if (ptype.isPrimitive()) { 4991 result = insertArgumentPrimitive(result, pos, ptype, value); 4992 } else { 4993 value = ptype.cast(value); // throw CCE if needed 4994 result = result.bindArgumentL(pos, value); 4995 } 4996 } 4997 return result; 4998 } 4999 5000 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 5001 Class<?> ptype, Object value) { 5002 Wrapper w = Wrapper.forPrimitiveType(ptype); 5003 // perform unboxing and/or primitive conversion 5004 value = w.convert(value, ptype); 5005 return switch (w) { 5006 case INT -> result.bindArgumentI(pos, (int) value); 5007 case LONG -> result.bindArgumentJ(pos, (long) value); 5008 case FLOAT -> result.bindArgumentF(pos, (float) value); 5009 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5010 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5011 }; 5012 } 5013 5014 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5015 MethodType oldType = target.type(); 5016 int outargs = oldType.parameterCount(); 5017 int inargs = outargs - insCount; 5018 if (inargs < 0) 5019 throw newIllegalArgumentException("too many values to insert"); 5020 if (pos < 0 || pos > inargs) 5021 throw newIllegalArgumentException("no argument type to append"); 5022 return oldType.ptypes(); 5023 } 5024 5025 /** 5026 * Produces a method handle which will discard some dummy arguments 5027 * before calling some other specified <i>target</i> method handle. 5028 * The type of the new method handle will be the same as the target's type, 5029 * except it will also include the dummy argument types, 5030 * at some given position. 5031 * <p> 5032 * The {@code pos} argument may range between zero and <i>N</i>, 5033 * where <i>N</i> is the arity of the target. 5034 * If {@code pos} is zero, the dummy arguments will precede 5035 * the target's real arguments; if {@code pos} is <i>N</i> 5036 * they will come after. 5037 * <p> 5038 * <b>Example:</b> 5039 * {@snippet lang="java" : 5040 import static java.lang.invoke.MethodHandles.*; 5041 import static java.lang.invoke.MethodType.*; 5042 ... 5043 MethodHandle cat = lookup().findVirtual(String.class, 5044 "concat", methodType(String.class, String.class)); 5045 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5046 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5047 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5048 assertEquals(bigType, d0.type()); 5049 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5050 * } 5051 * <p> 5052 * This method is also equivalent to the following code: 5053 * <blockquote><pre> 5054 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5055 * </pre></blockquote> 5056 * @param target the method handle to invoke after the arguments are dropped 5057 * @param pos position of first argument to drop (zero for the leftmost) 5058 * @param valueTypes the type(s) of the argument(s) to drop 5059 * @return a method handle which drops arguments of the given types, 5060 * before calling the original method handle 5061 * @throws NullPointerException if the target is null, 5062 * or if the {@code valueTypes} list or any of its elements is null 5063 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5064 * or if {@code pos} is negative or greater than the arity of the target, 5065 * or if the new method handle's type would have too many parameters 5066 */ 5067 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5068 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5069 } 5070 5071 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5072 MethodType oldType = target.type(); // get NPE 5073 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5074 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5075 if (dropped == 0) return target; 5076 BoundMethodHandle result = target.rebind(); 5077 LambdaForm lform = result.form; 5078 int insertFormArg = 1 + pos; 5079 for (Class<?> ptype : valueTypes) { 5080 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5081 } 5082 result = result.copyWith(newType, lform); 5083 return result; 5084 } 5085 5086 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5087 int dropped = valueTypes.length; 5088 MethodType.checkSlotCount(dropped); 5089 int outargs = oldType.parameterCount(); 5090 int inargs = outargs + dropped; 5091 if (pos < 0 || pos > outargs) 5092 throw newIllegalArgumentException("no argument type to remove" 5093 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5094 ); 5095 return dropped; 5096 } 5097 5098 /** 5099 * Produces a method handle which will discard some dummy arguments 5100 * before calling some other specified <i>target</i> method handle. 5101 * The type of the new method handle will be the same as the target's type, 5102 * except it will also include the dummy argument types, 5103 * at some given position. 5104 * <p> 5105 * The {@code pos} argument may range between zero and <i>N</i>, 5106 * where <i>N</i> is the arity of the target. 5107 * If {@code pos} is zero, the dummy arguments will precede 5108 * the target's real arguments; if {@code pos} is <i>N</i> 5109 * they will come after. 5110 * @apiNote 5111 * {@snippet lang="java" : 5112 import static java.lang.invoke.MethodHandles.*; 5113 import static java.lang.invoke.MethodType.*; 5114 ... 5115 MethodHandle cat = lookup().findVirtual(String.class, 5116 "concat", methodType(String.class, String.class)); 5117 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5118 MethodHandle d0 = dropArguments(cat, 0, String.class); 5119 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5120 MethodHandle d1 = dropArguments(cat, 1, String.class); 5121 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5122 MethodHandle d2 = dropArguments(cat, 2, String.class); 5123 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5124 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5125 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5126 * } 5127 * <p> 5128 * This method is also equivalent to the following code: 5129 * <blockquote><pre> 5130 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5131 * </pre></blockquote> 5132 * @param target the method handle to invoke after the arguments are dropped 5133 * @param pos position of first argument to drop (zero for the leftmost) 5134 * @param valueTypes the type(s) of the argument(s) to drop 5135 * @return a method handle which drops arguments of the given types, 5136 * before calling the original method handle 5137 * @throws NullPointerException if the target is null, 5138 * or if the {@code valueTypes} array or any of its elements is null 5139 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5140 * or if {@code pos} is negative or greater than the arity of the target, 5141 * or if the new method handle's type would have 5142 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5143 */ 5144 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5145 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5146 } 5147 5148 /* Convenience overloads for trusting internal low-arity call-sites */ 5149 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5150 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5151 } 5152 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5153 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5154 } 5155 5156 // private version which allows caller some freedom with error handling 5157 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5158 boolean nullOnFailure) { 5159 Class<?>[] oldTypes = target.type().ptypes(); 5160 int match = oldTypes.length; 5161 if (skip != 0) { 5162 if (skip < 0 || skip > match) { 5163 throw newIllegalArgumentException("illegal skip", skip, target); 5164 } 5165 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5166 match -= skip; 5167 } 5168 Class<?>[] addTypes = newTypes; 5169 int add = addTypes.length; 5170 if (pos != 0) { 5171 if (pos < 0 || pos > add) { 5172 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5173 } 5174 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5175 add -= pos; 5176 assert(addTypes.length == add); 5177 } 5178 // Do not add types which already match the existing arguments. 5179 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5180 if (nullOnFailure) { 5181 return null; 5182 } 5183 throw newIllegalArgumentException("argument lists do not match", 5184 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5185 } 5186 addTypes = Arrays.copyOfRange(addTypes, match, add); 5187 add -= match; 5188 assert(addTypes.length == add); 5189 // newTypes: ( P*[pos], M*[match], A*[add] ) 5190 // target: ( S*[skip], M*[match] ) 5191 MethodHandle adapter = target; 5192 if (add > 0) { 5193 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5194 } 5195 // adapter: (S*[skip], M*[match], A*[add] ) 5196 if (pos > 0) { 5197 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5198 } 5199 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5200 return adapter; 5201 } 5202 5203 /** 5204 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5205 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5206 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5207 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5208 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5209 * {@link #dropArguments(MethodHandle, int, Class[])}. 5210 * <p> 5211 * The resulting handle will have the same return type as the target handle. 5212 * <p> 5213 * In more formal terms, assume these two type lists:<ul> 5214 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5215 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5216 * {@code newTypes}. 5217 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5218 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5219 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5220 * sub-list. 5221 * </ul> 5222 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5223 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5224 * {@link #dropArguments(MethodHandle, int, Class[])}. 5225 * 5226 * @apiNote 5227 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5228 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5229 * {@snippet lang="java" : 5230 import static java.lang.invoke.MethodHandles.*; 5231 import static java.lang.invoke.MethodType.*; 5232 ... 5233 ... 5234 MethodHandle h0 = constant(boolean.class, true); 5235 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5236 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5237 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5238 if (h1.type().parameterCount() < h2.type().parameterCount()) 5239 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5240 else 5241 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5242 MethodHandle h3 = guardWithTest(h0, h1, h2); 5243 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5244 * } 5245 * @param target the method handle to adapt 5246 * @param skip number of targets parameters to disregard (they will be unchanged) 5247 * @param newTypes the list of types to match {@code target}'s parameter type list to 5248 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5249 * @return a possibly adapted method handle 5250 * @throws NullPointerException if either argument is null 5251 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5252 * or if {@code skip} is negative or greater than the arity of the target, 5253 * or if {@code pos} is negative or greater than the newTypes list size, 5254 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5255 * {@code pos}. 5256 * @since 9 5257 */ 5258 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5259 Objects.requireNonNull(target); 5260 Objects.requireNonNull(newTypes); 5261 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5262 } 5263 5264 /** 5265 * Drop the return value of the target handle (if any). 5266 * The returned method handle will have a {@code void} return type. 5267 * 5268 * @param target the method handle to adapt 5269 * @return a possibly adapted method handle 5270 * @throws NullPointerException if {@code target} is null 5271 * @since 16 5272 */ 5273 public static MethodHandle dropReturn(MethodHandle target) { 5274 Objects.requireNonNull(target); 5275 MethodType oldType = target.type(); 5276 Class<?> oldReturnType = oldType.returnType(); 5277 if (oldReturnType == void.class) 5278 return target; 5279 MethodType newType = oldType.changeReturnType(void.class); 5280 BoundMethodHandle result = target.rebind(); 5281 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5282 result = result.copyWith(newType, lform); 5283 return result; 5284 } 5285 5286 /** 5287 * Adapts a target method handle by pre-processing 5288 * one or more of its arguments, each with its own unary filter function, 5289 * and then calling the target with each pre-processed argument 5290 * replaced by the result of its corresponding filter function. 5291 * <p> 5292 * The pre-processing is performed by one or more method handles, 5293 * specified in the elements of the {@code filters} array. 5294 * The first element of the filter array corresponds to the {@code pos} 5295 * argument of the target, and so on in sequence. 5296 * The filter functions are invoked in left to right order. 5297 * <p> 5298 * Null arguments in the array are treated as identity functions, 5299 * and the corresponding arguments left unchanged. 5300 * (If there are no non-null elements in the array, the original target is returned.) 5301 * Each filter is applied to the corresponding argument of the adapter. 5302 * <p> 5303 * If a filter {@code F} applies to the {@code N}th argument of 5304 * the target, then {@code F} must be a method handle which 5305 * takes exactly one argument. The type of {@code F}'s sole argument 5306 * replaces the corresponding argument type of the target 5307 * in the resulting adapted method handle. 5308 * The return type of {@code F} must be identical to the corresponding 5309 * parameter type of the target. 5310 * <p> 5311 * It is an error if there are elements of {@code filters} 5312 * (null or not) 5313 * which do not correspond to argument positions in the target. 5314 * <p><b>Example:</b> 5315 * {@snippet lang="java" : 5316 import static java.lang.invoke.MethodHandles.*; 5317 import static java.lang.invoke.MethodType.*; 5318 ... 5319 MethodHandle cat = lookup().findVirtual(String.class, 5320 "concat", methodType(String.class, String.class)); 5321 MethodHandle upcase = lookup().findVirtual(String.class, 5322 "toUpperCase", methodType(String.class)); 5323 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5324 MethodHandle f0 = filterArguments(cat, 0, upcase); 5325 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5326 MethodHandle f1 = filterArguments(cat, 1, upcase); 5327 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5328 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5329 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5330 * } 5331 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5332 * denotes the return type of both the {@code target} and resulting adapter. 5333 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5334 * of the parameters and arguments that precede and follow the filter position 5335 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5336 * values of the filtered parameters and arguments; they also represent the 5337 * return types of the {@code filter[i]} handles. The latter accept arguments 5338 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5339 * the resulting adapter. 5340 * {@snippet lang="java" : 5341 * T target(P... p, A[i]... a[i], B... b); 5342 * A[i] filter[i](V[i]); 5343 * T adapter(P... p, V[i]... v[i], B... b) { 5344 * return target(p..., filter[i](v[i])..., b...); 5345 * } 5346 * } 5347 * <p> 5348 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5349 * variable-arity method handle}, even if the original target method handle was. 5350 * 5351 * @param target the method handle to invoke after arguments are filtered 5352 * @param pos the position of the first argument to filter 5353 * @param filters method handles to call initially on filtered arguments 5354 * @return method handle which incorporates the specified argument filtering logic 5355 * @throws NullPointerException if the target is null 5356 * or if the {@code filters} array is null 5357 * @throws IllegalArgumentException if a non-null element of {@code filters} 5358 * does not match a corresponding argument type of target as described above, 5359 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5360 * or if the resulting method handle's type would have 5361 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5362 */ 5363 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5364 // In method types arguments start at index 0, while the LF 5365 // editor have the MH receiver at position 0 - adjust appropriately. 5366 final int MH_RECEIVER_OFFSET = 1; 5367 filterArgumentsCheckArity(target, pos, filters); 5368 MethodHandle adapter = target; 5369 5370 // keep track of currently matched filters, as to optimize repeated filters 5371 int index = 0; 5372 int[] positions = new int[filters.length]; 5373 MethodHandle filter = null; 5374 5375 // process filters in reverse order so that the invocation of 5376 // the resulting adapter will invoke the filters in left-to-right order 5377 for (int i = filters.length - 1; i >= 0; --i) { 5378 MethodHandle newFilter = filters[i]; 5379 if (newFilter == null) continue; // ignore null elements of filters 5380 5381 // flush changes on update 5382 if (filter != newFilter) { 5383 if (filter != null) { 5384 if (index > 1) { 5385 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5386 } else { 5387 adapter = filterArgument(adapter, positions[0] - 1, filter); 5388 } 5389 } 5390 filter = newFilter; 5391 index = 0; 5392 } 5393 5394 filterArgumentChecks(target, pos + i, newFilter); 5395 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5396 } 5397 if (index > 1) { 5398 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5399 } else if (index == 1) { 5400 adapter = filterArgument(adapter, positions[0] - 1, filter); 5401 } 5402 return adapter; 5403 } 5404 5405 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5406 MethodType targetType = adapter.type(); 5407 MethodType filterType = filter.type(); 5408 BoundMethodHandle result = adapter.rebind(); 5409 Class<?> newParamType = filterType.parameterType(0); 5410 5411 Class<?>[] ptypes = targetType.ptypes().clone(); 5412 for (int pos : positions) { 5413 ptypes[pos - 1] = newParamType; 5414 } 5415 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5416 5417 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5418 return result.copyWithExtendL(newType, lform, filter); 5419 } 5420 5421 /*non-public*/ 5422 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5423 filterArgumentChecks(target, pos, filter); 5424 MethodType targetType = target.type(); 5425 MethodType filterType = filter.type(); 5426 BoundMethodHandle result = target.rebind(); 5427 Class<?> newParamType = filterType.parameterType(0); 5428 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5429 MethodType newType = targetType.changeParameterType(pos, newParamType); 5430 result = result.copyWithExtendL(newType, lform, filter); 5431 return result; 5432 } 5433 5434 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5435 MethodType targetType = target.type(); 5436 int maxPos = targetType.parameterCount(); 5437 if (pos + filters.length > maxPos) 5438 throw newIllegalArgumentException("too many filters"); 5439 } 5440 5441 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5442 MethodType targetType = target.type(); 5443 MethodType filterType = filter.type(); 5444 if (filterType.parameterCount() != 1 5445 || filterType.returnType() != targetType.parameterType(pos)) 5446 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5447 } 5448 5449 /** 5450 * Adapts a target method handle by pre-processing 5451 * a sub-sequence of its arguments with a filter (another method handle). 5452 * The pre-processed arguments are replaced by the result (if any) of the 5453 * filter function. 5454 * The target is then called on the modified (usually shortened) argument list. 5455 * <p> 5456 * If the filter returns a value, the target must accept that value as 5457 * its argument in position {@code pos}, preceded and/or followed by 5458 * any arguments not passed to the filter. 5459 * If the filter returns void, the target must accept all arguments 5460 * not passed to the filter. 5461 * No arguments are reordered, and a result returned from the filter 5462 * replaces (in order) the whole subsequence of arguments originally 5463 * passed to the adapter. 5464 * <p> 5465 * The argument types (if any) of the filter 5466 * replace zero or one argument types of the target, at position {@code pos}, 5467 * in the resulting adapted method handle. 5468 * The return type of the filter (if any) must be identical to the 5469 * argument type of the target at position {@code pos}, and that target argument 5470 * is supplied by the return value of the filter. 5471 * <p> 5472 * In all cases, {@code pos} must be greater than or equal to zero, and 5473 * {@code pos} must also be less than or equal to the target's arity. 5474 * <p><b>Example:</b> 5475 * {@snippet lang="java" : 5476 import static java.lang.invoke.MethodHandles.*; 5477 import static java.lang.invoke.MethodType.*; 5478 ... 5479 MethodHandle deepToString = publicLookup() 5480 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5481 5482 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5483 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5484 5485 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5486 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5487 5488 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5489 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5490 assertEquals("[top, [up, down], strange]", 5491 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5492 5493 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5494 assertEquals("[top, [up, down], [strange]]", 5495 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5496 5497 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5498 assertEquals("[top, [[up, down, strange], charm], bottom]", 5499 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5500 * } 5501 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5502 * represents the return type of the {@code target} and resulting adapter. 5503 * {@code V}/{@code v} stand for the return type and value of the 5504 * {@code filter}, which are also found in the signature and arguments of 5505 * the {@code target}, respectively, unless {@code V} is {@code void}. 5506 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5507 * and values preceding and following the collection position, {@code pos}, 5508 * in the {@code target}'s signature. They also turn up in the resulting 5509 * adapter's signature and arguments, where they surround 5510 * {@code B}/{@code b}, which represent the parameter types and arguments 5511 * to the {@code filter} (if any). 5512 * {@snippet lang="java" : 5513 * T target(A...,V,C...); 5514 * V filter(B...); 5515 * T adapter(A... a,B... b,C... c) { 5516 * V v = filter(b...); 5517 * return target(a...,v,c...); 5518 * } 5519 * // and if the filter has no arguments: 5520 * T target2(A...,V,C...); 5521 * V filter2(); 5522 * T adapter2(A... a,C... c) { 5523 * V v = filter2(); 5524 * return target2(a...,v,c...); 5525 * } 5526 * // and if the filter has a void return: 5527 * T target3(A...,C...); 5528 * void filter3(B...); 5529 * T adapter3(A... a,B... b,C... c) { 5530 * filter3(b...); 5531 * return target3(a...,c...); 5532 * } 5533 * } 5534 * <p> 5535 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5536 * one which first "folds" the affected arguments, and then drops them, in separate 5537 * steps as follows: 5538 * {@snippet lang="java" : 5539 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5540 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5541 * } 5542 * If the target method handle consumes no arguments besides than the result 5543 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5544 * is equivalent to {@code filterReturnValue(coll, mh)}. 5545 * If the filter method handle {@code coll} consumes one argument and produces 5546 * a non-void result, then {@code collectArguments(mh, N, coll)} 5547 * is equivalent to {@code filterArguments(mh, N, coll)}. 5548 * Other equivalences are possible but would require argument permutation. 5549 * <p> 5550 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5551 * variable-arity method handle}, even if the original target method handle was. 5552 * 5553 * @param target the method handle to invoke after filtering the subsequence of arguments 5554 * @param pos the position of the first adapter argument to pass to the filter, 5555 * and/or the target argument which receives the result of the filter 5556 * @param filter method handle to call on the subsequence of arguments 5557 * @return method handle which incorporates the specified argument subsequence filtering logic 5558 * @throws NullPointerException if either argument is null 5559 * @throws IllegalArgumentException if the return type of {@code filter} 5560 * is non-void and is not the same as the {@code pos} argument of the target, 5561 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5562 * or if the resulting method handle's type would have 5563 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5564 * @see MethodHandles#foldArguments 5565 * @see MethodHandles#filterArguments 5566 * @see MethodHandles#filterReturnValue 5567 */ 5568 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5569 MethodType newType = collectArgumentsChecks(target, pos, filter); 5570 MethodType collectorType = filter.type(); 5571 BoundMethodHandle result = target.rebind(); 5572 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5573 return result.copyWithExtendL(newType, lform, filter); 5574 } 5575 5576 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5577 MethodType targetType = target.type(); 5578 MethodType filterType = filter.type(); 5579 Class<?> rtype = filterType.returnType(); 5580 Class<?>[] filterArgs = filterType.ptypes(); 5581 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5582 (rtype != void.class && pos >= targetType.parameterCount())) { 5583 throw newIllegalArgumentException("position is out of range for target", target, pos); 5584 } 5585 if (rtype == void.class) { 5586 return targetType.insertParameterTypes(pos, filterArgs); 5587 } 5588 if (rtype != targetType.parameterType(pos)) { 5589 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5590 } 5591 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5592 } 5593 5594 /** 5595 * Adapts a target method handle by post-processing 5596 * its return value (if any) with a filter (another method handle). 5597 * The result of the filter is returned from the adapter. 5598 * <p> 5599 * If the target returns a value, the filter must accept that value as 5600 * its only argument. 5601 * If the target returns void, the filter must accept no arguments. 5602 * <p> 5603 * The return type of the filter 5604 * replaces the return type of the target 5605 * in the resulting adapted method handle. 5606 * The argument type of the filter (if any) must be identical to the 5607 * return type of the target. 5608 * <p><b>Example:</b> 5609 * {@snippet lang="java" : 5610 import static java.lang.invoke.MethodHandles.*; 5611 import static java.lang.invoke.MethodType.*; 5612 ... 5613 MethodHandle cat = lookup().findVirtual(String.class, 5614 "concat", methodType(String.class, String.class)); 5615 MethodHandle length = lookup().findVirtual(String.class, 5616 "length", methodType(int.class)); 5617 System.out.println((String) cat.invokeExact("x", "y")); // xy 5618 MethodHandle f0 = filterReturnValue(cat, length); 5619 System.out.println((int) f0.invokeExact("x", "y")); // 2 5620 * } 5621 * <p>Here is pseudocode for the resulting adapter. In the code, 5622 * {@code T}/{@code t} represent the result type and value of the 5623 * {@code target}; {@code V}, the result type of the {@code filter}; and 5624 * {@code A}/{@code a}, the types and values of the parameters and arguments 5625 * of the {@code target} as well as the resulting adapter. 5626 * {@snippet lang="java" : 5627 * T target(A...); 5628 * V filter(T); 5629 * V adapter(A... a) { 5630 * T t = target(a...); 5631 * return filter(t); 5632 * } 5633 * // and if the target has a void return: 5634 * void target2(A...); 5635 * V filter2(); 5636 * V adapter2(A... a) { 5637 * target2(a...); 5638 * return filter2(); 5639 * } 5640 * // and if the filter has a void return: 5641 * T target3(A...); 5642 * void filter3(V); 5643 * void adapter3(A... a) { 5644 * T t = target3(a...); 5645 * filter3(t); 5646 * } 5647 * } 5648 * <p> 5649 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5650 * variable-arity method handle}, even if the original target method handle was. 5651 * @param target the method handle to invoke before filtering the return value 5652 * @param filter method handle to call on the return value 5653 * @return method handle which incorporates the specified return value filtering logic 5654 * @throws NullPointerException if either argument is null 5655 * @throws IllegalArgumentException if the argument list of {@code filter} 5656 * does not match the return type of target as described above 5657 */ 5658 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5659 MethodType targetType = target.type(); 5660 MethodType filterType = filter.type(); 5661 filterReturnValueChecks(targetType, filterType); 5662 BoundMethodHandle result = target.rebind(); 5663 BasicType rtype = BasicType.basicType(filterType.returnType()); 5664 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5665 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5666 result = result.copyWithExtendL(newType, lform, filter); 5667 return result; 5668 } 5669 5670 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5671 Class<?> rtype = targetType.returnType(); 5672 int filterValues = filterType.parameterCount(); 5673 if (filterValues == 0 5674 ? (rtype != void.class) 5675 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5676 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5677 } 5678 5679 /** 5680 * Filter the return value of a target method handle with a filter function. The filter function is 5681 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5682 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5683 * as follows: 5684 * {@snippet lang="java" : 5685 * T target(A...) 5686 * V filter(B... , T) 5687 * V adapter(A... a, B... b) { 5688 * T t = target(a...); 5689 * return filter(b..., t); 5690 * } 5691 * } 5692 * <p> 5693 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5694 * 5695 * @param target the target method handle 5696 * @param filter the filter method handle 5697 * @return the adapter method handle 5698 */ 5699 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5700 MethodType targetType = target.type(); 5701 MethodType filterType = filter.type(); 5702 BoundMethodHandle result = target.rebind(); 5703 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5704 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5705 if (filterType.parameterCount() > 1) { 5706 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5707 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5708 } 5709 } 5710 result = result.copyWithExtendL(newType, lform, filter); 5711 return result; 5712 } 5713 5714 /** 5715 * Adapts a target method handle by pre-processing 5716 * some of its arguments, and then calling the target with 5717 * the result of the pre-processing, inserted into the original 5718 * sequence of arguments. 5719 * <p> 5720 * The pre-processing is performed by {@code combiner}, a second method handle. 5721 * Of the arguments passed to the adapter, the first {@code N} arguments 5722 * are copied to the combiner, which is then called. 5723 * (Here, {@code N} is defined as the parameter count of the combiner.) 5724 * After this, control passes to the target, with any result 5725 * from the combiner inserted before the original {@code N} incoming 5726 * arguments. 5727 * <p> 5728 * If the combiner returns a value, the first parameter type of the target 5729 * must be identical with the return type of the combiner, and the next 5730 * {@code N} parameter types of the target must exactly match the parameters 5731 * of the combiner. 5732 * <p> 5733 * If the combiner has a void return, no result will be inserted, 5734 * and the first {@code N} parameter types of the target 5735 * must exactly match the parameters of the combiner. 5736 * <p> 5737 * The resulting adapter is the same type as the target, except that the 5738 * first parameter type is dropped, 5739 * if it corresponds to the result of the combiner. 5740 * <p> 5741 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5742 * that either the combiner or the target does not wish to receive. 5743 * If some of the incoming arguments are destined only for the combiner, 5744 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5745 * arguments will not need to be live on the stack on entry to the 5746 * target.) 5747 * <p><b>Example:</b> 5748 * {@snippet lang="java" : 5749 import static java.lang.invoke.MethodHandles.*; 5750 import static java.lang.invoke.MethodType.*; 5751 ... 5752 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5753 "println", methodType(void.class, String.class)) 5754 .bindTo(System.out); 5755 MethodHandle cat = lookup().findVirtual(String.class, 5756 "concat", methodType(String.class, String.class)); 5757 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5758 MethodHandle catTrace = foldArguments(cat, trace); 5759 // also prints "boo": 5760 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5761 * } 5762 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5763 * represents the result type of the {@code target} and resulting adapter. 5764 * {@code V}/{@code v} represent the type and value of the parameter and argument 5765 * of {@code target} that precedes the folding position; {@code V} also is 5766 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5767 * types and values of the {@code N} parameters and arguments at the folding 5768 * position. {@code B}/{@code b} represent the types and values of the 5769 * {@code target} parameters and arguments that follow the folded parameters 5770 * and arguments. 5771 * {@snippet lang="java" : 5772 * // there are N arguments in A... 5773 * T target(V, A[N]..., B...); 5774 * V combiner(A...); 5775 * T adapter(A... a, B... b) { 5776 * V v = combiner(a...); 5777 * return target(v, a..., b...); 5778 * } 5779 * // and if the combiner has a void return: 5780 * T target2(A[N]..., B...); 5781 * void combiner2(A...); 5782 * T adapter2(A... a, B... b) { 5783 * combiner2(a...); 5784 * return target2(a..., b...); 5785 * } 5786 * } 5787 * <p> 5788 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5789 * variable-arity method handle}, even if the original target method handle was. 5790 * @param target the method handle to invoke after arguments are combined 5791 * @param combiner method handle to call initially on the incoming arguments 5792 * @return method handle which incorporates the specified argument folding logic 5793 * @throws NullPointerException if either argument is null 5794 * @throws IllegalArgumentException if {@code combiner}'s return type 5795 * is non-void and not the same as the first argument type of 5796 * the target, or if the initial {@code N} argument types 5797 * of the target 5798 * (skipping one matching the {@code combiner}'s return type) 5799 * are not identical with the argument types of {@code combiner} 5800 */ 5801 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5802 return foldArguments(target, 0, combiner); 5803 } 5804 5805 /** 5806 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 5807 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 5808 * before the folded arguments. 5809 * <p> 5810 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 5811 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 5812 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 5813 * 0. 5814 * 5815 * @apiNote Example: 5816 * {@snippet lang="java" : 5817 import static java.lang.invoke.MethodHandles.*; 5818 import static java.lang.invoke.MethodType.*; 5819 ... 5820 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5821 "println", methodType(void.class, String.class)) 5822 .bindTo(System.out); 5823 MethodHandle cat = lookup().findVirtual(String.class, 5824 "concat", methodType(String.class, String.class)); 5825 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5826 MethodHandle catTrace = foldArguments(cat, 1, trace); 5827 // also prints "jum": 5828 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5829 * } 5830 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5831 * represents the result type of the {@code target} and resulting adapter. 5832 * {@code V}/{@code v} represent the type and value of the parameter and argument 5833 * of {@code target} that precedes the folding position; {@code V} also is 5834 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5835 * types and values of the {@code N} parameters and arguments at the folding 5836 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 5837 * and values of the {@code target} parameters and arguments that precede and 5838 * follow the folded parameters and arguments starting at {@code pos}, 5839 * respectively. 5840 * {@snippet lang="java" : 5841 * // there are N arguments in A... 5842 * T target(Z..., V, A[N]..., B...); 5843 * V combiner(A...); 5844 * T adapter(Z... z, A... a, B... b) { 5845 * V v = combiner(a...); 5846 * return target(z..., v, a..., b...); 5847 * } 5848 * // and if the combiner has a void return: 5849 * T target2(Z..., A[N]..., B...); 5850 * void combiner2(A...); 5851 * T adapter2(Z... z, A... a, B... b) { 5852 * combiner2(a...); 5853 * return target2(z..., a..., b...); 5854 * } 5855 * } 5856 * <p> 5857 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5858 * variable-arity method handle}, even if the original target method handle was. 5859 * 5860 * @param target the method handle to invoke after arguments are combined 5861 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 5862 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5863 * @param combiner method handle to call initially on the incoming arguments 5864 * @return method handle which incorporates the specified argument folding logic 5865 * @throws NullPointerException if either argument is null 5866 * @throws IllegalArgumentException if either of the following two conditions holds: 5867 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5868 * {@code pos} of the target signature; 5869 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 5870 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 5871 * 5872 * @see #foldArguments(MethodHandle, MethodHandle) 5873 * @since 9 5874 */ 5875 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 5876 MethodType targetType = target.type(); 5877 MethodType combinerType = combiner.type(); 5878 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 5879 BoundMethodHandle result = target.rebind(); 5880 boolean dropResult = rtype == void.class; 5881 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 5882 MethodType newType = targetType; 5883 if (!dropResult) { 5884 newType = newType.dropParameterTypes(pos, pos + 1); 5885 } 5886 result = result.copyWithExtendL(newType, lform, combiner); 5887 return result; 5888 } 5889 5890 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 5891 int foldArgs = combinerType.parameterCount(); 5892 Class<?> rtype = combinerType.returnType(); 5893 int foldVals = rtype == void.class ? 0 : 1; 5894 int afterInsertPos = foldPos + foldVals; 5895 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 5896 if (ok) { 5897 for (int i = 0; i < foldArgs; i++) { 5898 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 5899 ok = false; 5900 break; 5901 } 5902 } 5903 } 5904 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 5905 ok = false; 5906 if (!ok) 5907 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5908 return rtype; 5909 } 5910 5911 /** 5912 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 5913 * of the pre-processing replacing the argument at the given position. 5914 * 5915 * @param target the method handle to invoke after arguments are combined 5916 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5917 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5918 * @param combiner method handle to call initially on the incoming arguments 5919 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5920 * @return method handle which incorporates the specified argument folding logic 5921 * @throws NullPointerException if either argument is null 5922 * @throws IllegalArgumentException if either of the following two conditions holds: 5923 * (1) {@code combiner}'s return type is not the same as the argument type at position 5924 * {@code pos} of the target signature; 5925 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 5926 * not identical with the argument types of {@code combiner}. 5927 */ 5928 /*non-public*/ 5929 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5930 return argumentsWithCombiner(true, target, position, combiner, argPositions); 5931 } 5932 5933 /** 5934 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 5935 * the pre-processing inserted into the original sequence of arguments at the given position. 5936 * 5937 * @param target the method handle to invoke after arguments are combined 5938 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5939 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5940 * @param combiner method handle to call initially on the incoming arguments 5941 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5942 * @return method handle which incorporates the specified argument folding logic 5943 * @throws NullPointerException if either argument is null 5944 * @throws IllegalArgumentException if either of the following two conditions holds: 5945 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5946 * {@code pos} of the target signature; 5947 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 5948 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 5949 * with the argument types of {@code combiner}. 5950 */ 5951 /*non-public*/ 5952 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5953 return argumentsWithCombiner(false, target, position, combiner, argPositions); 5954 } 5955 5956 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5957 MethodType targetType = target.type(); 5958 MethodType combinerType = combiner.type(); 5959 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 5960 BoundMethodHandle result = target.rebind(); 5961 5962 MethodType newType = targetType; 5963 LambdaForm lform; 5964 if (filter) { 5965 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 5966 } else { 5967 boolean dropResult = rtype == void.class; 5968 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 5969 if (!dropResult) { 5970 newType = newType.dropParameterTypes(position, position + 1); 5971 } 5972 } 5973 result = result.copyWithExtendL(newType, lform, combiner); 5974 return result; 5975 } 5976 5977 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 5978 int combinerArgs = combinerType.parameterCount(); 5979 if (argPos.length != combinerArgs) { 5980 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 5981 } 5982 Class<?> rtype = combinerType.returnType(); 5983 5984 for (int i = 0; i < combinerArgs; i++) { 5985 int arg = argPos[i]; 5986 if (arg < 0 || arg > targetType.parameterCount()) { 5987 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 5988 } 5989 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 5990 throw newIllegalArgumentException("target argument type at position " + arg 5991 + " must match combiner argument type at index " + i + ": " + targetType 5992 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 5993 } 5994 } 5995 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 5996 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5997 } 5998 return rtype; 5999 } 6000 6001 /** 6002 * Makes a method handle which adapts a target method handle, 6003 * by guarding it with a test, a boolean-valued method handle. 6004 * If the guard fails, a fallback handle is called instead. 6005 * All three method handles must have the same corresponding 6006 * argument and return types, except that the return type 6007 * of the test must be boolean, and the test is allowed 6008 * to have fewer arguments than the other two method handles. 6009 * <p> 6010 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6011 * represents the uniform result type of the three involved handles; 6012 * {@code A}/{@code a}, the types and values of the {@code target} 6013 * parameters and arguments that are consumed by the {@code test}; and 6014 * {@code B}/{@code b}, those types and values of the {@code target} 6015 * parameters and arguments that are not consumed by the {@code test}. 6016 * {@snippet lang="java" : 6017 * boolean test(A...); 6018 * T target(A...,B...); 6019 * T fallback(A...,B...); 6020 * T adapter(A... a,B... b) { 6021 * if (test(a...)) 6022 * return target(a..., b...); 6023 * else 6024 * return fallback(a..., b...); 6025 * } 6026 * } 6027 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6028 * be modified by execution of the test, and so are passed unchanged 6029 * from the caller to the target or fallback as appropriate. 6030 * @param test method handle used for test, must return boolean 6031 * @param target method handle to call if test passes 6032 * @param fallback method handle to call if test fails 6033 * @return method handle which incorporates the specified if/then/else logic 6034 * @throws NullPointerException if any argument is null 6035 * @throws IllegalArgumentException if {@code test} does not return boolean, 6036 * or if all three method types do not match (with the return 6037 * type of {@code test} changed to match that of the target). 6038 */ 6039 public static MethodHandle guardWithTest(MethodHandle test, 6040 MethodHandle target, 6041 MethodHandle fallback) { 6042 MethodType gtype = test.type(); 6043 MethodType ttype = target.type(); 6044 MethodType ftype = fallback.type(); 6045 if (!ttype.equals(ftype)) 6046 throw misMatchedTypes("target and fallback types", ttype, ftype); 6047 if (gtype.returnType() != boolean.class) 6048 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6049 6050 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6051 if (test == null) { 6052 throw misMatchedTypes("target and test types", ttype, gtype); 6053 } 6054 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6055 } 6056 6057 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6058 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6059 } 6060 6061 /** 6062 * Makes a method handle which adapts a target method handle, 6063 * by running it inside an exception handler. 6064 * If the target returns normally, the adapter returns that value. 6065 * If an exception matching the specified type is thrown, the fallback 6066 * handle is called instead on the exception, plus the original arguments. 6067 * <p> 6068 * The target and handler must have the same corresponding 6069 * argument and return types, except that handler may omit trailing arguments 6070 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6071 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6072 * <p> 6073 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6074 * represents the return type of the {@code target} and {@code handler}, 6075 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6076 * the types and values of arguments to the resulting handle consumed by 6077 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6078 * resulting handle discarded by {@code handler}. 6079 * {@snippet lang="java" : 6080 * T target(A..., B...); 6081 * T handler(ExType, A...); 6082 * T adapter(A... a, B... b) { 6083 * try { 6084 * return target(a..., b...); 6085 * } catch (ExType ex) { 6086 * return handler(ex, a...); 6087 * } 6088 * } 6089 * } 6090 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6091 * be modified by execution of the target, and so are passed unchanged 6092 * from the caller to the handler, if the handler is invoked. 6093 * <p> 6094 * The target and handler must return the same type, even if the handler 6095 * always throws. (This might happen, for instance, because the handler 6096 * is simulating a {@code finally} clause). 6097 * To create such a throwing handler, compose the handler creation logic 6098 * with {@link #throwException throwException}, 6099 * in order to create a method handle of the correct return type. 6100 * @param target method handle to call 6101 * @param exType the type of exception which the handler will catch 6102 * @param handler method handle to call if a matching exception is thrown 6103 * @return method handle which incorporates the specified try/catch logic 6104 * @throws NullPointerException if any argument is null 6105 * @throws IllegalArgumentException if {@code handler} does not accept 6106 * the given exception type, or if the method handle types do 6107 * not match in their return types and their 6108 * corresponding parameters 6109 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6110 */ 6111 public static MethodHandle catchException(MethodHandle target, 6112 Class<? extends Throwable> exType, 6113 MethodHandle handler) { 6114 MethodType ttype = target.type(); 6115 MethodType htype = handler.type(); 6116 if (!Throwable.class.isAssignableFrom(exType)) 6117 throw new ClassCastException(exType.getName()); 6118 if (htype.parameterCount() < 1 || 6119 !htype.parameterType(0).isAssignableFrom(exType)) 6120 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6121 if (htype.returnType() != ttype.returnType()) 6122 throw misMatchedTypes("target and handler return types", ttype, htype); 6123 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6124 if (handler == null) { 6125 throw misMatchedTypes("target and handler types", ttype, htype); 6126 } 6127 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6128 } 6129 6130 /** 6131 * Produces a method handle which will throw exceptions of the given {@code exType}. 6132 * The method handle will accept a single argument of {@code exType}, 6133 * and immediately throw it as an exception. 6134 * The method type will nominally specify a return of {@code returnType}. 6135 * The return type may be anything convenient: It doesn't matter to the 6136 * method handle's behavior, since it will never return normally. 6137 * @param returnType the return type of the desired method handle 6138 * @param exType the parameter type of the desired method handle 6139 * @return method handle which can throw the given exceptions 6140 * @throws NullPointerException if either argument is null 6141 */ 6142 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6143 if (!Throwable.class.isAssignableFrom(exType)) 6144 throw new ClassCastException(exType.getName()); 6145 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6146 } 6147 6148 /** 6149 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6150 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6151 * delivers the loop's result, which is the return value of the resulting handle. 6152 * <p> 6153 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6154 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6155 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6156 * terms of method handles, each clause will specify up to four independent actions:<ul> 6157 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6158 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6159 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6160 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6161 * </ul> 6162 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6163 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6164 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6165 * <p> 6166 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6167 * this case. See below for a detailed description. 6168 * <p> 6169 * <em>Parameters optional everywhere:</em> 6170 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6171 * As an exception, the init functions cannot take any {@code v} parameters, 6172 * because those values are not yet computed when the init functions are executed. 6173 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6174 * In fact, any clause function may take no arguments at all. 6175 * <p> 6176 * <em>Loop parameters:</em> 6177 * A clause function may take all the iteration variable values it is entitled to, in which case 6178 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6179 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6180 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6181 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6182 * init function is automatically a loop parameter {@code a}.) 6183 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6184 * These loop parameters act as loop-invariant values visible across the whole loop. 6185 * <p> 6186 * <em>Parameters visible everywhere:</em> 6187 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6188 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6189 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6190 * Most clause functions will not need all of this information, but they will be formally connected to it 6191 * as if by {@link #dropArguments}. 6192 * <a id="astar"></a> 6193 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6194 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6195 * In that notation, the general form of an init function parameter list 6196 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6197 * <p> 6198 * <em>Checking clause structure:</em> 6199 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6200 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6201 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6202 * met by the inputs to the loop combinator. 6203 * <p> 6204 * <em>Effectively identical sequences:</em> 6205 * <a id="effid"></a> 6206 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6207 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6208 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6209 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6210 * that longest list. 6211 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6212 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6213 * <p> 6214 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6215 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6216 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6217 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6218 * four. Padding takes place by appending elements to the array. 6219 * <li>Clauses with all {@code null}s are disregarded. 6220 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6221 * </ol> 6222 * <p> 6223 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6224 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6225 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6226 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6227 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6228 * iteration variable type. 6229 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6230 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6231 * </ol> 6232 * <p> 6233 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6234 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6235 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6236 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6237 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6238 * (These types will be checked in step 2, along with all the clause function types.) 6239 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6240 * <li>All of the collected parameter lists must be effectively identical. 6241 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6242 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6243 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6244 * the "internal parameter list". 6245 * </ul> 6246 * <p> 6247 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6248 * <li>Examine fini function return types, disregarding omitted fini functions. 6249 * <li>If there are no fini functions, the loop return type is {@code void}. 6250 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6251 * type. 6252 * </ol> 6253 * <p> 6254 * <em>Step 1D: Check other types.</em><ol type="a"> 6255 * <li>There must be at least one non-omitted pred function. 6256 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6257 * </ol> 6258 * <p> 6259 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6260 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6261 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6262 * (Note that their parameter lists are already effectively identical to this list.) 6263 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6264 * effectively identical to the internal parameter list {@code (V... A...)}. 6265 * </ol> 6266 * <p> 6267 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6268 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6269 * type. 6270 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6271 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6272 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6273 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6274 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6275 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6276 * loop return type. 6277 * </ol> 6278 * <p> 6279 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6280 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6281 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6282 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6283 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6284 * pad out the end of the list. 6285 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6286 * </ol> 6287 * <p> 6288 * <em>Final observations.</em><ol type="a"> 6289 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6290 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6291 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6292 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6293 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6294 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6295 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6296 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6297 * </ol> 6298 * <p> 6299 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6300 * <ul> 6301 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6302 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6303 * (Only one {@code Pn} has to be non-{@code null}.) 6304 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6305 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6306 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6307 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6308 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6309 * the resulting loop handle's parameter types {@code (A...)}. 6310 * </ul> 6311 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6312 * which is natural if most of the loop computation happens in the steps. For some loops, 6313 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6314 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6315 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6316 * where the init functions will need the extra parameters. For such reasons, the rules for 6317 * determining these parameters are as symmetric as possible, across all clause parts. 6318 * In general, the loop parameters function as common invariant values across the whole 6319 * loop, while the iteration variables function as common variant values, or (if there is 6320 * no step function) as internal loop invariant temporaries. 6321 * <p> 6322 * <em>Loop execution.</em><ol type="a"> 6323 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6324 * every clause function. These locals are loop invariant. 6325 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6326 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6327 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6328 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6329 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6330 * (in argument order). 6331 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6332 * returns {@code false}. 6333 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6334 * sequence {@code (v...)} of loop variables. 6335 * The updated value is immediately visible to all subsequent function calls. 6336 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6337 * (of type {@code R}) is returned from the loop as a whole. 6338 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6339 * except by throwing an exception. 6340 * </ol> 6341 * <p> 6342 * <em>Usage tips.</em> 6343 * <ul> 6344 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6345 * sometimes a step function only needs to observe the current value of its own variable. 6346 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6347 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6348 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6349 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6350 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6351 * <li>If some of the clause functions are virtual methods on an instance, the instance 6352 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6353 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6354 * will be the first iteration variable value, and it will be easy to use virtual 6355 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6356 * </ul> 6357 * <p> 6358 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6359 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6360 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6361 * {@snippet lang="java" : 6362 * V... init...(A...); 6363 * boolean pred...(V..., A...); 6364 * V... step...(V..., A...); 6365 * R fini...(V..., A...); 6366 * R loop(A... a) { 6367 * V... v... = init...(a...); 6368 * for (;;) { 6369 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6370 * v = s(v..., a...); 6371 * if (!p(v..., a...)) { 6372 * return f(v..., a...); 6373 * } 6374 * } 6375 * } 6376 * } 6377 * } 6378 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6379 * to their full length, even though individual clause functions may neglect to take them all. 6380 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6381 * 6382 * @apiNote Example: 6383 * {@snippet lang="java" : 6384 * // iterative implementation of the factorial function as a loop handle 6385 * static int one(int k) { return 1; } 6386 * static int inc(int i, int acc, int k) { return i + 1; } 6387 * static int mult(int i, int acc, int k) { return i * acc; } 6388 * static boolean pred(int i, int acc, int k) { return i < k; } 6389 * static int fin(int i, int acc, int k) { return acc; } 6390 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6391 * // null initializer for counter, should initialize to 0 6392 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6393 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6394 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6395 * assertEquals(120, loop.invoke(5)); 6396 * } 6397 * The same example, dropping arguments and using combinators: 6398 * {@snippet lang="java" : 6399 * // simplified implementation of the factorial function as a loop handle 6400 * static int inc(int i) { return i + 1; } // drop acc, k 6401 * static int mult(int i, int acc) { return i * acc; } //drop k 6402 * static boolean cmp(int i, int k) { return i < k; } 6403 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6404 * // null initializer for counter, should initialize to 0 6405 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6406 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6407 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6408 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6409 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6410 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6411 * assertEquals(720, loop.invoke(6)); 6412 * } 6413 * A similar example, using a helper object to hold a loop parameter: 6414 * {@snippet lang="java" : 6415 * // instance-based implementation of the factorial function as a loop handle 6416 * static class FacLoop { 6417 * final int k; 6418 * FacLoop(int k) { this.k = k; } 6419 * int inc(int i) { return i + 1; } 6420 * int mult(int i, int acc) { return i * acc; } 6421 * boolean pred(int i) { return i < k; } 6422 * int fin(int i, int acc) { return acc; } 6423 * } 6424 * // assume MH_FacLoop is a handle to the constructor 6425 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6426 * // null initializer for counter, should initialize to 0 6427 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6428 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6429 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6430 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6431 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6432 * assertEquals(5040, loop.invoke(7)); 6433 * } 6434 * 6435 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6436 * 6437 * @return a method handle embodying the looping behavior as defined by the arguments. 6438 * 6439 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6440 * 6441 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6442 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6443 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6444 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6445 * @since 9 6446 */ 6447 public static MethodHandle loop(MethodHandle[]... clauses) { 6448 // Step 0: determine clause structure. 6449 loopChecks0(clauses); 6450 6451 List<MethodHandle> init = new ArrayList<>(); 6452 List<MethodHandle> step = new ArrayList<>(); 6453 List<MethodHandle> pred = new ArrayList<>(); 6454 List<MethodHandle> fini = new ArrayList<>(); 6455 6456 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6457 init.add(clause[0]); // all clauses have at least length 1 6458 step.add(clause.length <= 1 ? null : clause[1]); 6459 pred.add(clause.length <= 2 ? null : clause[2]); 6460 fini.add(clause.length <= 3 ? null : clause[3]); 6461 }); 6462 6463 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6464 final int nclauses = init.size(); 6465 6466 // Step 1A: determine iteration variables (V...). 6467 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6468 for (int i = 0; i < nclauses; ++i) { 6469 MethodHandle in = init.get(i); 6470 MethodHandle st = step.get(i); 6471 if (in == null && st == null) { 6472 iterationVariableTypes.add(void.class); 6473 } else if (in != null && st != null) { 6474 loopChecks1a(i, in, st); 6475 iterationVariableTypes.add(in.type().returnType()); 6476 } else { 6477 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6478 } 6479 } 6480 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6481 6482 // Step 1B: determine loop parameters (A...). 6483 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6484 loopChecks1b(init, commonSuffix); 6485 6486 // Step 1C: determine loop return type. 6487 // Step 1D: check other types. 6488 // local variable required here; see JDK-8223553 6489 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6490 .map(MethodType::returnType); 6491 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6492 loopChecks1cd(pred, fini, loopReturnType); 6493 6494 // Step 2: determine parameter lists. 6495 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6496 commonParameterSequence.addAll(commonSuffix); 6497 loopChecks2(step, pred, fini, commonParameterSequence); 6498 // Step 3: fill in omitted functions. 6499 for (int i = 0; i < nclauses; ++i) { 6500 Class<?> t = iterationVariableTypes.get(i); 6501 if (init.get(i) == null) { 6502 init.set(i, empty(methodType(t, commonSuffix))); 6503 } 6504 if (step.get(i) == null) { 6505 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6506 } 6507 if (pred.get(i) == null) { 6508 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6509 } 6510 if (fini.get(i) == null) { 6511 fini.set(i, empty(methodType(t, commonParameterSequence))); 6512 } 6513 } 6514 6515 // Step 4: fill in missing parameter types. 6516 // Also convert all handles to fixed-arity handles. 6517 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6518 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6519 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6520 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6521 6522 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6523 allMatch(pl -> pl.equals(commonSuffix)); 6524 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6525 allMatch(pl -> pl.equals(commonParameterSequence)); 6526 6527 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6528 } 6529 6530 private static void loopChecks0(MethodHandle[][] clauses) { 6531 if (clauses == null || clauses.length == 0) { 6532 throw newIllegalArgumentException("null or no clauses passed"); 6533 } 6534 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6535 throw newIllegalArgumentException("null clauses are not allowed"); 6536 } 6537 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6538 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6539 } 6540 } 6541 6542 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6543 if (in.type().returnType() != st.type().returnType()) { 6544 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6545 st.type().returnType()); 6546 } 6547 } 6548 6549 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6550 return mhs.filter(Objects::nonNull) 6551 // take only those that can contribute to a common suffix because they are longer than the prefix 6552 .map(MethodHandle::type) 6553 .filter(t -> t.parameterCount() > skipSize) 6554 .max(Comparator.comparingInt(MethodType::parameterCount)) 6555 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6556 .orElse(List.of()); 6557 } 6558 6559 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6560 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6561 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6562 return longest1.size() >= longest2.size() ? longest1 : longest2; 6563 } 6564 6565 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6566 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6567 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6568 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6569 " (common suffix: " + commonSuffix + ")"); 6570 } 6571 } 6572 6573 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6574 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6575 anyMatch(t -> t != loopReturnType)) { 6576 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6577 loopReturnType + ")"); 6578 } 6579 6580 if (pred.stream().noneMatch(Objects::nonNull)) { 6581 throw newIllegalArgumentException("no predicate found", pred); 6582 } 6583 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6584 anyMatch(t -> t != boolean.class)) { 6585 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6586 } 6587 } 6588 6589 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6590 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6591 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6592 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6593 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6594 } 6595 } 6596 6597 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6598 return hs.stream().map(h -> { 6599 int pc = h.type().parameterCount(); 6600 int tpsize = targetParams.size(); 6601 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6602 }).toList(); 6603 } 6604 6605 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6606 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6607 } 6608 6609 /** 6610 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6611 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6612 * <p> 6613 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6614 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6615 * evaluates to {@code true}). 6616 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6617 * <p> 6618 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6619 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6620 * and updated with the value returned from its invocation. The result of loop execution will be 6621 * the final value of the additional loop-local variable (if present). 6622 * <p> 6623 * The following rules hold for these argument handles:<ul> 6624 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6625 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6626 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6627 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6628 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6629 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6630 * It will constrain the parameter lists of the other loop parts. 6631 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6632 * list {@code (A...)} is called the <em>external parameter list</em>. 6633 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6634 * additional state variable of the loop. 6635 * The body must both accept and return a value of this type {@code V}. 6636 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6637 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6638 * <a href="MethodHandles.html#effid">effectively identical</a> 6639 * to the external parameter list {@code (A...)}. 6640 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6641 * {@linkplain #empty default value}. 6642 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6643 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6644 * effectively identical to the internal parameter list. 6645 * </ul> 6646 * <p> 6647 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6648 * <li>The loop handle's result type is the result type {@code V} of the body. 6649 * <li>The loop handle's parameter types are the types {@code (A...)}, 6650 * from the external parameter list. 6651 * </ul> 6652 * <p> 6653 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6654 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6655 * passed to the loop. 6656 * {@snippet lang="java" : 6657 * V init(A...); 6658 * boolean pred(V, A...); 6659 * V body(V, A...); 6660 * V whileLoop(A... a...) { 6661 * V v = init(a...); 6662 * while (pred(v, a...)) { 6663 * v = body(v, a...); 6664 * } 6665 * return v; 6666 * } 6667 * } 6668 * 6669 * @apiNote Example: 6670 * {@snippet lang="java" : 6671 * // implement the zip function for lists as a loop handle 6672 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6673 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6674 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6675 * zip.add(a.next()); 6676 * zip.add(b.next()); 6677 * return zip; 6678 * } 6679 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6680 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6681 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6682 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6683 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6684 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6685 * } 6686 * 6687 * 6688 * @apiNote The implementation of this method can be expressed as follows: 6689 * {@snippet lang="java" : 6690 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6691 * MethodHandle fini = (body.type().returnType() == void.class 6692 * ? null : identity(body.type().returnType())); 6693 * MethodHandle[] 6694 * checkExit = { null, null, pred, fini }, 6695 * varBody = { init, body }; 6696 * return loop(checkExit, varBody); 6697 * } 6698 * } 6699 * 6700 * @param init optional initializer, providing the initial value of the loop variable. 6701 * May be {@code null}, implying a default initial value. See above for other constraints. 6702 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6703 * above for other constraints. 6704 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6705 * See above for other constraints. 6706 * 6707 * @return a method handle implementing the {@code while} loop as described by the arguments. 6708 * @throws IllegalArgumentException if the rules for the arguments are violated. 6709 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6710 * 6711 * @see #loop(MethodHandle[][]) 6712 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6713 * @since 9 6714 */ 6715 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6716 whileLoopChecks(init, pred, body); 6717 MethodHandle fini = identityOrVoid(body.type().returnType()); 6718 MethodHandle[] checkExit = { null, null, pred, fini }; 6719 MethodHandle[] varBody = { init, body }; 6720 return loop(checkExit, varBody); 6721 } 6722 6723 /** 6724 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6725 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6726 * <p> 6727 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6728 * method will, in each iteration, first execute its body and then evaluate the predicate. 6729 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6730 * <p> 6731 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6732 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6733 * and updated with the value returned from its invocation. The result of loop execution will be 6734 * the final value of the additional loop-local variable (if present). 6735 * <p> 6736 * The following rules hold for these argument handles:<ul> 6737 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6738 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6739 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6740 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6741 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6742 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6743 * It will constrain the parameter lists of the other loop parts. 6744 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6745 * list {@code (A...)} is called the <em>external parameter list</em>. 6746 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6747 * additional state variable of the loop. 6748 * The body must both accept and return a value of this type {@code V}. 6749 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6750 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6751 * <a href="MethodHandles.html#effid">effectively identical</a> 6752 * to the external parameter list {@code (A...)}. 6753 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6754 * {@linkplain #empty default value}. 6755 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6756 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6757 * effectively identical to the internal parameter list. 6758 * </ul> 6759 * <p> 6760 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6761 * <li>The loop handle's result type is the result type {@code V} of the body. 6762 * <li>The loop handle's parameter types are the types {@code (A...)}, 6763 * from the external parameter list. 6764 * </ul> 6765 * <p> 6766 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6767 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6768 * passed to the loop. 6769 * {@snippet lang="java" : 6770 * V init(A...); 6771 * boolean pred(V, A...); 6772 * V body(V, A...); 6773 * V doWhileLoop(A... a...) { 6774 * V v = init(a...); 6775 * do { 6776 * v = body(v, a...); 6777 * } while (pred(v, a...)); 6778 * return v; 6779 * } 6780 * } 6781 * 6782 * @apiNote Example: 6783 * {@snippet lang="java" : 6784 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6785 * static int zero(int limit) { return 0; } 6786 * static int step(int i, int limit) { return i + 1; } 6787 * static boolean pred(int i, int limit) { return i < limit; } 6788 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6789 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6790 * assertEquals(23, loop.invoke(23)); 6791 * } 6792 * 6793 * 6794 * @apiNote The implementation of this method can be expressed as follows: 6795 * {@snippet lang="java" : 6796 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6797 * MethodHandle fini = (body.type().returnType() == void.class 6798 * ? null : identity(body.type().returnType())); 6799 * MethodHandle[] clause = { init, body, pred, fini }; 6800 * return loop(clause); 6801 * } 6802 * } 6803 * 6804 * @param init optional initializer, providing the initial value of the loop variable. 6805 * May be {@code null}, implying a default initial value. See above for other constraints. 6806 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6807 * See above for other constraints. 6808 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6809 * above for other constraints. 6810 * 6811 * @return a method handle implementing the {@code while} loop as described by the arguments. 6812 * @throws IllegalArgumentException if the rules for the arguments are violated. 6813 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6814 * 6815 * @see #loop(MethodHandle[][]) 6816 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 6817 * @since 9 6818 */ 6819 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6820 whileLoopChecks(init, pred, body); 6821 MethodHandle fini = identityOrVoid(body.type().returnType()); 6822 MethodHandle[] clause = {init, body, pred, fini }; 6823 return loop(clause); 6824 } 6825 6826 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 6827 Objects.requireNonNull(pred); 6828 Objects.requireNonNull(body); 6829 MethodType bodyType = body.type(); 6830 Class<?> returnType = bodyType.returnType(); 6831 List<Class<?>> innerList = bodyType.parameterList(); 6832 List<Class<?>> outerList = innerList; 6833 if (returnType == void.class) { 6834 // OK 6835 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 6836 // leading V argument missing => error 6837 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6838 throw misMatchedTypes("body function", bodyType, expected); 6839 } else { 6840 outerList = innerList.subList(1, innerList.size()); 6841 } 6842 MethodType predType = pred.type(); 6843 if (predType.returnType() != boolean.class || 6844 !predType.effectivelyIdenticalParameters(0, innerList)) { 6845 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 6846 } 6847 if (init != null) { 6848 MethodType initType = init.type(); 6849 if (initType.returnType() != returnType || 6850 !initType.effectivelyIdenticalParameters(0, outerList)) { 6851 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6852 } 6853 } 6854 } 6855 6856 /** 6857 * Constructs a loop that runs a given number of iterations. 6858 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6859 * <p> 6860 * The number of iterations is determined by the {@code iterations} handle evaluation result. 6861 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 6862 * It will be initialized to 0 and incremented by 1 in each iteration. 6863 * <p> 6864 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6865 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6866 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6867 * <p> 6868 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6869 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6870 * iteration variable. 6871 * The result of the loop handle execution will be the final {@code V} value of that variable 6872 * (or {@code void} if there is no {@code V} variable). 6873 * <p> 6874 * The following rules hold for the argument handles:<ul> 6875 * <li>The {@code iterations} handle must not be {@code null}, and must return 6876 * the type {@code int}, referred to here as {@code I} in parameter type lists. 6877 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6878 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6879 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6880 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6881 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6882 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6883 * of types called the <em>internal parameter list</em>. 6884 * It will constrain the parameter lists of the other loop parts. 6885 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6886 * with no additional {@code A} types, then the internal parameter list is extended by 6887 * the argument types {@code A...} of the {@code iterations} handle. 6888 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6889 * list {@code (A...)} is called the <em>external parameter list</em>. 6890 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6891 * additional state variable of the loop. 6892 * The body must both accept a leading parameter and return a value of this type {@code V}. 6893 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6894 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6895 * <a href="MethodHandles.html#effid">effectively identical</a> 6896 * to the external parameter list {@code (A...)}. 6897 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6898 * {@linkplain #empty default value}. 6899 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 6900 * effectively identical to the external parameter list {@code (A...)}. 6901 * </ul> 6902 * <p> 6903 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6904 * <li>The loop handle's result type is the result type {@code V} of the body. 6905 * <li>The loop handle's parameter types are the types {@code (A...)}, 6906 * from the external parameter list. 6907 * </ul> 6908 * <p> 6909 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6910 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6911 * arguments passed to the loop. 6912 * {@snippet lang="java" : 6913 * int iterations(A...); 6914 * V init(A...); 6915 * V body(V, int, A...); 6916 * V countedLoop(A... a...) { 6917 * int end = iterations(a...); 6918 * V v = init(a...); 6919 * for (int i = 0; i < end; ++i) { 6920 * v = body(v, i, a...); 6921 * } 6922 * return v; 6923 * } 6924 * } 6925 * 6926 * @apiNote Example with a fully conformant body method: 6927 * {@snippet lang="java" : 6928 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6929 * // => a variation on a well known theme 6930 * static String step(String v, int counter, String init) { return "na " + v; } 6931 * // assume MH_step is a handle to the method above 6932 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 6933 * MethodHandle start = MethodHandles.identity(String.class); 6934 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 6935 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 6936 * } 6937 * 6938 * @apiNote Example with the simplest possible body method type, 6939 * and passing the number of iterations to the loop invocation: 6940 * {@snippet lang="java" : 6941 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6942 * // => a variation on a well known theme 6943 * static String step(String v, int counter ) { return "na " + v; } 6944 * // assume MH_step is a handle to the method above 6945 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 6946 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 6947 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 6948 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 6949 * } 6950 * 6951 * @apiNote Example that treats the number of iterations, string to append to, and string to append 6952 * as loop parameters: 6953 * {@snippet lang="java" : 6954 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6955 * // => a variation on a well known theme 6956 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 6957 * // assume MH_step is a handle to the method above 6958 * MethodHandle count = MethodHandles.identity(int.class); 6959 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 6960 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 6961 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 6962 * } 6963 * 6964 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 6965 * to enforce a loop type: 6966 * {@snippet lang="java" : 6967 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6968 * // => a variation on a well known theme 6969 * static String step(String v, int counter, String pre) { return pre + " " + v; } 6970 * // assume MH_step is a handle to the method above 6971 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 6972 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 6973 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 6974 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 6975 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 6976 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 6977 * } 6978 * 6979 * @apiNote The implementation of this method can be expressed as follows: 6980 * {@snippet lang="java" : 6981 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6982 * return countedLoop(empty(iterations.type()), iterations, init, body); 6983 * } 6984 * } 6985 * 6986 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 6987 * result type must be {@code int}. See above for other constraints. 6988 * @param init optional initializer, providing the initial value of the loop variable. 6989 * May be {@code null}, implying a default initial value. See above for other constraints. 6990 * @param body body of the loop, which may not be {@code null}. 6991 * It controls the loop parameters and result type in the standard case (see above for details). 6992 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6993 * and may accept any number of additional types. 6994 * See above for other constraints. 6995 * 6996 * @return a method handle representing the loop. 6997 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 6998 * @throws IllegalArgumentException if any argument violates the rules formulated above. 6999 * 7000 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 7001 * @since 9 7002 */ 7003 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 7004 return countedLoop(empty(iterations.type()), iterations, init, body); 7005 } 7006 7007 /** 7008 * Constructs a loop that counts over a range of numbers. 7009 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7010 * <p> 7011 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7012 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7013 * values of the loop counter. 7014 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7015 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7016 * <p> 7017 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7018 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7019 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7020 * <p> 7021 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7022 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7023 * iteration variable. 7024 * The result of the loop handle execution will be the final {@code V} value of that variable 7025 * (or {@code void} if there is no {@code V} variable). 7026 * <p> 7027 * The following rules hold for the argument handles:<ul> 7028 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7029 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7030 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7031 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7032 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7033 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7034 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7035 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7036 * of types called the <em>internal parameter list</em>. 7037 * It will constrain the parameter lists of the other loop parts. 7038 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7039 * with no additional {@code A} types, then the internal parameter list is extended by 7040 * the argument types {@code A...} of the {@code end} handle. 7041 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7042 * list {@code (A...)} is called the <em>external parameter list</em>. 7043 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7044 * additional state variable of the loop. 7045 * The body must both accept a leading parameter and return a value of this type {@code V}. 7046 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7047 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7048 * <a href="MethodHandles.html#effid">effectively identical</a> 7049 * to the external parameter list {@code (A...)}. 7050 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7051 * {@linkplain #empty default value}. 7052 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7053 * effectively identical to the external parameter list {@code (A...)}. 7054 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7055 * to the external parameter list. 7056 * </ul> 7057 * <p> 7058 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7059 * <li>The loop handle's result type is the result type {@code V} of the body. 7060 * <li>The loop handle's parameter types are the types {@code (A...)}, 7061 * from the external parameter list. 7062 * </ul> 7063 * <p> 7064 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7065 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7066 * arguments passed to the loop. 7067 * {@snippet lang="java" : 7068 * int start(A...); 7069 * int end(A...); 7070 * V init(A...); 7071 * V body(V, int, A...); 7072 * V countedLoop(A... a...) { 7073 * int e = end(a...); 7074 * int s = start(a...); 7075 * V v = init(a...); 7076 * for (int i = s; i < e; ++i) { 7077 * v = body(v, i, a...); 7078 * } 7079 * return v; 7080 * } 7081 * } 7082 * 7083 * @apiNote The implementation of this method can be expressed as follows: 7084 * {@snippet lang="java" : 7085 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7086 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7087 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7088 * // the following semantics: 7089 * // MH_increment: (int limit, int counter) -> counter + 1 7090 * // MH_predicate: (int limit, int counter) -> counter < limit 7091 * Class<?> counterType = start.type().returnType(); // int 7092 * Class<?> returnType = body.type().returnType(); 7093 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7094 * if (returnType != void.class) { // ignore the V variable 7095 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7096 * pred = dropArguments(pred, 1, returnType); // ditto 7097 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7098 * } 7099 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7100 * MethodHandle[] 7101 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7102 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7103 * indexVar = { start, incr }; // i = start(); i = i + 1 7104 * return loop(loopLimit, bodyClause, indexVar); 7105 * } 7106 * } 7107 * 7108 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7109 * See above for other constraints. 7110 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7111 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7112 * @param init optional initializer, providing the initial value of the loop variable. 7113 * May be {@code null}, implying a default initial value. See above for other constraints. 7114 * @param body body of the loop, which may not be {@code null}. 7115 * It controls the loop parameters and result type in the standard case (see above for details). 7116 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7117 * and may accept any number of additional types. 7118 * See above for other constraints. 7119 * 7120 * @return a method handle representing the loop. 7121 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7122 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7123 * 7124 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7125 * @since 9 7126 */ 7127 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7128 countedLoopChecks(start, end, init, body); 7129 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7130 Class<?> limitType = end.type().returnType(); // yes, int again 7131 Class<?> returnType = body.type().returnType(); 7132 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7133 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7134 MethodHandle retv = null; 7135 if (returnType != void.class) { 7136 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7137 pred = dropArguments(pred, 1, returnType); // ditto 7138 retv = dropArguments(identity(returnType), 0, counterType); 7139 } 7140 body = dropArguments(body, 0, counterType); // ignore the limit variable 7141 MethodHandle[] 7142 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7143 bodyClause = { init, body }, // v = init(); v = body(v, i) 7144 indexVar = { start, incr }; // i = start(); i = i + 1 7145 return loop(loopLimit, bodyClause, indexVar); 7146 } 7147 7148 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7149 Objects.requireNonNull(start); 7150 Objects.requireNonNull(end); 7151 Objects.requireNonNull(body); 7152 Class<?> counterType = start.type().returnType(); 7153 if (counterType != int.class) { 7154 MethodType expected = start.type().changeReturnType(int.class); 7155 throw misMatchedTypes("start function", start.type(), expected); 7156 } else if (end.type().returnType() != counterType) { 7157 MethodType expected = end.type().changeReturnType(counterType); 7158 throw misMatchedTypes("end function", end.type(), expected); 7159 } 7160 MethodType bodyType = body.type(); 7161 Class<?> returnType = bodyType.returnType(); 7162 List<Class<?>> innerList = bodyType.parameterList(); 7163 // strip leading V value if present 7164 int vsize = (returnType == void.class ? 0 : 1); 7165 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7166 // argument list has no "V" => error 7167 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7168 throw misMatchedTypes("body function", bodyType, expected); 7169 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7170 // missing I type => error 7171 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7172 throw misMatchedTypes("body function", bodyType, expected); 7173 } 7174 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7175 if (outerList.isEmpty()) { 7176 // special case; take lists from end handle 7177 outerList = end.type().parameterList(); 7178 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7179 } 7180 MethodType expected = methodType(counterType, outerList); 7181 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7182 throw misMatchedTypes("start parameter types", start.type(), expected); 7183 } 7184 if (end.type() != start.type() && 7185 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7186 throw misMatchedTypes("end parameter types", end.type(), expected); 7187 } 7188 if (init != null) { 7189 MethodType initType = init.type(); 7190 if (initType.returnType() != returnType || 7191 !initType.effectivelyIdenticalParameters(0, outerList)) { 7192 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7193 } 7194 } 7195 } 7196 7197 /** 7198 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7199 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7200 * <p> 7201 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7202 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7203 * <p> 7204 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7205 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7206 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7207 * <p> 7208 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7209 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7210 * iteration variable. 7211 * The result of the loop handle execution will be the final {@code V} value of that variable 7212 * (or {@code void} if there is no {@code V} variable). 7213 * <p> 7214 * The following rules hold for the argument handles:<ul> 7215 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7216 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7217 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7218 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7219 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7220 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7221 * of types called the <em>internal parameter list</em>. 7222 * It will constrain the parameter lists of the other loop parts. 7223 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7224 * with no additional {@code A} types, then the internal parameter list is extended by 7225 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7226 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7227 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7228 * list {@code (A...)} is called the <em>external parameter list</em>. 7229 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7230 * additional state variable of the loop. 7231 * The body must both accept a leading parameter and return a value of this type {@code V}. 7232 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7233 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7234 * <a href="MethodHandles.html#effid">effectively identical</a> 7235 * to the external parameter list {@code (A...)}. 7236 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7237 * {@linkplain #empty default value}. 7238 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7239 * type {@code java.util.Iterator} or a subtype thereof. 7240 * The iterator it produces when the loop is executed will be assumed 7241 * to yield values which can be converted to type {@code T}. 7242 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7243 * effectively identical to the external parameter list {@code (A...)}. 7244 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7245 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7246 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7247 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7248 * the {@link MethodHandle#asType asType} conversion method. 7249 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7250 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7251 * </ul> 7252 * <p> 7253 * The type {@code T} may be either a primitive or reference. 7254 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7255 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7256 * as if by the {@link MethodHandle#asType asType} conversion method. 7257 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7258 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7259 * <p> 7260 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7261 * <li>The loop handle's result type is the result type {@code V} of the body. 7262 * <li>The loop handle's parameter types are the types {@code (A...)}, 7263 * from the external parameter list. 7264 * </ul> 7265 * <p> 7266 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7267 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7268 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7269 * {@snippet lang="java" : 7270 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7271 * V init(A...); 7272 * V body(V,T,A...); 7273 * V iteratedLoop(A... a...) { 7274 * Iterator<T> it = iterator(a...); 7275 * V v = init(a...); 7276 * while (it.hasNext()) { 7277 * T t = it.next(); 7278 * v = body(v, t, a...); 7279 * } 7280 * return v; 7281 * } 7282 * } 7283 * 7284 * @apiNote Example: 7285 * {@snippet lang="java" : 7286 * // get an iterator from a list 7287 * static List<String> reverseStep(List<String> r, String e) { 7288 * r.add(0, e); 7289 * return r; 7290 * } 7291 * static List<String> newArrayList() { return new ArrayList<>(); } 7292 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7293 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7294 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7295 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7296 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7297 * } 7298 * 7299 * @apiNote The implementation of this method can be expressed approximately as follows: 7300 * {@snippet lang="java" : 7301 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7302 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7303 * Class<?> returnType = body.type().returnType(); 7304 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7305 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7306 * MethodHandle retv = null, step = body, startIter = iterator; 7307 * if (returnType != void.class) { 7308 * // the simple thing first: in (I V A...), drop the I to get V 7309 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7310 * // body type signature (V T A...), internal loop types (I V A...) 7311 * step = swapArguments(body, 0, 1); // swap V <-> T 7312 * } 7313 * if (startIter == null) startIter = MH_getIter; 7314 * MethodHandle[] 7315 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7316 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7317 * return loop(iterVar, bodyClause); 7318 * } 7319 * } 7320 * 7321 * @param iterator an optional handle to return the iterator to start the loop. 7322 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7323 * See above for other constraints. 7324 * @param init optional initializer, providing the initial value of the loop variable. 7325 * May be {@code null}, implying a default initial value. See above for other constraints. 7326 * @param body body of the loop, which may not be {@code null}. 7327 * It controls the loop parameters and result type in the standard case (see above for details). 7328 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7329 * and may accept any number of additional types. 7330 * See above for other constraints. 7331 * 7332 * @return a method handle embodying the iteration loop functionality. 7333 * @throws NullPointerException if the {@code body} handle is {@code null}. 7334 * @throws IllegalArgumentException if any argument violates the above requirements. 7335 * 7336 * @since 9 7337 */ 7338 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7339 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7340 Class<?> returnType = body.type().returnType(); 7341 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7342 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7343 MethodHandle startIter; 7344 MethodHandle nextVal; 7345 { 7346 MethodType iteratorType; 7347 if (iterator == null) { 7348 // derive argument type from body, if available, else use Iterable 7349 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7350 iteratorType = startIter.type().changeParameterType(0, iterableType); 7351 } else { 7352 // force return type to the internal iterator class 7353 iteratorType = iterator.type().changeReturnType(Iterator.class); 7354 startIter = iterator; 7355 } 7356 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7357 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7358 7359 // perform the asType transforms under an exception transformer, as per spec.: 7360 try { 7361 startIter = startIter.asType(iteratorType); 7362 nextVal = nextRaw.asType(nextValType); 7363 } catch (WrongMethodTypeException ex) { 7364 throw new IllegalArgumentException(ex); 7365 } 7366 } 7367 7368 MethodHandle retv = null, step = body; 7369 if (returnType != void.class) { 7370 // the simple thing first: in (I V A...), drop the I to get V 7371 retv = dropArguments(identity(returnType), 0, Iterator.class); 7372 // body type signature (V T A...), internal loop types (I V A...) 7373 step = swapArguments(body, 0, 1); // swap V <-> T 7374 } 7375 7376 MethodHandle[] 7377 iterVar = { startIter, null, hasNext, retv }, 7378 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7379 return loop(iterVar, bodyClause); 7380 } 7381 7382 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7383 Objects.requireNonNull(body); 7384 MethodType bodyType = body.type(); 7385 Class<?> returnType = bodyType.returnType(); 7386 List<Class<?>> internalParamList = bodyType.parameterList(); 7387 // strip leading V value if present 7388 int vsize = (returnType == void.class ? 0 : 1); 7389 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7390 // argument list has no "V" => error 7391 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7392 throw misMatchedTypes("body function", bodyType, expected); 7393 } else if (internalParamList.size() <= vsize) { 7394 // missing T type => error 7395 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7396 throw misMatchedTypes("body function", bodyType, expected); 7397 } 7398 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7399 Class<?> iterableType = null; 7400 if (iterator != null) { 7401 // special case; if the body handle only declares V and T then 7402 // the external parameter list is obtained from iterator handle 7403 if (externalParamList.isEmpty()) { 7404 externalParamList = iterator.type().parameterList(); 7405 } 7406 MethodType itype = iterator.type(); 7407 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7408 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7409 } 7410 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7411 MethodType expected = methodType(itype.returnType(), externalParamList); 7412 throw misMatchedTypes("iterator parameters", itype, expected); 7413 } 7414 } else { 7415 if (externalParamList.isEmpty()) { 7416 // special case; if the iterator handle is null and the body handle 7417 // only declares V and T then the external parameter list consists 7418 // of Iterable 7419 externalParamList = List.of(Iterable.class); 7420 iterableType = Iterable.class; 7421 } else { 7422 // special case; if the iterator handle is null and the external 7423 // parameter list is not empty then the first parameter must be 7424 // assignable to Iterable 7425 iterableType = externalParamList.get(0); 7426 if (!Iterable.class.isAssignableFrom(iterableType)) { 7427 throw newIllegalArgumentException( 7428 "inferred first loop argument must inherit from Iterable: " + iterableType); 7429 } 7430 } 7431 } 7432 if (init != null) { 7433 MethodType initType = init.type(); 7434 if (initType.returnType() != returnType || 7435 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7436 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7437 } 7438 } 7439 return iterableType; // help the caller a bit 7440 } 7441 7442 /*non-public*/ 7443 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7444 // there should be a better way to uncross my wires 7445 int arity = mh.type().parameterCount(); 7446 int[] order = new int[arity]; 7447 for (int k = 0; k < arity; k++) order[k] = k; 7448 order[i] = j; order[j] = i; 7449 Class<?>[] types = mh.type().parameterArray(); 7450 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7451 MethodType swapType = methodType(mh.type().returnType(), types); 7452 return permuteArguments(mh, swapType, order); 7453 } 7454 7455 /** 7456 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7457 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7458 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7459 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7460 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7461 * {@code try-finally} handle. 7462 * <p> 7463 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7464 * The first is the exception thrown during the 7465 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7466 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7467 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7468 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7469 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7470 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7471 * <p> 7472 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7473 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7474 * two extra leading parameters:<ul> 7475 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7476 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7477 * the result from the execution of the {@code target} handle. 7478 * This parameter is not present if the {@code target} returns {@code void}. 7479 * </ul> 7480 * <p> 7481 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7482 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7483 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7484 * the cleanup. 7485 * {@snippet lang="java" : 7486 * V target(A..., B...); 7487 * V cleanup(Throwable, V, A...); 7488 * V adapter(A... a, B... b) { 7489 * V result = (zero value for V); 7490 * Throwable throwable = null; 7491 * try { 7492 * result = target(a..., b...); 7493 * } catch (Throwable t) { 7494 * throwable = t; 7495 * throw t; 7496 * } finally { 7497 * result = cleanup(throwable, result, a...); 7498 * } 7499 * return result; 7500 * } 7501 * } 7502 * <p> 7503 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7504 * be modified by execution of the target, and so are passed unchanged 7505 * from the caller to the cleanup, if it is invoked. 7506 * <p> 7507 * The target and cleanup must return the same type, even if the cleanup 7508 * always throws. 7509 * To create such a throwing cleanup, compose the cleanup logic 7510 * with {@link #throwException throwException}, 7511 * in order to create a method handle of the correct return type. 7512 * <p> 7513 * Note that {@code tryFinally} never converts exceptions into normal returns. 7514 * In rare cases where exceptions must be converted in that way, first wrap 7515 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7516 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7517 * <p> 7518 * It is recommended that the first parameter type of {@code cleanup} be 7519 * declared {@code Throwable} rather than a narrower subtype. This ensures 7520 * {@code cleanup} will always be invoked with whatever exception that 7521 * {@code target} throws. Declaring a narrower type may result in a 7522 * {@code ClassCastException} being thrown by the {@code try-finally} 7523 * handle if the type of the exception thrown by {@code target} is not 7524 * assignable to the first parameter type of {@code cleanup}. Note that 7525 * various exception types of {@code VirtualMachineError}, 7526 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7527 * thrown by almost any kind of Java code, and a finally clause that 7528 * catches (say) only {@code IOException} would mask any of the others 7529 * behind a {@code ClassCastException}. 7530 * 7531 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7532 * @param cleanup the handle that is invoked in the finally block. 7533 * 7534 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7535 * @throws NullPointerException if any argument is null 7536 * @throws IllegalArgumentException if {@code cleanup} does not accept 7537 * the required leading arguments, or if the method handle types do 7538 * not match in their return types and their 7539 * corresponding trailing parameters 7540 * 7541 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7542 * @since 9 7543 */ 7544 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7545 Class<?>[] targetParamTypes = target.type().ptypes(); 7546 Class<?> rtype = target.type().returnType(); 7547 7548 tryFinallyChecks(target, cleanup); 7549 7550 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7551 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7552 // target parameter list. 7553 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7554 7555 // Ensure that the intrinsic type checks the instance thrown by the 7556 // target against the first parameter of cleanup 7557 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7558 7559 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7560 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7561 } 7562 7563 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7564 Class<?> rtype = target.type().returnType(); 7565 if (rtype != cleanup.type().returnType()) { 7566 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7567 } 7568 MethodType cleanupType = cleanup.type(); 7569 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7570 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7571 } 7572 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7573 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7574 } 7575 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7576 // target parameter list. 7577 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7578 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7579 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7580 cleanup.type(), target.type()); 7581 } 7582 } 7583 7584 /** 7585 * Creates a table switch method handle, which can be used to switch over a set of target 7586 * method handles, based on a given target index, called selector. 7587 * <p> 7588 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7589 * and where {@code N} is the number of target method handles, the table switch method 7590 * handle will invoke the n-th target method handle from the list of target method handles. 7591 * <p> 7592 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7593 * method handle will invoke the given fallback method handle. 7594 * <p> 7595 * All method handles passed to this method must have the same type, with the additional 7596 * requirement that the leading parameter be of type {@code int}. The leading parameter 7597 * represents the selector. 7598 * <p> 7599 * Any trailing parameters present in the type will appear on the returned table switch 7600 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7601 * together with the selector value, to the selected method handle when invoking it. 7602 * 7603 * @apiNote Example: 7604 * The cases each drop the {@code selector} value they are given, and take an additional 7605 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7606 * to a specific constant label string for each case: 7607 * {@snippet lang="java" : 7608 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7609 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7610 * MethodType.methodType(String.class, String.class)); 7611 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7612 * 7613 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7614 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7615 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7616 * 7617 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7618 * caseDefault, 7619 * case0, 7620 * case1 7621 * ); 7622 * 7623 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7624 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7625 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7626 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7627 * } 7628 * 7629 * @param fallback the fallback method handle that is called when the selector is not 7630 * within the range {@code [0, N)}. 7631 * @param targets array of target method handles. 7632 * @return the table switch method handle. 7633 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7634 * any of the elements of the {@code targets} array are 7635 * {@code null}. 7636 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7637 * parameter of the fallback handle or any of the target 7638 * handles is not {@code int}, or if the types of 7639 * the fallback handle and all of target handles are 7640 * not the same. 7641 * 7642 * @since 17 7643 */ 7644 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7645 Objects.requireNonNull(fallback); 7646 Objects.requireNonNull(targets); 7647 targets = targets.clone(); 7648 MethodType type = tableSwitchChecks(fallback, targets); 7649 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7650 } 7651 7652 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7653 if (caseActions.length == 0) 7654 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7655 7656 MethodType expectedType = defaultCase.type(); 7657 7658 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7659 throw new IllegalArgumentException( 7660 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7661 7662 for (MethodHandle mh : caseActions) { 7663 Objects.requireNonNull(mh); 7664 if (mh.type() != expectedType) 7665 throw new IllegalArgumentException( 7666 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7667 } 7668 7669 return expectedType; 7670 } 7671 7672 /** 7673 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7674 * <p> 7675 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7676 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7677 * to the target var handle. 7678 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7679 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7680 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7681 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7682 * <p> 7683 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7684 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7685 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7686 * will be appended to the coordinates of the target var handle). 7687 * <p> 7688 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7689 * throw an {@link IllegalStateException}. 7690 * <p> 7691 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7692 * atomic access guarantees as those featured by the target var handle. 7693 * 7694 * @param target the target var handle 7695 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7696 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7697 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7698 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7699 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7700 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7701 * @throws NullPointerException if any of the arguments is {@code null}. 7702 * @since 22 7703 */ 7704 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7705 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7706 } 7707 7708 /** 7709 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7710 * <p> 7711 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7712 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7713 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7714 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7715 * by the adaptation) to the target var handle. 7716 * <p> 7717 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7718 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7719 * <p> 7720 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7721 * throw an {@link IllegalStateException}. 7722 * <p> 7723 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7724 * atomic access guarantees as those featured by the target var handle. 7725 * 7726 * @param target the target var handle 7727 * @param pos the position of the first coordinate to be transformed 7728 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7729 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7730 * to the new coordinate values. 7731 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7732 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7733 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7734 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7735 * or if it's determined that any of the filters throws any checked exceptions. 7736 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 7737 * @since 22 7738 */ 7739 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 7740 return VarHandles.filterCoordinates(target, pos, filters); 7741 } 7742 7743 /** 7744 * Provides a target var handle with one or more <em>bound coordinates</em> 7745 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 7746 * coordinate types than the target var handle. 7747 * <p> 7748 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 7749 * are joined with bound coordinate values, and then passed to the target var handle. 7750 * <p> 7751 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 7752 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7753 * <p> 7754 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7755 * atomic access guarantees as those featured by the target var handle. 7756 * 7757 * @param target the var handle to invoke after the bound coordinates are inserted 7758 * @param pos the position of the first coordinate to be inserted 7759 * @param values the series of bound coordinates to insert 7760 * @return an adapter var handle which inserts additional coordinates, 7761 * before calling the target var handle 7762 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7763 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 7764 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 7765 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 7766 * of the target var handle. 7767 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 7768 * @since 22 7769 */ 7770 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 7771 return VarHandles.insertCoordinates(target, pos, values); 7772 } 7773 7774 /** 7775 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 7776 * so that the new coordinates match the provided ones. 7777 * <p> 7778 * The given array controls the reordering. 7779 * Call {@code #I} the number of incoming coordinates (the value 7780 * {@code newCoordinates.size()}), and call {@code #O} the number 7781 * of outgoing coordinates (the number of coordinates associated with the target var handle). 7782 * Then the length of the reordering array must be {@code #O}, 7783 * and each element must be a non-negative number less than {@code #I}. 7784 * For every {@code N} less than {@code #O}, the {@code N}-th 7785 * outgoing coordinate will be taken from the {@code I}-th incoming 7786 * coordinate, where {@code I} is {@code reorder[N]}. 7787 * <p> 7788 * No coordinate value conversions are applied. 7789 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 7790 * must be identical to the type of the corresponding outgoing coordinate 7791 * in the target var handle. 7792 * <p> 7793 * The reordering array need not specify an actual permutation. 7794 * An incoming coordinate will be duplicated if its index appears 7795 * more than once in the array, and an incoming coordinate will be dropped 7796 * if its index does not appear in the array. 7797 * <p> 7798 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7799 * atomic access guarantees as those featured by the target var handle. 7800 * @param target the var handle to invoke after the coordinates have been reordered 7801 * @param newCoordinates the new coordinate types 7802 * @param reorder an index array which controls the reordering 7803 * @return an adapter var handle which re-arranges the incoming coordinate values, 7804 * before calling the target var handle 7805 * @throws IllegalArgumentException if the index array length is not equal to 7806 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 7807 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 7808 * the target var handle and in {@code newCoordinates} are not identical. 7809 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 7810 * @since 22 7811 */ 7812 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 7813 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 7814 } 7815 7816 /** 7817 * Adapts a target var handle by pre-processing 7818 * a sub-sequence of its coordinate values with a filter (a method handle). 7819 * The pre-processed coordinates are replaced by the result (if any) of the 7820 * filter function and the target var handle is then called on the modified (usually shortened) 7821 * coordinate list. 7822 * <p> 7823 * If {@code R} is the return type of the filter, then: 7824 * <ul> 7825 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 7826 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 7827 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 7828 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 7829 * target var handle.</li> 7830 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 7831 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 7832 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 7833 * downstream invocation of the target var handle.</li> 7834 * </ul> 7835 * <p> 7836 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7837 * throw an {@link IllegalStateException}. 7838 * <p> 7839 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7840 * atomic access guarantees as those featured by the target var handle. 7841 * 7842 * @param target the var handle to invoke after the coordinates have been filtered 7843 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 7844 * @param filter the filter method handle 7845 * @return an adapter var handle which filters the incoming coordinate values, 7846 * before calling the target var handle 7847 * @throws IllegalArgumentException if the return type of {@code filter} 7848 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 7849 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7850 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 7851 * or if it's determined that {@code filter} throws any checked exceptions. 7852 * @throws NullPointerException if any of the arguments is {@code null}. 7853 * @since 22 7854 */ 7855 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 7856 return VarHandles.collectCoordinates(target, pos, filter); 7857 } 7858 7859 /** 7860 * Returns a var handle which will discard some dummy coordinates before delegating to the 7861 * target var handle. As a consequence, the resulting var handle will feature more 7862 * coordinate types than the target var handle. 7863 * <p> 7864 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 7865 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 7866 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 7867 * <p> 7868 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7869 * atomic access guarantees as those featured by the target var handle. 7870 * 7871 * @param target the var handle to invoke after the dummy coordinates are dropped 7872 * @param pos position of the first coordinate to drop (zero for the leftmost) 7873 * @param valueTypes the type(s) of the coordinate(s) to drop 7874 * @return an adapter var handle which drops some dummy coordinates, 7875 * before calling the target var handle 7876 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 7877 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 7878 * @since 22 7879 */ 7880 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 7881 return VarHandles.dropCoordinates(target, pos, valueTypes); 7882 } 7883 }