1 /* 2 * Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.access.SharedSecrets; 29 import jdk.internal.misc.Unsafe; 30 import jdk.internal.misc.VM; 31 import jdk.internal.reflect.CallerSensitive; 32 import jdk.internal.reflect.CallerSensitiveAdapter; 33 import jdk.internal.reflect.Reflection; 34 import jdk.internal.util.ClassFileDumper; 35 import jdk.internal.vm.annotation.ForceInline; 36 import jdk.internal.vm.annotation.Stable; 37 import sun.invoke.util.ValueConversions; 38 import sun.invoke.util.VerifyAccess; 39 import sun.invoke.util.Wrapper; 40 41 import java.lang.classfile.ClassFile; 42 import java.lang.classfile.ClassModel; 43 import java.lang.constant.ClassDesc; 44 import java.lang.constant.ConstantDescs; 45 import java.lang.invoke.LambdaForm.BasicType; 46 import java.lang.invoke.MethodHandleImpl.Intrinsic; 47 import java.lang.reflect.Constructor; 48 import java.lang.reflect.Field; 49 import java.lang.reflect.Member; 50 import java.lang.reflect.Method; 51 import java.lang.reflect.Modifier; 52 import java.nio.ByteOrder; 53 import java.security.ProtectionDomain; 54 import java.util.ArrayList; 55 import java.util.Arrays; 56 import java.util.BitSet; 57 import java.util.Comparator; 58 import java.util.Iterator; 59 import java.util.List; 60 import java.util.Objects; 61 import java.util.Set; 62 import java.util.concurrent.ConcurrentHashMap; 63 import java.util.stream.Stream; 64 65 import static java.lang.classfile.ClassFile.*; 66 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE; 67 import static java.lang.invoke.MethodHandleNatives.Constants.*; 68 import static java.lang.invoke.MethodHandleStatics.*; 69 import static java.lang.invoke.MethodType.methodType; 70 71 /** 72 * This class consists exclusively of static methods that operate on or return 73 * method handles. They fall into several categories: 74 * <ul> 75 * <li>Lookup methods which help create method handles for methods and fields. 76 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 77 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 78 * </ul> 79 * A lookup, combinator, or factory method will fail and throw an 80 * {@code IllegalArgumentException} if the created method handle's type 81 * would have <a href="MethodHandle.html#maxarity">too many parameters</a>. 82 * 83 * @author John Rose, JSR 292 EG 84 * @since 1.7 85 */ 86 public final class MethodHandles { 87 88 private MethodHandles() { } // do not instantiate 89 90 static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 91 92 // See IMPL_LOOKUP below. 93 94 //--- Method handle creation from ordinary methods. 95 96 /** 97 * Returns a {@link Lookup lookup object} with 98 * full capabilities to emulate all supported bytecode behaviors of the caller. 99 * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller. 100 * Factory methods on the lookup object can create 101 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 102 * for any member that the caller has access to via bytecodes, 103 * including protected and private fields and methods. 104 * This lookup object is created by the original lookup class 105 * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set. 106 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 107 * Do not store it in place where untrusted code can access it. 108 * <p> 109 * This method is caller sensitive, which means that it may return different 110 * values to different callers. 111 * In cases where {@code MethodHandles.lookup} is called from a context where 112 * there is no caller frame on the stack (e.g. when called directly 113 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 114 * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will 115 * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()} 116 * to obtain a low-privileged lookup instead. 117 * @return a lookup object for the caller of this method, with 118 * {@linkplain Lookup#ORIGINAL original} and 119 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}. 120 * @throws IllegalCallerException if there is no caller frame on the stack. 121 */ 122 @CallerSensitive 123 @ForceInline // to ensure Reflection.getCallerClass optimization 124 public static Lookup lookup() { 125 final Class<?> c = Reflection.getCallerClass(); 126 if (c == null) { 127 throw new IllegalCallerException("no caller frame"); 128 } 129 return new Lookup(c); 130 } 131 132 /** 133 * This lookup method is the alternate implementation of 134 * the lookup method with a leading caller class argument which is 135 * non-caller-sensitive. This method is only invoked by reflection 136 * and method handle. 137 */ 138 @CallerSensitiveAdapter 139 private static Lookup lookup(Class<?> caller) { 140 if (caller.getClassLoader() == null) { 141 throw newInternalError("calling lookup() reflectively is not supported: "+caller); 142 } 143 return new Lookup(caller); 144 } 145 146 /** 147 * Returns a {@link Lookup lookup object} which is trusted minimally. 148 * The lookup has the {@code UNCONDITIONAL} mode. 149 * It can only be used to create method handles to public members of 150 * public classes in packages that are exported unconditionally. 151 * <p> 152 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class} 153 * of this lookup object will be {@link java.lang.Object}. 154 * 155 * @apiNote The use of Object is conventional, and because the lookup modes are 156 * limited, there is no special access provided to the internals of Object, its package 157 * or its module. This public lookup object or other lookup object with 158 * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class 159 * is not used to determine the lookup context. 160 * 161 * <p style="font-size:smaller;"> 162 * <em>Discussion:</em> 163 * The lookup class can be changed to any other class {@code C} using an expression of the form 164 * {@link Lookup#in publicLookup().in(C.class)}. 165 * Also, it cannot access 166 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 167 * @return a lookup object which is trusted minimally 168 */ 169 public static Lookup publicLookup() { 170 return Lookup.PUBLIC_LOOKUP; 171 } 172 173 /** 174 * Returns a {@link Lookup lookup} object on a target class to emulate all supported 175 * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>. 176 * The returned lookup object can provide access to classes in modules and packages, 177 * and members of those classes, outside the normal rules of Java access control, 178 * instead conforming to the more permissive rules for modular <em>deep reflection</em>. 179 * <p> 180 * A caller, specified as a {@code Lookup} object, in module {@code M1} is 181 * allowed to do deep reflection on module {@code M2} and package of the target class 182 * if and only if all of the following conditions are {@code true}: 183 * <ul> 184 * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess() 185 * full privilege access}. Specifically: 186 * <ul> 187 * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode. 188 * (This is because otherwise there would be no way to ensure the original lookup 189 * creator was a member of any particular module, and so any subsequent checks 190 * for readability and qualified exports would become ineffective.) 191 * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access. 192 * (This is because an application intending to share intra-module access 193 * using {@link Lookup#MODULE MODULE} alone will inadvertently also share 194 * deep reflection to its own module.) 195 * </ul> 196 * <li>The target class must be a proper class, not a primitive or array class. 197 * (Thus, {@code M2} is well-defined.) 198 * <li>If the caller module {@code M1} differs from 199 * the target module {@code M2} then both of the following must be true: 200 * <ul> 201 * <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li> 202 * <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package 203 * containing the target class to at least {@code M1}.</li> 204 * </ul> 205 * </ul> 206 * <p> 207 * If any of the above checks is violated, this method fails with an 208 * exception. 209 * <p> 210 * Otherwise, if {@code M1} and {@code M2} are the same module, this method 211 * returns a {@code Lookup} on {@code targetClass} with 212 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} 213 * with {@code null} previous lookup class. 214 * <p> 215 * Otherwise, {@code M1} and {@code M2} are two different modules. This method 216 * returns a {@code Lookup} on {@code targetClass} that records 217 * the lookup class of the caller as the new previous lookup class with 218 * {@code PRIVATE} access but no {@code MODULE} access. 219 * <p> 220 * The resulting {@code Lookup} object has no {@code ORIGINAL} access. 221 * 222 * @apiNote The {@code Lookup} object returned by this method is allowed to 223 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 224 * of {@code targetClass}. Extreme caution should be taken when opening a package 225 * to another module as such defined classes have the same full privilege 226 * access as other members in {@code targetClass}'s module. 227 * 228 * @param targetClass the target class 229 * @param caller the caller lookup object 230 * @return a lookup object for the target class, with private access 231 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class 232 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 233 * @throws IllegalAccessException if any of the other access checks specified above fails 234 * @since 9 235 * @see Lookup#dropLookupMode 236 * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a> 237 */ 238 public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException { 239 if (caller.allowedModes == Lookup.TRUSTED) { 240 return new Lookup(targetClass); 241 } 242 243 if (targetClass.isPrimitive()) 244 throw new IllegalArgumentException(targetClass + " is a primitive class"); 245 if (targetClass.isArray()) 246 throw new IllegalArgumentException(targetClass + " is an array class"); 247 // Ensure that we can reason accurately about private and module access. 248 int requireAccess = Lookup.PRIVATE|Lookup.MODULE; 249 if ((caller.lookupModes() & requireAccess) != requireAccess) 250 throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode"); 251 252 // previous lookup class is never set if it has MODULE access 253 assert caller.previousLookupClass() == null; 254 255 Class<?> callerClass = caller.lookupClass(); 256 Module callerModule = callerClass.getModule(); // M1 257 Module targetModule = targetClass.getModule(); // M2 258 Class<?> newPreviousClass = null; 259 int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL; 260 261 if (targetModule != callerModule) { 262 if (!callerModule.canRead(targetModule)) 263 throw new IllegalAccessException(callerModule + " does not read " + targetModule); 264 if (targetModule.isNamed()) { 265 String pn = targetClass.getPackageName(); 266 assert !pn.isEmpty() : "unnamed package cannot be in named module"; 267 if (!targetModule.isOpen(pn, callerModule)) 268 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 269 } 270 271 // M2 != M1, set previous lookup class to M1 and drop MODULE access 272 newPreviousClass = callerClass; 273 newModes &= ~Lookup.MODULE; 274 } 275 return Lookup.newLookup(targetClass, newPreviousClass, newModes); 276 } 277 278 /** 279 * Returns the <em>class data</em> associated with the lookup class 280 * of the given {@code caller} lookup object, or {@code null}. 281 * 282 * <p> A hidden class with class data can be created by calling 283 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 284 * Lookup::defineHiddenClassWithClassData}. 285 * This method will cause the static class initializer of the lookup 286 * class of the given {@code caller} lookup object be executed if 287 * it has not been initialized. 288 * 289 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 290 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 291 * {@code null} is returned if this method is called on the lookup object 292 * on these classes. 293 * 294 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 295 * must have {@linkplain Lookup#ORIGINAL original access} 296 * in order to retrieve the class data. 297 * 298 * @apiNote 299 * This method can be called as a bootstrap method for a dynamically computed 300 * constant. A framework can create a hidden class with class data, for 301 * example that can be {@code Class} or {@code MethodHandle} object. 302 * The class data is accessible only to the lookup object 303 * created by the original caller but inaccessible to other members 304 * in the same nest. If a framework passes security sensitive objects 305 * to a hidden class via class data, it is recommended to load the value 306 * of class data as a dynamically computed constant instead of storing 307 * the class data in private static field(s) which are accessible to 308 * other nestmates. 309 * 310 * @param <T> the type to cast the class data object to 311 * @param caller the lookup context describing the class performing the 312 * operation (normally stacked by the JVM) 313 * @param name must be {@link ConstantDescs#DEFAULT_NAME} 314 * ({@code "_"}) 315 * @param type the type of the class data 316 * @return the value of the class data if present in the lookup class; 317 * otherwise {@code null} 318 * @throws IllegalArgumentException if name is not {@code "_"} 319 * @throws IllegalAccessException if the lookup context does not have 320 * {@linkplain Lookup#ORIGINAL original} access 321 * @throws ClassCastException if the class data cannot be converted to 322 * the given {@code type} 323 * @throws NullPointerException if {@code caller} or {@code type} argument 324 * is {@code null} 325 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 326 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 327 * @since 16 328 * @jvms 5.5 Initialization 329 */ 330 public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException { 331 Objects.requireNonNull(caller); 332 Objects.requireNonNull(type); 333 if (!ConstantDescs.DEFAULT_NAME.equals(name)) { 334 throw new IllegalArgumentException("name must be \"_\": " + name); 335 } 336 337 if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL) { 338 throw new IllegalAccessException(caller + " does not have ORIGINAL access"); 339 } 340 341 Object classdata = classData(caller.lookupClass()); 342 if (classdata == null) return null; 343 344 try { 345 return BootstrapMethodInvoker.widenAndCast(classdata, type); 346 } catch (RuntimeException|Error e) { 347 throw e; // let CCE and other runtime exceptions through 348 } catch (Throwable e) { 349 throw new InternalError(e); 350 } 351 } 352 353 /* 354 * Returns the class data set by the VM in the Class::classData field. 355 * 356 * This is also invoked by LambdaForms as it cannot use condy via 357 * MethodHandles::classData due to bootstrapping issue. 358 */ 359 static Object classData(Class<?> c) { 360 UNSAFE.ensureClassInitialized(c); 361 return SharedSecrets.getJavaLangAccess().classData(c); 362 } 363 364 /** 365 * Returns the element at the specified index in the 366 * {@linkplain #classData(Lookup, String, Class) class data}, 367 * if the class data associated with the lookup class 368 * of the given {@code caller} lookup object is a {@code List}. 369 * If the class data is not present in this lookup class, this method 370 * returns {@code null}. 371 * 372 * <p> A hidden class with class data can be created by calling 373 * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 374 * Lookup::defineHiddenClassWithClassData}. 375 * This method will cause the static class initializer of the lookup 376 * class of the given {@code caller} lookup object be executed if 377 * it has not been initialized. 378 * 379 * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...) 380 * Lookup::defineHiddenClass} and non-hidden classes have no class data. 381 * {@code null} is returned if this method is called on the lookup object 382 * on these classes. 383 * 384 * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup 385 * must have {@linkplain Lookup#ORIGINAL original access} 386 * in order to retrieve the class data. 387 * 388 * @apiNote 389 * This method can be called as a bootstrap method for a dynamically computed 390 * constant. A framework can create a hidden class with class data, for 391 * example that can be {@code List.of(o1, o2, o3....)} containing more than 392 * one object and use this method to load one element at a specific index. 393 * The class data is accessible only to the lookup object 394 * created by the original caller but inaccessible to other members 395 * in the same nest. If a framework passes security sensitive objects 396 * to a hidden class via class data, it is recommended to load the value 397 * of class data as a dynamically computed constant instead of storing 398 * the class data in private static field(s) which are accessible to other 399 * nestmates. 400 * 401 * @param <T> the type to cast the result object to 402 * @param caller the lookup context describing the class performing the 403 * operation (normally stacked by the JVM) 404 * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME} 405 * ({@code "_"}) 406 * @param type the type of the element at the given index in the class data 407 * @param index index of the element in the class data 408 * @return the element at the given index in the class data 409 * if the class data is present; otherwise {@code null} 410 * @throws IllegalArgumentException if name is not {@code "_"} 411 * @throws IllegalAccessException if the lookup context does not have 412 * {@linkplain Lookup#ORIGINAL original} access 413 * @throws ClassCastException if the class data cannot be converted to {@code List} 414 * or the element at the specified index cannot be converted to the given type 415 * @throws IndexOutOfBoundsException if the index is out of range 416 * @throws NullPointerException if {@code caller} or {@code type} argument is 417 * {@code null}; or if unboxing operation fails because 418 * the element at the given index is {@code null} 419 * 420 * @since 16 421 * @see #classData(Lookup, String, Class) 422 * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...) 423 */ 424 public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index) 425 throws IllegalAccessException 426 { 427 @SuppressWarnings("unchecked") 428 List<Object> classdata = (List<Object>)classData(caller, name, List.class); 429 if (classdata == null) return null; 430 431 try { 432 Object element = classdata.get(index); 433 return BootstrapMethodInvoker.widenAndCast(element, type); 434 } catch (RuntimeException|Error e) { 435 throw e; // let specified exceptions and other runtime exceptions/errors through 436 } catch (Throwable e) { 437 throw new InternalError(e); 438 } 439 } 440 441 /** 442 * Performs an unchecked "crack" of a 443 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 444 * The result is as if the user had obtained a lookup object capable enough 445 * to crack the target method handle, called 446 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 447 * on the target to obtain its symbolic reference, and then called 448 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 449 * to resolve the symbolic reference to a member. 450 * @param <T> the desired type of the result, either {@link Member} or a subtype 451 * @param expected a class object representing the desired result type {@code T} 452 * @param target a direct method handle to crack into symbolic reference components 453 * @return a reference to the method, constructor, or field object 454 * @throws NullPointerException if either argument is {@code null} 455 * @throws IllegalArgumentException if the target is not a direct method handle 456 * @throws ClassCastException if the member is not of the expected type 457 * @since 1.8 458 */ 459 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { 460 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 461 return lookup.revealDirect(target).reflectAs(expected, lookup); 462 } 463 464 /** 465 * A <em>lookup object</em> is a factory for creating method handles, 466 * when the creation requires access checking. 467 * Method handles do not perform 468 * access checks when they are called, but rather when they are created. 469 * Therefore, method handle access 470 * restrictions must be enforced when a method handle is created. 471 * The caller class against which those restrictions are enforced 472 * is known as the {@linkplain #lookupClass() lookup class}. 473 * <p> 474 * A lookup class which needs to create method handles will call 475 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself. 476 * When the {@code Lookup} factory object is created, the identity of the lookup class is 477 * determined, and securely stored in the {@code Lookup} object. 478 * The lookup class (or its delegates) may then use factory methods 479 * on the {@code Lookup} object to create method handles for access-checked members. 480 * This includes all methods, constructors, and fields which are allowed to the lookup class, 481 * even private ones. 482 * 483 * <h2><a id="lookups"></a>Lookup Factory Methods</h2> 484 * The factory methods on a {@code Lookup} object correspond to all major 485 * use cases for methods, constructors, and fields. 486 * Each method handle created by a factory method is the functional 487 * equivalent of a particular <em>bytecode behavior</em>. 488 * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of 489 * the Java Virtual Machine Specification.) 490 * Here is a summary of the correspondence between these factory methods and 491 * the behavior of the resulting method handles: 492 * <table class="striped"> 493 * <caption style="display:none">lookup method behaviors</caption> 494 * <thead> 495 * <tr> 496 * <th scope="col"><a id="equiv"></a>lookup expression</th> 497 * <th scope="col">member</th> 498 * <th scope="col">bytecode behavior</th> 499 * </tr> 500 * </thead> 501 * <tbody> 502 * <tr> 503 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th> 504 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 505 * </tr> 506 * <tr> 507 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th> 508 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td> 509 * </tr> 510 * <tr> 511 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th> 512 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 513 * </tr> 514 * <tr> 515 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th> 516 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 517 * </tr> 518 * <tr> 519 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th> 520 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 521 * </tr> 522 * <tr> 523 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th> 524 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 525 * </tr> 526 * <tr> 527 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th> 528 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 529 * </tr> 530 * <tr> 531 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th> 532 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 533 * </tr> 534 * <tr> 535 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th> 536 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 537 * </tr> 538 * <tr> 539 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th> 540 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 541 * </tr> 542 * <tr> 543 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th> 544 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 545 * </tr> 546 * <tr> 547 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th> 548 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 549 * </tr> 550 * <tr> 551 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th> 552 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 553 * </tr> 554 * <tr> 555 * <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th> 556 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 557 * </tr> 558 * </tbody> 559 * </table> 560 * 561 * Here, the type {@code C} is the class or interface being searched for a member, 562 * documented as a parameter named {@code refc} in the lookup methods. 563 * The method type {@code MT} is composed from the return type {@code T} 564 * and the sequence of argument types {@code A*}. 565 * The constructor also has a sequence of argument types {@code A*} and 566 * is deemed to return the newly-created object of type {@code C}. 567 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 568 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 569 * if it is present, it is always the leading argument to the method handle invocation. 570 * (In the case of some {@code protected} members, {@code this} may be 571 * restricted in type to the lookup class; see below.) 572 * The name {@code arg} stands for all the other method handle arguments. 573 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 574 * stands for a null reference if the accessed method or field is static, 575 * and {@code this} otherwise. 576 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 577 * for reflective objects corresponding to the given members declared in type {@code C}. 578 * <p> 579 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 580 * as if by {@code ldc CONSTANT_Class}. 581 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 582 * <p> 583 * In cases where the given member is of variable arity (i.e., a method or constructor) 584 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 585 * In all other cases, the returned method handle will be of fixed arity. 586 * <p style="font-size:smaller;"> 587 * <em>Discussion:</em> 588 * The equivalence between looked-up method handles and underlying 589 * class members and bytecode behaviors 590 * can break down in a few ways: 591 * <ul style="font-size:smaller;"> 592 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 593 * the lookup can still succeed, even when there is no equivalent 594 * Java expression or bytecoded constant. 595 * <li>Likewise, if {@code T} or {@code MT} 596 * is not symbolically accessible from the lookup class's loader, 597 * the lookup can still succeed. 598 * For example, lookups for {@code MethodHandle.invokeExact} and 599 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 600 * <li>If the looked-up method has a 601 * <a href="MethodHandle.html#maxarity">very large arity</a>, 602 * the method handle creation may fail with an 603 * {@code IllegalArgumentException}, due to the method handle type having 604 * <a href="MethodHandle.html#maxarity">too many parameters.</a> 605 * </ul> 606 * 607 * <h2><a id="access"></a>Access checking</h2> 608 * Access checks are applied in the factory methods of {@code Lookup}, 609 * when a method handle is created. 610 * This is a key difference from the Core Reflection API, since 611 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 612 * performs access checking against every caller, on every call. 613 * <p> 614 * All access checks start from a {@code Lookup} object, which 615 * compares its recorded lookup class against all requests to 616 * create method handles. 617 * A single {@code Lookup} object can be used to create any number 618 * of access-checked method handles, all checked against a single 619 * lookup class. 620 * <p> 621 * A {@code Lookup} object can be shared with other trusted code, 622 * such as a metaobject protocol. 623 * A shared {@code Lookup} object delegates the capability 624 * to create method handles on private members of the lookup class. 625 * Even if privileged code uses the {@code Lookup} object, 626 * the access checking is confined to the privileges of the 627 * original lookup class. 628 * <p> 629 * A lookup can fail, because 630 * the containing class is not accessible to the lookup class, or 631 * because the desired class member is missing, or because the 632 * desired class member is not accessible to the lookup class, or 633 * because the lookup object is not trusted enough to access the member. 634 * In the case of a field setter function on a {@code final} field, 635 * finality enforcement is treated as a kind of access control, 636 * and the lookup will fail, except in special cases of 637 * {@link Lookup#unreflectSetter Lookup.unreflectSetter}. 638 * In any of these cases, a {@code ReflectiveOperationException} will be 639 * thrown from the attempted lookup. The exact class will be one of 640 * the following: 641 * <ul> 642 * <li>NoSuchMethodException — if a method is requested but does not exist 643 * <li>NoSuchFieldException — if a field is requested but does not exist 644 * <li>IllegalAccessException — if the member exists but an access check fails 645 * </ul> 646 * <p> 647 * In general, the conditions under which a method handle may be 648 * looked up for a method {@code M} are no more restrictive than the conditions 649 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 650 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 651 * a method handle lookup will generally raise a corresponding 652 * checked exception, such as {@code NoSuchMethodException}. 653 * And the effect of invoking the method handle resulting from the lookup 654 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 655 * to executing the compiled, verified, and resolved call to {@code M}. 656 * The same point is true of fields and constructors. 657 * <p style="font-size:smaller;"> 658 * <em>Discussion:</em> 659 * Access checks only apply to named and reflected methods, 660 * constructors, and fields. 661 * Other method handle creation methods, such as 662 * {@link MethodHandle#asType MethodHandle.asType}, 663 * do not require any access checks, and are used 664 * independently of any {@code Lookup} object. 665 * <p> 666 * If the desired member is {@code protected}, the usual JVM rules apply, 667 * including the requirement that the lookup class must either be in the 668 * same package as the desired member, or must inherit that member. 669 * (See the Java Virtual Machine Specification, sections {@jvms 670 * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.) 671 * In addition, if the desired member is a non-static field or method 672 * in a different package, the resulting method handle may only be applied 673 * to objects of the lookup class or one of its subclasses. 674 * This requirement is enforced by narrowing the type of the leading 675 * {@code this} parameter from {@code C} 676 * (which will necessarily be a superclass of the lookup class) 677 * to the lookup class itself. 678 * <p> 679 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 680 * that the receiver argument must match both the resolved method <em>and</em> 681 * the current class. Again, this requirement is enforced by narrowing the 682 * type of the leading parameter to the resulting method handle. 683 * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.) 684 * <p> 685 * The JVM represents constructors and static initializer blocks as internal methods 686 * with special names ({@value ConstantDescs#INIT_NAME} and {@value 687 * ConstantDescs#CLASS_INIT_NAME}). 688 * The internal syntax of invocation instructions allows them to refer to such internal 689 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 690 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 691 * <p> 692 * If the relationship between nested types is expressed directly through the 693 * {@code NestHost} and {@code NestMembers} attributes 694 * (see the Java Virtual Machine Specification, sections {@jvms 695 * 4.7.28} and {@jvms 4.7.29}), 696 * then the associated {@code Lookup} object provides direct access to 697 * the lookup class and all of its nestmates 698 * (see {@link java.lang.Class#getNestHost Class.getNestHost}). 699 * Otherwise, access between nested classes is obtained by the Java compiler creating 700 * a wrapper method to access a private method of another class in the same nest. 701 * For example, a nested class {@code C.D} 702 * can access private members within other related classes such as 703 * {@code C}, {@code C.D.E}, or {@code C.B}, 704 * but the Java compiler may need to generate wrapper methods in 705 * those related classes. In such cases, a {@code Lookup} object on 706 * {@code C.E} would be unable to access those private members. 707 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 708 * which can transform a lookup on {@code C.E} into one on any of those other 709 * classes, without special elevation of privilege. 710 * <p> 711 * The accesses permitted to a given lookup object may be limited, 712 * according to its set of {@link #lookupModes lookupModes}, 713 * to a subset of members normally accessible to the lookup class. 714 * For example, the {@link MethodHandles#publicLookup publicLookup} 715 * method produces a lookup object which is only allowed to access 716 * public members in public classes of exported packages. 717 * The caller sensitive method {@link MethodHandles#lookup lookup} 718 * produces a lookup object with full capabilities relative to 719 * its caller class, to emulate all supported bytecode behaviors. 720 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 721 * with fewer access modes than the original lookup object. 722 * 723 * <p style="font-size:smaller;"> 724 * <a id="privacc"></a> 725 * <em>Discussion of private and module access:</em> 726 * We say that a lookup has <em>private access</em> 727 * if its {@linkplain #lookupModes lookup modes} 728 * include the possibility of accessing {@code private} members 729 * (which includes the private members of nestmates). 730 * As documented in the relevant methods elsewhere, 731 * only lookups with private access possess the following capabilities: 732 * <ul style="font-size:smaller;"> 733 * <li>access private fields, methods, and constructors of the lookup class and its nestmates 734 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 735 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 736 * within the same package member 737 * </ul> 738 * <p style="font-size:smaller;"> 739 * Similarly, a lookup with module access ensures that the original lookup creator was 740 * a member in the same module as the lookup class. 741 * <p style="font-size:smaller;"> 742 * Private and module access are independently determined modes; a lookup may have 743 * either or both or neither. A lookup which possesses both access modes is said to 744 * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}. 745 * <p style="font-size:smaller;"> 746 * A lookup with <em>original access</em> ensures that this lookup is created by 747 * the original lookup class and the bootstrap method invoked by the VM. 748 * Such a lookup with original access also has private and module access 749 * which has the following additional capability: 750 * <ul style="font-size:smaller;"> 751 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 752 * such as {@code Class.forName} 753 * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class) 754 * class data} associated with the lookup class</li> 755 * </ul> 756 * <p style="font-size:smaller;"> 757 * Each of these permissions is a consequence of the fact that a lookup object 758 * with private access can be securely traced back to an originating class, 759 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 760 * can be reliably determined and emulated by method handles. 761 * 762 * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2> 763 * When a lookup class in one module {@code M1} accesses a class in another module 764 * {@code M2}, extra access checking is performed beyond the access mode bits. 765 * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1} 766 * can access public types in {@code M2} when {@code M2} is readable to {@code M1} 767 * and when the type is in a package of {@code M2} that is exported to 768 * at least {@code M1}. 769 * <p> 770 * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class 771 * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup) 772 * MethodHandles.privateLookupIn} methods. 773 * Teleporting across modules will always record the original lookup class as 774 * the <em>{@linkplain #previousLookupClass() previous lookup class}</em> 775 * and drops {@link Lookup#MODULE MODULE} access. 776 * If the target class is in the same module as the lookup class {@code C}, 777 * then the target class becomes the new lookup class 778 * and there is no change to the previous lookup class. 779 * If the target class is in a different module from {@code M1} ({@code C}'s module), 780 * {@code C} becomes the new previous lookup class 781 * and the target class becomes the new lookup class. 782 * In that case, if there was already a previous lookup class in {@code M0}, 783 * and it differs from {@code M1} and {@code M2}, then the resulting lookup 784 * drops all privileges. 785 * For example, 786 * {@snippet lang="java" : 787 * Lookup lookup = MethodHandles.lookup(); // in class C 788 * Lookup lookup2 = lookup.in(D.class); 789 * MethodHandle mh = lookup2.findStatic(E.class, "m", MT); 790 * } 791 * <p> 792 * The {@link #lookup()} factory method produces a {@code Lookup} object 793 * with {@code null} previous lookup class. 794 * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C} 795 * to class {@code D} without elevation of privileges. 796 * If {@code C} and {@code D} are in the same module, 797 * {@code lookup2} records {@code D} as the new lookup class and keeps the 798 * same previous lookup class as the original {@code lookup}, or 799 * {@code null} if not present. 800 * <p> 801 * When a {@code Lookup} teleports from a class 802 * in one nest to another nest, {@code PRIVATE} access is dropped. 803 * When a {@code Lookup} teleports from a class in one package to 804 * another package, {@code PACKAGE} access is dropped. 805 * When a {@code Lookup} teleports from a class in one module to another module, 806 * {@code MODULE} access is dropped. 807 * Teleporting across modules drops the ability to access non-exported classes 808 * in both the module of the new lookup class and the module of the old lookup class 809 * and the resulting {@code Lookup} remains only {@code PUBLIC} access. 810 * A {@code Lookup} can teleport back and forth to a class in the module of 811 * the lookup class and the module of the previous class lookup. 812 * Teleporting across modules can only decrease access but cannot increase it. 813 * Teleporting to some third module drops all accesses. 814 * <p> 815 * In the above example, if {@code C} and {@code D} are in different modules, 816 * {@code lookup2} records {@code D} as its lookup class and 817 * {@code C} as its previous lookup class and {@code lookup2} has only 818 * {@code PUBLIC} access. {@code lookup2} can teleport to other class in 819 * {@code C}'s module and {@code D}'s module. 820 * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates 821 * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup 822 * class {@code D} is recorded as its previous lookup class. 823 * <p> 824 * Teleporting across modules restricts access to the public types that 825 * both the lookup class and the previous lookup class can equally access 826 * (see below). 827 * <p> 828 * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)} 829 * can be used to teleport a {@code lookup} from class {@code C} to class {@code T} 830 * and produce a new {@code Lookup} with <a href="#privacc">private access</a> 831 * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}. 832 * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access 833 * to call {@code privateLookupIn}. 834 * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection 835 * on all classes in {@code M1}. If {@code T} is in {@code M1}, {@code privateLookupIn} 836 * produces a new {@code Lookup} on {@code T} with full capabilities. 837 * A {@code lookup} on {@code C} is also allowed 838 * to do deep reflection on {@code T} in another module {@code M2} if 839 * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens} 840 * the package containing {@code T} to at least {@code M1}. 841 * {@code T} becomes the new lookup class and {@code C} becomes the new previous 842 * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}. 843 * The resulting {@code Lookup} can be used to do member lookup or teleport 844 * to another lookup class by calling {@link #in Lookup::in}. But 845 * it cannot be used to obtain another private {@code Lookup} by calling 846 * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn} 847 * because it has no {@code MODULE} access. 848 * <p> 849 * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to 850 * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package 851 * of {@code T}. Extreme caution should be taken when opening a package 852 * to another module as such defined classes have the same full privilege 853 * access as other members in {@code M2}. 854 * 855 * <h2><a id="module-access-check"></a>Cross-module access checks</h2> 856 * 857 * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode 858 * allows cross-module access. The access checking is performed with respect 859 * to both the lookup class and the previous lookup class if present. 860 * <p> 861 * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type 862 * in all modules when the type is in a package that is {@linkplain Module#isExported(String) 863 * exported unconditionally}. 864 * <p> 865 * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class, 866 * the lookup with {@link #PUBLIC} mode can access all public types in modules 867 * that are readable to {@code M1} and the type is in a package that is exported 868 * at least to {@code M1}. 869 * <p> 870 * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class 871 * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access 872 * the intersection of all public types that are accessible to {@code M1} 873 * with all public types that are accessible to {@code M0}. {@code M0} 874 * reads {@code M1} and hence the set of accessible types includes: 875 * 876 * <ul> 877 * <li>unconditional-exported packages from {@code M1}</li> 878 * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li> 879 * <li> 880 * unconditional-exported packages from a third module {@code M2}if both {@code M0} 881 * and {@code M1} read {@code M2} 882 * </li> 883 * <li>qualified-exported packages from {@code M1} to {@code M0}</li> 884 * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li> 885 * <li> 886 * qualified-exported packages from a third module {@code M2} to both {@code M0} and 887 * {@code M1} if both {@code M0} and {@code M1} read {@code M2} 888 * </li> 889 * </ul> 890 * 891 * <h2><a id="access-modes"></a>Access modes</h2> 892 * 893 * The table below shows the access modes of a {@code Lookup} produced by 894 * any of the following factory or transformation methods: 895 * <ul> 896 * <li>{@link #lookup() MethodHandles::lookup}</li> 897 * <li>{@link #publicLookup() MethodHandles::publicLookup}</li> 898 * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li> 899 * <li>{@link Lookup#in Lookup::in}</li> 900 * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li> 901 * </ul> 902 * 903 * <table class="striped"> 904 * <caption style="display:none"> 905 * Access mode summary 906 * </caption> 907 * <thead> 908 * <tr> 909 * <th scope="col">Lookup object</th> 910 * <th style="text-align:center">original</th> 911 * <th style="text-align:center">protected</th> 912 * <th style="text-align:center">private</th> 913 * <th style="text-align:center">package</th> 914 * <th style="text-align:center">module</th> 915 * <th style="text-align:center">public</th> 916 * </tr> 917 * </thead> 918 * <tbody> 919 * <tr> 920 * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th> 921 * <td style="text-align:center">ORI</td> 922 * <td style="text-align:center">PRO</td> 923 * <td style="text-align:center">PRI</td> 924 * <td style="text-align:center">PAC</td> 925 * <td style="text-align:center">MOD</td> 926 * <td style="text-align:center">1R</td> 927 * </tr> 928 * <tr> 929 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th> 930 * <td></td> 931 * <td></td> 932 * <td></td> 933 * <td style="text-align:center">PAC</td> 934 * <td style="text-align:center">MOD</td> 935 * <td style="text-align:center">1R</td> 936 * </tr> 937 * <tr> 938 * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th> 939 * <td></td> 940 * <td></td> 941 * <td></td> 942 * <td></td> 943 * <td style="text-align:center">MOD</td> 944 * <td style="text-align:center">1R</td> 945 * </tr> 946 * <tr> 947 * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th> 948 * <td></td> 949 * <td></td> 950 * <td></td> 951 * <td></td> 952 * <td></td> 953 * <td style="text-align:center">2R</td> 954 * </tr> 955 * <tr> 956 * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th> 957 * <td></td> 958 * <td></td> 959 * <td></td> 960 * <td></td> 961 * <td></td> 962 * <td style="text-align:center">2R</td> 963 * </tr> 964 * <tr> 965 * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th> 966 * <td></td> 967 * <td style="text-align:center">PRO</td> 968 * <td style="text-align:center">PRI</td> 969 * <td style="text-align:center">PAC</td> 970 * <td style="text-align:center">MOD</td> 971 * <td style="text-align:center">1R</td> 972 * </tr> 973 * <tr> 974 * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th> 975 * <td></td> 976 * <td style="text-align:center">PRO</td> 977 * <td style="text-align:center">PRI</td> 978 * <td style="text-align:center">PAC</td> 979 * <td style="text-align:center">MOD</td> 980 * <td style="text-align:center">1R</td> 981 * </tr> 982 * <tr> 983 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th> 984 * <td></td> 985 * <td></td> 986 * <td></td> 987 * <td style="text-align:center">PAC</td> 988 * <td style="text-align:center">MOD</td> 989 * <td style="text-align:center">1R</td> 990 * </tr> 991 * <tr> 992 * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th> 993 * <td></td> 994 * <td></td> 995 * <td></td> 996 * <td></td> 997 * <td style="text-align:center">MOD</td> 998 * <td style="text-align:center">1R</td> 999 * </tr> 1000 * <tr> 1001 * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th> 1002 * <td></td> 1003 * <td></td> 1004 * <td></td> 1005 * <td></td> 1006 * <td></td> 1007 * <td style="text-align:center">2R</td> 1008 * </tr> 1009 * <tr> 1010 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th> 1011 * <td></td> 1012 * <td></td> 1013 * <td style="text-align:center">PRI</td> 1014 * <td style="text-align:center">PAC</td> 1015 * <td style="text-align:center">MOD</td> 1016 * <td style="text-align:center">1R</td> 1017 * </tr> 1018 * <tr> 1019 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th> 1020 * <td></td> 1021 * <td></td> 1022 * <td></td> 1023 * <td style="text-align:center">PAC</td> 1024 * <td style="text-align:center">MOD</td> 1025 * <td style="text-align:center">1R</td> 1026 * </tr> 1027 * <tr> 1028 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th> 1029 * <td></td> 1030 * <td></td> 1031 * <td></td> 1032 * <td></td> 1033 * <td style="text-align:center">MOD</td> 1034 * <td style="text-align:center">1R</td> 1035 * </tr> 1036 * <tr> 1037 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th> 1038 * <td></td> 1039 * <td></td> 1040 * <td></td> 1041 * <td></td> 1042 * <td></td> 1043 * <td style="text-align:center">1R</td> 1044 * </tr> 1045 * <tr> 1046 * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th> 1047 * <td></td> 1048 * <td></td> 1049 * <td></td> 1050 * <td></td> 1051 * <td></td> 1052 * <td style="text-align:center">none</td> 1053 * <tr> 1054 * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th> 1055 * <td></td> 1056 * <td style="text-align:center">PRO</td> 1057 * <td style="text-align:center">PRI</td> 1058 * <td style="text-align:center">PAC</td> 1059 * <td></td> 1060 * <td style="text-align:center">2R</td> 1061 * </tr> 1062 * <tr> 1063 * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th> 1064 * <td></td> 1065 * <td style="text-align:center">PRO</td> 1066 * <td style="text-align:center">PRI</td> 1067 * <td style="text-align:center">PAC</td> 1068 * <td></td> 1069 * <td style="text-align:center">2R</td> 1070 * </tr> 1071 * <tr> 1072 * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th> 1073 * <td></td> 1074 * <td></td> 1075 * <td></td> 1076 * <td></td> 1077 * <td></td> 1078 * <td style="text-align:center">IAE</td> 1079 * </tr> 1080 * <tr> 1081 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th> 1082 * <td></td> 1083 * <td></td> 1084 * <td></td> 1085 * <td style="text-align:center">PAC</td> 1086 * <td></td> 1087 * <td style="text-align:center">2R</td> 1088 * </tr> 1089 * <tr> 1090 * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th> 1091 * <td></td> 1092 * <td></td> 1093 * <td></td> 1094 * <td></td> 1095 * <td></td> 1096 * <td style="text-align:center">2R</td> 1097 * </tr> 1098 * <tr> 1099 * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th> 1100 * <td></td> 1101 * <td></td> 1102 * <td></td> 1103 * <td></td> 1104 * <td></td> 1105 * <td style="text-align:center">2R</td> 1106 * </tr> 1107 * <tr> 1108 * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th> 1109 * <td></td> 1110 * <td></td> 1111 * <td></td> 1112 * <td></td> 1113 * <td></td> 1114 * <td style="text-align:center">none</td> 1115 * </tr> 1116 * <tr> 1117 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th> 1118 * <td></td> 1119 * <td></td> 1120 * <td style="text-align:center">PRI</td> 1121 * <td style="text-align:center">PAC</td> 1122 * <td></td> 1123 * <td style="text-align:center">2R</td> 1124 * </tr> 1125 * <tr> 1126 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th> 1127 * <td></td> 1128 * <td></td> 1129 * <td></td> 1130 * <td style="text-align:center">PAC</td> 1131 * <td></td> 1132 * <td style="text-align:center">2R</td> 1133 * </tr> 1134 * <tr> 1135 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th> 1136 * <td></td> 1137 * <td></td> 1138 * <td></td> 1139 * <td></td> 1140 * <td></td> 1141 * <td style="text-align:center">2R</td> 1142 * </tr> 1143 * <tr> 1144 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th> 1145 * <td></td> 1146 * <td></td> 1147 * <td></td> 1148 * <td></td> 1149 * <td></td> 1150 * <td style="text-align:center">2R</td> 1151 * </tr> 1152 * <tr> 1153 * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th> 1154 * <td></td> 1155 * <td></td> 1156 * <td></td> 1157 * <td></td> 1158 * <td></td> 1159 * <td style="text-align:center">none</td> 1160 * </tr> 1161 * <tr> 1162 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th> 1163 * <td></td> 1164 * <td></td> 1165 * <td style="text-align:center">PRI</td> 1166 * <td style="text-align:center">PAC</td> 1167 * <td style="text-align:center">MOD</td> 1168 * <td style="text-align:center">1R</td> 1169 * </tr> 1170 * <tr> 1171 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th> 1172 * <td></td> 1173 * <td></td> 1174 * <td></td> 1175 * <td style="text-align:center">PAC</td> 1176 * <td style="text-align:center">MOD</td> 1177 * <td style="text-align:center">1R</td> 1178 * </tr> 1179 * <tr> 1180 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th> 1181 * <td></td> 1182 * <td></td> 1183 * <td></td> 1184 * <td></td> 1185 * <td style="text-align:center">MOD</td> 1186 * <td style="text-align:center">1R</td> 1187 * </tr> 1188 * <tr> 1189 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th> 1190 * <td></td> 1191 * <td></td> 1192 * <td></td> 1193 * <td></td> 1194 * <td></td> 1195 * <td style="text-align:center">1R</td> 1196 * </tr> 1197 * <tr> 1198 * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th> 1199 * <td></td> 1200 * <td></td> 1201 * <td></td> 1202 * <td></td> 1203 * <td></td> 1204 * <td style="text-align:center">none</td> 1205 * </tr> 1206 * <tr> 1207 * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th> 1208 * <td></td> 1209 * <td></td> 1210 * <td></td> 1211 * <td></td> 1212 * <td></td> 1213 * <td style="text-align:center">U</td> 1214 * </tr> 1215 * <tr> 1216 * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th> 1217 * <td></td> 1218 * <td></td> 1219 * <td></td> 1220 * <td></td> 1221 * <td></td> 1222 * <td style="text-align:center">U</td> 1223 * </tr> 1224 * <tr> 1225 * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th> 1226 * <td></td> 1227 * <td></td> 1228 * <td></td> 1229 * <td></td> 1230 * <td></td> 1231 * <td style="text-align:center">U</td> 1232 * </tr> 1233 * <tr> 1234 * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th> 1235 * <td></td> 1236 * <td></td> 1237 * <td></td> 1238 * <td></td> 1239 * <td></td> 1240 * <td style="text-align:center">none</td> 1241 * </tr> 1242 * <tr> 1243 * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th> 1244 * <td></td> 1245 * <td></td> 1246 * <td></td> 1247 * <td></td> 1248 * <td></td> 1249 * <td style="text-align:center">IAE</td> 1250 * </tr> 1251 * <tr> 1252 * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th> 1253 * <td></td> 1254 * <td></td> 1255 * <td></td> 1256 * <td></td> 1257 * <td></td> 1258 * <td style="text-align:center">none</td> 1259 * </tr> 1260 * </tbody> 1261 * </table> 1262 * 1263 * <p> 1264 * Notes: 1265 * <ul> 1266 * <li>Class {@code C} and class {@code C1} are in module {@code M1}, 1267 * but {@code D} and {@code D2} are in module {@code M2}, and {@code E} 1268 * is in module {@code M3}. {@code X} stands for class which is inaccessible 1269 * to the lookup. {@code ANY} stands for any of the example lookups.</li> 1270 * <li>{@code ORI} indicates {@link #ORIGINAL} bit set, 1271 * {@code PRO} indicates {@link #PROTECTED} bit set, 1272 * {@code PRI} indicates {@link #PRIVATE} bit set, 1273 * {@code PAC} indicates {@link #PACKAGE} bit set, 1274 * {@code MOD} indicates {@link #MODULE} bit set, 1275 * {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set, 1276 * {@code U} indicates {@link #UNCONDITIONAL} bit set, 1277 * {@code IAE} indicates {@code IllegalAccessException} thrown.</li> 1278 * <li>Public access comes in three kinds: 1279 * <ul> 1280 * <li>unconditional ({@code U}): the lookup assumes readability. 1281 * The lookup has {@code null} previous lookup class. 1282 * <li>one-module-reads ({@code 1R}): the module access checking is 1283 * performed with respect to the lookup class. The lookup has {@code null} 1284 * previous lookup class. 1285 * <li>two-module-reads ({@code 2R}): the module access checking is 1286 * performed with respect to the lookup class and the previous lookup class. 1287 * The lookup has a non-null previous lookup class which is in a 1288 * different module from the current lookup class. 1289 * </ul> 1290 * <li>Any attempt to reach a third module loses all access.</li> 1291 * <li>If a target class {@code X} is not accessible to {@code Lookup::in} 1292 * all access modes are dropped.</li> 1293 * </ul> 1294 * 1295 * <h2><a id="callsens"></a>Caller sensitive methods</h2> 1296 * A small number of Java methods have a special property called caller sensitivity. 1297 * A <em>caller-sensitive</em> method can behave differently depending on the 1298 * identity of its immediate caller. 1299 * <p> 1300 * If a method handle for a caller-sensitive method is requested, 1301 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 1302 * but they take account of the lookup class in a special way. 1303 * The resulting method handle behaves as if it were called 1304 * from an instruction contained in the lookup class, 1305 * so that the caller-sensitive method detects the lookup class. 1306 * (By contrast, the invoker of the method handle is disregarded.) 1307 * Thus, in the case of caller-sensitive methods, 1308 * different lookup classes may give rise to 1309 * differently behaving method handles. 1310 * <p> 1311 * In cases where the lookup object is 1312 * {@link MethodHandles#publicLookup() publicLookup()}, 1313 * or some other lookup object without the 1314 * {@linkplain #ORIGINAL original access}, 1315 * the lookup class is disregarded. 1316 * In such cases, no caller-sensitive method handle can be created, 1317 * access is forbidden, and the lookup fails with an 1318 * {@code IllegalAccessException}. 1319 * <p style="font-size:smaller;"> 1320 * <em>Discussion:</em> 1321 * For example, the caller-sensitive method 1322 * {@link java.lang.Class#forName(String) Class.forName(x)} 1323 * can return varying classes or throw varying exceptions, 1324 * depending on the class loader of the class that calls it. 1325 * A public lookup of {@code Class.forName} will fail, because 1326 * there is no reasonable way to determine its bytecode behavior. 1327 * <p style="font-size:smaller;"> 1328 * If an application caches method handles for broad sharing, 1329 * it should use {@code publicLookup()} to create them. 1330 * If there is a lookup of {@code Class.forName}, it will fail, 1331 * and the application must take appropriate action in that case. 1332 * It may be that a later lookup, perhaps during the invocation of a 1333 * bootstrap method, can incorporate the specific identity 1334 * of the caller, making the method accessible. 1335 * <p style="font-size:smaller;"> 1336 * The function {@code MethodHandles.lookup} is caller sensitive 1337 * so that there can be a secure foundation for lookups. 1338 * Nearly all other methods in the JSR 292 API rely on lookup 1339 * objects to check access requests. 1340 */ 1341 public static final 1342 class Lookup { 1343 /** The class on behalf of whom the lookup is being performed. */ 1344 private final Class<?> lookupClass; 1345 1346 /** previous lookup class */ 1347 private final Class<?> prevLookupClass; 1348 1349 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 1350 private final int allowedModes; 1351 1352 static { 1353 Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes")); 1354 } 1355 1356 /** A single-bit mask representing {@code public} access, 1357 * which may contribute to the result of {@link #lookupModes lookupModes}. 1358 * The value, {@code 0x01}, happens to be the same as the value of the 1359 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 1360 * <p> 1361 * A {@code Lookup} with this lookup mode performs cross-module access check 1362 * with respect to the {@linkplain #lookupClass() lookup class} and 1363 * {@linkplain #previousLookupClass() previous lookup class} if present. 1364 */ 1365 public static final int PUBLIC = Modifier.PUBLIC; 1366 1367 /** A single-bit mask representing {@code private} access, 1368 * which may contribute to the result of {@link #lookupModes lookupModes}. 1369 * The value, {@code 0x02}, happens to be the same as the value of the 1370 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 1371 */ 1372 public static final int PRIVATE = Modifier.PRIVATE; 1373 1374 /** A single-bit mask representing {@code protected} access, 1375 * which may contribute to the result of {@link #lookupModes lookupModes}. 1376 * The value, {@code 0x04}, happens to be the same as the value of the 1377 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 1378 */ 1379 public static final int PROTECTED = Modifier.PROTECTED; 1380 1381 /** A single-bit mask representing {@code package} access (default access), 1382 * which may contribute to the result of {@link #lookupModes lookupModes}. 1383 * The value is {@code 0x08}, which does not correspond meaningfully to 1384 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1385 */ 1386 public static final int PACKAGE = Modifier.STATIC; 1387 1388 /** A single-bit mask representing {@code module} access, 1389 * which may contribute to the result of {@link #lookupModes lookupModes}. 1390 * The value is {@code 0x10}, which does not correspond meaningfully to 1391 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1392 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 1393 * with this lookup mode can access all public types in the module of the 1394 * lookup class and public types in packages exported by other modules 1395 * to the module of the lookup class. 1396 * <p> 1397 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1398 * previous lookup class} is always {@code null}. 1399 * 1400 * @since 9 1401 */ 1402 public static final int MODULE = PACKAGE << 1; 1403 1404 /** A single-bit mask representing {@code unconditional} access 1405 * which may contribute to the result of {@link #lookupModes lookupModes}. 1406 * The value is {@code 0x20}, which does not correspond meaningfully to 1407 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1408 * A {@code Lookup} with this lookup mode assumes {@linkplain 1409 * java.lang.Module#canRead(java.lang.Module) readability}. 1410 * This lookup mode can access all public members of public types 1411 * of all modules when the type is in a package that is {@link 1412 * java.lang.Module#isExported(String) exported unconditionally}. 1413 * 1414 * <p> 1415 * If this lookup mode is set, the {@linkplain #previousLookupClass() 1416 * previous lookup class} is always {@code null}. 1417 * 1418 * @since 9 1419 * @see #publicLookup() 1420 */ 1421 public static final int UNCONDITIONAL = PACKAGE << 2; 1422 1423 /** A single-bit mask representing {@code original} access 1424 * which may contribute to the result of {@link #lookupModes lookupModes}. 1425 * The value is {@code 0x40}, which does not correspond meaningfully to 1426 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 1427 * 1428 * <p> 1429 * If this lookup mode is set, the {@code Lookup} object must be 1430 * created by the original lookup class by calling 1431 * {@link MethodHandles#lookup()} method or by a bootstrap method 1432 * invoked by the VM. The {@code Lookup} object with this lookup 1433 * mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}. 1434 * 1435 * @since 16 1436 */ 1437 public static final int ORIGINAL = PACKAGE << 3; 1438 1439 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL); 1440 private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL); // with original access 1441 private static final int TRUSTED = -1; 1442 1443 /* 1444 * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL 1445 * Adjust 0 => PACKAGE 1446 */ 1447 private static int fixmods(int mods) { 1448 mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL); 1449 if (Modifier.isPublic(mods)) 1450 mods |= UNCONDITIONAL; 1451 return (mods != 0) ? mods : PACKAGE; 1452 } 1453 1454 /** Tells which class is performing the lookup. It is this class against 1455 * which checks are performed for visibility and access permissions. 1456 * <p> 1457 * If this lookup object has a {@linkplain #previousLookupClass() previous lookup class}, 1458 * access checks are performed against both the lookup class and the previous lookup class. 1459 * <p> 1460 * The class implies a maximum level of access permission, 1461 * but the permissions may be additionally limited by the bitmask 1462 * {@link #lookupModes lookupModes}, which controls whether non-public members 1463 * can be accessed. 1464 * @return the lookup class, on behalf of which this lookup object finds members 1465 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1466 */ 1467 public Class<?> lookupClass() { 1468 return lookupClass; 1469 } 1470 1471 /** Reports a lookup class in another module that this lookup object 1472 * was previously teleported from, or {@code null}. 1473 * <p> 1474 * A {@code Lookup} object produced by the factory methods, such as the 1475 * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method, 1476 * has {@code null} previous lookup class. 1477 * A {@code Lookup} object has a non-null previous lookup class 1478 * when this lookup was teleported from an old lookup class 1479 * in one module to a new lookup class in another module. 1480 * 1481 * @return the lookup class in another module that this lookup object was 1482 * previously teleported from, or {@code null} 1483 * @since 14 1484 * @see #in(Class) 1485 * @see MethodHandles#privateLookupIn(Class, Lookup) 1486 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1487 */ 1488 public Class<?> previousLookupClass() { 1489 return prevLookupClass; 1490 } 1491 1492 // This is just for calling out to MethodHandleImpl. 1493 private Class<?> lookupClassOrNull() { 1494 return (allowedModes == TRUSTED) ? null : lookupClass; 1495 } 1496 1497 /** Tells which access-protection classes of members this lookup object can produce. 1498 * The result is a bit-mask of the bits 1499 * {@linkplain #PUBLIC PUBLIC (0x01)}, 1500 * {@linkplain #PRIVATE PRIVATE (0x02)}, 1501 * {@linkplain #PROTECTED PROTECTED (0x04)}, 1502 * {@linkplain #PACKAGE PACKAGE (0x08)}, 1503 * {@linkplain #MODULE MODULE (0x10)}, 1504 * {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}, 1505 * and {@linkplain #ORIGINAL ORIGINAL (0x40)}. 1506 * <p> 1507 * A freshly-created lookup object 1508 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has 1509 * all possible bits set, except {@code UNCONDITIONAL}. 1510 * A lookup object on a new lookup class 1511 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 1512 * may have some mode bits set to zero. 1513 * Mode bits can also be 1514 * {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}. 1515 * Once cleared, mode bits cannot be restored from the downgraded lookup object. 1516 * The purpose of this is to restrict access via the new lookup object, 1517 * so that it can access only names which can be reached by the original 1518 * lookup object, and also by the new lookup class. 1519 * @return the lookup modes, which limit the kinds of access performed by this lookup object 1520 * @see #in 1521 * @see #dropLookupMode 1522 */ 1523 public int lookupModes() { 1524 return allowedModes & ALL_MODES; 1525 } 1526 1527 /** Embody the current class (the lookupClass) as a lookup class 1528 * for method handle creation. 1529 * Must be called by from a method in this package, 1530 * which in turn is called by a method not in this package. 1531 */ 1532 Lookup(Class<?> lookupClass) { 1533 this(lookupClass, null, FULL_POWER_MODES); 1534 } 1535 1536 private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1537 assert prevLookupClass == null || ((allowedModes & MODULE) == 0 1538 && prevLookupClass.getModule() != lookupClass.getModule()); 1539 assert !lookupClass.isArray() && !lookupClass.isPrimitive(); 1540 this.lookupClass = lookupClass; 1541 this.prevLookupClass = prevLookupClass; 1542 this.allowedModes = allowedModes; 1543 } 1544 1545 private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) { 1546 // make sure we haven't accidentally picked up a privileged class: 1547 checkUnprivilegedlookupClass(lookupClass); 1548 return new Lookup(lookupClass, prevLookupClass, allowedModes); 1549 } 1550 1551 /** 1552 * Creates a lookup on the specified new lookup class. 1553 * The resulting object will report the specified 1554 * class as its own {@link #lookupClass() lookupClass}. 1555 * 1556 * <p> 1557 * However, the resulting {@code Lookup} object is guaranteed 1558 * to have no more access capabilities than the original. 1559 * In particular, access capabilities can be lost as follows:<ul> 1560 * <li>If the new lookup class is different from the old lookup class, 1561 * i.e. {@link #ORIGINAL ORIGINAL} access is lost. 1562 * <li>If the new lookup class is in a different module from the old one, 1563 * i.e. {@link #MODULE MODULE} access is lost. 1564 * <li>If the new lookup class is in a different package 1565 * than the old one, protected and default (package) members will not be accessible, 1566 * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost. 1567 * <li>If the new lookup class is not within the same package member 1568 * as the old one, private members will not be accessible, and protected members 1569 * will not be accessible by virtue of inheritance, 1570 * i.e. {@link #PRIVATE PRIVATE} access is lost. 1571 * (Protected members may continue to be accessible because of package sharing.) 1572 * <li>If the new lookup class is not 1573 * {@linkplain #accessClass(Class) accessible} to this lookup, 1574 * then no members, not even public members, will be accessible 1575 * i.e. all access modes are lost. 1576 * <li>If the new lookup class, the old lookup class and the previous lookup class 1577 * are all in different modules i.e. teleporting to a third module, 1578 * all access modes are lost. 1579 * </ul> 1580 * <p> 1581 * The new previous lookup class is chosen as follows: 1582 * <ul> 1583 * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit, 1584 * the new previous lookup class is {@code null}. 1585 * <li>If the new lookup class is in the same module as the old lookup class, 1586 * the new previous lookup class is the old previous lookup class. 1587 * <li>If the new lookup class is in a different module from the old lookup class, 1588 * the new previous lookup class is the old lookup class. 1589 *</ul> 1590 * <p> 1591 * The resulting lookup's capabilities for loading classes 1592 * (used during {@link #findClass} invocations) 1593 * are determined by the lookup class' loader, 1594 * which may change due to this operation. 1595 * 1596 * @param requestedLookupClass the desired lookup class for the new lookup object 1597 * @return a lookup object which reports the desired lookup class, or the same object 1598 * if there is no change 1599 * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class 1600 * @throws NullPointerException if the argument is null 1601 * 1602 * @see #accessClass(Class) 1603 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 1604 */ 1605 public Lookup in(Class<?> requestedLookupClass) { 1606 Objects.requireNonNull(requestedLookupClass); 1607 if (requestedLookupClass.isPrimitive()) 1608 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class"); 1609 if (requestedLookupClass.isArray()) 1610 throw new IllegalArgumentException(requestedLookupClass + " is an array class"); 1611 1612 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 1613 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES); 1614 if (requestedLookupClass == this.lookupClass) 1615 return this; // keep same capabilities 1616 int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL; 1617 Module fromModule = this.lookupClass.getModule(); 1618 Module targetModule = requestedLookupClass.getModule(); 1619 Class<?> plc = this.previousLookupClass(); 1620 if ((this.allowedModes & UNCONDITIONAL) != 0) { 1621 assert plc == null; 1622 newModes = UNCONDITIONAL; 1623 } else if (fromModule != targetModule) { 1624 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) { 1625 // allow hopping back and forth between fromModule and plc's module 1626 // but not the third module 1627 newModes = 0; 1628 } 1629 // drop MODULE access 1630 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED); 1631 // teleport from this lookup class 1632 plc = this.lookupClass; 1633 } 1634 if ((newModes & PACKAGE) != 0 1635 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 1636 newModes &= ~(PACKAGE|PRIVATE|PROTECTED); 1637 } 1638 // Allow nestmate lookups to be created without special privilege: 1639 if ((newModes & PRIVATE) != 0 1640 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 1641 newModes &= ~(PRIVATE|PROTECTED); 1642 } 1643 if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0 1644 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) { 1645 // The requested class it not accessible from the lookup class. 1646 // No permissions. 1647 newModes = 0; 1648 } 1649 return newLookup(requestedLookupClass, plc, newModes); 1650 } 1651 1652 /** 1653 * Creates a lookup on the same lookup class which this lookup object 1654 * finds members, but with a lookup mode that has lost the given lookup mode. 1655 * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE 1656 * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED}, 1657 * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or 1658 * {@link #UNCONDITIONAL UNCONDITIONAL}. 1659 * 1660 * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup}, 1661 * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set. 1662 * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting 1663 * lookup has no access. 1664 * 1665 * <p> If this lookup is not a public lookup, then the following applies 1666 * regardless of its {@linkplain #lookupModes() lookup modes}. 1667 * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always 1668 * dropped and so the resulting lookup mode will never have these access 1669 * capabilities. When dropping {@code PACKAGE} 1670 * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE} 1671 * access. When dropping {@code MODULE} then the resulting lookup will not 1672 * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. 1673 * When dropping {@code PUBLIC} then the resulting lookup has no access. 1674 * 1675 * @apiNote 1676 * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely 1677 * delegate non-public access within the package of the lookup class without 1678 * conferring <a href="MethodHandles.Lookup.html#privacc">private access</a>. 1679 * A lookup with {@code MODULE} but not 1680 * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within 1681 * the module of the lookup class without conferring package access. 1682 * A lookup with a {@linkplain #previousLookupClass() previous lookup class} 1683 * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access 1684 * to public classes accessible to both the module of the lookup class 1685 * and the module of the previous lookup class. 1686 * 1687 * @param modeToDrop the lookup mode to drop 1688 * @return a lookup object which lacks the indicated mode, or the same object if there is no change 1689 * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC}, 1690 * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL} 1691 * or {@code UNCONDITIONAL} 1692 * @see MethodHandles#privateLookupIn 1693 * @since 9 1694 */ 1695 public Lookup dropLookupMode(int modeToDrop) { 1696 int oldModes = lookupModes(); 1697 int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL); 1698 switch (modeToDrop) { 1699 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break; 1700 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break; 1701 case PACKAGE: newModes &= ~(PRIVATE); break; 1702 case PROTECTED: 1703 case PRIVATE: 1704 case ORIGINAL: 1705 case UNCONDITIONAL: break; 1706 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop"); 1707 } 1708 if (newModes == oldModes) return this; // return self if no change 1709 return newLookup(lookupClass(), previousLookupClass(), newModes); 1710 } 1711 1712 /** 1713 * Creates and links a class or interface from {@code bytes} 1714 * with the same class loader and in the same runtime package and 1715 * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's 1716 * {@linkplain #lookupClass() lookup class} as if calling 1717 * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1718 * ClassLoader::defineClass}. 1719 * 1720 * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include 1721 * {@link #PACKAGE PACKAGE} access as default (package) members will be 1722 * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate 1723 * that the lookup object was created by a caller in the runtime package (or derived 1724 * from a lookup originally created by suitably privileged code to a target class in 1725 * the runtime package). </p> 1726 * 1727 * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined 1728 * by the <em>The Java Virtual Machine Specification</em>) with a class name in the 1729 * same package as the lookup class. </p> 1730 * 1731 * <p> This method does not run the class initializer. The class initializer may 1732 * run at a later time, as detailed in section 12.4 of the <em>The Java Language 1733 * Specification</em>. </p> 1734 * 1735 * @param bytes the class bytes 1736 * @return the {@code Class} object for the class 1737 * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access 1738 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1739 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1740 * than the lookup class or {@code bytes} is not a class or interface 1741 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1742 * @throws VerifyError if the newly created class cannot be verified 1743 * @throws LinkageError if the newly created class cannot be linked for any other reason 1744 * @throws NullPointerException if {@code bytes} is {@code null} 1745 * @since 9 1746 * @see MethodHandles#privateLookupIn 1747 * @see Lookup#dropLookupMode 1748 * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain) 1749 */ 1750 public Class<?> defineClass(byte[] bytes) throws IllegalAccessException { 1751 if ((lookupModes() & PACKAGE) == 0) 1752 throw new IllegalAccessException("Lookup does not have PACKAGE access"); 1753 return makeClassDefiner(bytes.clone()).defineClass(false); 1754 } 1755 1756 /** 1757 * The set of class options that specify whether a hidden class created by 1758 * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 1759 * Lookup::defineHiddenClass} method is dynamically added as a new member 1760 * to the nest of a lookup class and/or whether a hidden class has 1761 * a strong relationship with the class loader marked as its defining loader. 1762 * 1763 * @since 15 1764 */ 1765 public enum ClassOption { 1766 /** 1767 * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest} 1768 * of a lookup class as a nestmate. 1769 * 1770 * <p> A hidden nestmate class has access to the private members of all 1771 * classes and interfaces in the same nest. 1772 * 1773 * @see Class#getNestHost() 1774 */ 1775 NESTMATE(NESTMATE_CLASS), 1776 1777 /** 1778 * Specifies that a hidden class has a <em>strong</em> 1779 * relationship with the class loader marked as its defining loader, 1780 * as a normal class or interface has with its own defining loader. 1781 * This means that the hidden class may be unloaded if and only if 1782 * its defining loader is not reachable and thus may be reclaimed 1783 * by a garbage collector (JLS {@jls 12.7}). 1784 * 1785 * <p> By default, a hidden class or interface may be unloaded 1786 * even if the class loader that is marked as its defining loader is 1787 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1788 1789 * 1790 * @jls 12.7 Unloading of Classes and Interfaces 1791 */ 1792 STRONG(STRONG_LOADER_LINK); 1793 1794 /* the flag value is used by VM at define class time */ 1795 private final int flag; 1796 ClassOption(int flag) { 1797 this.flag = flag; 1798 } 1799 1800 static int optionsToFlag(ClassOption[] options) { 1801 int flags = 0; 1802 for (ClassOption cp : options) { 1803 if ((flags & cp.flag) != 0) { 1804 throw new IllegalArgumentException("Duplicate ClassOption " + cp); 1805 } 1806 flags |= cp.flag; 1807 } 1808 return flags; 1809 } 1810 } 1811 1812 /** 1813 * Creates a <em>hidden</em> class or interface from {@code bytes}, 1814 * returning a {@code Lookup} on the newly created class or interface. 1815 * 1816 * <p> Ordinarily, a class or interface {@code C} is created by a class loader, 1817 * which either defines {@code C} directly or delegates to another class loader. 1818 * A class loader defines {@code C} directly by invoking 1819 * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1820 * ClassLoader::defineClass}, which causes the Java Virtual Machine 1821 * to derive {@code C} from a purported representation in {@code class} file format. 1822 * In situations where use of a class loader is undesirable, a class or interface 1823 * {@code C} can be created by this method instead. This method is capable of 1824 * defining {@code C}, and thereby creating it, without invoking 1825 * {@code ClassLoader::defineClass}. 1826 * Instead, this method defines {@code C} as if by arranging for 1827 * the Java Virtual Machine to derive a nonarray class or interface {@code C} 1828 * from a purported representation in {@code class} file format 1829 * using the following rules: 1830 * 1831 * <ol> 1832 * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup} 1833 * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access. 1834 * This level of access is needed to create {@code C} in the module 1835 * of the lookup class of this {@code Lookup}.</li> 1836 * 1837 * <li> The purported representation in {@code bytes} must be a {@code ClassFile} 1838 * structure (JVMS {@jvms 4.1}) of a supported major and minor version. 1839 * The major and minor version may differ from the {@code class} file version 1840 * of the lookup class of this {@code Lookup}.</li> 1841 * 1842 * <li> The value of {@code this_class} must be a valid index in the 1843 * {@code constant_pool} table, and the entry at that index must be a valid 1844 * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name 1845 * encoded in internal form that is specified by this structure. {@code N} must 1846 * denote a class or interface in the same package as the lookup class.</li> 1847 * 1848 * <li> Let {@code CN} be the string {@code N + "." + <suffix>}, 1849 * where {@code <suffix>} is an unqualified name. 1850 * 1851 * <p> Let {@code newBytes} be the {@code ClassFile} structure given by 1852 * {@code bytes} with an additional entry in the {@code constant_pool} table, 1853 * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and 1854 * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class} 1855 * refers to the new {@code CONSTANT_Utf8_info} structure. 1856 * 1857 * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}. 1858 * 1859 * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and 1860 * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5}, 1861 * with the following adjustments: 1862 * <ul> 1863 * <li> The constant indicated by {@code this_class} is permitted to specify a name 1864 * that includes a single {@code "."} character, even though this is not a valid 1865 * binary class or interface name in internal form.</li> 1866 * 1867 * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C}, 1868 * but no class loader is recorded as an initiating class loader of {@code C}.</li> 1869 * 1870 * <li> {@code C} is considered to have the same runtime 1871 * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module} 1872 * and {@linkplain java.security.ProtectionDomain protection domain} 1873 * as the lookup class of this {@code Lookup}. 1874 * <li> Let {@code GN} be the binary name obtained by taking {@code N} 1875 * (a binary name encoded in internal form) and replacing ASCII forward slashes with 1876 * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}: 1877 * <ul> 1878 * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>}, 1879 * even though this is not a valid binary class or interface name.</li> 1880 * <li> {@link Class#descriptorString()} returns the string 1881 * {@code "L" + N + "." + <suffix> + ";"}, 1882 * even though this is not a valid type descriptor name.</li> 1883 * <li> {@link Class#describeConstable()} returns an empty optional as {@code C} 1884 * cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li> 1885 * </ul> 1886 * </ul> 1887 * </li> 1888 * </ol> 1889 * 1890 * <p> After {@code C} is derived, it is linked by the Java Virtual Machine. 1891 * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments: 1892 * <ul> 1893 * <li> During verification, whenever it is necessary to load the class named 1894 * {@code CN}, the attempt succeeds, producing class {@code C}. No request is 1895 * made of any class loader.</li> 1896 * 1897 * <li> On any attempt to resolve the entry in the run-time constant pool indicated 1898 * by {@code this_class}, the symbolic reference is considered to be resolved to 1899 * {@code C} and resolution always succeeds immediately.</li> 1900 * </ul> 1901 * 1902 * <p> If the {@code initialize} parameter is {@code true}, 1903 * then {@code C} is initialized by the Java Virtual Machine. 1904 * 1905 * <p> The newly created class or interface {@code C} serves as the 1906 * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object 1907 * returned by this method. {@code C} is <em>hidden</em> in the sense that 1908 * no other class or interface can refer to {@code C} via a constant pool entry. 1909 * That is, a hidden class or interface cannot be named as a supertype, a field type, 1910 * a method parameter type, or a method return type by any other class. 1911 * This is because a hidden class or interface does not have a binary name, so 1912 * there is no internal form available to record in any class's constant pool. 1913 * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)}, 1914 * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and 1915 * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class) 1916 * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html"> 1917 * JVM Tool Interface</a>. 1918 * 1919 * <p> A class or interface created by 1920 * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain) 1921 * a class loader} has a strong relationship with that class loader. 1922 * That is, every {@code Class} object contains a reference to the {@code ClassLoader} 1923 * that {@linkplain Class#getClassLoader() defined it}. 1924 * This means that a class created by a class loader may be unloaded if and 1925 * only if its defining loader is not reachable and thus may be reclaimed 1926 * by a garbage collector (JLS {@jls 12.7}). 1927 * 1928 * By default, however, a hidden class or interface may be unloaded even if 1929 * the class loader that is marked as its defining loader is 1930 * <a href="../ref/package-summary.html#reachability">reachable</a>. 1931 * This behavior is useful when a hidden class or interface serves multiple 1932 * classes defined by arbitrary class loaders. In other cases, a hidden 1933 * class or interface may be linked to a single class (or a small number of classes) 1934 * with the same defining loader as the hidden class or interface. 1935 * In such cases, where the hidden class or interface must be coterminous 1936 * with a normal class or interface, the {@link ClassOption#STRONG STRONG} 1937 * option may be passed in {@code options}. 1938 * This arranges for a hidden class to have the same strong relationship 1939 * with the class loader marked as its defining loader, 1940 * as a normal class or interface has with its own defining loader. 1941 * 1942 * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass} 1943 * may still prevent a hidden class or interface from being 1944 * unloaded by ensuring that the {@code Class} object is reachable. 1945 * 1946 * <p> The unloading characteristics are set for each hidden class when it is 1947 * defined, and cannot be changed later. An advantage of allowing hidden classes 1948 * to be unloaded independently of the class loader marked as their defining loader 1949 * is that a very large number of hidden classes may be created by an application. 1950 * In contrast, if {@code STRONG} is used, then the JVM may run out of memory, 1951 * just as if normal classes were created by class loaders. 1952 * 1953 * <p> Classes and interfaces in a nest are allowed to have mutual access to 1954 * their private members. The nest relationship is determined by 1955 * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and 1956 * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file. 1957 * By default, a hidden class belongs to a nest consisting only of itself 1958 * because a hidden class has no binary name. 1959 * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options} 1960 * to create a hidden class or interface {@code C} as a member of a nest. 1961 * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute 1962 * in the {@code ClassFile} structure from which {@code C} was derived. 1963 * Instead, the following rules determine the nest host of {@code C}: 1964 * <ul> 1965 * <li>If the nest host of the lookup class of this {@code Lookup} has previously 1966 * been determined, then let {@code H} be the nest host of the lookup class. 1967 * Otherwise, the nest host of the lookup class is determined using the 1968 * algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li> 1969 * <li>The nest host of {@code C} is determined to be {@code H}, 1970 * the nest host of the lookup class.</li> 1971 * </ul> 1972 * 1973 * <p> A hidden class or interface may be serializable, but this requires a custom 1974 * serialization mechanism in order to ensure that instances are properly serialized 1975 * and deserialized. The default serialization mechanism supports only classes and 1976 * interfaces that are discoverable by their class name. 1977 * 1978 * @param bytes the bytes that make up the class data, 1979 * in the format of a valid {@code class} file as defined by 1980 * <cite>The Java Virtual Machine Specification</cite>. 1981 * @param initialize if {@code true} the class will be initialized. 1982 * @param options {@linkplain ClassOption class options} 1983 * @return the {@code Lookup} object on the hidden class, 1984 * with {@linkplain #ORIGINAL original} and 1985 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 1986 * 1987 * @throws IllegalAccessException if this {@code Lookup} does not have 1988 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 1989 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 1990 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 1991 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 1992 * than the lookup class or {@code bytes} is not a class or interface 1993 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 1994 * @throws IncompatibleClassChangeError if the class or interface named as 1995 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 1996 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 1997 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 1998 * {@code C} is {@code C} itself 1999 * @throws VerifyError if the newly created class cannot be verified 2000 * @throws LinkageError if the newly created class cannot be linked for any other reason 2001 * @throws NullPointerException if any parameter is {@code null} 2002 * 2003 * @since 15 2004 * @see Class#isHidden() 2005 * @jvms 4.2.1 Binary Class and Interface Names 2006 * @jvms 4.2.2 Unqualified Names 2007 * @jvms 4.7.28 The {@code NestHost} Attribute 2008 * @jvms 4.7.29 The {@code NestMembers} Attribute 2009 * @jvms 5.4.3.1 Class and Interface Resolution 2010 * @jvms 5.4.4 Access Control 2011 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2012 * @jvms 5.4 Linking 2013 * @jvms 5.5 Initialization 2014 * @jls 12.7 Unloading of Classes and Interfaces 2015 */ 2016 @SuppressWarnings("doclint:reference") // cross-module links 2017 public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options) 2018 throws IllegalAccessException 2019 { 2020 Objects.requireNonNull(bytes); 2021 int flags = ClassOption.optionsToFlag(options); 2022 if (!hasFullPrivilegeAccess()) { 2023 throw new IllegalAccessException(this + " does not have full privilege access"); 2024 } 2025 2026 return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize); 2027 } 2028 2029 /** 2030 * Creates a <em>hidden</em> class or interface from {@code bytes} with associated 2031 * {@linkplain MethodHandles#classData(Lookup, String, Class) class data}, 2032 * returning a {@code Lookup} on the newly created class or interface. 2033 * 2034 * <p> This method is equivalent to calling 2035 * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)} 2036 * as if the hidden class is injected with a private static final <i>unnamed</i> 2037 * field which is initialized with the given {@code classData} at 2038 * the first instruction of the class initializer. 2039 * The newly created class is linked by the Java Virtual Machine. 2040 * 2041 * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} 2042 * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt} 2043 * methods can be used to retrieve the {@code classData}. 2044 * 2045 * @apiNote 2046 * A framework can create a hidden class with class data with one or more 2047 * objects and load the class data as dynamically-computed constant(s) 2048 * via a bootstrap method. {@link MethodHandles#classData(Lookup, String, Class) 2049 * Class data} is accessible only to the lookup object created by the newly 2050 * defined hidden class but inaccessible to other members in the same nest 2051 * (unlike private static fields that are accessible to nestmates). 2052 * Care should be taken w.r.t. mutability for example when passing 2053 * an array or other mutable structure through the class data. 2054 * Changing any value stored in the class data at runtime may lead to 2055 * unpredictable behavior. 2056 * If the class data is a {@code List}, it is good practice to make it 2057 * unmodifiable for example via {@link List#of List::of}. 2058 * 2059 * @param bytes the class bytes 2060 * @param classData pre-initialized class data 2061 * @param initialize if {@code true} the class will be initialized. 2062 * @param options {@linkplain ClassOption class options} 2063 * @return the {@code Lookup} object on the hidden class, 2064 * with {@linkplain #ORIGINAL original} and 2065 * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access 2066 * 2067 * @throws IllegalAccessException if this {@code Lookup} does not have 2068 * {@linkplain #hasFullPrivilegeAccess() full privilege} access 2069 * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure 2070 * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version 2071 * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package 2072 * than the lookup class or {@code bytes} is not a class or interface 2073 * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item) 2074 * @throws IncompatibleClassChangeError if the class or interface named as 2075 * the direct superclass of {@code C} is in fact an interface, or if any of the classes 2076 * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces 2077 * @throws ClassCircularityError if any of the superclasses or superinterfaces of 2078 * {@code C} is {@code C} itself 2079 * @throws VerifyError if the newly created class cannot be verified 2080 * @throws LinkageError if the newly created class cannot be linked for any other reason 2081 * @throws NullPointerException if any parameter is {@code null} 2082 * 2083 * @since 16 2084 * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...) 2085 * @see Class#isHidden() 2086 * @see MethodHandles#classData(Lookup, String, Class) 2087 * @see MethodHandles#classDataAt(Lookup, String, Class, int) 2088 * @jvms 4.2.1 Binary Class and Interface Names 2089 * @jvms 4.2.2 Unqualified Names 2090 * @jvms 4.7.28 The {@code NestHost} Attribute 2091 * @jvms 4.7.29 The {@code NestMembers} Attribute 2092 * @jvms 5.4.3.1 Class and Interface Resolution 2093 * @jvms 5.4.4 Access Control 2094 * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation 2095 * @jvms 5.4 Linking 2096 * @jvms 5.5 Initialization 2097 * @jls 12.7 Unloading of Classes and Interfaces 2098 */ 2099 public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options) 2100 throws IllegalAccessException 2101 { 2102 Objects.requireNonNull(bytes); 2103 Objects.requireNonNull(classData); 2104 2105 int flags = ClassOption.optionsToFlag(options); 2106 2107 if (!hasFullPrivilegeAccess()) { 2108 throw new IllegalAccessException(this + " does not have full privilege access"); 2109 } 2110 2111 return makeHiddenClassDefiner(bytes.clone(), false, flags) 2112 .defineClassAsLookup(initialize, classData); 2113 } 2114 2115 // A default dumper for writing class files passed to Lookup::defineClass 2116 // and Lookup::defineHiddenClass to disk for debugging purposes. To enable, 2117 // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or 2118 // -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true 2119 // 2120 // This default dumper does not dump hidden classes defined by LambdaMetafactory 2121 // and LambdaForms and method handle internals. They are dumped via 2122 // different ClassFileDumpers. 2123 private static ClassFileDumper defaultDumper() { 2124 return DEFAULT_DUMPER; 2125 } 2126 2127 private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance( 2128 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES"); 2129 2130 /** 2131 * This method checks the class file version and the structure of `this_class`. 2132 * and checks if the bytes is a class or interface (ACC_MODULE flag not set) 2133 * that is in the named package. 2134 * 2135 * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags 2136 * or the class is not in the given package name. 2137 */ 2138 static String validateAndFindInternalName(byte[] bytes, String pkgName) { 2139 int magic = readInt(bytes, 0); 2140 if (magic != ClassFile.MAGIC_NUMBER) { 2141 throw new ClassFormatError("Incompatible magic value: " + magic); 2142 } 2143 // We have to read major and minor this way as ClassFile API throws IAE 2144 // yet we want distinct ClassFormatError and UnsupportedClassVersionError 2145 int minor = readUnsignedShort(bytes, 4); 2146 int major = readUnsignedShort(bytes, 6); 2147 2148 if (!VM.isSupportedClassFileVersion(major, minor)) { 2149 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor); 2150 } 2151 2152 String name; 2153 ClassDesc sym; 2154 int accessFlags; 2155 try { 2156 ClassModel cm = ClassFile.of().parse(bytes); 2157 var thisClass = cm.thisClass(); 2158 name = thisClass.asInternalName(); 2159 sym = thisClass.asSymbol(); 2160 accessFlags = cm.flags().flagsMask(); 2161 } catch (IllegalArgumentException e) { 2162 ClassFormatError cfe = new ClassFormatError(); 2163 cfe.initCause(e); 2164 throw cfe; 2165 } 2166 // must be a class or interface 2167 if ((accessFlags & ACC_MODULE) != 0) { 2168 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set"); 2169 } 2170 2171 String pn = sym.packageName(); 2172 if (!pn.equals(pkgName)) { 2173 throw newIllegalArgumentException(name + " not in same package as lookup class"); 2174 } 2175 2176 return name; 2177 } 2178 2179 private static int readInt(byte[] bytes, int offset) { 2180 if ((offset + 4) > bytes.length) { 2181 throw new ClassFormatError("Invalid ClassFile structure"); 2182 } 2183 return ((bytes[offset] & 0xFF) << 24) 2184 | ((bytes[offset + 1] & 0xFF) << 16) 2185 | ((bytes[offset + 2] & 0xFF) << 8) 2186 | (bytes[offset + 3] & 0xFF); 2187 } 2188 2189 private static int readUnsignedShort(byte[] bytes, int offset) { 2190 if ((offset+2) > bytes.length) { 2191 throw new ClassFormatError("Invalid ClassFile structure"); 2192 } 2193 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF); 2194 } 2195 2196 /* 2197 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2198 * from the given bytes. 2199 * 2200 * Caller should make a defensive copy of the arguments if needed 2201 * before calling this factory method. 2202 * 2203 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2204 * {@code bytes} denotes a class in a different package than the lookup class 2205 */ 2206 private ClassDefiner makeClassDefiner(byte[] bytes) { 2207 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2208 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper()); 2209 } 2210 2211 /** 2212 * Returns a ClassDefiner that creates a {@code Class} object of a normal class 2213 * from the given bytes. No package name check on the given bytes. 2214 * 2215 * @param internalName internal name 2216 * @param bytes class bytes 2217 * @param dumper dumper to write the given bytes to the dumper's output directory 2218 * @return ClassDefiner that defines a normal class of the given bytes. 2219 */ 2220 ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2221 // skip package name validation 2222 return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper); 2223 } 2224 2225 /** 2226 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2227 * from the given bytes. The name must be in the same package as the lookup class. 2228 * 2229 * Caller should make a defensive copy of the arguments if needed 2230 * before calling this factory method. 2231 * 2232 * @param bytes class bytes 2233 * @param dumper dumper to write the given bytes to the dumper's output directory 2234 * @return ClassDefiner that defines a hidden class of the given bytes. 2235 * 2236 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2237 * {@code bytes} denotes a class in a different package than the lookup class 2238 */ 2239 ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) { 2240 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2241 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2242 } 2243 2244 /** 2245 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2246 * from the given bytes and options. 2247 * The name must be in the same package as the lookup class. 2248 * 2249 * Caller should make a defensive copy of the arguments if needed 2250 * before calling this factory method. 2251 * 2252 * @param bytes class bytes 2253 * @param flags class option flag mask 2254 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2255 * @return ClassDefiner that defines a hidden class of the given bytes and options 2256 * 2257 * @throws IllegalArgumentException if {@code bytes} is not a class or interface or 2258 * {@code bytes} denotes a class in a different package than the lookup class 2259 */ 2260 private ClassDefiner makeHiddenClassDefiner(byte[] bytes, 2261 boolean accessVmAnnotations, 2262 int flags) { 2263 var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName()); 2264 return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags); 2265 } 2266 2267 /** 2268 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2269 * from the given bytes and the given options. No package name check on the given bytes. 2270 * 2271 * @param internalName internal name that specifies the prefix of the hidden class 2272 * @param bytes class bytes 2273 * @param dumper dumper to write the given bytes to the dumper's output directory 2274 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2275 */ 2276 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) { 2277 Objects.requireNonNull(dumper); 2278 // skip name and access flags validation 2279 return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0); 2280 } 2281 2282 /** 2283 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2284 * from the given bytes and the given options. No package name check on the given bytes. 2285 * 2286 * @param internalName internal name that specifies the prefix of the hidden class 2287 * @param bytes class bytes 2288 * @param flags class options flag mask 2289 * @param dumper dumper to write the given bytes to the dumper's output directory 2290 * @return ClassDefiner that defines a hidden class of the given bytes and options. 2291 */ 2292 ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) { 2293 Objects.requireNonNull(dumper); 2294 // skip name and access flags validation 2295 return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags); 2296 } 2297 2298 /** 2299 * Returns a ClassDefiner that creates a {@code Class} object of a hidden class 2300 * from the given class file and options. 2301 * 2302 * @param internalName internal name 2303 * @param bytes Class byte array 2304 * @param flags class option flag mask 2305 * @param accessVmAnnotations true to give the hidden class access to VM annotations 2306 * @param dumper dumper to write the given bytes to the dumper's output directory 2307 */ 2308 private ClassDefiner makeHiddenClassDefiner(String internalName, 2309 byte[] bytes, 2310 boolean accessVmAnnotations, 2311 ClassFileDumper dumper, 2312 int flags) { 2313 flags |= HIDDEN_CLASS; 2314 if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) { 2315 // jdk.internal.vm.annotations are permitted for classes 2316 // defined to boot loader and platform loader 2317 flags |= ACCESS_VM_ANNOTATIONS; 2318 } 2319 2320 return new ClassDefiner(this, internalName, bytes, flags, dumper); 2321 } 2322 2323 record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) { 2324 ClassDefiner { 2325 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK); 2326 } 2327 2328 Class<?> defineClass(boolean initialize) { 2329 return defineClass(initialize, null); 2330 } 2331 2332 Lookup defineClassAsLookup(boolean initialize) { 2333 Class<?> c = defineClass(initialize, null); 2334 return new Lookup(c, null, FULL_POWER_MODES); 2335 } 2336 2337 /** 2338 * Defines the class of the given bytes and the given classData. 2339 * If {@code initialize} parameter is true, then the class will be initialized. 2340 * 2341 * @param initialize true if the class to be initialized 2342 * @param classData classData or null 2343 * @return the class 2344 * 2345 * @throws LinkageError linkage error 2346 */ 2347 Class<?> defineClass(boolean initialize, Object classData) { 2348 Class<?> lookupClass = lookup.lookupClass(); 2349 ClassLoader loader = lookupClass.getClassLoader(); 2350 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null; 2351 Class<?> c = null; 2352 try { 2353 c = SharedSecrets.getJavaLangAccess() 2354 .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData); 2355 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost(); 2356 return c; 2357 } finally { 2358 // dump the classfile for debugging 2359 if (dumper.isEnabled()) { 2360 String name = internalName(); 2361 if (c != null) { 2362 dumper.dumpClass(name, c, bytes); 2363 } else { 2364 dumper.dumpFailedClass(name, bytes); 2365 } 2366 } 2367 } 2368 } 2369 2370 /** 2371 * Defines the class of the given bytes and the given classData. 2372 * If {@code initialize} parameter is true, then the class will be initialized. 2373 * 2374 * @param initialize true if the class to be initialized 2375 * @param classData classData or null 2376 * @return a Lookup for the defined class 2377 * 2378 * @throws LinkageError linkage error 2379 */ 2380 Lookup defineClassAsLookup(boolean initialize, Object classData) { 2381 Class<?> c = defineClass(initialize, classData); 2382 return new Lookup(c, null, FULL_POWER_MODES); 2383 } 2384 2385 private boolean isNestmate() { 2386 return (classFlags & NESTMATE_CLASS) != 0; 2387 } 2388 } 2389 2390 private ProtectionDomain lookupClassProtectionDomain() { 2391 ProtectionDomain pd = cachedProtectionDomain; 2392 if (pd == null) { 2393 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass); 2394 } 2395 return pd; 2396 } 2397 2398 // cached protection domain 2399 private volatile ProtectionDomain cachedProtectionDomain; 2400 2401 // Make sure outer class is initialized first. 2402 static { IMPL_NAMES.getClass(); } 2403 2404 /** Package-private version of lookup which is trusted. */ 2405 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED); 2406 2407 /** Version of lookup which is trusted minimally. 2408 * It can only be used to create method handles to publicly accessible 2409 * members in packages that are exported unconditionally. 2410 */ 2411 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL); 2412 2413 private static void checkUnprivilegedlookupClass(Class<?> lookupClass) { 2414 String name = lookupClass.getName(); 2415 if (name.startsWith("java.lang.invoke.")) 2416 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 2417 } 2418 2419 /** 2420 * Displays the name of the class from which lookups are to be made, 2421 * followed by "/" and the name of the {@linkplain #previousLookupClass() 2422 * previous lookup class} if present. 2423 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 2424 * If there are restrictions on the access permitted to this lookup, 2425 * this is indicated by adding a suffix to the class name, consisting 2426 * of a slash and a keyword. The keyword represents the strongest 2427 * allowed access, and is chosen as follows: 2428 * <ul> 2429 * <li>If no access is allowed, the suffix is "/noaccess". 2430 * <li>If only unconditional access is allowed, the suffix is "/publicLookup". 2431 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 2432 * <li>If only public and module access are allowed, the suffix is "/module". 2433 * <li>If public and package access are allowed, the suffix is "/package". 2434 * <li>If public, package, and private access are allowed, the suffix is "/private". 2435 * </ul> 2436 * If none of the above cases apply, it is the case that 2437 * {@linkplain #hasFullPrivilegeAccess() full privilege access} 2438 * (public, module, package, private, and protected) is allowed. 2439 * In this case, no suffix is added. 2440 * This is true only of an object obtained originally from 2441 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 2442 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 2443 * always have restricted access, and will display a suffix. 2444 * <p> 2445 * (It may seem strange that protected access should be 2446 * stronger than private access. Viewed independently from 2447 * package access, protected access is the first to be lost, 2448 * because it requires a direct subclass relationship between 2449 * caller and callee.) 2450 * @see #in 2451 */ 2452 @Override 2453 public String toString() { 2454 String cname = lookupClass.getName(); 2455 if (prevLookupClass != null) 2456 cname += "/" + prevLookupClass.getName(); 2457 switch (allowedModes) { 2458 case 0: // no privileges 2459 return cname + "/noaccess"; 2460 case UNCONDITIONAL: 2461 return cname + "/publicLookup"; 2462 case PUBLIC: 2463 return cname + "/public"; 2464 case PUBLIC|MODULE: 2465 return cname + "/module"; 2466 case PUBLIC|PACKAGE: 2467 case PUBLIC|MODULE|PACKAGE: 2468 return cname + "/package"; 2469 case PUBLIC|PACKAGE|PRIVATE: 2470 case PUBLIC|MODULE|PACKAGE|PRIVATE: 2471 return cname + "/private"; 2472 case PUBLIC|PACKAGE|PRIVATE|PROTECTED: 2473 case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED: 2474 case FULL_POWER_MODES: 2475 return cname; 2476 case TRUSTED: 2477 return "/trusted"; // internal only; not exported 2478 default: // Should not happen, but it's a bitfield... 2479 cname = cname + "/" + Integer.toHexString(allowedModes); 2480 assert(false) : cname; 2481 return cname; 2482 } 2483 } 2484 2485 /** 2486 * Produces a method handle for a static method. 2487 * The type of the method handle will be that of the method. 2488 * (Since static methods do not take receivers, there is no 2489 * additional receiver argument inserted into the method handle type, 2490 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 2491 * The method and all its argument types must be accessible to the lookup object. 2492 * <p> 2493 * The returned method handle will have 2494 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2495 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2496 * <p> 2497 * If the returned method handle is invoked, the method's class will 2498 * be initialized, if it has not already been initialized. 2499 * <p><b>Example:</b> 2500 * {@snippet lang="java" : 2501 import static java.lang.invoke.MethodHandles.*; 2502 import static java.lang.invoke.MethodType.*; 2503 ... 2504 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 2505 "asList", methodType(List.class, Object[].class)); 2506 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 2507 * } 2508 * @param refc the class from which the method is accessed 2509 * @param name the name of the method 2510 * @param type the type of the method 2511 * @return the desired method handle 2512 * @throws NoSuchMethodException if the method does not exist 2513 * @throws IllegalAccessException if access checking fails, 2514 * or if the method is not {@code static}, 2515 * or if the method's variable arity modifier bit 2516 * is set and {@code asVarargsCollector} fails 2517 * @throws NullPointerException if any argument is null 2518 */ 2519 public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2520 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 2521 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method)); 2522 } 2523 2524 /** 2525 * Produces a method handle for a virtual method. 2526 * The type of the method handle will be that of the method, 2527 * with the receiver type (usually {@code refc}) prepended. 2528 * The method and all its argument types must be accessible to the lookup object. 2529 * <p> 2530 * When called, the handle will treat the first argument as a receiver 2531 * and, for non-private methods, dispatch on the receiver's type to determine which method 2532 * implementation to enter. 2533 * For private methods the named method in {@code refc} will be invoked on the receiver. 2534 * (The dispatching action is identical with that performed by an 2535 * {@code invokevirtual} or {@code invokeinterface} instruction.) 2536 * <p> 2537 * The first argument will be of type {@code refc} if the lookup 2538 * class has full privileges to access the member. Otherwise 2539 * the member must be {@code protected} and the first argument 2540 * will be restricted in type to the lookup class. 2541 * <p> 2542 * The returned method handle will have 2543 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2544 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2545 * <p> 2546 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 2547 * instructions and method handles produced by {@code findVirtual}, 2548 * if the class is {@code MethodHandle} and the name string is 2549 * {@code invokeExact} or {@code invoke}, the resulting 2550 * method handle is equivalent to one produced by 2551 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 2552 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 2553 * with the same {@code type} argument. 2554 * <p> 2555 * If the class is {@code VarHandle} and the name string corresponds to 2556 * the name of a signature-polymorphic access mode method, the resulting 2557 * method handle is equivalent to one produced by 2558 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 2559 * the access mode corresponding to the name string and with the same 2560 * {@code type} arguments. 2561 * <p> 2562 * <b>Example:</b> 2563 * {@snippet lang="java" : 2564 import static java.lang.invoke.MethodHandles.*; 2565 import static java.lang.invoke.MethodType.*; 2566 ... 2567 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 2568 "concat", methodType(String.class, String.class)); 2569 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 2570 "hashCode", methodType(int.class)); 2571 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 2572 "hashCode", methodType(int.class)); 2573 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 2574 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 2575 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 2576 // interface method: 2577 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 2578 "subSequence", methodType(CharSequence.class, int.class, int.class)); 2579 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 2580 // constructor "internal method" must be accessed differently: 2581 MethodType MT_newString = methodType(void.class); //()V for new String() 2582 try { assertEquals("impossible", lookup() 2583 .findVirtual(String.class, "<init>", MT_newString)); 2584 } catch (NoSuchMethodException ex) { } // OK 2585 MethodHandle MH_newString = publicLookup() 2586 .findConstructor(String.class, MT_newString); 2587 assertEquals("", (String) MH_newString.invokeExact()); 2588 * } 2589 * 2590 * @param refc the class or interface from which the method is accessed 2591 * @param name the name of the method 2592 * @param type the type of the method, with the receiver argument omitted 2593 * @return the desired method handle 2594 * @throws NoSuchMethodException if the method does not exist 2595 * @throws IllegalAccessException if access checking fails, 2596 * or if the method is {@code static}, 2597 * or if the method's variable arity modifier bit 2598 * is set and {@code asVarargsCollector} fails 2599 * @throws NullPointerException if any argument is null 2600 */ 2601 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2602 if (refc == MethodHandle.class) { 2603 MethodHandle mh = findVirtualForMH(name, type); 2604 if (mh != null) return mh; 2605 } else if (refc == VarHandle.class) { 2606 MethodHandle mh = findVirtualForVH(name, type); 2607 if (mh != null) return mh; 2608 } 2609 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 2610 MemberName method = resolveOrFail(refKind, refc, name, type); 2611 return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method)); 2612 } 2613 private MethodHandle findVirtualForMH(String name, MethodType type) { 2614 // these names require special lookups because of the implicit MethodType argument 2615 if ("invoke".equals(name)) 2616 return invoker(type); 2617 if ("invokeExact".equals(name)) 2618 return exactInvoker(type); 2619 assert(!MemberName.isMethodHandleInvokeName(name)); 2620 return null; 2621 } 2622 private MethodHandle findVirtualForVH(String name, MethodType type) { 2623 try { 2624 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 2625 } catch (IllegalArgumentException e) { 2626 return null; 2627 } 2628 } 2629 2630 /** 2631 * Produces a method handle which creates an object and initializes it, using 2632 * the constructor of the specified type. 2633 * The parameter types of the method handle will be those of the constructor, 2634 * while the return type will be a reference to the constructor's class. 2635 * The constructor and all its argument types must be accessible to the lookup object. 2636 * <p> 2637 * The requested type must have a return type of {@code void}. 2638 * (This is consistent with the JVM's treatment of constructor type descriptors.) 2639 * <p> 2640 * The returned method handle will have 2641 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2642 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 2643 * <p> 2644 * If the returned method handle is invoked, the constructor's class will 2645 * be initialized, if it has not already been initialized. 2646 * <p><b>Example:</b> 2647 * {@snippet lang="java" : 2648 import static java.lang.invoke.MethodHandles.*; 2649 import static java.lang.invoke.MethodType.*; 2650 ... 2651 MethodHandle MH_newArrayList = publicLookup().findConstructor( 2652 ArrayList.class, methodType(void.class, Collection.class)); 2653 Collection orig = Arrays.asList("x", "y"); 2654 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 2655 assert(orig != copy); 2656 assertEquals(orig, copy); 2657 // a variable-arity constructor: 2658 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 2659 ProcessBuilder.class, methodType(void.class, String[].class)); 2660 ProcessBuilder pb = (ProcessBuilder) 2661 MH_newProcessBuilder.invoke("x", "y", "z"); 2662 assertEquals("[x, y, z]", pb.command().toString()); 2663 * } 2664 * @param refc the class or interface from which the method is accessed 2665 * @param type the type of the method, with the receiver argument omitted, and a void return type 2666 * @return the desired method handle 2667 * @throws NoSuchMethodException if the constructor does not exist 2668 * @throws IllegalAccessException if access checking fails 2669 * or if the method's variable arity modifier bit 2670 * is set and {@code asVarargsCollector} fails 2671 * @throws NullPointerException if any argument is null 2672 */ 2673 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 2674 if (refc.isArray()) { 2675 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 2676 } 2677 String name = ConstantDescs.INIT_NAME; 2678 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 2679 return getDirectConstructor(refc, ctor); 2680 } 2681 2682 /** 2683 * Looks up a class by name from the lookup context defined by this {@code Lookup} object, 2684 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction. 2685 * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class, 2686 * and then determines whether the class is accessible to this lookup object. 2687 * <p> 2688 * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}. 2689 * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences 2690 * of {@code '['} and followed by the element type as encoded in the 2691 * {@linkplain Class##nameFormat table} specified in {@link Class#getName}. 2692 * <p> 2693 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, 2694 * its class loader, and the {@linkplain #lookupModes() lookup modes}. 2695 * 2696 * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class 2697 * or the string representing an array class 2698 * @return the requested class. 2699 * @throws LinkageError if the linkage fails 2700 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 2701 * @throws IllegalAccessException if the class is not accessible, using the allowed access 2702 * modes. 2703 * @throws NullPointerException if {@code targetName} is null 2704 * @since 9 2705 * @jvms 5.4.3.1 Class and Interface Resolution 2706 */ 2707 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 2708 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 2709 return accessClass(targetClass); 2710 } 2711 2712 /** 2713 * Ensures that {@code targetClass} has been initialized. The class 2714 * to be initialized must be {@linkplain #accessClass accessible} 2715 * to this {@code Lookup} object. This method causes {@code targetClass} 2716 * to be initialized if it has not been already initialized, 2717 * as specified in JVMS {@jvms 5.5}. 2718 * 2719 * <p> 2720 * This method returns when {@code targetClass} is fully initialized, or 2721 * when {@code targetClass} is being initialized by the current thread. 2722 * 2723 * @param <T> the type of the class to be initialized 2724 * @param targetClass the class to be initialized 2725 * @return {@code targetClass} that has been initialized, or that is being 2726 * initialized by the current thread. 2727 * 2728 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or {@code void} 2729 * or array class 2730 * @throws IllegalAccessException if {@code targetClass} is not 2731 * {@linkplain #accessClass accessible} to this lookup 2732 * @throws ExceptionInInitializerError if the class initialization provoked 2733 * by this method fails 2734 * @since 15 2735 * @jvms 5.5 Initialization 2736 */ 2737 public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException { 2738 if (targetClass.isPrimitive()) 2739 throw new IllegalArgumentException(targetClass + " is a primitive class"); 2740 if (targetClass.isArray()) 2741 throw new IllegalArgumentException(targetClass + " is an array class"); 2742 2743 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) { 2744 throw makeAccessException(targetClass); 2745 } 2746 2747 // ensure class initialization 2748 Unsafe.getUnsafe().ensureClassInitialized(targetClass); 2749 return targetClass; 2750 } 2751 2752 /* 2753 * Returns IllegalAccessException due to access violation to the given targetClass. 2754 * 2755 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized} 2756 * which verifies access to a class rather a member. 2757 */ 2758 private IllegalAccessException makeAccessException(Class<?> targetClass) { 2759 String message = "access violation: "+ targetClass; 2760 if (this == MethodHandles.publicLookup()) { 2761 message += ", from public Lookup"; 2762 } else { 2763 Module m = lookupClass().getModule(); 2764 message += ", from " + lookupClass() + " (" + m + ")"; 2765 if (prevLookupClass != null) { 2766 message += ", previous lookup " + 2767 prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")"; 2768 } 2769 } 2770 return new IllegalAccessException(message); 2771 } 2772 2773 /** 2774 * Determines if a class can be accessed from the lookup context defined by 2775 * this {@code Lookup} object. The static initializer of the class is not run. 2776 * If {@code targetClass} is an array class, {@code targetClass} is accessible 2777 * if the element type of the array class is accessible. Otherwise, 2778 * {@code targetClass} is determined as accessible as follows. 2779 * 2780 * <p> 2781 * If {@code targetClass} is in the same module as the lookup class, 2782 * the lookup class is {@code LC} in module {@code M1} and 2783 * the previous lookup class is in module {@code M0} or 2784 * {@code null} if not present, 2785 * {@code targetClass} is accessible if and only if one of the following is true: 2786 * <ul> 2787 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is 2788 * {@code LC} or other class in the same nest of {@code LC}.</li> 2789 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is 2790 * in the same runtime package of {@code LC}.</li> 2791 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is 2792 * a public type in {@code M1}.</li> 2793 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is 2794 * a public type in a package exported by {@code M1} to at least {@code M0} 2795 * if the previous lookup class is present; otherwise, {@code targetClass} 2796 * is a public type in a package exported by {@code M1} unconditionally.</li> 2797 * </ul> 2798 * 2799 * <p> 2800 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup 2801 * can access public types in all modules when the type is in a package 2802 * that is exported unconditionally. 2803 * <p> 2804 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass}, 2805 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass} 2806 * is inaccessible. 2807 * <p> 2808 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class}, 2809 * {@code M1} is the module containing {@code lookupClass} and 2810 * {@code M2} is the module containing {@code targetClass}, 2811 * then {@code targetClass} is accessible if and only if 2812 * <ul> 2813 * <li>{@code M1} reads {@code M2}, and 2814 * <li>{@code targetClass} is public and in a package exported by 2815 * {@code M2} at least to {@code M1}. 2816 * </ul> 2817 * <p> 2818 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class}, 2819 * {@code M1} and {@code M2} are as before, and {@code M0} is the module 2820 * containing the previous lookup class, then {@code targetClass} is accessible 2821 * if and only if one of the following is true: 2822 * <ul> 2823 * <li>{@code targetClass} is in {@code M0} and {@code M1} 2824 * {@linkplain Module#reads reads} {@code M0} and the type is 2825 * in a package that is exported to at least {@code M1}. 2826 * <li>{@code targetClass} is in {@code M1} and {@code M0} 2827 * {@linkplain Module#reads reads} {@code M1} and the type is 2828 * in a package that is exported to at least {@code M0}. 2829 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0} 2830 * and {@code M1} reads {@code M2} and the type is in a package 2831 * that is exported to at least both {@code M0} and {@code M2}. 2832 * </ul> 2833 * <p> 2834 * Otherwise, {@code targetClass} is not accessible. 2835 * 2836 * @param <T> the type of the class to be access-checked 2837 * @param targetClass the class to be access-checked 2838 * @return {@code targetClass} that has been access-checked 2839 * @throws IllegalAccessException if the class is not accessible from the lookup class 2840 * and previous lookup class, if present, using the allowed access modes. 2841 * @throws NullPointerException if {@code targetClass} is {@code null} 2842 * @since 9 2843 * @see <a href="#cross-module-lookup">Cross-module lookups</a> 2844 */ 2845 public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException { 2846 if (!isClassAccessible(targetClass)) { 2847 throw makeAccessException(targetClass); 2848 } 2849 return targetClass; 2850 } 2851 2852 /** 2853 * Produces an early-bound method handle for a virtual method. 2854 * It will bypass checks for overriding methods on the receiver, 2855 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 2856 * instruction from within the explicitly specified {@code specialCaller}. 2857 * The type of the method handle will be that of the method, 2858 * with a suitably restricted receiver type prepended. 2859 * (The receiver type will be {@code specialCaller} or a subtype.) 2860 * The method and all its argument types must be accessible 2861 * to the lookup object. 2862 * <p> 2863 * Before method resolution, 2864 * if the explicitly specified caller class is not identical with the 2865 * lookup class, or if this lookup object does not have 2866 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 2867 * privileges, the access fails. 2868 * <p> 2869 * The returned method handle will have 2870 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 2871 * the method's variable arity modifier bit ({@code 0x0080}) is set. 2872 * <p style="font-size:smaller;"> 2873 * <em>(Note: JVM internal methods named {@value ConstantDescs#INIT_NAME} 2874 * are not visible to this API, 2875 * even though the {@code invokespecial} instruction can refer to them 2876 * in special circumstances. Use {@link #findConstructor findConstructor} 2877 * to access instance initialization methods in a safe manner.)</em> 2878 * <p><b>Example:</b> 2879 * {@snippet lang="java" : 2880 import static java.lang.invoke.MethodHandles.*; 2881 import static java.lang.invoke.MethodType.*; 2882 ... 2883 static class Listie extends ArrayList { 2884 public String toString() { return "[wee Listie]"; } 2885 static Lookup lookup() { return MethodHandles.lookup(); } 2886 } 2887 ... 2888 // no access to constructor via invokeSpecial: 2889 MethodHandle MH_newListie = Listie.lookup() 2890 .findConstructor(Listie.class, methodType(void.class)); 2891 Listie l = (Listie) MH_newListie.invokeExact(); 2892 try { assertEquals("impossible", Listie.lookup().findSpecial( 2893 Listie.class, "<init>", methodType(void.class), Listie.class)); 2894 } catch (NoSuchMethodException ex) { } // OK 2895 // access to super and self methods via invokeSpecial: 2896 MethodHandle MH_super = Listie.lookup().findSpecial( 2897 ArrayList.class, "toString" , methodType(String.class), Listie.class); 2898 MethodHandle MH_this = Listie.lookup().findSpecial( 2899 Listie.class, "toString" , methodType(String.class), Listie.class); 2900 MethodHandle MH_duper = Listie.lookup().findSpecial( 2901 Object.class, "toString" , methodType(String.class), Listie.class); 2902 assertEquals("[]", (String) MH_super.invokeExact(l)); 2903 assertEquals(""+l, (String) MH_this.invokeExact(l)); 2904 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 2905 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 2906 String.class, "toString", methodType(String.class), Listie.class)); 2907 } catch (IllegalAccessException ex) { } // OK 2908 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 2909 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 2910 * } 2911 * 2912 * @param refc the class or interface from which the method is accessed 2913 * @param name the name of the method (which must not be "<init>") 2914 * @param type the type of the method, with the receiver argument omitted 2915 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 2916 * @return the desired method handle 2917 * @throws NoSuchMethodException if the method does not exist 2918 * @throws IllegalAccessException if access checking fails, 2919 * or if the method is {@code static}, 2920 * or if the method's variable arity modifier bit 2921 * is set and {@code asVarargsCollector} fails 2922 * @throws NullPointerException if any argument is null 2923 */ 2924 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 2925 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 2926 checkSpecialCaller(specialCaller, refc); 2927 Lookup specialLookup = this.in(specialCaller); 2928 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 2929 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method)); 2930 } 2931 2932 /** 2933 * Produces a method handle giving read access to a non-static field. 2934 * The type of the method handle will have a return type of the field's 2935 * value type. 2936 * The method handle's single argument will be the instance containing 2937 * the field. 2938 * Access checking is performed immediately on behalf of the lookup class. 2939 * @param refc the class or interface from which the method is accessed 2940 * @param name the field's name 2941 * @param type the field's type 2942 * @return a method handle which can load values from the field 2943 * @throws NoSuchFieldException if the field does not exist 2944 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2945 * @throws NullPointerException if any argument is null 2946 * @see #findVarHandle(Class, String, Class) 2947 */ 2948 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2949 MemberName field = resolveOrFail(REF_getField, refc, name, type); 2950 return getDirectField(REF_getField, refc, field); 2951 } 2952 2953 /** 2954 * Produces a method handle giving write access to a non-static field. 2955 * The type of the method handle will have a void return type. 2956 * The method handle will take two arguments, the instance containing 2957 * the field, and the value to be stored. 2958 * The second argument will be of the field's value type. 2959 * Access checking is performed immediately on behalf of the lookup class. 2960 * @param refc the class or interface from which the method is accessed 2961 * @param name the field's name 2962 * @param type the field's type 2963 * @return a method handle which can store values into the field 2964 * @throws NoSuchFieldException if the field does not exist 2965 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 2966 * or {@code final} 2967 * @throws NullPointerException if any argument is null 2968 * @see #findVarHandle(Class, String, Class) 2969 */ 2970 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 2971 MemberName field = resolveOrFail(REF_putField, refc, name, type); 2972 return getDirectField(REF_putField, refc, field); 2973 } 2974 2975 /** 2976 * Produces a VarHandle giving access to a non-static field {@code name} 2977 * of type {@code type} declared in a class of type {@code recv}. 2978 * The VarHandle's variable type is {@code type} and it has one 2979 * coordinate type, {@code recv}. 2980 * <p> 2981 * Access checking is performed immediately on behalf of the lookup 2982 * class. 2983 * <p> 2984 * Certain access modes of the returned VarHandle are unsupported under 2985 * the following conditions: 2986 * <ul> 2987 * <li>if the field is declared {@code final}, then the write, atomic 2988 * update, numeric atomic update, and bitwise atomic update access 2989 * modes are unsupported. 2990 * <li>if the field type is anything other than {@code byte}, 2991 * {@code short}, {@code char}, {@code int}, {@code long}, 2992 * {@code float}, or {@code double} then numeric atomic update 2993 * access modes are unsupported. 2994 * <li>if the field type is anything other than {@code boolean}, 2995 * {@code byte}, {@code short}, {@code char}, {@code int} or 2996 * {@code long} then bitwise atomic update access modes are 2997 * unsupported. 2998 * </ul> 2999 * <p> 3000 * If the field is declared {@code volatile} then the returned VarHandle 3001 * will override access to the field (effectively ignore the 3002 * {@code volatile} declaration) in accordance to its specified 3003 * access modes. 3004 * <p> 3005 * If the field type is {@code float} or {@code double} then numeric 3006 * and atomic update access modes compare values using their bitwise 3007 * representation (see {@link Float#floatToRawIntBits} and 3008 * {@link Double#doubleToRawLongBits}, respectively). 3009 * @apiNote 3010 * Bitwise comparison of {@code float} values or {@code double} values, 3011 * as performed by the numeric and atomic update access modes, differ 3012 * from the primitive {@code ==} operator and the {@link Float#equals} 3013 * and {@link Double#equals} methods, specifically with respect to 3014 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3015 * Care should be taken when performing a compare and set or a compare 3016 * and exchange operation with such values since the operation may 3017 * unexpectedly fail. 3018 * There are many possible NaN values that are considered to be 3019 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3020 * provided by Java can distinguish between them. Operation failure can 3021 * occur if the expected or witness value is a NaN value and it is 3022 * transformed (perhaps in a platform specific manner) into another NaN 3023 * value, and thus has a different bitwise representation (see 3024 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3025 * details). 3026 * The values {@code -0.0} and {@code +0.0} have different bitwise 3027 * representations but are considered equal when using the primitive 3028 * {@code ==} operator. Operation failure can occur if, for example, a 3029 * numeric algorithm computes an expected value to be say {@code -0.0} 3030 * and previously computed the witness value to be say {@code +0.0}. 3031 * @param recv the receiver class, of type {@code R}, that declares the 3032 * non-static field 3033 * @param name the field's name 3034 * @param type the field's type, of type {@code T} 3035 * @return a VarHandle giving access to non-static fields. 3036 * @throws NoSuchFieldException if the field does not exist 3037 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 3038 * @throws NullPointerException if any argument is null 3039 * @since 9 3040 */ 3041 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3042 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 3043 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 3044 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 3045 } 3046 3047 /** 3048 * Produces a method handle giving read access to a static field. 3049 * The type of the method handle will have a return type of the field's 3050 * value type. 3051 * The method handle will take no arguments. 3052 * Access checking is performed immediately on behalf of the lookup class. 3053 * <p> 3054 * If the returned method handle is invoked, the field's class will 3055 * be initialized, if it has not already been initialized. 3056 * @param refc the class or interface from which the method is accessed 3057 * @param name the field's name 3058 * @param type the field's type 3059 * @return a method handle which can load values from the field 3060 * @throws NoSuchFieldException if the field does not exist 3061 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3062 * @throws NullPointerException if any argument is null 3063 */ 3064 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3065 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 3066 return getDirectField(REF_getStatic, refc, field); 3067 } 3068 3069 /** 3070 * Produces a method handle giving write access to a static field. 3071 * The type of the method handle will have a void return type. 3072 * The method handle will take a single 3073 * argument, of the field's value type, the value to be stored. 3074 * Access checking is performed immediately on behalf of the lookup class. 3075 * <p> 3076 * If the returned method handle is invoked, the field's class will 3077 * be initialized, if it has not already been initialized. 3078 * @param refc the class or interface from which the method is accessed 3079 * @param name the field's name 3080 * @param type the field's type 3081 * @return a method handle which can store values into the field 3082 * @throws NoSuchFieldException if the field does not exist 3083 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3084 * or is {@code final} 3085 * @throws NullPointerException if any argument is null 3086 */ 3087 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3088 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 3089 return getDirectField(REF_putStatic, refc, field); 3090 } 3091 3092 /** 3093 * Produces a VarHandle giving access to a static field {@code name} of 3094 * type {@code type} declared in a class of type {@code decl}. 3095 * The VarHandle's variable type is {@code type} and it has no 3096 * coordinate types. 3097 * <p> 3098 * Access checking is performed immediately on behalf of the lookup 3099 * class. 3100 * <p> 3101 * If the returned VarHandle is operated on, the declaring class will be 3102 * initialized, if it has not already been initialized. 3103 * <p> 3104 * Certain access modes of the returned VarHandle are unsupported under 3105 * the following conditions: 3106 * <ul> 3107 * <li>if the field is declared {@code final}, then the write, atomic 3108 * update, numeric atomic update, and bitwise atomic update access 3109 * modes are unsupported. 3110 * <li>if the field type is anything other than {@code byte}, 3111 * {@code short}, {@code char}, {@code int}, {@code long}, 3112 * {@code float}, or {@code double}, then numeric atomic update 3113 * access modes are unsupported. 3114 * <li>if the field type is anything other than {@code boolean}, 3115 * {@code byte}, {@code short}, {@code char}, {@code int} or 3116 * {@code long} then bitwise atomic update access modes are 3117 * unsupported. 3118 * </ul> 3119 * <p> 3120 * If the field is declared {@code volatile} then the returned VarHandle 3121 * will override access to the field (effectively ignore the 3122 * {@code volatile} declaration) in accordance to its specified 3123 * access modes. 3124 * <p> 3125 * If the field type is {@code float} or {@code double} then numeric 3126 * and atomic update access modes compare values using their bitwise 3127 * representation (see {@link Float#floatToRawIntBits} and 3128 * {@link Double#doubleToRawLongBits}, respectively). 3129 * @apiNote 3130 * Bitwise comparison of {@code float} values or {@code double} values, 3131 * as performed by the numeric and atomic update access modes, differ 3132 * from the primitive {@code ==} operator and the {@link Float#equals} 3133 * and {@link Double#equals} methods, specifically with respect to 3134 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3135 * Care should be taken when performing a compare and set or a compare 3136 * and exchange operation with such values since the operation may 3137 * unexpectedly fail. 3138 * There are many possible NaN values that are considered to be 3139 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3140 * provided by Java can distinguish between them. Operation failure can 3141 * occur if the expected or witness value is a NaN value and it is 3142 * transformed (perhaps in a platform specific manner) into another NaN 3143 * value, and thus has a different bitwise representation (see 3144 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3145 * details). 3146 * The values {@code -0.0} and {@code +0.0} have different bitwise 3147 * representations but are considered equal when using the primitive 3148 * {@code ==} operator. Operation failure can occur if, for example, a 3149 * numeric algorithm computes an expected value to be say {@code -0.0} 3150 * and previously computed the witness value to be say {@code +0.0}. 3151 * @param decl the class that declares the static field 3152 * @param name the field's name 3153 * @param type the field's type, of type {@code T} 3154 * @return a VarHandle giving access to a static field 3155 * @throws NoSuchFieldException if the field does not exist 3156 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 3157 * @throws NullPointerException if any argument is null 3158 * @since 9 3159 */ 3160 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3161 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 3162 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 3163 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 3164 } 3165 3166 /** 3167 * Produces an early-bound method handle for a non-static method. 3168 * The receiver must have a supertype {@code defc} in which a method 3169 * of the given name and type is accessible to the lookup class. 3170 * The method and all its argument types must be accessible to the lookup object. 3171 * The type of the method handle will be that of the method, 3172 * without any insertion of an additional receiver parameter. 3173 * The given receiver will be bound into the method handle, 3174 * so that every call to the method handle will invoke the 3175 * requested method on the given receiver. 3176 * <p> 3177 * The returned method handle will have 3178 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3179 * the method's variable arity modifier bit ({@code 0x0080}) is set 3180 * <em>and</em> the trailing array argument is not the only argument. 3181 * (If the trailing array argument is the only argument, 3182 * the given receiver value will be bound to it.) 3183 * <p> 3184 * This is almost equivalent to the following code, with some differences noted below: 3185 * {@snippet lang="java" : 3186 import static java.lang.invoke.MethodHandles.*; 3187 import static java.lang.invoke.MethodType.*; 3188 ... 3189 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 3190 MethodHandle mh1 = mh0.bindTo(receiver); 3191 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 3192 return mh1; 3193 * } 3194 * where {@code defc} is either {@code receiver.getClass()} or a super 3195 * type of that class, in which the requested method is accessible 3196 * to the lookup class. 3197 * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity. 3198 * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would 3199 * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and 3200 * the receiver is restricted by {@code findVirtual} to the lookup class.) 3201 * @param receiver the object from which the method is accessed 3202 * @param name the name of the method 3203 * @param type the type of the method, with the receiver argument omitted 3204 * @return the desired method handle 3205 * @throws NoSuchMethodException if the method does not exist 3206 * @throws IllegalAccessException if access checking fails 3207 * or if the method's variable arity modifier bit 3208 * is set and {@code asVarargsCollector} fails 3209 * @throws NullPointerException if any argument is null 3210 * @see MethodHandle#bindTo 3211 * @see #findVirtual 3212 */ 3213 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3214 Class<? extends Object> refc = receiver.getClass(); // may get NPE 3215 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 3216 MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method)); 3217 if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) { 3218 throw new IllegalAccessException("The restricted defining class " + 3219 mh.type().leadingReferenceParameter().getName() + 3220 " is not assignable from receiver class " + 3221 receiver.getClass().getName()); 3222 } 3223 return mh.bindArgumentL(0, receiver).setVarargs(method); 3224 } 3225 3226 /** 3227 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3228 * to <i>m</i>, if the lookup class has permission. 3229 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 3230 * If <i>m</i> is virtual, overriding is respected on every call. 3231 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 3232 * The type of the method handle will be that of the method, 3233 * with the receiver type prepended (but only if it is non-static). 3234 * If the method's {@code accessible} flag is not set, 3235 * access checking is performed immediately on behalf of the lookup class. 3236 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 3237 * <p> 3238 * The returned method handle will have 3239 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3240 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3241 * <p> 3242 * If <i>m</i> is static, and 3243 * if the returned method handle is invoked, the method's class will 3244 * be initialized, if it has not already been initialized. 3245 * @param m the reflected method 3246 * @return a method handle which can invoke the reflected method 3247 * @throws IllegalAccessException if access checking fails 3248 * or if the method's variable arity modifier bit 3249 * is set and {@code asVarargsCollector} fails 3250 * @throws NullPointerException if the argument is null 3251 */ 3252 public MethodHandle unreflect(Method m) throws IllegalAccessException { 3253 if (m.getDeclaringClass() == MethodHandle.class) { 3254 MethodHandle mh = unreflectForMH(m); 3255 if (mh != null) return mh; 3256 } 3257 if (m.getDeclaringClass() == VarHandle.class) { 3258 MethodHandle mh = unreflectForVH(m); 3259 if (mh != null) return mh; 3260 } 3261 MemberName method = new MemberName(m); 3262 byte refKind = method.getReferenceKind(); 3263 if (refKind == REF_invokeSpecial) 3264 refKind = REF_invokeVirtual; 3265 assert(method.isMethod()); 3266 @SuppressWarnings("deprecation") 3267 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 3268 return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3269 } 3270 private MethodHandle unreflectForMH(Method m) { 3271 // these names require special lookups because they throw UnsupportedOperationException 3272 if (MemberName.isMethodHandleInvokeName(m.getName())) 3273 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 3274 return null; 3275 } 3276 private MethodHandle unreflectForVH(Method m) { 3277 // these names require special lookups because they throw UnsupportedOperationException 3278 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 3279 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 3280 return null; 3281 } 3282 3283 /** 3284 * Produces a method handle for a reflected method. 3285 * It will bypass checks for overriding methods on the receiver, 3286 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 3287 * instruction from within the explicitly specified {@code specialCaller}. 3288 * The type of the method handle will be that of the method, 3289 * with a suitably restricted receiver type prepended. 3290 * (The receiver type will be {@code specialCaller} or a subtype.) 3291 * If the method's {@code accessible} flag is not set, 3292 * access checking is performed immediately on behalf of the lookup class, 3293 * as if {@code invokespecial} instruction were being linked. 3294 * <p> 3295 * Before method resolution, 3296 * if the explicitly specified caller class is not identical with the 3297 * lookup class, or if this lookup object does not have 3298 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 3299 * privileges, the access fails. 3300 * <p> 3301 * The returned method handle will have 3302 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3303 * the method's variable arity modifier bit ({@code 0x0080}) is set. 3304 * @param m the reflected method 3305 * @param specialCaller the class nominally calling the method 3306 * @return a method handle which can invoke the reflected method 3307 * @throws IllegalAccessException if access checking fails, 3308 * or if the method is {@code static}, 3309 * or if the method's variable arity modifier bit 3310 * is set and {@code asVarargsCollector} fails 3311 * @throws NullPointerException if any argument is null 3312 */ 3313 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 3314 checkSpecialCaller(specialCaller, m.getDeclaringClass()); 3315 Lookup specialLookup = this.in(specialCaller); 3316 MemberName method = new MemberName(m, true); 3317 assert(method.isMethod()); 3318 // ignore m.isAccessible: this is a new kind of access 3319 return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method)); 3320 } 3321 3322 /** 3323 * Produces a method handle for a reflected constructor. 3324 * The type of the method handle will be that of the constructor, 3325 * with the return type changed to the declaring class. 3326 * The method handle will perform a {@code newInstance} operation, 3327 * creating a new instance of the constructor's class on the 3328 * arguments passed to the method handle. 3329 * <p> 3330 * If the constructor's {@code accessible} flag is not set, 3331 * access checking is performed immediately on behalf of the lookup class. 3332 * <p> 3333 * The returned method handle will have 3334 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 3335 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 3336 * <p> 3337 * If the returned method handle is invoked, the constructor's class will 3338 * be initialized, if it has not already been initialized. 3339 * @param c the reflected constructor 3340 * @return a method handle which can invoke the reflected constructor 3341 * @throws IllegalAccessException if access checking fails 3342 * or if the method's variable arity modifier bit 3343 * is set and {@code asVarargsCollector} fails 3344 * @throws NullPointerException if the argument is null 3345 */ 3346 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 3347 MemberName ctor = new MemberName(c); 3348 assert(ctor.isConstructor()); 3349 @SuppressWarnings("deprecation") 3350 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 3351 return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor); 3352 } 3353 3354 /* 3355 * Produces a method handle that is capable of creating instances of the given class 3356 * and instantiated by the given constructor. 3357 * 3358 * This method should only be used by ReflectionFactory::newConstructorForSerialization. 3359 */ 3360 /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException { 3361 MemberName ctor = new MemberName(c); 3362 assert(ctor.isConstructor() && constructorInSuperclass(decl, c)); 3363 checkAccess(REF_newInvokeSpecial, decl, ctor); 3364 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3365 return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor); 3366 } 3367 3368 private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) { 3369 if (decl == ctor.getDeclaringClass()) 3370 return true; 3371 3372 Class<?> cl = decl; 3373 while ((cl = cl.getSuperclass()) != null) { 3374 if (cl == ctor.getDeclaringClass()) { 3375 return true; 3376 } 3377 } 3378 return false; 3379 } 3380 3381 /** 3382 * Produces a method handle giving read access to a reflected field. 3383 * The type of the method handle will have a return type of the field's 3384 * value type. 3385 * If the field is {@code static}, the method handle will take no arguments. 3386 * Otherwise, its single argument will be the instance containing 3387 * the field. 3388 * If the {@code Field} object's {@code accessible} flag is not set, 3389 * access checking is performed immediately on behalf of the lookup class. 3390 * <p> 3391 * If the field is static, and 3392 * if the returned method handle is invoked, the field's class will 3393 * be initialized, if it has not already been initialized. 3394 * @param f the reflected field 3395 * @return a method handle which can load values from the reflected field 3396 * @throws IllegalAccessException if access checking fails 3397 * @throws NullPointerException if the argument is null 3398 */ 3399 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 3400 return unreflectField(f, false); 3401 } 3402 3403 /** 3404 * Produces a method handle giving write access to a reflected field. 3405 * The type of the method handle will have a void return type. 3406 * If the field is {@code static}, the method handle will take a single 3407 * argument, of the field's value type, the value to be stored. 3408 * Otherwise, the two arguments will be the instance containing 3409 * the field, and the value to be stored. 3410 * If the {@code Field} object's {@code accessible} flag is not set, 3411 * access checking is performed immediately on behalf of the lookup class. 3412 * <p> 3413 * If the field is {@code final}, write access will not be 3414 * allowed and access checking will fail, except under certain 3415 * narrow circumstances documented for {@link Field#set Field.set}. 3416 * A method handle is returned only if a corresponding call to 3417 * the {@code Field} object's {@code set} method could return 3418 * normally. In particular, fields which are both {@code static} 3419 * and {@code final} may never be set. 3420 * <p> 3421 * If the field is {@code static}, and 3422 * if the returned method handle is invoked, the field's class will 3423 * be initialized, if it has not already been initialized. 3424 * @param f the reflected field 3425 * @return a method handle which can store values into the reflected field 3426 * @throws IllegalAccessException if access checking fails, 3427 * or if the field is {@code final} and write access 3428 * is not enabled on the {@code Field} object 3429 * @throws NullPointerException if the argument is null 3430 */ 3431 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 3432 return unreflectField(f, true); 3433 } 3434 3435 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 3436 MemberName field = new MemberName(f, isSetter); 3437 if (isSetter && field.isFinal()) { 3438 if (field.isTrustedFinalField()) { 3439 String msg = field.isStatic() ? "static final field has no write access" 3440 : "final field has no write access"; 3441 throw field.makeAccessException(msg, this); 3442 } 3443 } 3444 assert(isSetter 3445 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 3446 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 3447 @SuppressWarnings("deprecation") 3448 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 3449 return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field); 3450 } 3451 3452 /** 3453 * Produces a VarHandle giving access to a reflected field {@code f} 3454 * of type {@code T} declared in a class of type {@code R}. 3455 * The VarHandle's variable type is {@code T}. 3456 * If the field is non-static the VarHandle has one coordinate type, 3457 * {@code R}. Otherwise, the field is static, and the VarHandle has no 3458 * coordinate types. 3459 * <p> 3460 * Access checking is performed immediately on behalf of the lookup 3461 * class, regardless of the value of the field's {@code accessible} 3462 * flag. 3463 * <p> 3464 * If the field is static, and if the returned VarHandle is operated 3465 * on, the field's declaring class will be initialized, if it has not 3466 * already been initialized. 3467 * <p> 3468 * Certain access modes of the returned VarHandle are unsupported under 3469 * the following conditions: 3470 * <ul> 3471 * <li>if the field is declared {@code final}, then the write, atomic 3472 * update, numeric atomic update, and bitwise atomic update access 3473 * modes are unsupported. 3474 * <li>if the field type is anything other than {@code byte}, 3475 * {@code short}, {@code char}, {@code int}, {@code long}, 3476 * {@code float}, or {@code double} then numeric atomic update 3477 * access modes are unsupported. 3478 * <li>if the field type is anything other than {@code boolean}, 3479 * {@code byte}, {@code short}, {@code char}, {@code int} or 3480 * {@code long} then bitwise atomic update access modes are 3481 * unsupported. 3482 * </ul> 3483 * <p> 3484 * If the field is declared {@code volatile} then the returned VarHandle 3485 * will override access to the field (effectively ignore the 3486 * {@code volatile} declaration) in accordance to its specified 3487 * access modes. 3488 * <p> 3489 * If the field type is {@code float} or {@code double} then numeric 3490 * and atomic update access modes compare values using their bitwise 3491 * representation (see {@link Float#floatToRawIntBits} and 3492 * {@link Double#doubleToRawLongBits}, respectively). 3493 * @apiNote 3494 * Bitwise comparison of {@code float} values or {@code double} values, 3495 * as performed by the numeric and atomic update access modes, differ 3496 * from the primitive {@code ==} operator and the {@link Float#equals} 3497 * and {@link Double#equals} methods, specifically with respect to 3498 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 3499 * Care should be taken when performing a compare and set or a compare 3500 * and exchange operation with such values since the operation may 3501 * unexpectedly fail. 3502 * There are many possible NaN values that are considered to be 3503 * {@code NaN} in Java, although no IEEE 754 floating-point operation 3504 * provided by Java can distinguish between them. Operation failure can 3505 * occur if the expected or witness value is a NaN value and it is 3506 * transformed (perhaps in a platform specific manner) into another NaN 3507 * value, and thus has a different bitwise representation (see 3508 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 3509 * details). 3510 * The values {@code -0.0} and {@code +0.0} have different bitwise 3511 * representations but are considered equal when using the primitive 3512 * {@code ==} operator. Operation failure can occur if, for example, a 3513 * numeric algorithm computes an expected value to be say {@code -0.0} 3514 * and previously computed the witness value to be say {@code +0.0}. 3515 * @param f the reflected field, with a field of type {@code T}, and 3516 * a declaring class of type {@code R} 3517 * @return a VarHandle giving access to non-static fields or a static 3518 * field 3519 * @throws IllegalAccessException if access checking fails 3520 * @throws NullPointerException if the argument is null 3521 * @since 9 3522 */ 3523 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 3524 MemberName getField = new MemberName(f, false); 3525 MemberName putField = new MemberName(f, true); 3526 return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(), 3527 f.getDeclaringClass(), getField, putField); 3528 } 3529 3530 /** 3531 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 3532 * created by this lookup object or a similar one. 3533 * Security and access checks are performed to ensure that this lookup object 3534 * is capable of reproducing the target method handle. 3535 * This means that the cracking may fail if target is a direct method handle 3536 * but was created by an unrelated lookup object. 3537 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 3538 * and was created by a lookup object for a different class. 3539 * @param target a direct method handle to crack into symbolic reference components 3540 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 3541 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 3542 * @throws NullPointerException if the target is {@code null} 3543 * @see MethodHandleInfo 3544 * @since 1.8 3545 */ 3546 public MethodHandleInfo revealDirect(MethodHandle target) { 3547 if (!target.isCrackable()) { 3548 throw newIllegalArgumentException("not a direct method handle"); 3549 } 3550 MemberName member = target.internalMemberName(); 3551 Class<?> defc = member.getDeclaringClass(); 3552 byte refKind = member.getReferenceKind(); 3553 assert(MethodHandleNatives.refKindIsValid(refKind)); 3554 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 3555 // Devirtualized method invocation is usually formally virtual. 3556 // To avoid creating extra MemberName objects for this common case, 3557 // we encode this extra degree of freedom using MH.isInvokeSpecial. 3558 refKind = REF_invokeVirtual; 3559 if (refKind == REF_invokeVirtual && defc.isInterface()) 3560 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 3561 refKind = REF_invokeInterface; 3562 // Check member access before cracking. 3563 try { 3564 checkAccess(refKind, defc, member); 3565 } catch (IllegalAccessException ex) { 3566 throw new IllegalArgumentException(ex); 3567 } 3568 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 3569 Class<?> callerClass = target.internalCallerClass(); 3570 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass()) 3571 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 3572 } 3573 // Produce the handle to the results. 3574 return new InfoFromMemberName(this, member, refKind); 3575 } 3576 3577 //--- Helper methods, all package-private. 3578 3579 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 3580 checkSymbolicClass(refc); // do this before attempting to resolve 3581 Objects.requireNonNull(name); 3582 Objects.requireNonNull(type); 3583 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3584 NoSuchFieldException.class); 3585 } 3586 3587 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 3588 checkSymbolicClass(refc); // do this before attempting to resolve 3589 Objects.requireNonNull(type); 3590 checkMethodName(refKind, name); // implicit null-check of name 3591 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes, 3592 NoSuchMethodException.class); 3593 } 3594 3595 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 3596 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 3597 Objects.requireNonNull(member.getName()); 3598 Objects.requireNonNull(member.getType()); 3599 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes, 3600 ReflectiveOperationException.class); 3601 } 3602 3603 MemberName resolveOrNull(byte refKind, MemberName member) { 3604 // do this before attempting to resolve 3605 if (!isClassAccessible(member.getDeclaringClass())) { 3606 return null; 3607 } 3608 Objects.requireNonNull(member.getName()); 3609 Objects.requireNonNull(member.getType()); 3610 return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes); 3611 } 3612 3613 MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) { 3614 // do this before attempting to resolve 3615 if (!isClassAccessible(refc)) { 3616 return null; 3617 } 3618 Objects.requireNonNull(type); 3619 // implicit null-check of name 3620 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) { 3621 return null; 3622 } 3623 return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes); 3624 } 3625 3626 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 3627 if (!isClassAccessible(refc)) { 3628 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 3629 } 3630 } 3631 3632 boolean isClassAccessible(Class<?> refc) { 3633 Objects.requireNonNull(refc); 3634 Class<?> caller = lookupClassOrNull(); 3635 Class<?> type = refc; 3636 while (type.isArray()) { 3637 type = type.getComponentType(); 3638 } 3639 return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes); 3640 } 3641 3642 /** Check name for an illegal leading "<" character. */ 3643 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 3644 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 3645 throw new NoSuchMethodException("illegal method name: "+name); 3646 } 3647 3648 /** 3649 * Find my trustable caller class if m is a caller sensitive method. 3650 * If this lookup object has original full privilege access, then the caller class is the lookupClass. 3651 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 3652 */ 3653 Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException { 3654 if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) { 3655 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods 3656 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3657 } 3658 return this; 3659 } 3660 3661 /** 3662 * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3663 * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access. 3664 * 3665 * @deprecated This method was originally designed to test {@code PRIVATE} access 3666 * that implies full privilege access but {@code MODULE} access has since become 3667 * independent of {@code PRIVATE} access. It is recommended to call 3668 * {@link #hasFullPrivilegeAccess()} instead. 3669 * @since 9 3670 */ 3671 @Deprecated(since="14") 3672 public boolean hasPrivateAccess() { 3673 return hasFullPrivilegeAccess(); 3674 } 3675 3676 /** 3677 * Returns {@code true} if this lookup has <em>full privilege access</em>, 3678 * i.e. {@code PRIVATE} and {@code MODULE} access. 3679 * A {@code Lookup} object must have full privilege access in order to 3680 * access all members that are allowed to the 3681 * {@linkplain #lookupClass() lookup class}. 3682 * 3683 * @return {@code true} if this lookup has full privilege access. 3684 * @since 14 3685 * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a> 3686 */ 3687 public boolean hasFullPrivilegeAccess() { 3688 return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE); 3689 } 3690 3691 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3692 boolean wantStatic = (refKind == REF_invokeStatic); 3693 String message; 3694 if (m.isConstructor()) 3695 message = "expected a method, not a constructor"; 3696 else if (!m.isMethod()) 3697 message = "expected a method"; 3698 else if (wantStatic != m.isStatic()) 3699 message = wantStatic ? "expected a static method" : "expected a non-static method"; 3700 else 3701 { checkAccess(refKind, refc, m); return; } 3702 throw m.makeAccessException(message, this); 3703 } 3704 3705 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3706 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 3707 String message; 3708 if (wantStatic != m.isStatic()) 3709 message = wantStatic ? "expected a static field" : "expected a non-static field"; 3710 else 3711 { checkAccess(refKind, refc, m); return; } 3712 throw m.makeAccessException(message, this); 3713 } 3714 3715 private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) { 3716 return Modifier.isProtected(m.getModifiers()) && 3717 refKind == REF_invokeVirtual && 3718 m.getDeclaringClass() == Object.class && 3719 m.getName().equals("clone") && 3720 refc.isArray(); 3721 } 3722 3723 /** Check public/protected/private bits on the symbolic reference class and its member. */ 3724 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 3725 assert(m.referenceKindIsConsistentWith(refKind) && 3726 MethodHandleNatives.refKindIsValid(refKind) && 3727 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 3728 int allowedModes = this.allowedModes; 3729 if (allowedModes == TRUSTED) return; 3730 int mods = m.getModifiers(); 3731 if (isArrayClone(refKind, refc, m)) { 3732 // The JVM does this hack also. 3733 // (See ClassVerifier::verify_invoke_instructions 3734 // and LinkResolver::check_method_accessability.) 3735 // Because the JVM does not allow separate methods on array types, 3736 // there is no separate method for int[].clone. 3737 // All arrays simply inherit Object.clone. 3738 // But for access checking logic, we make Object.clone 3739 // (normally protected) appear to be public. 3740 // Later on, when the DirectMethodHandle is created, 3741 // its leading argument will be restricted to the 3742 // requested array type. 3743 // N.B. The return type is not adjusted, because 3744 // that is *not* the bytecode behavior. 3745 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 3746 } 3747 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 3748 // cannot "new" a protected ctor in a different package 3749 mods ^= Modifier.PROTECTED; 3750 } 3751 if (Modifier.isFinal(mods) && 3752 MethodHandleNatives.refKindIsSetter(refKind)) 3753 throw m.makeAccessException("unexpected set of a final field", this); 3754 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 3755 if ((requestedModes & allowedModes) != 0) { 3756 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 3757 mods, lookupClass(), previousLookupClass(), allowedModes)) 3758 return; 3759 } else { 3760 // Protected members can also be checked as if they were package-private. 3761 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 3762 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 3763 return; 3764 } 3765 throw m.makeAccessException(accessFailedMessage(refc, m), this); 3766 } 3767 3768 String accessFailedMessage(Class<?> refc, MemberName m) { 3769 Class<?> defc = m.getDeclaringClass(); 3770 int mods = m.getModifiers(); 3771 // check the class first: 3772 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 3773 (defc == refc || 3774 Modifier.isPublic(refc.getModifiers()))); 3775 if (!classOK && (allowedModes & PACKAGE) != 0) { 3776 // ignore previous lookup class to check if default package access 3777 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) && 3778 (defc == refc || 3779 VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES))); 3780 } 3781 if (!classOK) 3782 return "class is not public"; 3783 if (Modifier.isPublic(mods)) 3784 return "access to public member failed"; // (how?, module not readable?) 3785 if (Modifier.isPrivate(mods)) 3786 return "member is private"; 3787 if (Modifier.isProtected(mods)) 3788 return "member is protected"; 3789 return "member is private to package"; 3790 } 3791 3792 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 3793 int allowedModes = this.allowedModes; 3794 if (allowedModes == TRUSTED) return; 3795 if ((lookupModes() & PRIVATE) == 0 3796 || (specialCaller != lookupClass() 3797 // ensure non-abstract methods in superinterfaces can be special-invoked 3798 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)))) 3799 throw new MemberName(specialCaller). 3800 makeAccessException("no private access for invokespecial", this); 3801 } 3802 3803 private boolean restrictProtectedReceiver(MemberName method) { 3804 // The accessing class only has the right to use a protected member 3805 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 3806 if (!method.isProtected() || method.isStatic() 3807 || allowedModes == TRUSTED 3808 || method.getDeclaringClass() == lookupClass() 3809 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())) 3810 return false; 3811 return true; 3812 } 3813 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 3814 assert(!method.isStatic()); 3815 // receiver type of mh is too wide; narrow to caller 3816 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 3817 throw method.makeAccessException("caller class must be a subclass below the method", caller); 3818 } 3819 MethodType rawType = mh.type(); 3820 if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow 3821 MethodType narrowType = rawType.changeParameterType(0, caller); 3822 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 3823 assert(mh.viewAsTypeChecks(narrowType, true)); 3824 return mh.copyWith(narrowType, mh.form); 3825 } 3826 3827 /** Check access and get the requested method. */ 3828 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3829 final boolean doRestrict = true; 3830 return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup); 3831 } 3832 /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */ 3833 private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException { 3834 final boolean doRestrict = false; 3835 return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup); 3836 } 3837 /** Common code for all methods; do not call directly except from immediately above. */ 3838 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 3839 boolean doRestrict, 3840 Lookup boundCaller) throws IllegalAccessException { 3841 checkMethod(refKind, refc, method); 3842 assert(!method.isMethodHandleInvoke()); 3843 3844 if (refKind == REF_invokeSpecial && 3845 refc != lookupClass() && 3846 !refc.isInterface() && !lookupClass().isInterface() && 3847 refc != lookupClass().getSuperclass() && 3848 refc.isAssignableFrom(lookupClass())) { 3849 assert(!method.getName().equals(ConstantDescs.INIT_NAME)); // not this code path 3850 3851 // Per JVMS 6.5, desc. of invokespecial instruction: 3852 // If the method is in a superclass of the LC, 3853 // and if our original search was above LC.super, 3854 // repeat the search (symbolic lookup) from LC.super 3855 // and continue with the direct superclass of that class, 3856 // and so forth, until a match is found or no further superclasses exist. 3857 // FIXME: MemberName.resolve should handle this instead. 3858 Class<?> refcAsSuper = lookupClass(); 3859 MemberName m2; 3860 do { 3861 refcAsSuper = refcAsSuper.getSuperclass(); 3862 m2 = new MemberName(refcAsSuper, 3863 method.getName(), 3864 method.getMethodType(), 3865 REF_invokeSpecial); 3866 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes); 3867 } while (m2 == null && // no method is found yet 3868 refc != refcAsSuper); // search up to refc 3869 if (m2 == null) throw new InternalError(method.toString()); 3870 method = m2; 3871 refc = refcAsSuper; 3872 // redo basic checks 3873 checkMethod(refKind, refc, method); 3874 } 3875 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass()); 3876 MethodHandle mh = dmh; 3877 // Optionally narrow the receiver argument to lookupClass using restrictReceiver. 3878 if ((doRestrict && refKind == REF_invokeSpecial) || 3879 (MethodHandleNatives.refKindHasReceiver(refKind) && 3880 restrictProtectedReceiver(method) && 3881 // All arrays simply inherit the protected Object.clone method. 3882 // The leading argument is already restricted to the requested 3883 // array type (not the lookup class). 3884 !isArrayClone(refKind, refc, method))) { 3885 mh = restrictReceiver(method, dmh, lookupClass()); 3886 } 3887 mh = maybeBindCaller(method, mh, boundCaller); 3888 mh = mh.setVarargs(method); 3889 return mh; 3890 } 3891 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller) 3892 throws IllegalAccessException { 3893 if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 3894 return mh; 3895 3896 // boundCaller must have full privilege access. 3897 // It should have been checked by findBoundCallerLookup. Safe to check this again. 3898 if ((boundCaller.lookupModes() & ORIGINAL) == 0) 3899 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 3900 3901 assert boundCaller.hasFullPrivilegeAccess(); 3902 3903 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass); 3904 // Note: caller will apply varargs after this step happens. 3905 return cbmh; 3906 } 3907 3908 /** Check access and get the requested field. */ 3909 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3910 return getDirectFieldCommon(refKind, refc, field); 3911 } 3912 /** Common code for all fields; do not call directly except from immediately above. */ 3913 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 3914 checkField(refKind, refc, field); 3915 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 3916 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 3917 restrictProtectedReceiver(field)); 3918 if (doRestrict) 3919 return restrictReceiver(field, dmh, lookupClass()); 3920 return dmh; 3921 } 3922 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 3923 Class<?> refc, MemberName getField, MemberName putField) 3924 throws IllegalAccessException { 3925 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField); 3926 } 3927 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 3928 Class<?> refc, MemberName getField, 3929 MemberName putField) throws IllegalAccessException { 3930 assert getField.isStatic() == putField.isStatic(); 3931 assert getField.isGetter() && putField.isSetter(); 3932 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 3933 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 3934 3935 checkField(getRefKind, refc, getField); 3936 3937 if (!putField.isFinal()) { 3938 // A VarHandle does not support updates to final fields, any 3939 // such VarHandle to a final field will be read-only and 3940 // therefore the following write-based accessibility checks are 3941 // only required for non-final fields 3942 checkField(putRefKind, refc, putField); 3943 } 3944 3945 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 3946 restrictProtectedReceiver(getField)); 3947 if (doRestrict) { 3948 assert !getField.isStatic(); 3949 // receiver type of VarHandle is too wide; narrow to caller 3950 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 3951 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 3952 } 3953 refc = lookupClass(); 3954 } 3955 return VarHandles.makeFieldHandle(getField, refc, 3956 this.allowedModes == TRUSTED && !getField.isTrustedFinalField()); 3957 } 3958 /** Check access and get the requested constructor. */ 3959 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3960 return getDirectConstructorCommon(refc, ctor); 3961 } 3962 /** Common code for all constructors; do not call directly except from immediately above. */ 3963 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException { 3964 assert(ctor.isConstructor()); 3965 checkAccess(REF_newInvokeSpecial, refc, ctor); 3966 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 3967 return DirectMethodHandle.make(ctor).setVarargs(ctor); 3968 } 3969 3970 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 3971 */ 3972 /*non-public*/ 3973 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) 3974 throws ReflectiveOperationException { 3975 if (!(type instanceof Class || type instanceof MethodType)) 3976 throw new InternalError("unresolved MemberName"); 3977 MemberName member = new MemberName(refKind, defc, name, type); 3978 MethodHandle mh = LOOKASIDE_TABLE.get(member); 3979 if (mh != null) { 3980 checkSymbolicClass(defc); 3981 return mh; 3982 } 3983 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 3984 // Treat MethodHandle.invoke and invokeExact specially. 3985 mh = findVirtualForMH(member.getName(), member.getMethodType()); 3986 if (mh != null) { 3987 return mh; 3988 } 3989 } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) { 3990 // Treat signature-polymorphic methods on VarHandle specially. 3991 mh = findVirtualForVH(member.getName(), member.getMethodType()); 3992 if (mh != null) { 3993 return mh; 3994 } 3995 } 3996 MemberName resolved = resolveOrFail(refKind, member); 3997 mh = getDirectMethodForConstant(refKind, defc, resolved); 3998 if (mh instanceof DirectMethodHandle dmh 3999 && canBeCached(refKind, defc, resolved)) { 4000 MemberName key = mh.internalMemberName(); 4001 if (key != null) { 4002 key = key.asNormalOriginal(); 4003 } 4004 if (member.equals(key)) { // better safe than sorry 4005 LOOKASIDE_TABLE.put(key, dmh); 4006 } 4007 } 4008 return mh; 4009 } 4010 private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 4011 if (refKind == REF_invokeSpecial) { 4012 return false; 4013 } 4014 if (!Modifier.isPublic(defc.getModifiers()) || 4015 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 4016 !member.isPublic() || 4017 member.isCallerSensitive()) { 4018 return false; 4019 } 4020 ClassLoader loader = defc.getClassLoader(); 4021 if (loader != null) { 4022 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 4023 boolean found = false; 4024 while (sysl != null) { 4025 if (loader == sysl) { found = true; break; } 4026 sysl = sysl.getParent(); 4027 } 4028 if (!found) { 4029 return false; 4030 } 4031 } 4032 MemberName resolved2 = publicLookup().resolveOrNull(refKind, 4033 new MemberName(refKind, defc, member.getName(), member.getType())); 4034 if (resolved2 == null) { 4035 return false; 4036 } 4037 return true; 4038 } 4039 private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 4040 throws ReflectiveOperationException { 4041 if (MethodHandleNatives.refKindIsField(refKind)) { 4042 return getDirectField(refKind, defc, member); 4043 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 4044 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member)); 4045 } else if (refKind == REF_newInvokeSpecial) { 4046 return getDirectConstructor(defc, member); 4047 } 4048 // oops 4049 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 4050 } 4051 4052 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 4053 } 4054 4055 /** 4056 * Produces a method handle constructing arrays of a desired type, 4057 * as if by the {@code anewarray} bytecode. 4058 * The return type of the method handle will be the array type. 4059 * The type of its sole argument will be {@code int}, which specifies the size of the array. 4060 * 4061 * <p> If the returned method handle is invoked with a negative 4062 * array size, a {@code NegativeArraySizeException} will be thrown. 4063 * 4064 * @param arrayClass an array type 4065 * @return a method handle which can create arrays of the given type 4066 * @throws NullPointerException if the argument is {@code null} 4067 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 4068 * @see java.lang.reflect.Array#newInstance(Class, int) 4069 * @jvms 6.5 {@code anewarray} Instruction 4070 * @since 9 4071 */ 4072 public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 4073 if (!arrayClass.isArray()) { 4074 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 4075 } 4076 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 4077 bindTo(arrayClass.getComponentType()); 4078 return ani.asType(ani.type().changeReturnType(arrayClass)); 4079 } 4080 4081 /** 4082 * Produces a method handle returning the length of an array, 4083 * as if by the {@code arraylength} bytecode. 4084 * The type of the method handle will have {@code int} as return type, 4085 * and its sole argument will be the array type. 4086 * 4087 * <p> If the returned method handle is invoked with a {@code null} 4088 * array reference, a {@code NullPointerException} will be thrown. 4089 * 4090 * @param arrayClass an array type 4091 * @return a method handle which can retrieve the length of an array of the given array type 4092 * @throws NullPointerException if the argument is {@code null} 4093 * @throws IllegalArgumentException if arrayClass is not an array type 4094 * @jvms 6.5 {@code arraylength} Instruction 4095 * @since 9 4096 */ 4097 public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 4098 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 4099 } 4100 4101 /** 4102 * Produces a method handle giving read access to elements of an array, 4103 * as if by the {@code aaload} bytecode. 4104 * The type of the method handle will have a return type of the array's 4105 * element type. Its first argument will be the array type, 4106 * and the second will be {@code int}. 4107 * 4108 * <p> When the returned method handle is invoked, 4109 * the array reference and array index are checked. 4110 * A {@code NullPointerException} will be thrown if the array reference 4111 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4112 * thrown if the index is negative or if it is greater than or equal to 4113 * the length of the array. 4114 * 4115 * @param arrayClass an array type 4116 * @return a method handle which can load values from the given array type 4117 * @throws NullPointerException if the argument is null 4118 * @throws IllegalArgumentException if arrayClass is not an array type 4119 * @jvms 6.5 {@code aaload} Instruction 4120 */ 4121 public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 4122 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 4123 } 4124 4125 /** 4126 * Produces a method handle giving write access to elements of an array, 4127 * as if by the {@code astore} bytecode. 4128 * The type of the method handle will have a void return type. 4129 * Its last argument will be the array's element type. 4130 * The first and second arguments will be the array type and int. 4131 * 4132 * <p> When the returned method handle is invoked, 4133 * the array reference and array index are checked. 4134 * A {@code NullPointerException} will be thrown if the array reference 4135 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4136 * thrown if the index is negative or if it is greater than or equal to 4137 * the length of the array. 4138 * 4139 * @param arrayClass the class of an array 4140 * @return a method handle which can store values into the array type 4141 * @throws NullPointerException if the argument is null 4142 * @throws IllegalArgumentException if arrayClass is not an array type 4143 * @jvms 6.5 {@code aastore} Instruction 4144 */ 4145 public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 4146 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 4147 } 4148 4149 /** 4150 * Produces a VarHandle giving access to elements of an array of type 4151 * {@code arrayClass}. The VarHandle's variable type is the component type 4152 * of {@code arrayClass} and the list of coordinate types is 4153 * {@code (arrayClass, int)}, where the {@code int} coordinate type 4154 * corresponds to an argument that is an index into an array. 4155 * <p> 4156 * Certain access modes of the returned VarHandle are unsupported under 4157 * the following conditions: 4158 * <ul> 4159 * <li>if the component type is anything other than {@code byte}, 4160 * {@code short}, {@code char}, {@code int}, {@code long}, 4161 * {@code float}, or {@code double} then numeric atomic update access 4162 * modes are unsupported. 4163 * <li>if the component type is anything other than {@code boolean}, 4164 * {@code byte}, {@code short}, {@code char}, {@code int} or 4165 * {@code long} then bitwise atomic update access modes are 4166 * unsupported. 4167 * </ul> 4168 * <p> 4169 * If the component type is {@code float} or {@code double} then numeric 4170 * and atomic update access modes compare values using their bitwise 4171 * representation (see {@link Float#floatToRawIntBits} and 4172 * {@link Double#doubleToRawLongBits}, respectively). 4173 * 4174 * <p> When the returned {@code VarHandle} is invoked, 4175 * the array reference and array index are checked. 4176 * A {@code NullPointerException} will be thrown if the array reference 4177 * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be 4178 * thrown if the index is negative or if it is greater than or equal to 4179 * the length of the array. 4180 * 4181 * @apiNote 4182 * Bitwise comparison of {@code float} values or {@code double} values, 4183 * as performed by the numeric and atomic update access modes, differ 4184 * from the primitive {@code ==} operator and the {@link Float#equals} 4185 * and {@link Double#equals} methods, specifically with respect to 4186 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 4187 * Care should be taken when performing a compare and set or a compare 4188 * and exchange operation with such values since the operation may 4189 * unexpectedly fail. 4190 * There are many possible NaN values that are considered to be 4191 * {@code NaN} in Java, although no IEEE 754 floating-point operation 4192 * provided by Java can distinguish between them. Operation failure can 4193 * occur if the expected or witness value is a NaN value and it is 4194 * transformed (perhaps in a platform specific manner) into another NaN 4195 * value, and thus has a different bitwise representation (see 4196 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 4197 * details). 4198 * The values {@code -0.0} and {@code +0.0} have different bitwise 4199 * representations but are considered equal when using the primitive 4200 * {@code ==} operator. Operation failure can occur if, for example, a 4201 * numeric algorithm computes an expected value to be say {@code -0.0} 4202 * and previously computed the witness value to be say {@code +0.0}. 4203 * @param arrayClass the class of an array, of type {@code T[]} 4204 * @return a VarHandle giving access to elements of an array 4205 * @throws NullPointerException if the arrayClass is null 4206 * @throws IllegalArgumentException if arrayClass is not an array type 4207 * @since 9 4208 */ 4209 public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 4210 return VarHandles.makeArrayElementHandle(arrayClass); 4211 } 4212 4213 /** 4214 * Produces a VarHandle giving access to elements of a {@code byte[]} array 4215 * viewed as if it were a different primitive array type, such as 4216 * {@code int[]} or {@code long[]}. 4217 * The VarHandle's variable type is the component type of 4218 * {@code viewArrayClass} and the list of coordinate types is 4219 * {@code (byte[], int)}, where the {@code int} coordinate type 4220 * corresponds to an argument that is an index into a {@code byte[]} array. 4221 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 4222 * array, composing bytes to or from a value of the component type of 4223 * {@code viewArrayClass} according to the given endianness. 4224 * <p> 4225 * The supported component types (variables types) are {@code short}, 4226 * {@code char}, {@code int}, {@code long}, {@code float} and 4227 * {@code double}. 4228 * <p> 4229 * Access of bytes at a given index will result in an 4230 * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0} 4231 * or greater than the {@code byte[]} array length minus the size (in bytes) 4232 * of {@code T}. 4233 * <p> 4234 * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set} 4235 * access modes are supported by the returned var handle. For all other access modes, an 4236 * {@link UnsupportedOperationException} will be thrown. 4237 * 4238 * @apiNote if access modes other than plain access are required, clients should 4239 * consider using off-heap memory through 4240 * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or 4241 * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments}, 4242 * or memory segments backed by a 4243 * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}}, 4244 * for which stronger alignment guarantees can be made. 4245 * 4246 * @param viewArrayClass the view array class, with a component type of 4247 * type {@code T} 4248 * @param byteOrder the endianness of the view array elements, as 4249 * stored in the underlying {@code byte} array 4250 * @return a VarHandle giving access to elements of a {@code byte[]} array 4251 * viewed as if elements corresponding to the components type of the view 4252 * array class 4253 * @throws NullPointerException if viewArrayClass or byteOrder is null 4254 * @throws IllegalArgumentException if viewArrayClass is not an array type 4255 * @throws UnsupportedOperationException if the component type of 4256 * viewArrayClass is not supported as a variable type 4257 * @since 9 4258 */ 4259 public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 4260 ByteOrder byteOrder) throws IllegalArgumentException { 4261 Objects.requireNonNull(byteOrder); 4262 return VarHandles.byteArrayViewHandle(viewArrayClass, 4263 byteOrder == ByteOrder.BIG_ENDIAN); 4264 } 4265 4266 /** 4267 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 4268 * viewed as if it were an array of elements of a different primitive 4269 * component type to that of {@code byte}, such as {@code int[]} or 4270 * {@code long[]}. 4271 * The VarHandle's variable type is the component type of 4272 * {@code viewArrayClass} and the list of coordinate types is 4273 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 4274 * corresponds to an argument that is an index into a {@code byte[]} array. 4275 * The returned VarHandle accesses bytes at an index in a 4276 * {@code ByteBuffer}, composing bytes to or from a value of the component 4277 * type of {@code viewArrayClass} according to the given endianness. 4278 * <p> 4279 * The supported component types (variables types) are {@code short}, 4280 * {@code char}, {@code int}, {@code long}, {@code float} and 4281 * {@code double}. 4282 * <p> 4283 * Access will result in a {@code ReadOnlyBufferException} for anything 4284 * other than the read access modes if the {@code ByteBuffer} is read-only. 4285 * <p> 4286 * Access of bytes at a given index will result in an 4287 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 4288 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 4289 * {@code T}. 4290 * <p> 4291 * For heap byte buffers, access is always unaligned. As a result, only the plain 4292 * {@linkplain VarHandle.AccessMode#GET get} 4293 * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the 4294 * returned var handle. For all other access modes, an {@link IllegalStateException} 4295 * will be thrown. 4296 * <p> 4297 * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T}, 4298 * with respect to the underlying memory address, {@code A} say, associated 4299 * with the {@code ByteBuffer} and index. 4300 * If access is misaligned then access for anything other than the 4301 * {@code get} and {@code set} access modes will result in an 4302 * {@code IllegalStateException}. In such cases atomic access is only 4303 * guaranteed with respect to the largest power of two that divides the GCD 4304 * of {@code A} and the size (in bytes) of {@code T}. 4305 * If access is aligned then following access modes are supported and are 4306 * guaranteed to support atomic access: 4307 * <ul> 4308 * <li>read write access modes for all {@code T}, with the exception of 4309 * access modes {@code get} and {@code set} for {@code long} and 4310 * {@code double} on 32-bit platforms. 4311 * <li>atomic update access modes for {@code int}, {@code long}, 4312 * {@code float} or {@code double}. 4313 * (Future major platform releases of the JDK may support additional 4314 * types for certain currently unsupported access modes.) 4315 * <li>numeric atomic update access modes for {@code int} and {@code long}. 4316 * (Future major platform releases of the JDK may support additional 4317 * numeric types for certain currently unsupported access modes.) 4318 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 4319 * (Future major platform releases of the JDK may support additional 4320 * numeric types for certain currently unsupported access modes.) 4321 * </ul> 4322 * <p> 4323 * Misaligned access, and therefore atomicity guarantees, may be determined 4324 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 4325 * {@code index}, {@code T} and its corresponding boxed type, 4326 * {@code T_BOX}, as follows: 4327 * <pre>{@code 4328 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 4329 * ByteBuffer bb = ... 4330 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 4331 * boolean isMisaligned = misalignedAtIndex != 0; 4332 * }</pre> 4333 * <p> 4334 * If the variable type is {@code float} or {@code double} then atomic 4335 * update access modes compare values using their bitwise representation 4336 * (see {@link Float#floatToRawIntBits} and 4337 * {@link Double#doubleToRawLongBits}, respectively). 4338 * @param viewArrayClass the view array class, with a component type of 4339 * type {@code T} 4340 * @param byteOrder the endianness of the view array elements, as 4341 * stored in the underlying {@code ByteBuffer} (Note this overrides the 4342 * endianness of a {@code ByteBuffer}) 4343 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 4344 * viewed as if elements corresponding to the components type of the view 4345 * array class 4346 * @throws NullPointerException if viewArrayClass or byteOrder is null 4347 * @throws IllegalArgumentException if viewArrayClass is not an array type 4348 * @throws UnsupportedOperationException if the component type of 4349 * viewArrayClass is not supported as a variable type 4350 * @since 9 4351 */ 4352 public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 4353 ByteOrder byteOrder) throws IllegalArgumentException { 4354 Objects.requireNonNull(byteOrder); 4355 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 4356 byteOrder == ByteOrder.BIG_ENDIAN); 4357 } 4358 4359 4360 //--- method handle invocation (reflective style) 4361 4362 /** 4363 * Produces a method handle which will invoke any method handle of the 4364 * given {@code type}, with a given number of trailing arguments replaced by 4365 * a single trailing {@code Object[]} array. 4366 * The resulting invoker will be a method handle with the following 4367 * arguments: 4368 * <ul> 4369 * <li>a single {@code MethodHandle} target 4370 * <li>zero or more leading values (counted by {@code leadingArgCount}) 4371 * <li>an {@code Object[]} array containing trailing arguments 4372 * </ul> 4373 * <p> 4374 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 4375 * the indicated {@code type}. 4376 * That is, if the target is exactly of the given {@code type}, it will behave 4377 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 4378 * is used to convert the target to the required {@code type}. 4379 * <p> 4380 * The type of the returned invoker will not be the given {@code type}, but rather 4381 * will have all parameters except the first {@code leadingArgCount} 4382 * replaced by a single array of type {@code Object[]}, which will be 4383 * the final parameter. 4384 * <p> 4385 * Before invoking its target, the invoker will spread the final array, apply 4386 * reference casts as necessary, and unbox and widen primitive arguments. 4387 * If, when the invoker is called, the supplied array argument does 4388 * not have the correct number of elements, the invoker will throw 4389 * an {@link IllegalArgumentException} instead of invoking the target. 4390 * <p> 4391 * This method is equivalent to the following code (though it may be more efficient): 4392 * {@snippet lang="java" : 4393 MethodHandle invoker = MethodHandles.invoker(type); 4394 int spreadArgCount = type.parameterCount() - leadingArgCount; 4395 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 4396 return invoker; 4397 * } 4398 * This method throws no reflective exceptions. 4399 * @param type the desired target type 4400 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 4401 * @return a method handle suitable for invoking any method handle of the given type 4402 * @throws NullPointerException if {@code type} is null 4403 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 4404 * the range from 0 to {@code type.parameterCount()} inclusive, 4405 * or if the resulting method handle's type would have 4406 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4407 */ 4408 public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 4409 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 4410 throw newIllegalArgumentException("bad argument count", leadingArgCount); 4411 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 4412 return type.invokers().spreadInvoker(leadingArgCount); 4413 } 4414 4415 /** 4416 * Produces a special <em>invoker method handle</em> which can be used to 4417 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 4418 * The resulting invoker will have a type which is 4419 * exactly equal to the desired type, except that it will accept 4420 * an additional leading argument of type {@code MethodHandle}. 4421 * <p> 4422 * This method is equivalent to the following code (though it may be more efficient): 4423 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 4424 * 4425 * <p style="font-size:smaller;"> 4426 * <em>Discussion:</em> 4427 * Invoker method handles can be useful when working with variable method handles 4428 * of unknown types. 4429 * For example, to emulate an {@code invokeExact} call to a variable method 4430 * handle {@code M}, extract its type {@code T}, 4431 * look up the invoker method {@code X} for {@code T}, 4432 * and call the invoker method, as {@code X.invoke(T, A...)}. 4433 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 4434 * is unknown.) 4435 * If spreading, collecting, or other argument transformations are required, 4436 * they can be applied once to the invoker {@code X} and reused on many {@code M} 4437 * method handle values, as long as they are compatible with the type of {@code X}. 4438 * <p style="font-size:smaller;"> 4439 * <em>(Note: The invoker method is not available via the Core Reflection API. 4440 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4441 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4442 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4443 * <p> 4444 * This method throws no reflective exceptions. 4445 * @param type the desired target type 4446 * @return a method handle suitable for invoking any method handle of the given type 4447 * @throws IllegalArgumentException if the resulting method handle's type would have 4448 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4449 */ 4450 public static MethodHandle exactInvoker(MethodType type) { 4451 return type.invokers().exactInvoker(); 4452 } 4453 4454 /** 4455 * Produces a special <em>invoker method handle</em> which can be used to 4456 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 4457 * The resulting invoker will have a type which is 4458 * exactly equal to the desired type, except that it will accept 4459 * an additional leading argument of type {@code MethodHandle}. 4460 * <p> 4461 * Before invoking its target, if the target differs from the expected type, 4462 * the invoker will apply reference casts as 4463 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 4464 * Similarly, the return value will be converted as necessary. 4465 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 4466 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 4467 * <p> 4468 * This method is equivalent to the following code (though it may be more efficient): 4469 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 4470 * <p style="font-size:smaller;"> 4471 * <em>Discussion:</em> 4472 * A {@linkplain MethodType#genericMethodType general method type} is one which 4473 * mentions only {@code Object} arguments and return values. 4474 * An invoker for such a type is capable of calling any method handle 4475 * of the same arity as the general type. 4476 * <p style="font-size:smaller;"> 4477 * <em>(Note: The invoker method is not available via the Core Reflection API. 4478 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 4479 * on the declared {@code invokeExact} or {@code invoke} method will raise an 4480 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 4481 * <p> 4482 * This method throws no reflective exceptions. 4483 * @param type the desired target type 4484 * @return a method handle suitable for invoking any method handle convertible to the given type 4485 * @throws IllegalArgumentException if the resulting method handle's type would have 4486 * <a href="MethodHandle.html#maxarity">too many parameters</a> 4487 */ 4488 public static MethodHandle invoker(MethodType type) { 4489 return type.invokers().genericInvoker(); 4490 } 4491 4492 /** 4493 * Produces a special <em>invoker method handle</em> which can be used to 4494 * invoke a signature-polymorphic access mode method on any VarHandle whose 4495 * associated access mode type is compatible with the given type. 4496 * The resulting invoker will have a type which is exactly equal to the 4497 * desired given type, except that it will accept an additional leading 4498 * argument of type {@code VarHandle}. 4499 * 4500 * @param accessMode the VarHandle access mode 4501 * @param type the desired target type 4502 * @return a method handle suitable for invoking an access mode method of 4503 * any VarHandle whose access mode type is of the given type. 4504 * @since 9 4505 */ 4506 public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4507 return type.invokers().varHandleMethodExactInvoker(accessMode); 4508 } 4509 4510 /** 4511 * Produces a special <em>invoker method handle</em> which can be used to 4512 * invoke a signature-polymorphic access mode method on any VarHandle whose 4513 * associated access mode type is compatible with the given type. 4514 * The resulting invoker will have a type which is exactly equal to the 4515 * desired given type, except that it will accept an additional leading 4516 * argument of type {@code VarHandle}. 4517 * <p> 4518 * Before invoking its target, if the access mode type differs from the 4519 * desired given type, the invoker will apply reference casts as necessary 4520 * and box, unbox, or widen primitive values, as if by 4521 * {@link MethodHandle#asType asType}. Similarly, the return value will be 4522 * converted as necessary. 4523 * <p> 4524 * This method is equivalent to the following code (though it may be more 4525 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 4526 * 4527 * @param accessMode the VarHandle access mode 4528 * @param type the desired target type 4529 * @return a method handle suitable for invoking an access mode method of 4530 * any VarHandle whose access mode type is convertible to the given 4531 * type. 4532 * @since 9 4533 */ 4534 public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 4535 return type.invokers().varHandleMethodInvoker(accessMode); 4536 } 4537 4538 /*non-public*/ 4539 static MethodHandle basicInvoker(MethodType type) { 4540 return type.invokers().basicInvoker(); 4541 } 4542 4543 //--- method handle modification (creation from other method handles) 4544 4545 /** 4546 * Produces a method handle which adapts the type of the 4547 * given method handle to a new type by pairwise argument and return type conversion. 4548 * The original type and new type must have the same number of arguments. 4549 * The resulting method handle is guaranteed to report a type 4550 * which is equal to the desired new type. 4551 * <p> 4552 * If the original type and new type are equal, returns target. 4553 * <p> 4554 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 4555 * and some additional conversions are also applied if those conversions fail. 4556 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 4557 * if possible, before or instead of any conversions done by {@code asType}: 4558 * <ul> 4559 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 4560 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 4561 * (This treatment of interfaces follows the usage of the bytecode verifier.) 4562 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 4563 * the boolean is converted to a byte value, 1 for true, 0 for false. 4564 * (This treatment follows the usage of the bytecode verifier.) 4565 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 4566 * <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}), 4567 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 4568 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 4569 * then a Java casting conversion (JLS {@jls 5.5}) is applied. 4570 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 4571 * widening and/or narrowing.) 4572 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 4573 * conversion will be applied at runtime, possibly followed 4574 * by a Java casting conversion (JLS {@jls 5.5}) on the primitive value, 4575 * possibly followed by a conversion from byte to boolean by testing 4576 * the low-order bit. 4577 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 4578 * and if the reference is null at runtime, a zero value is introduced. 4579 * </ul> 4580 * @param target the method handle to invoke after arguments are retyped 4581 * @param newType the expected type of the new method handle 4582 * @return a method handle which delegates to the target after performing 4583 * any necessary argument conversions, and arranges for any 4584 * necessary return value conversions 4585 * @throws NullPointerException if either argument is null 4586 * @throws WrongMethodTypeException if the conversion cannot be made 4587 * @see MethodHandle#asType 4588 */ 4589 public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 4590 explicitCastArgumentsChecks(target, newType); 4591 // use the asTypeCache when possible: 4592 MethodType oldType = target.type(); 4593 if (oldType == newType) return target; 4594 if (oldType.explicitCastEquivalentToAsType(newType)) { 4595 return target.asFixedArity().asType(newType); 4596 } 4597 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 4598 } 4599 4600 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 4601 if (target.type().parameterCount() != newType.parameterCount()) { 4602 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 4603 } 4604 } 4605 4606 /** 4607 * Produces a method handle which adapts the calling sequence of the 4608 * given method handle to a new type, by reordering the arguments. 4609 * The resulting method handle is guaranteed to report a type 4610 * which is equal to the desired new type. 4611 * <p> 4612 * The given array controls the reordering. 4613 * Call {@code #I} the number of incoming parameters (the value 4614 * {@code newType.parameterCount()}, and call {@code #O} the number 4615 * of outgoing parameters (the value {@code target.type().parameterCount()}). 4616 * Then the length of the reordering array must be {@code #O}, 4617 * and each element must be a non-negative number less than {@code #I}. 4618 * For every {@code N} less than {@code #O}, the {@code N}-th 4619 * outgoing argument will be taken from the {@code I}-th incoming 4620 * argument, where {@code I} is {@code reorder[N]}. 4621 * <p> 4622 * No argument or return value conversions are applied. 4623 * The type of each incoming argument, as determined by {@code newType}, 4624 * must be identical to the type of the corresponding outgoing parameter 4625 * or parameters in the target method handle. 4626 * The return type of {@code newType} must be identical to the return 4627 * type of the original target. 4628 * <p> 4629 * The reordering array need not specify an actual permutation. 4630 * An incoming argument will be duplicated if its index appears 4631 * more than once in the array, and an incoming argument will be dropped 4632 * if its index does not appear in the array. 4633 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 4634 * incoming arguments which are not mentioned in the reordering array 4635 * may be of any type, as determined only by {@code newType}. 4636 * {@snippet lang="java" : 4637 import static java.lang.invoke.MethodHandles.*; 4638 import static java.lang.invoke.MethodType.*; 4639 ... 4640 MethodType intfn1 = methodType(int.class, int.class); 4641 MethodType intfn2 = methodType(int.class, int.class, int.class); 4642 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 4643 assert(sub.type().equals(intfn2)); 4644 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 4645 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 4646 assert((int)rsub.invokeExact(1, 100) == 99); 4647 MethodHandle add = ... (int x, int y) -> (x+y) ...; 4648 assert(add.type().equals(intfn2)); 4649 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 4650 assert(twice.type().equals(intfn1)); 4651 assert((int)twice.invokeExact(21) == 42); 4652 * } 4653 * <p> 4654 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4655 * variable-arity method handle}, even if the original target method handle was. 4656 * @param target the method handle to invoke after arguments are reordered 4657 * @param newType the expected type of the new method handle 4658 * @param reorder an index array which controls the reordering 4659 * @return a method handle which delegates to the target after it 4660 * drops unused arguments and moves and/or duplicates the other arguments 4661 * @throws NullPointerException if any argument is null 4662 * @throws IllegalArgumentException if the index array length is not equal to 4663 * the arity of the target, or if any index array element 4664 * not a valid index for a parameter of {@code newType}, 4665 * or if two corresponding parameter types in 4666 * {@code target.type()} and {@code newType} are not identical, 4667 */ 4668 public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 4669 reorder = reorder.clone(); // get a private copy 4670 MethodType oldType = target.type(); 4671 permuteArgumentChecks(reorder, newType, oldType); 4672 // first detect dropped arguments and handle them separately 4673 int[] originalReorder = reorder; 4674 BoundMethodHandle result = target.rebind(); 4675 LambdaForm form = result.form; 4676 int newArity = newType.parameterCount(); 4677 // Normalize the reordering into a real permutation, 4678 // by removing duplicates and adding dropped elements. 4679 // This somewhat improves lambda form caching, as well 4680 // as simplifying the transform by breaking it up into steps. 4681 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 4682 if (ddIdx > 0) { 4683 // We found a duplicated entry at reorder[ddIdx]. 4684 // Example: (x,y,z)->asList(x,y,z) 4685 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 4686 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 4687 // The starred element corresponds to the argument 4688 // deleted by the dupArgumentForm transform. 4689 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 4690 boolean killFirst = false; 4691 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 4692 // Set killFirst if the dup is larger than an intervening position. 4693 // This will remove at least one inversion from the permutation. 4694 if (dupVal > val) killFirst = true; 4695 } 4696 if (!killFirst) { 4697 srcPos = dstPos; 4698 dstPos = ddIdx; 4699 } 4700 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 4701 assert (reorder[srcPos] == reorder[dstPos]); 4702 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 4703 // contract the reordering by removing the element at dstPos 4704 int tailPos = dstPos + 1; 4705 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 4706 reorder = Arrays.copyOf(reorder, reorder.length - 1); 4707 } else { 4708 int dropVal = ~ddIdx, insPos = 0; 4709 while (insPos < reorder.length && reorder[insPos] < dropVal) { 4710 // Find first element of reorder larger than dropVal. 4711 // This is where we will insert the dropVal. 4712 insPos += 1; 4713 } 4714 Class<?> ptype = newType.parameterType(dropVal); 4715 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 4716 oldType = oldType.insertParameterTypes(insPos, ptype); 4717 // expand the reordering by inserting an element at insPos 4718 int tailPos = insPos + 1; 4719 reorder = Arrays.copyOf(reorder, reorder.length + 1); 4720 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 4721 reorder[insPos] = dropVal; 4722 } 4723 assert (permuteArgumentChecks(reorder, newType, oldType)); 4724 } 4725 assert (reorder.length == newArity); // a perfect permutation 4726 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 4727 form = form.editor().permuteArgumentsForm(1, reorder); 4728 if (newType == result.type() && form == result.internalForm()) 4729 return result; 4730 return result.copyWith(newType, form); 4731 } 4732 4733 /** 4734 * Return an indication of any duplicate or omission in reorder. 4735 * If the reorder contains a duplicate entry, return the index of the second occurrence. 4736 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 4737 * Otherwise, return zero. 4738 * If an element not in [0..newArity-1] is encountered, return reorder.length. 4739 */ 4740 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 4741 final int BIT_LIMIT = 63; // max number of bits in bit mask 4742 if (newArity < BIT_LIMIT) { 4743 long mask = 0; 4744 for (int i = 0; i < reorder.length; i++) { 4745 int arg = reorder[i]; 4746 if (arg >= newArity) { 4747 return reorder.length; 4748 } 4749 long bit = 1L << arg; 4750 if ((mask & bit) != 0) { 4751 return i; // >0 indicates a dup 4752 } 4753 mask |= bit; 4754 } 4755 if (mask == (1L << newArity) - 1) { 4756 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 4757 return 0; 4758 } 4759 // find first zero 4760 long zeroBit = Long.lowestOneBit(~mask); 4761 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 4762 assert(zeroPos <= newArity); 4763 if (zeroPos == newArity) { 4764 return 0; 4765 } 4766 return ~zeroPos; 4767 } else { 4768 // same algorithm, different bit set 4769 BitSet mask = new BitSet(newArity); 4770 for (int i = 0; i < reorder.length; i++) { 4771 int arg = reorder[i]; 4772 if (arg >= newArity) { 4773 return reorder.length; 4774 } 4775 if (mask.get(arg)) { 4776 return i; // >0 indicates a dup 4777 } 4778 mask.set(arg); 4779 } 4780 int zeroPos = mask.nextClearBit(0); 4781 assert(zeroPos <= newArity); 4782 if (zeroPos == newArity) { 4783 return 0; 4784 } 4785 return ~zeroPos; 4786 } 4787 } 4788 4789 static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 4790 if (newType.returnType() != oldType.returnType()) 4791 throw newIllegalArgumentException("return types do not match", 4792 oldType, newType); 4793 if (reorder.length != oldType.parameterCount()) 4794 throw newIllegalArgumentException("old type parameter count and reorder array length do not match", 4795 oldType, Arrays.toString(reorder)); 4796 4797 int limit = newType.parameterCount(); 4798 for (int j = 0; j < reorder.length; j++) { 4799 int i = reorder[j]; 4800 if (i < 0 || i >= limit) { 4801 throw newIllegalArgumentException("index is out of bounds for new type", 4802 i, newType); 4803 } 4804 Class<?> src = newType.parameterType(i); 4805 Class<?> dst = oldType.parameterType(j); 4806 if (src != dst) 4807 throw newIllegalArgumentException("parameter types do not match after reorder", 4808 oldType, newType); 4809 } 4810 return true; 4811 } 4812 4813 /** 4814 * Produces a method handle of the requested return type which returns the given 4815 * constant value every time it is invoked. 4816 * <p> 4817 * Before the method handle is returned, the passed-in value is converted to the requested type. 4818 * If the requested type is primitive, widening primitive conversions are attempted, 4819 * else reference conversions are attempted. 4820 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 4821 * @param type the return type of the desired method handle 4822 * @param value the value to return 4823 * @return a method handle of the given return type and no arguments, which always returns the given value 4824 * @throws NullPointerException if the {@code type} argument is null 4825 * @throws ClassCastException if the value cannot be converted to the required return type 4826 * @throws IllegalArgumentException if the given type is {@code void.class} 4827 */ 4828 public static MethodHandle constant(Class<?> type, Object value) { 4829 if (Objects.requireNonNull(type) == void.class) 4830 throw newIllegalArgumentException("void type"); 4831 return MethodHandleImpl.makeConstantReturning(type, value); 4832 } 4833 4834 /** 4835 * Produces a method handle which returns its sole argument when invoked. 4836 * @param type the type of the sole parameter and return value of the desired method handle 4837 * @return a unary method handle which accepts and returns the given type 4838 * @throws NullPointerException if the argument is null 4839 * @throws IllegalArgumentException if the given type is {@code void.class} 4840 */ 4841 public static MethodHandle identity(Class<?> type) { 4842 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 4843 int pos = btw.ordinal(); 4844 MethodHandle ident = IDENTITY_MHS[pos]; 4845 if (ident == null) { 4846 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 4847 } 4848 if (ident.type().returnType() == type) 4849 return ident; 4850 // something like identity(Foo.class); do not bother to intern these 4851 assert (btw == Wrapper.OBJECT); 4852 return makeIdentity(type); 4853 } 4854 4855 /** 4856 * Produces a constant method handle of the requested return type which 4857 * returns the default value for that type every time it is invoked. 4858 * The resulting constant method handle will have no side effects. 4859 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 4860 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 4861 * since {@code explicitCastArguments} converts {@code null} to default values. 4862 * @param type the expected return type of the desired method handle 4863 * @return a constant method handle that takes no arguments 4864 * and returns the default value of the given type (or void, if the type is void) 4865 * @throws NullPointerException if the argument is null 4866 * @see MethodHandles#constant 4867 * @see MethodHandles#empty 4868 * @see MethodHandles#explicitCastArguments 4869 * @since 9 4870 */ 4871 public static MethodHandle zero(Class<?> type) { 4872 Objects.requireNonNull(type); 4873 return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type)) 4874 : MethodHandleImpl.makeConstantReturning(type, null); 4875 } 4876 4877 private static MethodHandle identityOrVoid(Class<?> type) { 4878 return type == void.class ? zero(type) : identity(type); 4879 } 4880 4881 /** 4882 * Produces a method handle of the requested type which ignores any arguments, does nothing, 4883 * and returns a suitable default depending on the return type. 4884 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 4885 * <p>The returned method handle is equivalent to 4886 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 4887 * 4888 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 4889 * {@code guardWithTest(pred, target, empty(target.type())}. 4890 * @param type the type of the desired method handle 4891 * @return a constant method handle of the given type, which returns a default value of the given return type 4892 * @throws NullPointerException if the argument is null 4893 * @see MethodHandles#primitiveZero 4894 * @see MethodHandles#constant 4895 * @since 9 4896 */ 4897 public static MethodHandle empty(MethodType type) { 4898 Objects.requireNonNull(type); 4899 return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes()); 4900 } 4901 4902 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 4903 private static MethodHandle makeIdentity(Class<?> ptype) { 4904 MethodType mtype = methodType(ptype, ptype); // throws IAE for void 4905 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 4906 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 4907 } 4908 4909 private static MethodHandle primitiveZero(Wrapper w) { 4910 assert w != Wrapper.OBJECT : w; 4911 int pos = w.ordinal(); 4912 MethodHandle mh = PRIMITIVE_ZERO_MHS[pos]; 4913 if (mh == null) { 4914 mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w)); 4915 } 4916 assert (mh.type().returnType() == w.primitiveType()) : mh; 4917 return mh; 4918 } 4919 4920 private static MethodHandle makePrimitiveZero(Wrapper w) { 4921 if (w == Wrapper.VOID) { 4922 var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized 4923 return SimpleMethodHandle.make(MethodType.methodType(void.class), lf); 4924 } else { 4925 return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero()); 4926 } 4927 } 4928 4929 private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 4930 4931 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 4932 // Simulate a CAS, to avoid racy duplication of results. 4933 MethodHandle prev = cache[pos]; 4934 if (prev != null) return prev; 4935 return cache[pos] = value; 4936 } 4937 4938 /** 4939 * Provides a target method handle with one or more <em>bound arguments</em> 4940 * in advance of the method handle's invocation. 4941 * The formal parameters to the target corresponding to the bound 4942 * arguments are called <em>bound parameters</em>. 4943 * Returns a new method handle which saves away the bound arguments. 4944 * When it is invoked, it receives arguments for any non-bound parameters, 4945 * binds the saved arguments to their corresponding parameters, 4946 * and calls the original target. 4947 * <p> 4948 * The type of the new method handle will drop the types for the bound 4949 * parameters from the original target type, since the new method handle 4950 * will no longer require those arguments to be supplied by its callers. 4951 * <p> 4952 * Each given argument object must match the corresponding bound parameter type. 4953 * If a bound parameter type is a primitive, the argument object 4954 * must be a wrapper, and will be unboxed to produce the primitive value. 4955 * <p> 4956 * The {@code pos} argument selects which parameters are to be bound. 4957 * It may range between zero and <i>N-L</i> (inclusively), 4958 * where <i>N</i> is the arity of the target method handle 4959 * and <i>L</i> is the length of the values array. 4960 * <p> 4961 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4962 * variable-arity method handle}, even if the original target method handle was. 4963 * @param target the method handle to invoke after the argument is inserted 4964 * @param pos where to insert the argument (zero for the first) 4965 * @param values the series of arguments to insert 4966 * @return a method handle which inserts an additional argument, 4967 * before calling the original method handle 4968 * @throws NullPointerException if the target or the {@code values} array is null 4969 * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than 4970 * {@code N - L} where {@code N} is the arity of the target method handle and {@code L} 4971 * is the length of the values array. 4972 * @throws ClassCastException if an argument does not match the corresponding bound parameter 4973 * type. 4974 * @see MethodHandle#bindTo 4975 */ 4976 public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 4977 int insCount = values.length; 4978 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 4979 if (insCount == 0) return target; 4980 BoundMethodHandle result = target.rebind(); 4981 for (int i = 0; i < insCount; i++) { 4982 Object value = values[i]; 4983 Class<?> ptype = ptypes[pos+i]; 4984 if (ptype.isPrimitive()) { 4985 result = insertArgumentPrimitive(result, pos, ptype, value); 4986 } else { 4987 value = ptype.cast(value); // throw CCE if needed 4988 result = result.bindArgumentL(pos, value); 4989 } 4990 } 4991 return result; 4992 } 4993 4994 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 4995 Class<?> ptype, Object value) { 4996 Wrapper w = Wrapper.forPrimitiveType(ptype); 4997 // perform unboxing and/or primitive conversion 4998 value = w.convert(value, ptype); 4999 return switch (w) { 5000 case INT -> result.bindArgumentI(pos, (int) value); 5001 case LONG -> result.bindArgumentJ(pos, (long) value); 5002 case FLOAT -> result.bindArgumentF(pos, (float) value); 5003 case DOUBLE -> result.bindArgumentD(pos, (double) value); 5004 default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 5005 }; 5006 } 5007 5008 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 5009 MethodType oldType = target.type(); 5010 int outargs = oldType.parameterCount(); 5011 int inargs = outargs - insCount; 5012 if (inargs < 0) 5013 throw newIllegalArgumentException("too many values to insert"); 5014 if (pos < 0 || pos > inargs) 5015 throw newIllegalArgumentException("no argument type to append"); 5016 return oldType.ptypes(); 5017 } 5018 5019 /** 5020 * Produces a method handle which will discard some dummy arguments 5021 * before calling some other specified <i>target</i> method handle. 5022 * The type of the new method handle will be the same as the target's type, 5023 * except it will also include the dummy argument types, 5024 * at some given position. 5025 * <p> 5026 * The {@code pos} argument may range between zero and <i>N</i>, 5027 * where <i>N</i> is the arity of the target. 5028 * If {@code pos} is zero, the dummy arguments will precede 5029 * the target's real arguments; if {@code pos} is <i>N</i> 5030 * they will come after. 5031 * <p> 5032 * <b>Example:</b> 5033 * {@snippet lang="java" : 5034 import static java.lang.invoke.MethodHandles.*; 5035 import static java.lang.invoke.MethodType.*; 5036 ... 5037 MethodHandle cat = lookup().findVirtual(String.class, 5038 "concat", methodType(String.class, String.class)); 5039 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5040 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 5041 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 5042 assertEquals(bigType, d0.type()); 5043 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 5044 * } 5045 * <p> 5046 * This method is also equivalent to the following code: 5047 * <blockquote><pre> 5048 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 5049 * </pre></blockquote> 5050 * @param target the method handle to invoke after the arguments are dropped 5051 * @param pos position of first argument to drop (zero for the leftmost) 5052 * @param valueTypes the type(s) of the argument(s) to drop 5053 * @return a method handle which drops arguments of the given types, 5054 * before calling the original method handle 5055 * @throws NullPointerException if the target is null, 5056 * or if the {@code valueTypes} list or any of its elements is null 5057 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5058 * or if {@code pos} is negative or greater than the arity of the target, 5059 * or if the new method handle's type would have too many parameters 5060 */ 5061 public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 5062 return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone()); 5063 } 5064 5065 static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) { 5066 MethodType oldType = target.type(); // get NPE 5067 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 5068 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 5069 if (dropped == 0) return target; 5070 BoundMethodHandle result = target.rebind(); 5071 LambdaForm lform = result.form; 5072 int insertFormArg = 1 + pos; 5073 for (Class<?> ptype : valueTypes) { 5074 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 5075 } 5076 result = result.copyWith(newType, lform); 5077 return result; 5078 } 5079 5080 private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) { 5081 int dropped = valueTypes.length; 5082 MethodType.checkSlotCount(dropped); 5083 int outargs = oldType.parameterCount(); 5084 int inargs = outargs + dropped; 5085 if (pos < 0 || pos > outargs) 5086 throw newIllegalArgumentException("no argument type to remove" 5087 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 5088 ); 5089 return dropped; 5090 } 5091 5092 /** 5093 * Produces a method handle which will discard some dummy arguments 5094 * before calling some other specified <i>target</i> method handle. 5095 * The type of the new method handle will be the same as the target's type, 5096 * except it will also include the dummy argument types, 5097 * at some given position. 5098 * <p> 5099 * The {@code pos} argument may range between zero and <i>N</i>, 5100 * where <i>N</i> is the arity of the target. 5101 * If {@code pos} is zero, the dummy arguments will precede 5102 * the target's real arguments; if {@code pos} is <i>N</i> 5103 * they will come after. 5104 * @apiNote 5105 * {@snippet lang="java" : 5106 import static java.lang.invoke.MethodHandles.*; 5107 import static java.lang.invoke.MethodType.*; 5108 ... 5109 MethodHandle cat = lookup().findVirtual(String.class, 5110 "concat", methodType(String.class, String.class)); 5111 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5112 MethodHandle d0 = dropArguments(cat, 0, String.class); 5113 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 5114 MethodHandle d1 = dropArguments(cat, 1, String.class); 5115 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 5116 MethodHandle d2 = dropArguments(cat, 2, String.class); 5117 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 5118 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 5119 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 5120 * } 5121 * <p> 5122 * This method is also equivalent to the following code: 5123 * <blockquote><pre> 5124 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 5125 * </pre></blockquote> 5126 * @param target the method handle to invoke after the arguments are dropped 5127 * @param pos position of first argument to drop (zero for the leftmost) 5128 * @param valueTypes the type(s) of the argument(s) to drop 5129 * @return a method handle which drops arguments of the given types, 5130 * before calling the original method handle 5131 * @throws NullPointerException if the target is null, 5132 * or if the {@code valueTypes} array or any of its elements is null 5133 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 5134 * or if {@code pos} is negative or greater than the arity of the target, 5135 * or if the new method handle's type would have 5136 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5137 */ 5138 public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 5139 return dropArgumentsTrusted(target, pos, valueTypes.clone()); 5140 } 5141 5142 /* Convenience overloads for trusting internal low-arity call-sites */ 5143 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) { 5144 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 }); 5145 } 5146 static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) { 5147 return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 }); 5148 } 5149 5150 // private version which allows caller some freedom with error handling 5151 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos, 5152 boolean nullOnFailure) { 5153 Class<?>[] oldTypes = target.type().ptypes(); 5154 int match = oldTypes.length; 5155 if (skip != 0) { 5156 if (skip < 0 || skip > match) { 5157 throw newIllegalArgumentException("illegal skip", skip, target); 5158 } 5159 oldTypes = Arrays.copyOfRange(oldTypes, skip, match); 5160 match -= skip; 5161 } 5162 Class<?>[] addTypes = newTypes; 5163 int add = addTypes.length; 5164 if (pos != 0) { 5165 if (pos < 0 || pos > add) { 5166 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes)); 5167 } 5168 addTypes = Arrays.copyOfRange(addTypes, pos, add); 5169 add -= pos; 5170 assert(addTypes.length == add); 5171 } 5172 // Do not add types which already match the existing arguments. 5173 if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) { 5174 if (nullOnFailure) { 5175 return null; 5176 } 5177 throw newIllegalArgumentException("argument lists do not match", 5178 Arrays.toString(oldTypes), Arrays.toString(newTypes)); 5179 } 5180 addTypes = Arrays.copyOfRange(addTypes, match, add); 5181 add -= match; 5182 assert(addTypes.length == add); 5183 // newTypes: ( P*[pos], M*[match], A*[add] ) 5184 // target: ( S*[skip], M*[match] ) 5185 MethodHandle adapter = target; 5186 if (add > 0) { 5187 adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes); 5188 } 5189 // adapter: (S*[skip], M*[match], A*[add] ) 5190 if (pos > 0) { 5191 adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos)); 5192 } 5193 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 5194 return adapter; 5195 } 5196 5197 /** 5198 * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some 5199 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 5200 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 5201 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 5202 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 5203 * {@link #dropArguments(MethodHandle, int, Class[])}. 5204 * <p> 5205 * The resulting handle will have the same return type as the target handle. 5206 * <p> 5207 * In more formal terms, assume these two type lists:<ul> 5208 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 5209 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 5210 * {@code newTypes}. 5211 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 5212 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 5213 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 5214 * sub-list. 5215 * </ul> 5216 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 5217 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 5218 * {@link #dropArguments(MethodHandle, int, Class[])}. 5219 * 5220 * @apiNote 5221 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 5222 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 5223 * {@snippet lang="java" : 5224 import static java.lang.invoke.MethodHandles.*; 5225 import static java.lang.invoke.MethodType.*; 5226 ... 5227 ... 5228 MethodHandle h0 = constant(boolean.class, true); 5229 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 5230 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 5231 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 5232 if (h1.type().parameterCount() < h2.type().parameterCount()) 5233 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 5234 else 5235 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 5236 MethodHandle h3 = guardWithTest(h0, h1, h2); 5237 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 5238 * } 5239 * @param target the method handle to adapt 5240 * @param skip number of targets parameters to disregard (they will be unchanged) 5241 * @param newTypes the list of types to match {@code target}'s parameter type list to 5242 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 5243 * @return a possibly adapted method handle 5244 * @throws NullPointerException if either argument is null 5245 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 5246 * or if {@code skip} is negative or greater than the arity of the target, 5247 * or if {@code pos} is negative or greater than the newTypes list size, 5248 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 5249 * {@code pos}. 5250 * @since 9 5251 */ 5252 public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 5253 Objects.requireNonNull(target); 5254 Objects.requireNonNull(newTypes); 5255 return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false); 5256 } 5257 5258 /** 5259 * Drop the return value of the target handle (if any). 5260 * The returned method handle will have a {@code void} return type. 5261 * 5262 * @param target the method handle to adapt 5263 * @return a possibly adapted method handle 5264 * @throws NullPointerException if {@code target} is null 5265 * @since 16 5266 */ 5267 public static MethodHandle dropReturn(MethodHandle target) { 5268 Objects.requireNonNull(target); 5269 MethodType oldType = target.type(); 5270 Class<?> oldReturnType = oldType.returnType(); 5271 if (oldReturnType == void.class) 5272 return target; 5273 MethodType newType = oldType.changeReturnType(void.class); 5274 BoundMethodHandle result = target.rebind(); 5275 LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true); 5276 result = result.copyWith(newType, lform); 5277 return result; 5278 } 5279 5280 /** 5281 * Adapts a target method handle by pre-processing 5282 * one or more of its arguments, each with its own unary filter function, 5283 * and then calling the target with each pre-processed argument 5284 * replaced by the result of its corresponding filter function. 5285 * <p> 5286 * The pre-processing is performed by one or more method handles, 5287 * specified in the elements of the {@code filters} array. 5288 * The first element of the filter array corresponds to the {@code pos} 5289 * argument of the target, and so on in sequence. 5290 * The filter functions are invoked in left to right order. 5291 * <p> 5292 * Null arguments in the array are treated as identity functions, 5293 * and the corresponding arguments left unchanged. 5294 * (If there are no non-null elements in the array, the original target is returned.) 5295 * Each filter is applied to the corresponding argument of the adapter. 5296 * <p> 5297 * If a filter {@code F} applies to the {@code N}th argument of 5298 * the target, then {@code F} must be a method handle which 5299 * takes exactly one argument. The type of {@code F}'s sole argument 5300 * replaces the corresponding argument type of the target 5301 * in the resulting adapted method handle. 5302 * The return type of {@code F} must be identical to the corresponding 5303 * parameter type of the target. 5304 * <p> 5305 * It is an error if there are elements of {@code filters} 5306 * (null or not) 5307 * which do not correspond to argument positions in the target. 5308 * <p><b>Example:</b> 5309 * {@snippet lang="java" : 5310 import static java.lang.invoke.MethodHandles.*; 5311 import static java.lang.invoke.MethodType.*; 5312 ... 5313 MethodHandle cat = lookup().findVirtual(String.class, 5314 "concat", methodType(String.class, String.class)); 5315 MethodHandle upcase = lookup().findVirtual(String.class, 5316 "toUpperCase", methodType(String.class)); 5317 assertEquals("xy", (String) cat.invokeExact("x", "y")); 5318 MethodHandle f0 = filterArguments(cat, 0, upcase); 5319 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 5320 MethodHandle f1 = filterArguments(cat, 1, upcase); 5321 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 5322 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 5323 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 5324 * } 5325 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5326 * denotes the return type of both the {@code target} and resulting adapter. 5327 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 5328 * of the parameters and arguments that precede and follow the filter position 5329 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 5330 * values of the filtered parameters and arguments; they also represent the 5331 * return types of the {@code filter[i]} handles. The latter accept arguments 5332 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 5333 * the resulting adapter. 5334 * {@snippet lang="java" : 5335 * T target(P... p, A[i]... a[i], B... b); 5336 * A[i] filter[i](V[i]); 5337 * T adapter(P... p, V[i]... v[i], B... b) { 5338 * return target(p..., filter[i](v[i])..., b...); 5339 * } 5340 * } 5341 * <p> 5342 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5343 * variable-arity method handle}, even if the original target method handle was. 5344 * 5345 * @param target the method handle to invoke after arguments are filtered 5346 * @param pos the position of the first argument to filter 5347 * @param filters method handles to call initially on filtered arguments 5348 * @return method handle which incorporates the specified argument filtering logic 5349 * @throws NullPointerException if the target is null 5350 * or if the {@code filters} array is null 5351 * @throws IllegalArgumentException if a non-null element of {@code filters} 5352 * does not match a corresponding argument type of target as described above, 5353 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 5354 * or if the resulting method handle's type would have 5355 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5356 */ 5357 public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 5358 // In method types arguments start at index 0, while the LF 5359 // editor have the MH receiver at position 0 - adjust appropriately. 5360 final int MH_RECEIVER_OFFSET = 1; 5361 filterArgumentsCheckArity(target, pos, filters); 5362 MethodHandle adapter = target; 5363 5364 // keep track of currently matched filters, as to optimize repeated filters 5365 int index = 0; 5366 int[] positions = new int[filters.length]; 5367 MethodHandle filter = null; 5368 5369 // process filters in reverse order so that the invocation of 5370 // the resulting adapter will invoke the filters in left-to-right order 5371 for (int i = filters.length - 1; i >= 0; --i) { 5372 MethodHandle newFilter = filters[i]; 5373 if (newFilter == null) continue; // ignore null elements of filters 5374 5375 // flush changes on update 5376 if (filter != newFilter) { 5377 if (filter != null) { 5378 if (index > 1) { 5379 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5380 } else { 5381 adapter = filterArgument(adapter, positions[0] - 1, filter); 5382 } 5383 } 5384 filter = newFilter; 5385 index = 0; 5386 } 5387 5388 filterArgumentChecks(target, pos + i, newFilter); 5389 positions[index++] = pos + i + MH_RECEIVER_OFFSET; 5390 } 5391 if (index > 1) { 5392 adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index)); 5393 } else if (index == 1) { 5394 adapter = filterArgument(adapter, positions[0] - 1, filter); 5395 } 5396 return adapter; 5397 } 5398 5399 private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) { 5400 MethodType targetType = adapter.type(); 5401 MethodType filterType = filter.type(); 5402 BoundMethodHandle result = adapter.rebind(); 5403 Class<?> newParamType = filterType.parameterType(0); 5404 5405 Class<?>[] ptypes = targetType.ptypes().clone(); 5406 for (int pos : positions) { 5407 ptypes[pos - 1] = newParamType; 5408 } 5409 MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true); 5410 5411 LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions); 5412 return result.copyWithExtendL(newType, lform, filter); 5413 } 5414 5415 /*non-public*/ 5416 static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 5417 filterArgumentChecks(target, pos, filter); 5418 MethodType targetType = target.type(); 5419 MethodType filterType = filter.type(); 5420 BoundMethodHandle result = target.rebind(); 5421 Class<?> newParamType = filterType.parameterType(0); 5422 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 5423 MethodType newType = targetType.changeParameterType(pos, newParamType); 5424 result = result.copyWithExtendL(newType, lform, filter); 5425 return result; 5426 } 5427 5428 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 5429 MethodType targetType = target.type(); 5430 int maxPos = targetType.parameterCount(); 5431 if (pos + filters.length > maxPos) 5432 throw newIllegalArgumentException("too many filters"); 5433 } 5434 5435 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5436 MethodType targetType = target.type(); 5437 MethodType filterType = filter.type(); 5438 if (filterType.parameterCount() != 1 5439 || filterType.returnType() != targetType.parameterType(pos)) 5440 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5441 } 5442 5443 /** 5444 * Adapts a target method handle by pre-processing 5445 * a sub-sequence of its arguments with a filter (another method handle). 5446 * The pre-processed arguments are replaced by the result (if any) of the 5447 * filter function. 5448 * The target is then called on the modified (usually shortened) argument list. 5449 * <p> 5450 * If the filter returns a value, the target must accept that value as 5451 * its argument in position {@code pos}, preceded and/or followed by 5452 * any arguments not passed to the filter. 5453 * If the filter returns void, the target must accept all arguments 5454 * not passed to the filter. 5455 * No arguments are reordered, and a result returned from the filter 5456 * replaces (in order) the whole subsequence of arguments originally 5457 * passed to the adapter. 5458 * <p> 5459 * The argument types (if any) of the filter 5460 * replace zero or one argument types of the target, at position {@code pos}, 5461 * in the resulting adapted method handle. 5462 * The return type of the filter (if any) must be identical to the 5463 * argument type of the target at position {@code pos}, and that target argument 5464 * is supplied by the return value of the filter. 5465 * <p> 5466 * In all cases, {@code pos} must be greater than or equal to zero, and 5467 * {@code pos} must also be less than or equal to the target's arity. 5468 * <p><b>Example:</b> 5469 * {@snippet lang="java" : 5470 import static java.lang.invoke.MethodHandles.*; 5471 import static java.lang.invoke.MethodType.*; 5472 ... 5473 MethodHandle deepToString = publicLookup() 5474 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 5475 5476 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 5477 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 5478 5479 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 5480 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 5481 5482 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 5483 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 5484 assertEquals("[top, [up, down], strange]", 5485 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 5486 5487 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 5488 assertEquals("[top, [up, down], [strange]]", 5489 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 5490 5491 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 5492 assertEquals("[top, [[up, down, strange], charm], bottom]", 5493 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 5494 * } 5495 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5496 * represents the return type of the {@code target} and resulting adapter. 5497 * {@code V}/{@code v} stand for the return type and value of the 5498 * {@code filter}, which are also found in the signature and arguments of 5499 * the {@code target}, respectively, unless {@code V} is {@code void}. 5500 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 5501 * and values preceding and following the collection position, {@code pos}, 5502 * in the {@code target}'s signature. They also turn up in the resulting 5503 * adapter's signature and arguments, where they surround 5504 * {@code B}/{@code b}, which represent the parameter types and arguments 5505 * to the {@code filter} (if any). 5506 * {@snippet lang="java" : 5507 * T target(A...,V,C...); 5508 * V filter(B...); 5509 * T adapter(A... a,B... b,C... c) { 5510 * V v = filter(b...); 5511 * return target(a...,v,c...); 5512 * } 5513 * // and if the filter has no arguments: 5514 * T target2(A...,V,C...); 5515 * V filter2(); 5516 * T adapter2(A... a,C... c) { 5517 * V v = filter2(); 5518 * return target2(a...,v,c...); 5519 * } 5520 * // and if the filter has a void return: 5521 * T target3(A...,C...); 5522 * void filter3(B...); 5523 * T adapter3(A... a,B... b,C... c) { 5524 * filter3(b...); 5525 * return target3(a...,c...); 5526 * } 5527 * } 5528 * <p> 5529 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 5530 * one which first "folds" the affected arguments, and then drops them, in separate 5531 * steps as follows: 5532 * {@snippet lang="java" : 5533 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 5534 * mh = MethodHandles.foldArguments(mh, coll); //step 1 5535 * } 5536 * If the target method handle consumes no arguments besides than the result 5537 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 5538 * is equivalent to {@code filterReturnValue(coll, mh)}. 5539 * If the filter method handle {@code coll} consumes one argument and produces 5540 * a non-void result, then {@code collectArguments(mh, N, coll)} 5541 * is equivalent to {@code filterArguments(mh, N, coll)}. 5542 * Other equivalences are possible but would require argument permutation. 5543 * <p> 5544 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5545 * variable-arity method handle}, even if the original target method handle was. 5546 * 5547 * @param target the method handle to invoke after filtering the subsequence of arguments 5548 * @param pos the position of the first adapter argument to pass to the filter, 5549 * and/or the target argument which receives the result of the filter 5550 * @param filter method handle to call on the subsequence of arguments 5551 * @return method handle which incorporates the specified argument subsequence filtering logic 5552 * @throws NullPointerException if either argument is null 5553 * @throws IllegalArgumentException if the return type of {@code filter} 5554 * is non-void and is not the same as the {@code pos} argument of the target, 5555 * or if {@code pos} is not between 0 and the target's arity, inclusive, 5556 * or if the resulting method handle's type would have 5557 * <a href="MethodHandle.html#maxarity">too many parameters</a> 5558 * @see MethodHandles#foldArguments 5559 * @see MethodHandles#filterArguments 5560 * @see MethodHandles#filterReturnValue 5561 */ 5562 public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 5563 MethodType newType = collectArgumentsChecks(target, pos, filter); 5564 MethodType collectorType = filter.type(); 5565 BoundMethodHandle result = target.rebind(); 5566 LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 5567 return result.copyWithExtendL(newType, lform, filter); 5568 } 5569 5570 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 5571 MethodType targetType = target.type(); 5572 MethodType filterType = filter.type(); 5573 Class<?> rtype = filterType.returnType(); 5574 Class<?>[] filterArgs = filterType.ptypes(); 5575 if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) || 5576 (rtype != void.class && pos >= targetType.parameterCount())) { 5577 throw newIllegalArgumentException("position is out of range for target", target, pos); 5578 } 5579 if (rtype == void.class) { 5580 return targetType.insertParameterTypes(pos, filterArgs); 5581 } 5582 if (rtype != targetType.parameterType(pos)) { 5583 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5584 } 5585 return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs); 5586 } 5587 5588 /** 5589 * Adapts a target method handle by post-processing 5590 * its return value (if any) with a filter (another method handle). 5591 * The result of the filter is returned from the adapter. 5592 * <p> 5593 * If the target returns a value, the filter must accept that value as 5594 * its only argument. 5595 * If the target returns void, the filter must accept no arguments. 5596 * <p> 5597 * The return type of the filter 5598 * replaces the return type of the target 5599 * in the resulting adapted method handle. 5600 * The argument type of the filter (if any) must be identical to the 5601 * return type of the target. 5602 * <p><b>Example:</b> 5603 * {@snippet lang="java" : 5604 import static java.lang.invoke.MethodHandles.*; 5605 import static java.lang.invoke.MethodType.*; 5606 ... 5607 MethodHandle cat = lookup().findVirtual(String.class, 5608 "concat", methodType(String.class, String.class)); 5609 MethodHandle length = lookup().findVirtual(String.class, 5610 "length", methodType(int.class)); 5611 System.out.println((String) cat.invokeExact("x", "y")); // xy 5612 MethodHandle f0 = filterReturnValue(cat, length); 5613 System.out.println((int) f0.invokeExact("x", "y")); // 2 5614 * } 5615 * <p>Here is pseudocode for the resulting adapter. In the code, 5616 * {@code T}/{@code t} represent the result type and value of the 5617 * {@code target}; {@code V}, the result type of the {@code filter}; and 5618 * {@code A}/{@code a}, the types and values of the parameters and arguments 5619 * of the {@code target} as well as the resulting adapter. 5620 * {@snippet lang="java" : 5621 * T target(A...); 5622 * V filter(T); 5623 * V adapter(A... a) { 5624 * T t = target(a...); 5625 * return filter(t); 5626 * } 5627 * // and if the target has a void return: 5628 * void target2(A...); 5629 * V filter2(); 5630 * V adapter2(A... a) { 5631 * target2(a...); 5632 * return filter2(); 5633 * } 5634 * // and if the filter has a void return: 5635 * T target3(A...); 5636 * void filter3(V); 5637 * void adapter3(A... a) { 5638 * T t = target3(a...); 5639 * filter3(t); 5640 * } 5641 * } 5642 * <p> 5643 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5644 * variable-arity method handle}, even if the original target method handle was. 5645 * @param target the method handle to invoke before filtering the return value 5646 * @param filter method handle to call on the return value 5647 * @return method handle which incorporates the specified return value filtering logic 5648 * @throws NullPointerException if either argument is null 5649 * @throws IllegalArgumentException if the argument list of {@code filter} 5650 * does not match the return type of target as described above 5651 */ 5652 public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 5653 MethodType targetType = target.type(); 5654 MethodType filterType = filter.type(); 5655 filterReturnValueChecks(targetType, filterType); 5656 BoundMethodHandle result = target.rebind(); 5657 BasicType rtype = BasicType.basicType(filterType.returnType()); 5658 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 5659 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5660 result = result.copyWithExtendL(newType, lform, filter); 5661 return result; 5662 } 5663 5664 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 5665 Class<?> rtype = targetType.returnType(); 5666 int filterValues = filterType.parameterCount(); 5667 if (filterValues == 0 5668 ? (rtype != void.class) 5669 : (rtype != filterType.parameterType(0) || filterValues != 1)) 5670 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 5671 } 5672 5673 /** 5674 * Filter the return value of a target method handle with a filter function. The filter function is 5675 * applied to the return value of the original handle; if the filter specifies more than one parameters, 5676 * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works 5677 * as follows: 5678 * {@snippet lang="java" : 5679 * T target(A...) 5680 * V filter(B... , T) 5681 * V adapter(A... a, B... b) { 5682 * T t = target(a...); 5683 * return filter(b..., t); 5684 * } 5685 * } 5686 * <p> 5687 * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}. 5688 * 5689 * @param target the target method handle 5690 * @param filter the filter method handle 5691 * @return the adapter method handle 5692 */ 5693 /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) { 5694 MethodType targetType = target.type(); 5695 MethodType filterType = filter.type(); 5696 BoundMethodHandle result = target.rebind(); 5697 LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType()); 5698 MethodType newType = targetType.changeReturnType(filterType.returnType()); 5699 if (filterType.parameterCount() > 1) { 5700 for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) { 5701 newType = newType.appendParameterTypes(filterType.parameterType(i)); 5702 } 5703 } 5704 result = result.copyWithExtendL(newType, lform, filter); 5705 return result; 5706 } 5707 5708 /** 5709 * Adapts a target method handle by pre-processing 5710 * some of its arguments, and then calling the target with 5711 * the result of the pre-processing, inserted into the original 5712 * sequence of arguments. 5713 * <p> 5714 * The pre-processing is performed by {@code combiner}, a second method handle. 5715 * Of the arguments passed to the adapter, the first {@code N} arguments 5716 * are copied to the combiner, which is then called. 5717 * (Here, {@code N} is defined as the parameter count of the combiner.) 5718 * After this, control passes to the target, with any result 5719 * from the combiner inserted before the original {@code N} incoming 5720 * arguments. 5721 * <p> 5722 * If the combiner returns a value, the first parameter type of the target 5723 * must be identical with the return type of the combiner, and the next 5724 * {@code N} parameter types of the target must exactly match the parameters 5725 * of the combiner. 5726 * <p> 5727 * If the combiner has a void return, no result will be inserted, 5728 * and the first {@code N} parameter types of the target 5729 * must exactly match the parameters of the combiner. 5730 * <p> 5731 * The resulting adapter is the same type as the target, except that the 5732 * first parameter type is dropped, 5733 * if it corresponds to the result of the combiner. 5734 * <p> 5735 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 5736 * that either the combiner or the target does not wish to receive. 5737 * If some of the incoming arguments are destined only for the combiner, 5738 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 5739 * arguments will not need to be live on the stack on entry to the 5740 * target.) 5741 * <p><b>Example:</b> 5742 * {@snippet lang="java" : 5743 import static java.lang.invoke.MethodHandles.*; 5744 import static java.lang.invoke.MethodType.*; 5745 ... 5746 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5747 "println", methodType(void.class, String.class)) 5748 .bindTo(System.out); 5749 MethodHandle cat = lookup().findVirtual(String.class, 5750 "concat", methodType(String.class, String.class)); 5751 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5752 MethodHandle catTrace = foldArguments(cat, trace); 5753 // also prints "boo": 5754 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5755 * } 5756 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5757 * represents the result type of the {@code target} and resulting adapter. 5758 * {@code V}/{@code v} represent the type and value of the parameter and argument 5759 * of {@code target} that precedes the folding position; {@code V} also is 5760 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5761 * types and values of the {@code N} parameters and arguments at the folding 5762 * position. {@code B}/{@code b} represent the types and values of the 5763 * {@code target} parameters and arguments that follow the folded parameters 5764 * and arguments. 5765 * {@snippet lang="java" : 5766 * // there are N arguments in A... 5767 * T target(V, A[N]..., B...); 5768 * V combiner(A...); 5769 * T adapter(A... a, B... b) { 5770 * V v = combiner(a...); 5771 * return target(v, a..., b...); 5772 * } 5773 * // and if the combiner has a void return: 5774 * T target2(A[N]..., B...); 5775 * void combiner2(A...); 5776 * T adapter2(A... a, B... b) { 5777 * combiner2(a...); 5778 * return target2(a..., b...); 5779 * } 5780 * } 5781 * <p> 5782 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5783 * variable-arity method handle}, even if the original target method handle was. 5784 * @param target the method handle to invoke after arguments are combined 5785 * @param combiner method handle to call initially on the incoming arguments 5786 * @return method handle which incorporates the specified argument folding logic 5787 * @throws NullPointerException if either argument is null 5788 * @throws IllegalArgumentException if {@code combiner}'s return type 5789 * is non-void and not the same as the first argument type of 5790 * the target, or if the initial {@code N} argument types 5791 * of the target 5792 * (skipping one matching the {@code combiner}'s return type) 5793 * are not identical with the argument types of {@code combiner} 5794 */ 5795 public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 5796 return foldArguments(target, 0, combiner); 5797 } 5798 5799 /** 5800 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 5801 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 5802 * before the folded arguments. 5803 * <p> 5804 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 5805 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 5806 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 5807 * 0. 5808 * 5809 * @apiNote Example: 5810 * {@snippet lang="java" : 5811 import static java.lang.invoke.MethodHandles.*; 5812 import static java.lang.invoke.MethodType.*; 5813 ... 5814 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 5815 "println", methodType(void.class, String.class)) 5816 .bindTo(System.out); 5817 MethodHandle cat = lookup().findVirtual(String.class, 5818 "concat", methodType(String.class, String.class)); 5819 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 5820 MethodHandle catTrace = foldArguments(cat, 1, trace); 5821 // also prints "jum": 5822 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 5823 * } 5824 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 5825 * represents the result type of the {@code target} and resulting adapter. 5826 * {@code V}/{@code v} represent the type and value of the parameter and argument 5827 * of {@code target} that precedes the folding position; {@code V} also is 5828 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 5829 * types and values of the {@code N} parameters and arguments at the folding 5830 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 5831 * and values of the {@code target} parameters and arguments that precede and 5832 * follow the folded parameters and arguments starting at {@code pos}, 5833 * respectively. 5834 * {@snippet lang="java" : 5835 * // there are N arguments in A... 5836 * T target(Z..., V, A[N]..., B...); 5837 * V combiner(A...); 5838 * T adapter(Z... z, A... a, B... b) { 5839 * V v = combiner(a...); 5840 * return target(z..., v, a..., b...); 5841 * } 5842 * // and if the combiner has a void return: 5843 * T target2(Z..., A[N]..., B...); 5844 * void combiner2(A...); 5845 * T adapter2(Z... z, A... a, B... b) { 5846 * combiner2(a...); 5847 * return target2(z..., a..., b...); 5848 * } 5849 * } 5850 * <p> 5851 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 5852 * variable-arity method handle}, even if the original target method handle was. 5853 * 5854 * @param target the method handle to invoke after arguments are combined 5855 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 5856 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5857 * @param combiner method handle to call initially on the incoming arguments 5858 * @return method handle which incorporates the specified argument folding logic 5859 * @throws NullPointerException if either argument is null 5860 * @throws IllegalArgumentException if either of the following two conditions holds: 5861 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5862 * {@code pos} of the target signature; 5863 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 5864 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 5865 * 5866 * @see #foldArguments(MethodHandle, MethodHandle) 5867 * @since 9 5868 */ 5869 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 5870 MethodType targetType = target.type(); 5871 MethodType combinerType = combiner.type(); 5872 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 5873 BoundMethodHandle result = target.rebind(); 5874 boolean dropResult = rtype == void.class; 5875 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 5876 MethodType newType = targetType; 5877 if (!dropResult) { 5878 newType = newType.dropParameterTypes(pos, pos + 1); 5879 } 5880 result = result.copyWithExtendL(newType, lform, combiner); 5881 return result; 5882 } 5883 5884 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 5885 int foldArgs = combinerType.parameterCount(); 5886 Class<?> rtype = combinerType.returnType(); 5887 int foldVals = rtype == void.class ? 0 : 1; 5888 int afterInsertPos = foldPos + foldVals; 5889 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 5890 if (ok) { 5891 for (int i = 0; i < foldArgs; i++) { 5892 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 5893 ok = false; 5894 break; 5895 } 5896 } 5897 } 5898 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 5899 ok = false; 5900 if (!ok) 5901 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5902 return rtype; 5903 } 5904 5905 /** 5906 * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result 5907 * of the pre-processing replacing the argument at the given position. 5908 * 5909 * @param target the method handle to invoke after arguments are combined 5910 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5911 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5912 * @param combiner method handle to call initially on the incoming arguments 5913 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5914 * @return method handle which incorporates the specified argument folding logic 5915 * @throws NullPointerException if either argument is null 5916 * @throws IllegalArgumentException if either of the following two conditions holds: 5917 * (1) {@code combiner}'s return type is not the same as the argument type at position 5918 * {@code pos} of the target signature; 5919 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are 5920 * not identical with the argument types of {@code combiner}. 5921 */ 5922 /*non-public*/ 5923 static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5924 return argumentsWithCombiner(true, target, position, combiner, argPositions); 5925 } 5926 5927 /** 5928 * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of 5929 * the pre-processing inserted into the original sequence of arguments at the given position. 5930 * 5931 * @param target the method handle to invoke after arguments are combined 5932 * @param position the position at which to start folding and at which to insert the folding result; if this is {@code 5933 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 5934 * @param combiner method handle to call initially on the incoming arguments 5935 * @param argPositions indexes of the target to pick arguments sent to the combiner from 5936 * @return method handle which incorporates the specified argument folding logic 5937 * @throws NullPointerException if either argument is null 5938 * @throws IllegalArgumentException if either of the following two conditions holds: 5939 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 5940 * {@code pos} of the target signature; 5941 * (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature 5942 * (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical 5943 * with the argument types of {@code combiner}. 5944 */ 5945 /*non-public*/ 5946 static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5947 return argumentsWithCombiner(false, target, position, combiner, argPositions); 5948 } 5949 5950 private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) { 5951 MethodType targetType = target.type(); 5952 MethodType combinerType = combiner.type(); 5953 Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions); 5954 BoundMethodHandle result = target.rebind(); 5955 5956 MethodType newType = targetType; 5957 LambdaForm lform; 5958 if (filter) { 5959 lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions); 5960 } else { 5961 boolean dropResult = rtype == void.class; 5962 lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions); 5963 if (!dropResult) { 5964 newType = newType.dropParameterTypes(position, position + 1); 5965 } 5966 } 5967 result = result.copyWithExtendL(newType, lform, combiner); 5968 return result; 5969 } 5970 5971 private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) { 5972 int combinerArgs = combinerType.parameterCount(); 5973 if (argPos.length != combinerArgs) { 5974 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 5975 } 5976 Class<?> rtype = combinerType.returnType(); 5977 5978 for (int i = 0; i < combinerArgs; i++) { 5979 int arg = argPos[i]; 5980 if (arg < 0 || arg > targetType.parameterCount()) { 5981 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 5982 } 5983 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 5984 throw newIllegalArgumentException("target argument type at position " + arg 5985 + " must match combiner argument type at index " + i + ": " + targetType 5986 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 5987 } 5988 } 5989 if (filter && combinerType.returnType() != targetType.parameterType(position)) { 5990 throw misMatchedTypes("target and combiner types", targetType, combinerType); 5991 } 5992 return rtype; 5993 } 5994 5995 /** 5996 * Makes a method handle which adapts a target method handle, 5997 * by guarding it with a test, a boolean-valued method handle. 5998 * If the guard fails, a fallback handle is called instead. 5999 * All three method handles must have the same corresponding 6000 * argument and return types, except that the return type 6001 * of the test must be boolean, and the test is allowed 6002 * to have fewer arguments than the other two method handles. 6003 * <p> 6004 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6005 * represents the uniform result type of the three involved handles; 6006 * {@code A}/{@code a}, the types and values of the {@code target} 6007 * parameters and arguments that are consumed by the {@code test}; and 6008 * {@code B}/{@code b}, those types and values of the {@code target} 6009 * parameters and arguments that are not consumed by the {@code test}. 6010 * {@snippet lang="java" : 6011 * boolean test(A...); 6012 * T target(A...,B...); 6013 * T fallback(A...,B...); 6014 * T adapter(A... a,B... b) { 6015 * if (test(a...)) 6016 * return target(a..., b...); 6017 * else 6018 * return fallback(a..., b...); 6019 * } 6020 * } 6021 * Note that the test arguments ({@code a...} in the pseudocode) cannot 6022 * be modified by execution of the test, and so are passed unchanged 6023 * from the caller to the target or fallback as appropriate. 6024 * @param test method handle used for test, must return boolean 6025 * @param target method handle to call if test passes 6026 * @param fallback method handle to call if test fails 6027 * @return method handle which incorporates the specified if/then/else logic 6028 * @throws NullPointerException if any argument is null 6029 * @throws IllegalArgumentException if {@code test} does not return boolean, 6030 * or if all three method types do not match (with the return 6031 * type of {@code test} changed to match that of the target). 6032 */ 6033 public static MethodHandle guardWithTest(MethodHandle test, 6034 MethodHandle target, 6035 MethodHandle fallback) { 6036 MethodType gtype = test.type(); 6037 MethodType ttype = target.type(); 6038 MethodType ftype = fallback.type(); 6039 if (!ttype.equals(ftype)) 6040 throw misMatchedTypes("target and fallback types", ttype, ftype); 6041 if (gtype.returnType() != boolean.class) 6042 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 6043 6044 test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true); 6045 if (test == null) { 6046 throw misMatchedTypes("target and test types", ttype, gtype); 6047 } 6048 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 6049 } 6050 6051 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 6052 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 6053 } 6054 6055 /** 6056 * Makes a method handle which adapts a target method handle, 6057 * by running it inside an exception handler. 6058 * If the target returns normally, the adapter returns that value. 6059 * If an exception matching the specified type is thrown, the fallback 6060 * handle is called instead on the exception, plus the original arguments. 6061 * <p> 6062 * The target and handler must have the same corresponding 6063 * argument and return types, except that handler may omit trailing arguments 6064 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 6065 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 6066 * <p> 6067 * Here is pseudocode for the resulting adapter. In the code, {@code T} 6068 * represents the return type of the {@code target} and {@code handler}, 6069 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 6070 * the types and values of arguments to the resulting handle consumed by 6071 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 6072 * resulting handle discarded by {@code handler}. 6073 * {@snippet lang="java" : 6074 * T target(A..., B...); 6075 * T handler(ExType, A...); 6076 * T adapter(A... a, B... b) { 6077 * try { 6078 * return target(a..., b...); 6079 * } catch (ExType ex) { 6080 * return handler(ex, a...); 6081 * } 6082 * } 6083 * } 6084 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 6085 * be modified by execution of the target, and so are passed unchanged 6086 * from the caller to the handler, if the handler is invoked. 6087 * <p> 6088 * The target and handler must return the same type, even if the handler 6089 * always throws. (This might happen, for instance, because the handler 6090 * is simulating a {@code finally} clause). 6091 * To create such a throwing handler, compose the handler creation logic 6092 * with {@link #throwException throwException}, 6093 * in order to create a method handle of the correct return type. 6094 * @param target method handle to call 6095 * @param exType the type of exception which the handler will catch 6096 * @param handler method handle to call if a matching exception is thrown 6097 * @return method handle which incorporates the specified try/catch logic 6098 * @throws NullPointerException if any argument is null 6099 * @throws IllegalArgumentException if {@code handler} does not accept 6100 * the given exception type, or if the method handle types do 6101 * not match in their return types and their 6102 * corresponding parameters 6103 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 6104 */ 6105 public static MethodHandle catchException(MethodHandle target, 6106 Class<? extends Throwable> exType, 6107 MethodHandle handler) { 6108 MethodType ttype = target.type(); 6109 MethodType htype = handler.type(); 6110 if (!Throwable.class.isAssignableFrom(exType)) 6111 throw new ClassCastException(exType.getName()); 6112 if (htype.parameterCount() < 1 || 6113 !htype.parameterType(0).isAssignableFrom(exType)) 6114 throw newIllegalArgumentException("handler does not accept exception type "+exType); 6115 if (htype.returnType() != ttype.returnType()) 6116 throw misMatchedTypes("target and handler return types", ttype, htype); 6117 handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true); 6118 if (handler == null) { 6119 throw misMatchedTypes("target and handler types", ttype, htype); 6120 } 6121 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 6122 } 6123 6124 /** 6125 * Produces a method handle which will throw exceptions of the given {@code exType}. 6126 * The method handle will accept a single argument of {@code exType}, 6127 * and immediately throw it as an exception. 6128 * The method type will nominally specify a return of {@code returnType}. 6129 * The return type may be anything convenient: It doesn't matter to the 6130 * method handle's behavior, since it will never return normally. 6131 * @param returnType the return type of the desired method handle 6132 * @param exType the parameter type of the desired method handle 6133 * @return method handle which can throw the given exceptions 6134 * @throws NullPointerException if either argument is null 6135 */ 6136 public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 6137 if (!Throwable.class.isAssignableFrom(exType)) 6138 throw new ClassCastException(exType.getName()); 6139 return MethodHandleImpl.throwException(methodType(returnType, exType)); 6140 } 6141 6142 /** 6143 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 6144 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 6145 * delivers the loop's result, which is the return value of the resulting handle. 6146 * <p> 6147 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 6148 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 6149 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 6150 * terms of method handles, each clause will specify up to four independent actions:<ul> 6151 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 6152 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 6153 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 6154 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 6155 * </ul> 6156 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 6157 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 6158 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 6159 * <p> 6160 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 6161 * this case. See below for a detailed description. 6162 * <p> 6163 * <em>Parameters optional everywhere:</em> 6164 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 6165 * As an exception, the init functions cannot take any {@code v} parameters, 6166 * because those values are not yet computed when the init functions are executed. 6167 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 6168 * In fact, any clause function may take no arguments at all. 6169 * <p> 6170 * <em>Loop parameters:</em> 6171 * A clause function may take all the iteration variable values it is entitled to, in which case 6172 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 6173 * with their types and values notated as {@code (A...)} and {@code (a...)}. 6174 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 6175 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 6176 * init function is automatically a loop parameter {@code a}.) 6177 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 6178 * These loop parameters act as loop-invariant values visible across the whole loop. 6179 * <p> 6180 * <em>Parameters visible everywhere:</em> 6181 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 6182 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 6183 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 6184 * Most clause functions will not need all of this information, but they will be formally connected to it 6185 * as if by {@link #dropArguments}. 6186 * <a id="astar"></a> 6187 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 6188 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 6189 * In that notation, the general form of an init function parameter list 6190 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 6191 * <p> 6192 * <em>Checking clause structure:</em> 6193 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 6194 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 6195 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 6196 * met by the inputs to the loop combinator. 6197 * <p> 6198 * <em>Effectively identical sequences:</em> 6199 * <a id="effid"></a> 6200 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 6201 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 6202 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 6203 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 6204 * that longest list. 6205 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 6206 * and the same is true if more sequences of the form {@code (V... A*)} are added. 6207 * <p> 6208 * <em>Step 0: Determine clause structure.</em><ol type="a"> 6209 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 6210 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 6211 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 6212 * four. Padding takes place by appending elements to the array. 6213 * <li>Clauses with all {@code null}s are disregarded. 6214 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 6215 * </ol> 6216 * <p> 6217 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 6218 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 6219 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 6220 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 6221 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 6222 * iteration variable type. 6223 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 6224 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 6225 * </ol> 6226 * <p> 6227 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 6228 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 6229 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 6230 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 6231 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 6232 * (These types will be checked in step 2, along with all the clause function types.) 6233 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 6234 * <li>All of the collected parameter lists must be effectively identical. 6235 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 6236 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 6237 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 6238 * the "internal parameter list". 6239 * </ul> 6240 * <p> 6241 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 6242 * <li>Examine fini function return types, disregarding omitted fini functions. 6243 * <li>If there are no fini functions, the loop return type is {@code void}. 6244 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 6245 * type. 6246 * </ol> 6247 * <p> 6248 * <em>Step 1D: Check other types.</em><ol type="a"> 6249 * <li>There must be at least one non-omitted pred function. 6250 * <li>Every non-omitted pred function must have a {@code boolean} return type. 6251 * </ol> 6252 * <p> 6253 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 6254 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 6255 * <li>The parameter list for init functions will be adjusted to the external parameter list. 6256 * (Note that their parameter lists are already effectively identical to this list.) 6257 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 6258 * effectively identical to the internal parameter list {@code (V... A...)}. 6259 * </ol> 6260 * <p> 6261 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 6262 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 6263 * type. 6264 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 6265 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 6266 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 6267 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 6268 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 6269 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 6270 * loop return type. 6271 * </ol> 6272 * <p> 6273 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 6274 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 6275 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 6276 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 6277 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 6278 * pad out the end of the list. 6279 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 6280 * </ol> 6281 * <p> 6282 * <em>Final observations.</em><ol type="a"> 6283 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 6284 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 6285 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 6286 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 6287 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 6288 * <li>Each pair of init and step functions agrees in their return type {@code V}. 6289 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 6290 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 6291 * </ol> 6292 * <p> 6293 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 6294 * <ul> 6295 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 6296 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 6297 * (Only one {@code Pn} has to be non-{@code null}.) 6298 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 6299 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 6300 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 6301 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 6302 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 6303 * the resulting loop handle's parameter types {@code (A...)}. 6304 * </ul> 6305 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 6306 * which is natural if most of the loop computation happens in the steps. For some loops, 6307 * the burden of computation might be heaviest in the pred functions, and so the pred functions 6308 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 6309 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 6310 * where the init functions will need the extra parameters. For such reasons, the rules for 6311 * determining these parameters are as symmetric as possible, across all clause parts. 6312 * In general, the loop parameters function as common invariant values across the whole 6313 * loop, while the iteration variables function as common variant values, or (if there is 6314 * no step function) as internal loop invariant temporaries. 6315 * <p> 6316 * <em>Loop execution.</em><ol type="a"> 6317 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 6318 * every clause function. These locals are loop invariant. 6319 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 6320 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 6321 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 6322 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 6323 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 6324 * (in argument order). 6325 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 6326 * returns {@code false}. 6327 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 6328 * sequence {@code (v...)} of loop variables. 6329 * The updated value is immediately visible to all subsequent function calls. 6330 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 6331 * (of type {@code R}) is returned from the loop as a whole. 6332 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 6333 * except by throwing an exception. 6334 * </ol> 6335 * <p> 6336 * <em>Usage tips.</em> 6337 * <ul> 6338 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 6339 * sometimes a step function only needs to observe the current value of its own variable. 6340 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 6341 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 6342 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 6343 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 6344 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 6345 * <li>If some of the clause functions are virtual methods on an instance, the instance 6346 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 6347 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 6348 * will be the first iteration variable value, and it will be easy to use virtual 6349 * methods as clause parts, since all of them will take a leading instance reference matching that value. 6350 * </ul> 6351 * <p> 6352 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 6353 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 6354 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 6355 * {@snippet lang="java" : 6356 * V... init...(A...); 6357 * boolean pred...(V..., A...); 6358 * V... step...(V..., A...); 6359 * R fini...(V..., A...); 6360 * R loop(A... a) { 6361 * V... v... = init...(a...); 6362 * for (;;) { 6363 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 6364 * v = s(v..., a...); 6365 * if (!p(v..., a...)) { 6366 * return f(v..., a...); 6367 * } 6368 * } 6369 * } 6370 * } 6371 * } 6372 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 6373 * to their full length, even though individual clause functions may neglect to take them all. 6374 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 6375 * 6376 * @apiNote Example: 6377 * {@snippet lang="java" : 6378 * // iterative implementation of the factorial function as a loop handle 6379 * static int one(int k) { return 1; } 6380 * static int inc(int i, int acc, int k) { return i + 1; } 6381 * static int mult(int i, int acc, int k) { return i * acc; } 6382 * static boolean pred(int i, int acc, int k) { return i < k; } 6383 * static int fin(int i, int acc, int k) { return acc; } 6384 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6385 * // null initializer for counter, should initialize to 0 6386 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6387 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6388 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6389 * assertEquals(120, loop.invoke(5)); 6390 * } 6391 * The same example, dropping arguments and using combinators: 6392 * {@snippet lang="java" : 6393 * // simplified implementation of the factorial function as a loop handle 6394 * static int inc(int i) { return i + 1; } // drop acc, k 6395 * static int mult(int i, int acc) { return i * acc; } //drop k 6396 * static boolean cmp(int i, int k) { return i < k; } 6397 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 6398 * // null initializer for counter, should initialize to 0 6399 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6400 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 6401 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 6402 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6403 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6404 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 6405 * assertEquals(720, loop.invoke(6)); 6406 * } 6407 * A similar example, using a helper object to hold a loop parameter: 6408 * {@snippet lang="java" : 6409 * // instance-based implementation of the factorial function as a loop handle 6410 * static class FacLoop { 6411 * final int k; 6412 * FacLoop(int k) { this.k = k; } 6413 * int inc(int i) { return i + 1; } 6414 * int mult(int i, int acc) { return i * acc; } 6415 * boolean pred(int i) { return i < k; } 6416 * int fin(int i, int acc) { return acc; } 6417 * } 6418 * // assume MH_FacLoop is a handle to the constructor 6419 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 6420 * // null initializer for counter, should initialize to 0 6421 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 6422 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 6423 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 6424 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 6425 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 6426 * assertEquals(5040, loop.invoke(7)); 6427 * } 6428 * 6429 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 6430 * 6431 * @return a method handle embodying the looping behavior as defined by the arguments. 6432 * 6433 * @throws IllegalArgumentException in case any of the constraints described above is violated. 6434 * 6435 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 6436 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6437 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 6438 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 6439 * @since 9 6440 */ 6441 public static MethodHandle loop(MethodHandle[]... clauses) { 6442 // Step 0: determine clause structure. 6443 loopChecks0(clauses); 6444 6445 List<MethodHandle> init = new ArrayList<>(); 6446 List<MethodHandle> step = new ArrayList<>(); 6447 List<MethodHandle> pred = new ArrayList<>(); 6448 List<MethodHandle> fini = new ArrayList<>(); 6449 6450 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 6451 init.add(clause[0]); // all clauses have at least length 1 6452 step.add(clause.length <= 1 ? null : clause[1]); 6453 pred.add(clause.length <= 2 ? null : clause[2]); 6454 fini.add(clause.length <= 3 ? null : clause[3]); 6455 }); 6456 6457 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 6458 final int nclauses = init.size(); 6459 6460 // Step 1A: determine iteration variables (V...). 6461 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 6462 for (int i = 0; i < nclauses; ++i) { 6463 MethodHandle in = init.get(i); 6464 MethodHandle st = step.get(i); 6465 if (in == null && st == null) { 6466 iterationVariableTypes.add(void.class); 6467 } else if (in != null && st != null) { 6468 loopChecks1a(i, in, st); 6469 iterationVariableTypes.add(in.type().returnType()); 6470 } else { 6471 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 6472 } 6473 } 6474 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList(); 6475 6476 // Step 1B: determine loop parameters (A...). 6477 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 6478 loopChecks1b(init, commonSuffix); 6479 6480 // Step 1C: determine loop return type. 6481 // Step 1D: check other types. 6482 // local variable required here; see JDK-8223553 6483 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 6484 .map(MethodType::returnType); 6485 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 6486 loopChecks1cd(pred, fini, loopReturnType); 6487 6488 // Step 2: determine parameter lists. 6489 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 6490 commonParameterSequence.addAll(commonSuffix); 6491 loopChecks2(step, pred, fini, commonParameterSequence); 6492 // Step 3: fill in omitted functions. 6493 for (int i = 0; i < nclauses; ++i) { 6494 Class<?> t = iterationVariableTypes.get(i); 6495 if (init.get(i) == null) { 6496 init.set(i, empty(methodType(t, commonSuffix))); 6497 } 6498 if (step.get(i) == null) { 6499 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 6500 } 6501 if (pred.get(i) == null) { 6502 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); 6503 } 6504 if (fini.get(i) == null) { 6505 fini.set(i, empty(methodType(t, commonParameterSequence))); 6506 } 6507 } 6508 6509 // Step 4: fill in missing parameter types. 6510 // Also convert all handles to fixed-arity handles. 6511 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 6512 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 6513 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 6514 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 6515 6516 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 6517 allMatch(pl -> pl.equals(commonSuffix)); 6518 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 6519 allMatch(pl -> pl.equals(commonParameterSequence)); 6520 6521 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 6522 } 6523 6524 private static void loopChecks0(MethodHandle[][] clauses) { 6525 if (clauses == null || clauses.length == 0) { 6526 throw newIllegalArgumentException("null or no clauses passed"); 6527 } 6528 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 6529 throw newIllegalArgumentException("null clauses are not allowed"); 6530 } 6531 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 6532 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 6533 } 6534 } 6535 6536 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 6537 if (in.type().returnType() != st.type().returnType()) { 6538 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 6539 st.type().returnType()); 6540 } 6541 } 6542 6543 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 6544 return mhs.filter(Objects::nonNull) 6545 // take only those that can contribute to a common suffix because they are longer than the prefix 6546 .map(MethodHandle::type) 6547 .filter(t -> t.parameterCount() > skipSize) 6548 .max(Comparator.comparingInt(MethodType::parameterCount)) 6549 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount()))) 6550 .orElse(List.of()); 6551 } 6552 6553 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 6554 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 6555 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 6556 return longest1.size() >= longest2.size() ? longest1 : longest2; 6557 } 6558 6559 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 6560 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 6561 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 6562 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 6563 " (common suffix: " + commonSuffix + ")"); 6564 } 6565 } 6566 6567 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 6568 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6569 anyMatch(t -> t != loopReturnType)) { 6570 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 6571 loopReturnType + ")"); 6572 } 6573 6574 if (pred.stream().noneMatch(Objects::nonNull)) { 6575 throw newIllegalArgumentException("no predicate found", pred); 6576 } 6577 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 6578 anyMatch(t -> t != boolean.class)) { 6579 throw newIllegalArgumentException("predicates must have boolean return type", pred); 6580 } 6581 } 6582 6583 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 6584 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 6585 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 6586 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 6587 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 6588 } 6589 } 6590 6591 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 6592 return hs.stream().map(h -> { 6593 int pc = h.type().parameterCount(); 6594 int tpsize = targetParams.size(); 6595 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; 6596 }).toList(); 6597 } 6598 6599 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 6600 return hs.stream().map(MethodHandle::asFixedArity).toList(); 6601 } 6602 6603 /** 6604 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 6605 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6606 * <p> 6607 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6608 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 6609 * evaluates to {@code true}). 6610 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 6611 * <p> 6612 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6613 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6614 * and updated with the value returned from its invocation. The result of loop execution will be 6615 * the final value of the additional loop-local variable (if present). 6616 * <p> 6617 * The following rules hold for these argument handles:<ul> 6618 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6619 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6620 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6621 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6622 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6623 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6624 * It will constrain the parameter lists of the other loop parts. 6625 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6626 * list {@code (A...)} is called the <em>external parameter list</em>. 6627 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6628 * additional state variable of the loop. 6629 * The body must both accept and return a value of this type {@code V}. 6630 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6631 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6632 * <a href="MethodHandles.html#effid">effectively identical</a> 6633 * to the external parameter list {@code (A...)}. 6634 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6635 * {@linkplain #empty default value}. 6636 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6637 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6638 * effectively identical to the internal parameter list. 6639 * </ul> 6640 * <p> 6641 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6642 * <li>The loop handle's result type is the result type {@code V} of the body. 6643 * <li>The loop handle's parameter types are the types {@code (A...)}, 6644 * from the external parameter list. 6645 * </ul> 6646 * <p> 6647 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6648 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6649 * passed to the loop. 6650 * {@snippet lang="java" : 6651 * V init(A...); 6652 * boolean pred(V, A...); 6653 * V body(V, A...); 6654 * V whileLoop(A... a...) { 6655 * V v = init(a...); 6656 * while (pred(v, a...)) { 6657 * v = body(v, a...); 6658 * } 6659 * return v; 6660 * } 6661 * } 6662 * 6663 * @apiNote Example: 6664 * {@snippet lang="java" : 6665 * // implement the zip function for lists as a loop handle 6666 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 6667 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 6668 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 6669 * zip.add(a.next()); 6670 * zip.add(b.next()); 6671 * return zip; 6672 * } 6673 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 6674 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 6675 * List<String> a = Arrays.asList("a", "b", "c", "d"); 6676 * List<String> b = Arrays.asList("e", "f", "g", "h"); 6677 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 6678 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 6679 * } 6680 * 6681 * 6682 * @apiNote The implementation of this method can be expressed as follows: 6683 * {@snippet lang="java" : 6684 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6685 * MethodHandle fini = (body.type().returnType() == void.class 6686 * ? null : identity(body.type().returnType())); 6687 * MethodHandle[] 6688 * checkExit = { null, null, pred, fini }, 6689 * varBody = { init, body }; 6690 * return loop(checkExit, varBody); 6691 * } 6692 * } 6693 * 6694 * @param init optional initializer, providing the initial value of the loop variable. 6695 * May be {@code null}, implying a default initial value. See above for other constraints. 6696 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6697 * above for other constraints. 6698 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6699 * See above for other constraints. 6700 * 6701 * @return a method handle implementing the {@code while} loop as described by the arguments. 6702 * @throws IllegalArgumentException if the rules for the arguments are violated. 6703 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6704 * 6705 * @see #loop(MethodHandle[][]) 6706 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 6707 * @since 9 6708 */ 6709 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 6710 whileLoopChecks(init, pred, body); 6711 MethodHandle fini = identityOrVoid(body.type().returnType()); 6712 MethodHandle[] checkExit = { null, null, pred, fini }; 6713 MethodHandle[] varBody = { init, body }; 6714 return loop(checkExit, varBody); 6715 } 6716 6717 /** 6718 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 6719 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6720 * <p> 6721 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 6722 * method will, in each iteration, first execute its body and then evaluate the predicate. 6723 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 6724 * <p> 6725 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 6726 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 6727 * and updated with the value returned from its invocation. The result of loop execution will be 6728 * the final value of the additional loop-local variable (if present). 6729 * <p> 6730 * The following rules hold for these argument handles:<ul> 6731 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6732 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 6733 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6734 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 6735 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 6736 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 6737 * It will constrain the parameter lists of the other loop parts. 6738 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 6739 * list {@code (A...)} is called the <em>external parameter list</em>. 6740 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6741 * additional state variable of the loop. 6742 * The body must both accept and return a value of this type {@code V}. 6743 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6744 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6745 * <a href="MethodHandles.html#effid">effectively identical</a> 6746 * to the external parameter list {@code (A...)}. 6747 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6748 * {@linkplain #empty default value}. 6749 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 6750 * Its parameter list (either empty or of the form {@code (V A*)}) must be 6751 * effectively identical to the internal parameter list. 6752 * </ul> 6753 * <p> 6754 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6755 * <li>The loop handle's result type is the result type {@code V} of the body. 6756 * <li>The loop handle's parameter types are the types {@code (A...)}, 6757 * from the external parameter list. 6758 * </ul> 6759 * <p> 6760 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6761 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 6762 * passed to the loop. 6763 * {@snippet lang="java" : 6764 * V init(A...); 6765 * boolean pred(V, A...); 6766 * V body(V, A...); 6767 * V doWhileLoop(A... a...) { 6768 * V v = init(a...); 6769 * do { 6770 * v = body(v, a...); 6771 * } while (pred(v, a...)); 6772 * return v; 6773 * } 6774 * } 6775 * 6776 * @apiNote Example: 6777 * {@snippet lang="java" : 6778 * // int i = 0; while (i < limit) { ++i; } return i; => limit 6779 * static int zero(int limit) { return 0; } 6780 * static int step(int i, int limit) { return i + 1; } 6781 * static boolean pred(int i, int limit) { return i < limit; } 6782 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 6783 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 6784 * assertEquals(23, loop.invoke(23)); 6785 * } 6786 * 6787 * 6788 * @apiNote The implementation of this method can be expressed as follows: 6789 * {@snippet lang="java" : 6790 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6791 * MethodHandle fini = (body.type().returnType() == void.class 6792 * ? null : identity(body.type().returnType())); 6793 * MethodHandle[] clause = { init, body, pred, fini }; 6794 * return loop(clause); 6795 * } 6796 * } 6797 * 6798 * @param init optional initializer, providing the initial value of the loop variable. 6799 * May be {@code null}, implying a default initial value. See above for other constraints. 6800 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 6801 * See above for other constraints. 6802 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 6803 * above for other constraints. 6804 * 6805 * @return a method handle implementing the {@code while} loop as described by the arguments. 6806 * @throws IllegalArgumentException if the rules for the arguments are violated. 6807 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 6808 * 6809 * @see #loop(MethodHandle[][]) 6810 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 6811 * @since 9 6812 */ 6813 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 6814 whileLoopChecks(init, pred, body); 6815 MethodHandle fini = identityOrVoid(body.type().returnType()); 6816 MethodHandle[] clause = {init, body, pred, fini }; 6817 return loop(clause); 6818 } 6819 6820 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 6821 Objects.requireNonNull(pred); 6822 Objects.requireNonNull(body); 6823 MethodType bodyType = body.type(); 6824 Class<?> returnType = bodyType.returnType(); 6825 List<Class<?>> innerList = bodyType.parameterList(); 6826 List<Class<?>> outerList = innerList; 6827 if (returnType == void.class) { 6828 // OK 6829 } else if (innerList.isEmpty() || innerList.get(0) != returnType) { 6830 // leading V argument missing => error 6831 MethodType expected = bodyType.insertParameterTypes(0, returnType); 6832 throw misMatchedTypes("body function", bodyType, expected); 6833 } else { 6834 outerList = innerList.subList(1, innerList.size()); 6835 } 6836 MethodType predType = pred.type(); 6837 if (predType.returnType() != boolean.class || 6838 !predType.effectivelyIdenticalParameters(0, innerList)) { 6839 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 6840 } 6841 if (init != null) { 6842 MethodType initType = init.type(); 6843 if (initType.returnType() != returnType || 6844 !initType.effectivelyIdenticalParameters(0, outerList)) { 6845 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 6846 } 6847 } 6848 } 6849 6850 /** 6851 * Constructs a loop that runs a given number of iterations. 6852 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 6853 * <p> 6854 * The number of iterations is determined by the {@code iterations} handle evaluation result. 6855 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 6856 * It will be initialized to 0 and incremented by 1 in each iteration. 6857 * <p> 6858 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 6859 * of that type is also present. This variable is initialized using the optional {@code init} handle, 6860 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 6861 * <p> 6862 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 6863 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 6864 * iteration variable. 6865 * The result of the loop handle execution will be the final {@code V} value of that variable 6866 * (or {@code void} if there is no {@code V} variable). 6867 * <p> 6868 * The following rules hold for the argument handles:<ul> 6869 * <li>The {@code iterations} handle must not be {@code null}, and must return 6870 * the type {@code int}, referred to here as {@code I} in parameter type lists. 6871 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 6872 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 6873 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 6874 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 6875 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 6876 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 6877 * of types called the <em>internal parameter list</em>. 6878 * It will constrain the parameter lists of the other loop parts. 6879 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 6880 * with no additional {@code A} types, then the internal parameter list is extended by 6881 * the argument types {@code A...} of the {@code iterations} handle. 6882 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 6883 * list {@code (A...)} is called the <em>external parameter list</em>. 6884 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 6885 * additional state variable of the loop. 6886 * The body must both accept a leading parameter and return a value of this type {@code V}. 6887 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 6888 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 6889 * <a href="MethodHandles.html#effid">effectively identical</a> 6890 * to the external parameter list {@code (A...)}. 6891 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 6892 * {@linkplain #empty default value}. 6893 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 6894 * effectively identical to the external parameter list {@code (A...)}. 6895 * </ul> 6896 * <p> 6897 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 6898 * <li>The loop handle's result type is the result type {@code V} of the body. 6899 * <li>The loop handle's parameter types are the types {@code (A...)}, 6900 * from the external parameter list. 6901 * </ul> 6902 * <p> 6903 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 6904 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 6905 * arguments passed to the loop. 6906 * {@snippet lang="java" : 6907 * int iterations(A...); 6908 * V init(A...); 6909 * V body(V, int, A...); 6910 * V countedLoop(A... a...) { 6911 * int end = iterations(a...); 6912 * V v = init(a...); 6913 * for (int i = 0; i < end; ++i) { 6914 * v = body(v, i, a...); 6915 * } 6916 * return v; 6917 * } 6918 * } 6919 * 6920 * @apiNote Example with a fully conformant body method: 6921 * {@snippet lang="java" : 6922 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6923 * // => a variation on a well known theme 6924 * static String step(String v, int counter, String init) { return "na " + v; } 6925 * // assume MH_step is a handle to the method above 6926 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 6927 * MethodHandle start = MethodHandles.identity(String.class); 6928 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 6929 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 6930 * } 6931 * 6932 * @apiNote Example with the simplest possible body method type, 6933 * and passing the number of iterations to the loop invocation: 6934 * {@snippet lang="java" : 6935 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 6936 * // => a variation on a well known theme 6937 * static String step(String v, int counter ) { return "na " + v; } 6938 * // assume MH_step is a handle to the method above 6939 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 6940 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 6941 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 6942 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 6943 * } 6944 * 6945 * @apiNote Example that treats the number of iterations, string to append to, and string to append 6946 * as loop parameters: 6947 * {@snippet lang="java" : 6948 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6949 * // => a variation on a well known theme 6950 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 6951 * // assume MH_step is a handle to the method above 6952 * MethodHandle count = MethodHandles.identity(int.class); 6953 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 6954 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 6955 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 6956 * } 6957 * 6958 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 6959 * to enforce a loop type: 6960 * {@snippet lang="java" : 6961 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 6962 * // => a variation on a well known theme 6963 * static String step(String v, int counter, String pre) { return pre + " " + v; } 6964 * // assume MH_step is a handle to the method above 6965 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 6966 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 6967 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 6968 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 6969 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 6970 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 6971 * } 6972 * 6973 * @apiNote The implementation of this method can be expressed as follows: 6974 * {@snippet lang="java" : 6975 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6976 * return countedLoop(empty(iterations.type()), iterations, init, body); 6977 * } 6978 * } 6979 * 6980 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 6981 * result type must be {@code int}. See above for other constraints. 6982 * @param init optional initializer, providing the initial value of the loop variable. 6983 * May be {@code null}, implying a default initial value. See above for other constraints. 6984 * @param body body of the loop, which may not be {@code null}. 6985 * It controls the loop parameters and result type in the standard case (see above for details). 6986 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 6987 * and may accept any number of additional types. 6988 * See above for other constraints. 6989 * 6990 * @return a method handle representing the loop. 6991 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 6992 * @throws IllegalArgumentException if any argument violates the rules formulated above. 6993 * 6994 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 6995 * @since 9 6996 */ 6997 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 6998 return countedLoop(empty(iterations.type()), iterations, init, body); 6999 } 7000 7001 /** 7002 * Constructs a loop that counts over a range of numbers. 7003 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7004 * <p> 7005 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 7006 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 7007 * values of the loop counter. 7008 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 7009 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 7010 * <p> 7011 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7012 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7013 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7014 * <p> 7015 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7016 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7017 * iteration variable. 7018 * The result of the loop handle execution will be the final {@code V} value of that variable 7019 * (or {@code void} if there is no {@code V} variable). 7020 * <p> 7021 * The following rules hold for the argument handles:<ul> 7022 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 7023 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 7024 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7025 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 7026 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7027 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 7028 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 7029 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 7030 * of types called the <em>internal parameter list</em>. 7031 * It will constrain the parameter lists of the other loop parts. 7032 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 7033 * with no additional {@code A} types, then the internal parameter list is extended by 7034 * the argument types {@code A...} of the {@code end} handle. 7035 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 7036 * list {@code (A...)} is called the <em>external parameter list</em>. 7037 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7038 * additional state variable of the loop. 7039 * The body must both accept a leading parameter and return a value of this type {@code V}. 7040 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7041 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7042 * <a href="MethodHandles.html#effid">effectively identical</a> 7043 * to the external parameter list {@code (A...)}. 7044 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7045 * {@linkplain #empty default value}. 7046 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 7047 * effectively identical to the external parameter list {@code (A...)}. 7048 * <li>Likewise, the parameter list of {@code end} must be effectively identical 7049 * to the external parameter list. 7050 * </ul> 7051 * <p> 7052 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7053 * <li>The loop handle's result type is the result type {@code V} of the body. 7054 * <li>The loop handle's parameter types are the types {@code (A...)}, 7055 * from the external parameter list. 7056 * </ul> 7057 * <p> 7058 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7059 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 7060 * arguments passed to the loop. 7061 * {@snippet lang="java" : 7062 * int start(A...); 7063 * int end(A...); 7064 * V init(A...); 7065 * V body(V, int, A...); 7066 * V countedLoop(A... a...) { 7067 * int e = end(a...); 7068 * int s = start(a...); 7069 * V v = init(a...); 7070 * for (int i = s; i < e; ++i) { 7071 * v = body(v, i, a...); 7072 * } 7073 * return v; 7074 * } 7075 * } 7076 * 7077 * @apiNote The implementation of this method can be expressed as follows: 7078 * {@snippet lang="java" : 7079 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7080 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 7081 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 7082 * // the following semantics: 7083 * // MH_increment: (int limit, int counter) -> counter + 1 7084 * // MH_predicate: (int limit, int counter) -> counter < limit 7085 * Class<?> counterType = start.type().returnType(); // int 7086 * Class<?> returnType = body.type().returnType(); 7087 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 7088 * if (returnType != void.class) { // ignore the V variable 7089 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7090 * pred = dropArguments(pred, 1, returnType); // ditto 7091 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 7092 * } 7093 * body = dropArguments(body, 0, counterType); // ignore the limit variable 7094 * MethodHandle[] 7095 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7096 * bodyClause = { init, body }, // v = init(); v = body(v, i) 7097 * indexVar = { start, incr }; // i = start(); i = i + 1 7098 * return loop(loopLimit, bodyClause, indexVar); 7099 * } 7100 * } 7101 * 7102 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 7103 * See above for other constraints. 7104 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 7105 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 7106 * @param init optional initializer, providing the initial value of the loop variable. 7107 * May be {@code null}, implying a default initial value. See above for other constraints. 7108 * @param body body of the loop, which may not be {@code null}. 7109 * It controls the loop parameters and result type in the standard case (see above for details). 7110 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 7111 * and may accept any number of additional types. 7112 * See above for other constraints. 7113 * 7114 * @return a method handle representing the loop. 7115 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 7116 * @throws IllegalArgumentException if any argument violates the rules formulated above. 7117 * 7118 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 7119 * @since 9 7120 */ 7121 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7122 countedLoopChecks(start, end, init, body); 7123 Class<?> counterType = start.type().returnType(); // int, but who's counting? 7124 Class<?> limitType = end.type().returnType(); // yes, int again 7125 Class<?> returnType = body.type().returnType(); 7126 MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 7127 MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 7128 MethodHandle retv = null; 7129 if (returnType != void.class) { 7130 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 7131 pred = dropArguments(pred, 1, returnType); // ditto 7132 retv = dropArguments(identity(returnType), 0, counterType); 7133 } 7134 body = dropArguments(body, 0, counterType); // ignore the limit variable 7135 MethodHandle[] 7136 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 7137 bodyClause = { init, body }, // v = init(); v = body(v, i) 7138 indexVar = { start, incr }; // i = start(); i = i + 1 7139 return loop(loopLimit, bodyClause, indexVar); 7140 } 7141 7142 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 7143 Objects.requireNonNull(start); 7144 Objects.requireNonNull(end); 7145 Objects.requireNonNull(body); 7146 Class<?> counterType = start.type().returnType(); 7147 if (counterType != int.class) { 7148 MethodType expected = start.type().changeReturnType(int.class); 7149 throw misMatchedTypes("start function", start.type(), expected); 7150 } else if (end.type().returnType() != counterType) { 7151 MethodType expected = end.type().changeReturnType(counterType); 7152 throw misMatchedTypes("end function", end.type(), expected); 7153 } 7154 MethodType bodyType = body.type(); 7155 Class<?> returnType = bodyType.returnType(); 7156 List<Class<?>> innerList = bodyType.parameterList(); 7157 // strip leading V value if present 7158 int vsize = (returnType == void.class ? 0 : 1); 7159 if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) { 7160 // argument list has no "V" => error 7161 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7162 throw misMatchedTypes("body function", bodyType, expected); 7163 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 7164 // missing I type => error 7165 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 7166 throw misMatchedTypes("body function", bodyType, expected); 7167 } 7168 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 7169 if (outerList.isEmpty()) { 7170 // special case; take lists from end handle 7171 outerList = end.type().parameterList(); 7172 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 7173 } 7174 MethodType expected = methodType(counterType, outerList); 7175 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 7176 throw misMatchedTypes("start parameter types", start.type(), expected); 7177 } 7178 if (end.type() != start.type() && 7179 !end.type().effectivelyIdenticalParameters(0, outerList)) { 7180 throw misMatchedTypes("end parameter types", end.type(), expected); 7181 } 7182 if (init != null) { 7183 MethodType initType = init.type(); 7184 if (initType.returnType() != returnType || 7185 !initType.effectivelyIdenticalParameters(0, outerList)) { 7186 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 7187 } 7188 } 7189 } 7190 7191 /** 7192 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 7193 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 7194 * <p> 7195 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 7196 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 7197 * <p> 7198 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 7199 * of that type is also present. This variable is initialized using the optional {@code init} handle, 7200 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 7201 * <p> 7202 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 7203 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 7204 * iteration variable. 7205 * The result of the loop handle execution will be the final {@code V} value of that variable 7206 * (or {@code void} if there is no {@code V} variable). 7207 * <p> 7208 * The following rules hold for the argument handles:<ul> 7209 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 7210 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 7211 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 7212 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 7213 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 7214 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 7215 * of types called the <em>internal parameter list</em>. 7216 * It will constrain the parameter lists of the other loop parts. 7217 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 7218 * with no additional {@code A} types, then the internal parameter list is extended by 7219 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 7220 * single type {@code Iterable} is added and constitutes the {@code A...} list. 7221 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 7222 * list {@code (A...)} is called the <em>external parameter list</em>. 7223 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 7224 * additional state variable of the loop. 7225 * The body must both accept a leading parameter and return a value of this type {@code V}. 7226 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 7227 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 7228 * <a href="MethodHandles.html#effid">effectively identical</a> 7229 * to the external parameter list {@code (A...)}. 7230 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 7231 * {@linkplain #empty default value}. 7232 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 7233 * type {@code java.util.Iterator} or a subtype thereof. 7234 * The iterator it produces when the loop is executed will be assumed 7235 * to yield values which can be converted to type {@code T}. 7236 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 7237 * effectively identical to the external parameter list {@code (A...)}. 7238 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 7239 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 7240 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 7241 * handle parameter is adjusted to accept the leading {@code A} type, as if by 7242 * the {@link MethodHandle#asType asType} conversion method. 7243 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 7244 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 7245 * </ul> 7246 * <p> 7247 * The type {@code T} may be either a primitive or reference. 7248 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 7249 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 7250 * as if by the {@link MethodHandle#asType asType} conversion method. 7251 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 7252 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 7253 * <p> 7254 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 7255 * <li>The loop handle's result type is the result type {@code V} of the body. 7256 * <li>The loop handle's parameter types are the types {@code (A...)}, 7257 * from the external parameter list. 7258 * </ul> 7259 * <p> 7260 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 7261 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 7262 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 7263 * {@snippet lang="java" : 7264 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 7265 * V init(A...); 7266 * V body(V,T,A...); 7267 * V iteratedLoop(A... a...) { 7268 * Iterator<T> it = iterator(a...); 7269 * V v = init(a...); 7270 * while (it.hasNext()) { 7271 * T t = it.next(); 7272 * v = body(v, t, a...); 7273 * } 7274 * return v; 7275 * } 7276 * } 7277 * 7278 * @apiNote Example: 7279 * {@snippet lang="java" : 7280 * // get an iterator from a list 7281 * static List<String> reverseStep(List<String> r, String e) { 7282 * r.add(0, e); 7283 * return r; 7284 * } 7285 * static List<String> newArrayList() { return new ArrayList<>(); } 7286 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 7287 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 7288 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 7289 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 7290 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 7291 * } 7292 * 7293 * @apiNote The implementation of this method can be expressed approximately as follows: 7294 * {@snippet lang="java" : 7295 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7296 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 7297 * Class<?> returnType = body.type().returnType(); 7298 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7299 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 7300 * MethodHandle retv = null, step = body, startIter = iterator; 7301 * if (returnType != void.class) { 7302 * // the simple thing first: in (I V A...), drop the I to get V 7303 * retv = dropArguments(identity(returnType), 0, Iterator.class); 7304 * // body type signature (V T A...), internal loop types (I V A...) 7305 * step = swapArguments(body, 0, 1); // swap V <-> T 7306 * } 7307 * if (startIter == null) startIter = MH_getIter; 7308 * MethodHandle[] 7309 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 7310 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 7311 * return loop(iterVar, bodyClause); 7312 * } 7313 * } 7314 * 7315 * @param iterator an optional handle to return the iterator to start the loop. 7316 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 7317 * See above for other constraints. 7318 * @param init optional initializer, providing the initial value of the loop variable. 7319 * May be {@code null}, implying a default initial value. See above for other constraints. 7320 * @param body body of the loop, which may not be {@code null}. 7321 * It controls the loop parameters and result type in the standard case (see above for details). 7322 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 7323 * and may accept any number of additional types. 7324 * See above for other constraints. 7325 * 7326 * @return a method handle embodying the iteration loop functionality. 7327 * @throws NullPointerException if the {@code body} handle is {@code null}. 7328 * @throws IllegalArgumentException if any argument violates the above requirements. 7329 * 7330 * @since 9 7331 */ 7332 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7333 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 7334 Class<?> returnType = body.type().returnType(); 7335 MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 7336 MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 7337 MethodHandle startIter; 7338 MethodHandle nextVal; 7339 { 7340 MethodType iteratorType; 7341 if (iterator == null) { 7342 // derive argument type from body, if available, else use Iterable 7343 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 7344 iteratorType = startIter.type().changeParameterType(0, iterableType); 7345 } else { 7346 // force return type to the internal iterator class 7347 iteratorType = iterator.type().changeReturnType(Iterator.class); 7348 startIter = iterator; 7349 } 7350 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 7351 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 7352 7353 // perform the asType transforms under an exception transformer, as per spec.: 7354 try { 7355 startIter = startIter.asType(iteratorType); 7356 nextVal = nextRaw.asType(nextValType); 7357 } catch (WrongMethodTypeException ex) { 7358 throw new IllegalArgumentException(ex); 7359 } 7360 } 7361 7362 MethodHandle retv = null, step = body; 7363 if (returnType != void.class) { 7364 // the simple thing first: in (I V A...), drop the I to get V 7365 retv = dropArguments(identity(returnType), 0, Iterator.class); 7366 // body type signature (V T A...), internal loop types (I V A...) 7367 step = swapArguments(body, 0, 1); // swap V <-> T 7368 } 7369 7370 MethodHandle[] 7371 iterVar = { startIter, null, hasNext, retv }, 7372 bodyClause = { init, filterArgument(step, 0, nextVal) }; 7373 return loop(iterVar, bodyClause); 7374 } 7375 7376 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 7377 Objects.requireNonNull(body); 7378 MethodType bodyType = body.type(); 7379 Class<?> returnType = bodyType.returnType(); 7380 List<Class<?>> internalParamList = bodyType.parameterList(); 7381 // strip leading V value if present 7382 int vsize = (returnType == void.class ? 0 : 1); 7383 if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) { 7384 // argument list has no "V" => error 7385 MethodType expected = bodyType.insertParameterTypes(0, returnType); 7386 throw misMatchedTypes("body function", bodyType, expected); 7387 } else if (internalParamList.size() <= vsize) { 7388 // missing T type => error 7389 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 7390 throw misMatchedTypes("body function", bodyType, expected); 7391 } 7392 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 7393 Class<?> iterableType = null; 7394 if (iterator != null) { 7395 // special case; if the body handle only declares V and T then 7396 // the external parameter list is obtained from iterator handle 7397 if (externalParamList.isEmpty()) { 7398 externalParamList = iterator.type().parameterList(); 7399 } 7400 MethodType itype = iterator.type(); 7401 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 7402 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 7403 } 7404 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 7405 MethodType expected = methodType(itype.returnType(), externalParamList); 7406 throw misMatchedTypes("iterator parameters", itype, expected); 7407 } 7408 } else { 7409 if (externalParamList.isEmpty()) { 7410 // special case; if the iterator handle is null and the body handle 7411 // only declares V and T then the external parameter list consists 7412 // of Iterable 7413 externalParamList = List.of(Iterable.class); 7414 iterableType = Iterable.class; 7415 } else { 7416 // special case; if the iterator handle is null and the external 7417 // parameter list is not empty then the first parameter must be 7418 // assignable to Iterable 7419 iterableType = externalParamList.get(0); 7420 if (!Iterable.class.isAssignableFrom(iterableType)) { 7421 throw newIllegalArgumentException( 7422 "inferred first loop argument must inherit from Iterable: " + iterableType); 7423 } 7424 } 7425 } 7426 if (init != null) { 7427 MethodType initType = init.type(); 7428 if (initType.returnType() != returnType || 7429 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 7430 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 7431 } 7432 } 7433 return iterableType; // help the caller a bit 7434 } 7435 7436 /*non-public*/ 7437 static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 7438 // there should be a better way to uncross my wires 7439 int arity = mh.type().parameterCount(); 7440 int[] order = new int[arity]; 7441 for (int k = 0; k < arity; k++) order[k] = k; 7442 order[i] = j; order[j] = i; 7443 Class<?>[] types = mh.type().parameterArray(); 7444 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 7445 MethodType swapType = methodType(mh.type().returnType(), types); 7446 return permuteArguments(mh, swapType, order); 7447 } 7448 7449 /** 7450 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 7451 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 7452 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 7453 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 7454 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 7455 * {@code try-finally} handle. 7456 * <p> 7457 * The {@code cleanup} handle will be passed one or two additional leading arguments. 7458 * The first is the exception thrown during the 7459 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 7460 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 7461 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 7462 * The second argument is not present if the {@code target} handle has a {@code void} return type. 7463 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 7464 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 7465 * <p> 7466 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 7467 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 7468 * two extra leading parameters:<ul> 7469 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 7470 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 7471 * the result from the execution of the {@code target} handle. 7472 * This parameter is not present if the {@code target} returns {@code void}. 7473 * </ul> 7474 * <p> 7475 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 7476 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 7477 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 7478 * the cleanup. 7479 * {@snippet lang="java" : 7480 * V target(A..., B...); 7481 * V cleanup(Throwable, V, A...); 7482 * V adapter(A... a, B... b) { 7483 * V result = (zero value for V); 7484 * Throwable throwable = null; 7485 * try { 7486 * result = target(a..., b...); 7487 * } catch (Throwable t) { 7488 * throwable = t; 7489 * throw t; 7490 * } finally { 7491 * result = cleanup(throwable, result, a...); 7492 * } 7493 * return result; 7494 * } 7495 * } 7496 * <p> 7497 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 7498 * be modified by execution of the target, and so are passed unchanged 7499 * from the caller to the cleanup, if it is invoked. 7500 * <p> 7501 * The target and cleanup must return the same type, even if the cleanup 7502 * always throws. 7503 * To create such a throwing cleanup, compose the cleanup logic 7504 * with {@link #throwException throwException}, 7505 * in order to create a method handle of the correct return type. 7506 * <p> 7507 * Note that {@code tryFinally} never converts exceptions into normal returns. 7508 * In rare cases where exceptions must be converted in that way, first wrap 7509 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 7510 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 7511 * <p> 7512 * It is recommended that the first parameter type of {@code cleanup} be 7513 * declared {@code Throwable} rather than a narrower subtype. This ensures 7514 * {@code cleanup} will always be invoked with whatever exception that 7515 * {@code target} throws. Declaring a narrower type may result in a 7516 * {@code ClassCastException} being thrown by the {@code try-finally} 7517 * handle if the type of the exception thrown by {@code target} is not 7518 * assignable to the first parameter type of {@code cleanup}. Note that 7519 * various exception types of {@code VirtualMachineError}, 7520 * {@code LinkageError}, and {@code RuntimeException} can in principle be 7521 * thrown by almost any kind of Java code, and a finally clause that 7522 * catches (say) only {@code IOException} would mask any of the others 7523 * behind a {@code ClassCastException}. 7524 * 7525 * @param target the handle whose execution is to be wrapped in a {@code try} block. 7526 * @param cleanup the handle that is invoked in the finally block. 7527 * 7528 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 7529 * @throws NullPointerException if any argument is null 7530 * @throws IllegalArgumentException if {@code cleanup} does not accept 7531 * the required leading arguments, or if the method handle types do 7532 * not match in their return types and their 7533 * corresponding trailing parameters 7534 * 7535 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 7536 * @since 9 7537 */ 7538 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 7539 Class<?>[] targetParamTypes = target.type().ptypes(); 7540 Class<?> rtype = target.type().returnType(); 7541 7542 tryFinallyChecks(target, cleanup); 7543 7544 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 7545 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7546 // target parameter list. 7547 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false); 7548 7549 // Ensure that the intrinsic type checks the instance thrown by the 7550 // target against the first parameter of cleanup 7551 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 7552 7553 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 7554 return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 7555 } 7556 7557 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 7558 Class<?> rtype = target.type().returnType(); 7559 if (rtype != cleanup.type().returnType()) { 7560 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 7561 } 7562 MethodType cleanupType = cleanup.type(); 7563 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 7564 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 7565 } 7566 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 7567 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 7568 } 7569 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 7570 // target parameter list. 7571 int cleanupArgIndex = rtype == void.class ? 1 : 2; 7572 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 7573 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 7574 cleanup.type(), target.type()); 7575 } 7576 } 7577 7578 /** 7579 * Creates a table switch method handle, which can be used to switch over a set of target 7580 * method handles, based on a given target index, called selector. 7581 * <p> 7582 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)}, 7583 * and where {@code N} is the number of target method handles, the table switch method 7584 * handle will invoke the n-th target method handle from the list of target method handles. 7585 * <p> 7586 * For a selector value that does not fall in the range {@code [0, N)}, the table switch 7587 * method handle will invoke the given fallback method handle. 7588 * <p> 7589 * All method handles passed to this method must have the same type, with the additional 7590 * requirement that the leading parameter be of type {@code int}. The leading parameter 7591 * represents the selector. 7592 * <p> 7593 * Any trailing parameters present in the type will appear on the returned table switch 7594 * method handle as well. Any arguments assigned to these parameters will be forwarded, 7595 * together with the selector value, to the selected method handle when invoking it. 7596 * 7597 * @apiNote Example: 7598 * The cases each drop the {@code selector} value they are given, and take an additional 7599 * {@code String} argument, which is concatenated (using {@link String#concat(String)}) 7600 * to a specific constant label string for each case: 7601 * {@snippet lang="java" : 7602 * MethodHandles.Lookup lookup = MethodHandles.lookup(); 7603 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat", 7604 * MethodType.methodType(String.class, String.class)); 7605 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class); 7606 * 7607 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: "); 7608 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: "); 7609 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: "); 7610 * 7611 * MethodHandle mhSwitch = MethodHandles.tableSwitch( 7612 * caseDefault, 7613 * case0, 7614 * case1 7615 * ); 7616 * 7617 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data")); 7618 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data")); 7619 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data")); 7620 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data")); 7621 * } 7622 * 7623 * @param fallback the fallback method handle that is called when the selector is not 7624 * within the range {@code [0, N)}. 7625 * @param targets array of target method handles. 7626 * @return the table switch method handle. 7627 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any 7628 * any of the elements of the {@code targets} array are 7629 * {@code null}. 7630 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading 7631 * parameter of the fallback handle or any of the target 7632 * handles is not {@code int}, or if the types of 7633 * the fallback handle and all of target handles are 7634 * not the same. 7635 * 7636 * @since 17 7637 */ 7638 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) { 7639 Objects.requireNonNull(fallback); 7640 Objects.requireNonNull(targets); 7641 targets = targets.clone(); 7642 MethodType type = tableSwitchChecks(fallback, targets); 7643 return MethodHandleImpl.makeTableSwitch(type, fallback, targets); 7644 } 7645 7646 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) { 7647 if (caseActions.length == 0) 7648 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions)); 7649 7650 MethodType expectedType = defaultCase.type(); 7651 7652 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class) 7653 throw new IllegalArgumentException( 7654 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions)); 7655 7656 for (MethodHandle mh : caseActions) { 7657 Objects.requireNonNull(mh); 7658 if (mh.type() != expectedType) 7659 throw new IllegalArgumentException( 7660 "Case actions must have the same type: " + Arrays.toString(caseActions)); 7661 } 7662 7663 return expectedType; 7664 } 7665 7666 /** 7667 * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions. 7668 * <p> 7669 * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where 7670 * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed 7671 * to the target var handle. 7672 * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from 7673 * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function) 7674 * is processed using the second filter and returned to the caller. More advanced access mode types, such as 7675 * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time. 7676 * <p> 7677 * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and 7678 * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case, 7679 * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which 7680 * will be appended to the coordinates of the target var handle). 7681 * <p> 7682 * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will 7683 * throw an {@link IllegalStateException}. 7684 * <p> 7685 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7686 * atomic access guarantees as those featured by the target var handle. 7687 * 7688 * @param target the target var handle 7689 * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target} 7690 * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S} 7691 * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions. 7692 * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types 7693 * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle, 7694 * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions. 7695 * @throws NullPointerException if any of the arguments is {@code null}. 7696 * @since 22 7697 */ 7698 public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 7699 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 7700 } 7701 7702 /** 7703 * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions. 7704 * <p> 7705 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values 7706 * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types 7707 * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the 7708 * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered 7709 * by the adaptation) to the target var handle. 7710 * <p> 7711 * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn}, 7712 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7713 * <p> 7714 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7715 * throw an {@link IllegalStateException}. 7716 * <p> 7717 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7718 * atomic access guarantees as those featured by the target var handle. 7719 * 7720 * @param target the target var handle 7721 * @param pos the position of the first coordinate to be transformed 7722 * @param filters the unary functions which are used to transform coordinates starting at position {@code pos} 7723 * @return an adapter var handle which accepts new coordinate types, applying the provided transformation 7724 * to the new coordinate values. 7725 * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types 7726 * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting 7727 * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7728 * or if more filters are provided than the actual number of coordinate types available starting at {@code pos}, 7729 * or if it's determined that any of the filters throws any checked exceptions. 7730 * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}. 7731 * @since 22 7732 */ 7733 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 7734 return VarHandles.filterCoordinates(target, pos, filters); 7735 } 7736 7737 /** 7738 * Provides a target var handle with one or more <em>bound coordinates</em> 7739 * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less 7740 * coordinate types than the target var handle. 7741 * <p> 7742 * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values 7743 * are joined with bound coordinate values, and then passed to the target var handle. 7744 * <p> 7745 * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn }, 7746 * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle. 7747 * <p> 7748 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7749 * atomic access guarantees as those featured by the target var handle. 7750 * 7751 * @param target the var handle to invoke after the bound coordinates are inserted 7752 * @param pos the position of the first coordinate to be inserted 7753 * @param values the series of bound coordinates to insert 7754 * @return an adapter var handle which inserts additional coordinates, 7755 * before calling the target var handle 7756 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7757 * or if more values are provided than the actual number of coordinate types available starting at {@code pos}. 7758 * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types 7759 * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} 7760 * of the target var handle. 7761 * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}. 7762 * @since 22 7763 */ 7764 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 7765 return VarHandles.insertCoordinates(target, pos, values); 7766 } 7767 7768 /** 7769 * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them 7770 * so that the new coordinates match the provided ones. 7771 * <p> 7772 * The given array controls the reordering. 7773 * Call {@code #I} the number of incoming coordinates (the value 7774 * {@code newCoordinates.size()}), and call {@code #O} the number 7775 * of outgoing coordinates (the number of coordinates associated with the target var handle). 7776 * Then the length of the reordering array must be {@code #O}, 7777 * and each element must be a non-negative number less than {@code #I}. 7778 * For every {@code N} less than {@code #O}, the {@code N}-th 7779 * outgoing coordinate will be taken from the {@code I}-th incoming 7780 * coordinate, where {@code I} is {@code reorder[N]}. 7781 * <p> 7782 * No coordinate value conversions are applied. 7783 * The type of each incoming coordinate, as determined by {@code newCoordinates}, 7784 * must be identical to the type of the corresponding outgoing coordinate 7785 * in the target var handle. 7786 * <p> 7787 * The reordering array need not specify an actual permutation. 7788 * An incoming coordinate will be duplicated if its index appears 7789 * more than once in the array, and an incoming coordinate will be dropped 7790 * if its index does not appear in the array. 7791 * <p> 7792 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7793 * atomic access guarantees as those featured by the target var handle. 7794 * @param target the var handle to invoke after the coordinates have been reordered 7795 * @param newCoordinates the new coordinate types 7796 * @param reorder an index array which controls the reordering 7797 * @return an adapter var handle which re-arranges the incoming coordinate values, 7798 * before calling the target var handle 7799 * @throws IllegalArgumentException if the index array length is not equal to 7800 * the number of coordinates of the target var handle, or if any index array element is not a valid index for 7801 * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in 7802 * the target var handle and in {@code newCoordinates} are not identical. 7803 * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}. 7804 * @since 22 7805 */ 7806 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 7807 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 7808 } 7809 7810 /** 7811 * Adapts a target var handle by pre-processing 7812 * a sub-sequence of its coordinate values with a filter (a method handle). 7813 * The pre-processed coordinates are replaced by the result (if any) of the 7814 * filter function and the target var handle is then called on the modified (usually shortened) 7815 * coordinate list. 7816 * <p> 7817 * If {@code R} is the return type of the filter, then: 7818 * <ul> 7819 * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in 7820 * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos} 7821 * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first, 7822 * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the 7823 * target var handle.</li> 7824 * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the 7825 * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle 7826 * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a 7827 * downstream invocation of the target var handle.</li> 7828 * </ul> 7829 * <p> 7830 * If any of the filters throws a checked exception when invoked, the resulting var handle will 7831 * throw an {@link IllegalStateException}. 7832 * <p> 7833 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7834 * atomic access guarantees as those featured by the target var handle. 7835 * 7836 * @param target the var handle to invoke after the coordinates have been filtered 7837 * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted 7838 * @param filter the filter method handle 7839 * @return an adapter var handle which filters the incoming coordinate values, 7840 * before calling the target var handle 7841 * @throws IllegalArgumentException if the return type of {@code filter} 7842 * is not void, and it is not the same as the {@code pos} coordinate of the target var handle, 7843 * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive, 7844 * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>, 7845 * or if it's determined that {@code filter} throws any checked exceptions. 7846 * @throws NullPointerException if any of the arguments is {@code null}. 7847 * @since 22 7848 */ 7849 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 7850 return VarHandles.collectCoordinates(target, pos, filter); 7851 } 7852 7853 /** 7854 * Returns a var handle which will discard some dummy coordinates before delegating to the 7855 * target var handle. As a consequence, the resulting var handle will feature more 7856 * coordinate types than the target var handle. 7857 * <p> 7858 * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the 7859 * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede 7860 * the target's real arguments; if {@code pos} is <i>N</i> they will come after. 7861 * <p> 7862 * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and 7863 * atomic access guarantees as those featured by the target var handle. 7864 * 7865 * @param target the var handle to invoke after the dummy coordinates are dropped 7866 * @param pos position of the first coordinate to drop (zero for the leftmost) 7867 * @param valueTypes the type(s) of the coordinate(s) to drop 7868 * @return an adapter var handle which drops some dummy coordinates, 7869 * before calling the target var handle 7870 * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive. 7871 * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}. 7872 * @since 22 7873 */ 7874 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 7875 return VarHandles.dropCoordinates(target, pos, valueTypes); 7876 } 7877 }