1 /* 2 * Copyright (c) 2008, 2016, 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.org.objectweb.asm.ClassWriter; 29 import jdk.internal.org.objectweb.asm.Opcodes; 30 import jdk.internal.reflect.CallerSensitive; 31 import jdk.internal.reflect.Reflection; 32 import jdk.internal.vm.annotation.ForceInline; 33 import sun.invoke.util.ValueConversions; 34 import sun.invoke.util.VerifyAccess; 35 import sun.invoke.util.Wrapper; 36 import sun.reflect.misc.ReflectUtil; 37 import sun.security.util.SecurityConstants; 38 39 import java.lang.invoke.LambdaForm.BasicType; 40 import java.lang.reflect.Constructor; 41 import java.lang.reflect.Field; 42 import java.lang.reflect.Member; 43 import java.lang.reflect.Method; 44 import java.lang.reflect.Modifier; 45 import java.lang.reflect.ReflectPermission; 46 import java.nio.ByteOrder; 47 import java.security.AccessController; 48 import java.security.PrivilegedAction; 49 import java.util.ArrayList; 50 import java.util.Arrays; 51 import java.util.BitSet; 52 import java.util.Iterator; 53 import java.util.List; 54 import java.util.Objects; 55 import java.util.concurrent.ConcurrentHashMap; 56 import java.util.stream.Collectors; 57 import java.util.stream.Stream; 58 59 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 60 import static java.lang.invoke.MethodHandleNatives.Constants.*; 61 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 62 import static java.lang.invoke.MethodType.methodType; 63 64 /** 65 * This class consists exclusively of static methods that operate on or return 66 * method handles. They fall into several categories: 67 * <ul> 68 * <li>Lookup methods which help create method handles for methods and fields. 69 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 70 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 71 * </ul> 72 * 73 * @author John Rose, JSR 292 EG 74 * @since 1.7 75 */ 76 public class MethodHandles { 77 78 private MethodHandles() { } // do not instantiate 79 80 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 81 82 // See IMPL_LOOKUP below. 83 84 //// Method handle creation from ordinary methods. 85 86 /** 87 * Returns a {@link Lookup lookup object} with 88 * full capabilities to emulate all supported bytecode behaviors of the caller. 89 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. 90 * Factory methods on the lookup object can create 91 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 92 * for any member that the caller has access to via bytecodes, 93 * including protected and private fields and methods. 94 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 95 * Do not store it in place where untrusted code can access it. 96 * <p> 97 * This method is caller sensitive, which means that it may return different 98 * values to different callers. 99 * <p> 100 * For any given caller class {@code C}, the lookup object returned by this call 101 * has equivalent capabilities to any lookup object 102 * supplied by the JVM to the bootstrap method of an 103 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> 104 * executing in the same caller class {@code C}. 105 * @return a lookup object for the caller of this method, with private access 106 */ 107 @CallerSensitive 108 @ForceInline // to ensure Reflection.getCallerClass optimization 109 public static Lookup lookup() { 110 return new Lookup(Reflection.getCallerClass()); 111 } 112 113 /** 114 * Returns a {@link Lookup lookup object} which is trusted minimally. 115 * It can only be used to create method handles to public members in 116 * public classes in packages that are exported unconditionally. 117 * <p> 118 * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup 119 * object is in an unnamed module. 120 * Consequently, the lookup context of this lookup object will be the bootstrap 121 * class loader, which means it cannot find user classes. 122 * 123 * <p style="font-size:smaller;"> 124 * <em>Discussion:</em> 125 * The lookup class can be changed to any other class {@code C} using an expression of the form 126 * {@link Lookup#in publicLookup().in(C.class)}. 127 * but may change the lookup context by virtue of changing the class loader. 128 * A public lookup object is always subject to 129 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 130 * Also, it cannot access 131 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 132 * @return a lookup object which is trusted minimally 133 */ 134 public static Lookup publicLookup() { 135 // During VM startup then only classes in the java.base module can be 136 // loaded and linked. This is because java.base exports aren't setup until 137 // the module system is initialized, hence types in the unnamed module 138 // (or any named module) can't link to java/lang/Object. 139 if (!jdk.internal.misc.VM.isModuleSystemInited()) { 140 return new Lookup(Object.class, Lookup.PUBLIC); 141 } else { 142 return LookupHelper.PUBLIC_LOOKUP; 143 } 144 } 145 146 /** 147 * Performs an unchecked "crack" of a 148 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 149 * The result is as if the user had obtained a lookup object capable enough 150 * to crack the target method handle, called 151 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 152 * on the target to obtain its symbolic reference, and then called 153 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 154 * to resolve the symbolic reference to a member. 155 * <p> 156 * If there is a security manager, its {@code checkPermission} method 157 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 158 * @param <T> the desired type of the result, either {@link Member} or a subtype 159 * @param target a direct method handle to crack into symbolic reference components 160 * @param expected a class object representing the desired result type {@code T} 161 * @return a reference to the method, constructor, or field object 162 * @exception SecurityException if the caller is not privileged to call {@code setAccessible} 163 * @exception NullPointerException if either argument is {@code null} 164 * @exception IllegalArgumentException if the target is not a direct method handle 165 * @exception ClassCastException if the member is not of the expected type 166 * @since 1.8 167 */ 168 public static <T extends Member> T 169 reflectAs(Class<T> expected, MethodHandle target) { 170 SecurityManager smgr = System.getSecurityManager(); 171 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION); 172 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 173 return lookup.revealDirect(target).reflectAs(expected, lookup); 174 } 175 // Copied from AccessibleObject, as used by Method.setAccessible, etc.: 176 private static final java.security.Permission ACCESS_PERMISSION = 177 new ReflectPermission("suppressAccessChecks"); 178 179 /** 180 * A <em>lookup object</em> is a factory for creating method handles, 181 * when the creation requires access checking. 182 * Method handles do not perform 183 * access checks when they are called, but rather when they are created. 184 * Therefore, method handle access 185 * restrictions must be enforced when a method handle is created. 186 * The caller class against which those restrictions are enforced 187 * is known as the {@linkplain #lookupClass lookup class}. 188 * <p> 189 * A lookup class which needs to create method handles will call 190 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. 191 * When the {@code Lookup} factory object is created, the identity of the lookup class is 192 * determined, and securely stored in the {@code Lookup} object. 193 * The lookup class (or its delegates) may then use factory methods 194 * on the {@code Lookup} object to create method handles for access-checked members. 195 * This includes all methods, constructors, and fields which are allowed to the lookup class, 196 * even private ones. 197 * 198 * <h1><a name="lookups"></a>Lookup Factory Methods</h1> 199 * The factory methods on a {@code Lookup} object correspond to all major 200 * use cases for methods, constructors, and fields. 201 * Each method handle created by a factory method is the functional 202 * equivalent of a particular <em>bytecode behavior</em>. 203 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) 204 * Here is a summary of the correspondence between these factory methods and 205 * the behavior of the resulting method handles: 206 * <table border=1 cellpadding=5 summary="lookup method behaviors"> 207 * <tr> 208 * <th><a name="equiv"></a>lookup expression</th> 209 * <th>member</th> 210 * <th>bytecode behavior</th> 211 * </tr> 212 * <tr> 213 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> 214 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 215 * </tr> 216 * <tr> 217 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> 218 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> 219 * </tr> 220 * <tr> 221 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> 222 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 223 * </tr> 224 * <tr> 225 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> 226 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 227 * </tr> 228 * <tr> 229 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> 230 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 231 * </tr> 232 * <tr> 233 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> 234 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 235 * </tr> 236 * <tr> 237 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> 238 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 239 * </tr> 240 * <tr> 241 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> 242 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 243 * </tr> 244 * <tr> 245 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> 246 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 247 * </tr> 248 * <tr> 249 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> 250 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 251 * </tr> 252 * <tr> 253 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 254 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 255 * </tr> 256 * <tr> 257 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> 258 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 259 * </tr> 260 * <tr> 261 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 262 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 263 * </tr> 264 * <tr> 265 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td> 266 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> 267 * </tr> 268 * </table> 269 * 270 * Here, the type {@code C} is the class or interface being searched for a member, 271 * documented as a parameter named {@code refc} in the lookup methods. 272 * The method type {@code MT} is composed from the return type {@code T} 273 * and the sequence of argument types {@code A*}. 274 * The constructor also has a sequence of argument types {@code A*} and 275 * is deemed to return the newly-created object of type {@code C}. 276 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 277 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 278 * if it is present, it is always the leading argument to the method handle invocation. 279 * (In the case of some {@code protected} members, {@code this} may be 280 * restricted in type to the lookup class; see below.) 281 * The name {@code arg} stands for all the other method handle arguments. 282 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 283 * stands for a null reference if the accessed method or field is static, 284 * and {@code this} otherwise. 285 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 286 * for reflective objects corresponding to the given members. 287 * <p> 288 * The bytecode behavior for a {@code findClass} operation is a load of a constant class, 289 * as if by {@code ldc CONSTANT_Class}. 290 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. 291 * <p> 292 * In cases where the given member is of variable arity (i.e., a method or constructor) 293 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 294 * In all other cases, the returned method handle will be of fixed arity. 295 * <p style="font-size:smaller;"> 296 * <em>Discussion:</em> 297 * The equivalence between looked-up method handles and underlying 298 * class members and bytecode behaviors 299 * can break down in a few ways: 300 * <ul style="font-size:smaller;"> 301 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 302 * the lookup can still succeed, even when there is no equivalent 303 * Java expression or bytecoded constant. 304 * <li>Likewise, if {@code T} or {@code MT} 305 * is not symbolically accessible from the lookup class's loader, 306 * the lookup can still succeed. 307 * For example, lookups for {@code MethodHandle.invokeExact} and 308 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 309 * <li>If there is a security manager installed, it can forbid the lookup 310 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 311 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 312 * constant is not subject to security manager checks. 313 * <li>If the looked-up method has a 314 * <a href="MethodHandle.html#maxarity">very large arity</a>, 315 * the method handle creation may fail, due to the method handle 316 * type having too many parameters. 317 * </ul> 318 * 319 * <h1><a name="access"></a>Access checking</h1> 320 * Access checks are applied in the factory methods of {@code Lookup}, 321 * when a method handle is created. 322 * This is a key difference from the Core Reflection API, since 323 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 324 * performs access checking against every caller, on every call. 325 * <p> 326 * All access checks start from a {@code Lookup} object, which 327 * compares its recorded lookup class against all requests to 328 * create method handles. 329 * A single {@code Lookup} object can be used to create any number 330 * of access-checked method handles, all checked against a single 331 * lookup class. 332 * <p> 333 * A {@code Lookup} object can be shared with other trusted code, 334 * such as a metaobject protocol. 335 * A shared {@code Lookup} object delegates the capability 336 * to create method handles on private members of the lookup class. 337 * Even if privileged code uses the {@code Lookup} object, 338 * the access checking is confined to the privileges of the 339 * original lookup class. 340 * <p> 341 * A lookup can fail, because 342 * the containing class is not accessible to the lookup class, or 343 * because the desired class member is missing, or because the 344 * desired class member is not accessible to the lookup class, or 345 * because the lookup object is not trusted enough to access the member. 346 * In any of these cases, a {@code ReflectiveOperationException} will be 347 * thrown from the attempted lookup. The exact class will be one of 348 * the following: 349 * <ul> 350 * <li>NoSuchMethodException — if a method is requested but does not exist 351 * <li>NoSuchFieldException — if a field is requested but does not exist 352 * <li>IllegalAccessException — if the member exists but an access check fails 353 * </ul> 354 * <p> 355 * In general, the conditions under which a method handle may be 356 * looked up for a method {@code M} are no more restrictive than the conditions 357 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 358 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 359 * a method handle lookup will generally raise a corresponding 360 * checked exception, such as {@code NoSuchMethodException}. 361 * And the effect of invoking the method handle resulting from the lookup 362 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 363 * to executing the compiled, verified, and resolved call to {@code M}. 364 * The same point is true of fields and constructors. 365 * <p style="font-size:smaller;"> 366 * <em>Discussion:</em> 367 * Access checks only apply to named and reflected methods, 368 * constructors, and fields. 369 * Other method handle creation methods, such as 370 * {@link MethodHandle#asType MethodHandle.asType}, 371 * do not require any access checks, and are used 372 * independently of any {@code Lookup} object. 373 * <p> 374 * If the desired member is {@code protected}, the usual JVM rules apply, 375 * including the requirement that the lookup class must be either be in the 376 * same package as the desired member, or must inherit that member. 377 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) 378 * In addition, if the desired member is a non-static field or method 379 * in a different package, the resulting method handle may only be applied 380 * to objects of the lookup class or one of its subclasses. 381 * This requirement is enforced by narrowing the type of the leading 382 * {@code this} parameter from {@code C} 383 * (which will necessarily be a superclass of the lookup class) 384 * to the lookup class itself. 385 * <p> 386 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 387 * that the receiver argument must match both the resolved method <em>and</em> 388 * the current class. Again, this requirement is enforced by narrowing the 389 * type of the leading parameter to the resulting method handle. 390 * (See the Java Virtual Machine Specification, section 4.10.1.9.) 391 * <p> 392 * The JVM represents constructors and static initializer blocks as internal methods 393 * with special names ({@code "<init>"} and {@code "<clinit>"}). 394 * The internal syntax of invocation instructions allows them to refer to such internal 395 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 396 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 397 * <p> 398 * In some cases, access between nested classes is obtained by the Java compiler by creating 399 * an wrapper method to access a private method of another class 400 * in the same top-level declaration. 401 * For example, a nested class {@code C.D} 402 * can access private members within other related classes such as 403 * {@code C}, {@code C.D.E}, or {@code C.B}, 404 * but the Java compiler may need to generate wrapper methods in 405 * those related classes. In such cases, a {@code Lookup} object on 406 * {@code C.E} would be unable to those private members. 407 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 408 * which can transform a lookup on {@code C.E} into one on any of those other 409 * classes, without special elevation of privilege. 410 * <p> 411 * The accesses permitted to a given lookup object may be limited, 412 * according to its set of {@link #lookupModes lookupModes}, 413 * to a subset of members normally accessible to the lookup class. 414 * For example, the {@link MethodHandles#publicLookup publicLookup} 415 * method produces a lookup object which is only allowed to access 416 * public members in public classes of exported packages. 417 * The caller sensitive method {@link MethodHandles#lookup lookup} 418 * produces a lookup object with full capabilities relative to 419 * its caller class, to emulate all supported bytecode behaviors. 420 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 421 * with fewer access modes than the original lookup object. 422 * 423 * <p style="font-size:smaller;"> 424 * <a name="privacc"></a> 425 * <em>Discussion of private access:</em> 426 * We say that a lookup has <em>private access</em> 427 * if its {@linkplain #lookupModes lookup modes} 428 * include the possibility of accessing {@code private} members. 429 * As documented in the relevant methods elsewhere, 430 * only lookups with private access possess the following capabilities: 431 * <ul style="font-size:smaller;"> 432 * <li>access private fields, methods, and constructors of the lookup class 433 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 434 * such as {@code Class.forName} 435 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 436 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 437 * for classes accessible to the lookup class 438 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 439 * within the same package member 440 * </ul> 441 * <p style="font-size:smaller;"> 442 * Each of these permissions is a consequence of the fact that a lookup object 443 * with private access can be securely traced back to an originating class, 444 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 445 * can be reliably determined and emulated by method handles. 446 * 447 * <h1><a name="secmgr"></a>Security manager interactions</h1> 448 * Although bytecode instructions can only refer to classes in 449 * a related class loader, this API can search for methods in any 450 * class, as long as a reference to its {@code Class} object is 451 * available. Such cross-loader references are also possible with the 452 * Core Reflection API, and are impossible to bytecode instructions 453 * such as {@code invokestatic} or {@code getfield}. 454 * There is a {@linkplain java.lang.SecurityManager security manager API} 455 * to allow applications to check such cross-loader references. 456 * These checks apply to both the {@code MethodHandles.Lookup} API 457 * and the Core Reflection API 458 * (as found on {@link java.lang.Class Class}). 459 * <p> 460 * If a security manager is present, member and class lookups are subject to 461 * additional checks. 462 * From one to three calls are made to the security manager. 463 * Any of these calls can refuse access by throwing a 464 * {@link java.lang.SecurityException SecurityException}. 465 * Define {@code smgr} as the security manager, 466 * {@code lookc} as the lookup class of the current lookup object, 467 * {@code refc} as the containing class in which the member 468 * is being sought, and {@code defc} as the class in which the 469 * member is actually defined. 470 * (If a class or other type is being accessed, 471 * the {@code refc} and {@code defc} values are the class itself.) 472 * The value {@code lookc} is defined as <em>not present</em> 473 * if the current lookup object does not have 474 * <a href="MethodHandles.Lookup.html#privacc">private access</a>. 475 * The calls are made according to the following rules: 476 * <ul> 477 * <li><b>Step 1:</b> 478 * If {@code lookc} is not present, or if its class loader is not 479 * the same as or an ancestor of the class loader of {@code refc}, 480 * then {@link SecurityManager#checkPackageAccess 481 * smgr.checkPackageAccess(refcPkg)} is called, 482 * where {@code refcPkg} is the package of {@code refc}. 483 * <li><b>Step 2a:</b> 484 * If the retrieved member is not public and 485 * {@code lookc} is not present, then 486 * {@link SecurityManager#checkPermission smgr.checkPermission} 487 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 488 * <li><b>Step 2b:</b> 489 * If the retrieved class has a {@code null} class loader, 490 * and {@code lookc} is not present, then 491 * {@link SecurityManager#checkPermission smgr.checkPermission} 492 * with {@code RuntimePermission("getClassLoader")} is called. 493 * <li><b>Step 3:</b> 494 * If the retrieved member is not public, 495 * and if {@code lookc} is not present, 496 * and if {@code defc} and {@code refc} are different, 497 * then {@link SecurityManager#checkPackageAccess 498 * smgr.checkPackageAccess(defcPkg)} is called, 499 * where {@code defcPkg} is the package of {@code defc}. 500 * </ul> 501 * Security checks are performed after other access checks have passed. 502 * Therefore, the above rules presuppose a member or class that is public, 503 * or else that is being accessed from a lookup class that has 504 * rights to access the member or class. 505 * 506 * <h1><a name="callsens"></a>Caller sensitive methods</h1> 507 * A small number of Java methods have a special property called caller sensitivity. 508 * A <em>caller-sensitive</em> method can behave differently depending on the 509 * identity of its immediate caller. 510 * <p> 511 * If a method handle for a caller-sensitive method is requested, 512 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 513 * but they take account of the lookup class in a special way. 514 * The resulting method handle behaves as if it were called 515 * from an instruction contained in the lookup class, 516 * so that the caller-sensitive method detects the lookup class. 517 * (By contrast, the invoker of the method handle is disregarded.) 518 * Thus, in the case of caller-sensitive methods, 519 * different lookup classes may give rise to 520 * differently behaving method handles. 521 * <p> 522 * In cases where the lookup object is 523 * {@link MethodHandles#publicLookup() publicLookup()}, 524 * or some other lookup object without 525 * <a href="MethodHandles.Lookup.html#privacc">private access</a>, 526 * the lookup class is disregarded. 527 * In such cases, no caller-sensitive method handle can be created, 528 * access is forbidden, and the lookup fails with an 529 * {@code IllegalAccessException}. 530 * <p style="font-size:smaller;"> 531 * <em>Discussion:</em> 532 * For example, the caller-sensitive method 533 * {@link java.lang.Class#forName(String) Class.forName(x)} 534 * can return varying classes or throw varying exceptions, 535 * depending on the class loader of the class that calls it. 536 * A public lookup of {@code Class.forName} will fail, because 537 * there is no reasonable way to determine its bytecode behavior. 538 * <p style="font-size:smaller;"> 539 * If an application caches method handles for broad sharing, 540 * it should use {@code publicLookup()} to create them. 541 * If there is a lookup of {@code Class.forName}, it will fail, 542 * and the application must take appropriate action in that case. 543 * It may be that a later lookup, perhaps during the invocation of a 544 * bootstrap method, can incorporate the specific identity 545 * of the caller, making the method accessible. 546 * <p style="font-size:smaller;"> 547 * The function {@code MethodHandles.lookup} is caller sensitive 548 * so that there can be a secure foundation for lookups. 549 * Nearly all other methods in the JSR 292 API rely on lookup 550 * objects to check access requests. 551 */ 552 public static final 553 class Lookup { 554 /** The class on behalf of whom the lookup is being performed. */ 555 private final Class<?> lookupClass; 556 557 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 558 private final int allowedModes; 559 560 /** A single-bit mask representing {@code public} access, 561 * which may contribute to the result of {@link #lookupModes lookupModes}. 562 * The value, {@code 0x01}, happens to be the same as the value of the 563 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 564 */ 565 public static final int PUBLIC = Modifier.PUBLIC; 566 567 /** A single-bit mask representing {@code private} access, 568 * which may contribute to the result of {@link #lookupModes lookupModes}. 569 * The value, {@code 0x02}, happens to be the same as the value of the 570 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 571 */ 572 public static final int PRIVATE = Modifier.PRIVATE; 573 574 /** A single-bit mask representing {@code protected} access, 575 * which may contribute to the result of {@link #lookupModes lookupModes}. 576 * The value, {@code 0x04}, happens to be the same as the value of the 577 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 578 */ 579 public static final int PROTECTED = Modifier.PROTECTED; 580 581 /** A single-bit mask representing {@code package} access (default access), 582 * which may contribute to the result of {@link #lookupModes lookupModes}. 583 * The value is {@code 0x08}, which does not correspond meaningfully to 584 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 585 */ 586 public static final int PACKAGE = Modifier.STATIC; 587 588 /** A single-bit mask representing {@code module} access (default access), 589 * which may contribute to the result of {@link #lookupModes lookupModes}. 590 * The value is {@code 0x10}, which does not correspond meaningfully to 591 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 592 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} 593 * with this lookup mode can access all public types in the module of the 594 * lookup class and public types in packages exported by other modules 595 * to the module of the lookup class. 596 * @since 9 597 */ 598 public static final int MODULE = PACKAGE << 1; 599 600 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE); 601 private static final int TRUSTED = -1; 602 603 private static int fixmods(int mods) { 604 mods &= (ALL_MODES - PACKAGE - MODULE); 605 return (mods != 0) ? mods : (PACKAGE | MODULE); 606 } 607 608 /** Tells which class is performing the lookup. It is this class against 609 * which checks are performed for visibility and access permissions. 610 * <p> 611 * The class implies a maximum level of access permission, 612 * but the permissions may be additionally limited by the bitmask 613 * {@link #lookupModes lookupModes}, which controls whether non-public members 614 * can be accessed. 615 * @return the lookup class, on behalf of which this lookup object finds members 616 */ 617 public Class<?> lookupClass() { 618 return lookupClass; 619 } 620 621 // This is just for calling out to MethodHandleImpl. 622 private Class<?> lookupClassOrNull() { 623 return (allowedModes == TRUSTED) ? null : lookupClass; 624 } 625 626 /** Tells which access-protection classes of members this lookup object can produce. 627 * The result is a bit-mask of the bits 628 * {@linkplain #PUBLIC PUBLIC (0x01)}, 629 * {@linkplain #PRIVATE PRIVATE (0x02)}, 630 * {@linkplain #PROTECTED PROTECTED (0x04)}, 631 * {@linkplain #PACKAGE PACKAGE (0x08)}, 632 * and {@linkplain #MODULE MODULE (0x10)}. 633 * <p> 634 * A freshly-created lookup object 635 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} 636 * has all possible bits set, since the caller class can access all its own members, 637 * all public types in the caller's module, and all public types in packages exported 638 * by other modules to the caller's module. 639 * A lookup object on a new lookup class 640 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 641 * may have some mode bits set to zero. 642 * The purpose of this is to restrict access via the new lookup object, 643 * so that it can access only names which can be reached by the original 644 * lookup object, and also by the new lookup class. 645 * @return the lookup modes, which limit the kinds of access performed by this lookup object 646 */ 647 public int lookupModes() { 648 return allowedModes & ALL_MODES; 649 } 650 651 /** Embody the current class (the lookupClass) as a lookup class 652 * for method handle creation. 653 * Must be called by from a method in this package, 654 * which in turn is called by a method not in this package. 655 */ 656 Lookup(Class<?> lookupClass) { 657 this(lookupClass, ALL_MODES); 658 // make sure we haven't accidentally picked up a privileged class: 659 checkUnprivilegedlookupClass(lookupClass, ALL_MODES); 660 } 661 662 private Lookup(Class<?> lookupClass, int allowedModes) { 663 this.lookupClass = lookupClass; 664 this.allowedModes = allowedModes; 665 } 666 667 /** 668 * Creates a lookup on the specified new lookup class. 669 * The resulting object will report the specified 670 * class as its own {@link #lookupClass lookupClass}. 671 * <p> 672 * However, the resulting {@code Lookup} object is guaranteed 673 * to have no more access capabilities than the original. 674 * In particular, access capabilities can be lost as follows:<ul> 675 * <li>If the lookup class for this {@code Lookup} is not in a named module, 676 * and the new lookup class is in a named module {@code M}, then no members in 677 * {@code M}'s non-exported packages will be accessible. 678 * <li>If the lookup for this {@code Lookup} is in a named module, and the 679 * new lookup class is in a different module {@code M}, then no members, not even 680 * public members in {@code M}'s exported packages, will be accessible. 681 * <li>If the new lookup class differs from the old one, 682 * protected members will not be accessible by virtue of inheritance. 683 * (Protected members may continue to be accessible because of package sharing.) 684 * <li>If the new lookup class is in a different package 685 * than the old one, protected and default (package) members will not be accessible. 686 * <li>If the new lookup class is not within the same package member 687 * as the old one, private members will not be accessible. 688 * <li>If the new lookup class is not accessible to the old lookup class, 689 * then no members, not even public members, will be accessible. 690 * (In all other cases, public members will continue to be accessible.) 691 * </ul> 692 * <p> 693 * The resulting lookup's capabilities for loading classes 694 * (used during {@link #findClass} invocations) 695 * are determined by the lookup class' loader, 696 * which may change due to this operation. 697 * 698 * @param requestedLookupClass the desired lookup class for the new lookup object 699 * @return a lookup object which reports the desired lookup class 700 * @throws NullPointerException if the argument is null 701 */ 702 public Lookup in(Class<?> requestedLookupClass) { 703 Objects.requireNonNull(requestedLookupClass); 704 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 705 return new Lookup(requestedLookupClass, ALL_MODES); 706 if (requestedLookupClass == this.lookupClass) 707 return this; // keep same capabilities 708 709 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); 710 if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) { 711 // Allowed to teleport from an unnamed to a named module but resulting 712 // Lookup has no access to module private members 713 if (this.lookupClass.getModule().isNamed()) { 714 newModes = 0; 715 } else { 716 newModes &= ~MODULE; 717 } 718 } 719 if ((newModes & PACKAGE) != 0 720 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 721 newModes &= ~(PACKAGE|PRIVATE); 722 } 723 // Allow nestmate lookups to be created without special privilege: 724 if ((newModes & PRIVATE) != 0 725 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 726 newModes &= ~PRIVATE; 727 } 728 if ((newModes & PUBLIC) != 0 729 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { 730 // The requested class it not accessible from the lookup class. 731 // No permissions. 732 newModes = 0; 733 } 734 735 checkUnprivilegedlookupClass(requestedLookupClass, newModes); 736 return new Lookup(requestedLookupClass, newModes); 737 } 738 739 // Make sure outer class is initialized first. 740 static { IMPL_NAMES.getClass(); } 741 742 /** Package-private version of lookup which is trusted. */ 743 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); 744 745 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { 746 String name = lookupClass.getName(); 747 if (name.startsWith("java.lang.invoke.")) 748 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 749 750 // For caller-sensitive MethodHandles.lookup() disallow lookup from 751 // restricted packages. This a fragile and blunt approach. 752 // TODO replace with a more formal and less fragile mechanism 753 // that does not bluntly restrict classes under packages within 754 // java.base from looking up MethodHandles or VarHandles. 755 if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) { 756 if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) || 757 (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) { 758 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); 759 } 760 } 761 } 762 763 /** 764 * Displays the name of the class from which lookups are to be made. 765 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 766 * If there are restrictions on the access permitted to this lookup, 767 * this is indicated by adding a suffix to the class name, consisting 768 * of a slash and a keyword. The keyword represents the strongest 769 * allowed access, and is chosen as follows: 770 * <ul> 771 * <li>If no access is allowed, the suffix is "/noaccess". 772 * <li>If only public access to types in exported packages is allowed, the suffix is "/public". 773 * <li>If only public and module access are allowed, the suffix is "/module". 774 * <li>If only public, module and package access are allowed, the suffix is "/package". 775 * <li>If only public, module, package, and private access are allowed, the suffix is "/private". 776 * </ul> 777 * If none of the above cases apply, it is the case that full 778 * access (public, module, package, private, and protected) is allowed. 779 * In this case, no suffix is added. 780 * This is true only of an object obtained originally from 781 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 782 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 783 * always have restricted access, and will display a suffix. 784 * <p> 785 * (It may seem strange that protected access should be 786 * stronger than private access. Viewed independently from 787 * package access, protected access is the first to be lost, 788 * because it requires a direct subclass relationship between 789 * caller and callee.) 790 * @see #in 791 */ 792 @Override 793 public String toString() { 794 String cname = lookupClass.getName(); 795 switch (allowedModes) { 796 case 0: // no privileges 797 return cname + "/noaccess"; 798 case PUBLIC: 799 return cname + "/public"; 800 case PUBLIC|MODULE: 801 return cname + "/module"; 802 case PUBLIC|MODULE|PACKAGE: 803 return cname + "/package"; 804 case ALL_MODES & ~PROTECTED: 805 return cname + "/private"; 806 case ALL_MODES: 807 return cname; 808 case TRUSTED: 809 return "/trusted"; // internal only; not exported 810 default: // Should not happen, but it's a bitfield... 811 cname = cname + "/" + Integer.toHexString(allowedModes); 812 assert(false) : cname; 813 return cname; 814 } 815 } 816 817 /** 818 * Produces a method handle for a static method. 819 * The type of the method handle will be that of the method. 820 * (Since static methods do not take receivers, there is no 821 * additional receiver argument inserted into the method handle type, 822 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 823 * The method and all its argument types must be accessible to the lookup object. 824 * <p> 825 * The returned method handle will have 826 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 827 * the method's variable arity modifier bit ({@code 0x0080}) is set. 828 * <p> 829 * If the returned method handle is invoked, the method's class will 830 * be initialized, if it has not already been initialized. 831 * <p><b>Example:</b> 832 * <blockquote><pre>{@code 833 import static java.lang.invoke.MethodHandles.*; 834 import static java.lang.invoke.MethodType.*; 835 ... 836 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 837 "asList", methodType(List.class, Object[].class)); 838 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 839 * }</pre></blockquote> 840 * @param refc the class from which the method is accessed 841 * @param name the name of the method 842 * @param type the type of the method 843 * @return the desired method handle 844 * @throws NoSuchMethodException if the method does not exist 845 * @throws IllegalAccessException if access checking fails, 846 * or if the method is not {@code static}, 847 * or if the method's variable arity modifier bit 848 * is set and {@code asVarargsCollector} fails 849 * @exception SecurityException if a security manager is present and it 850 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 851 * @throws NullPointerException if any argument is null 852 */ 853 public 854 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 855 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 856 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method)); 857 } 858 859 /** 860 * Produces a method handle for a virtual method. 861 * The type of the method handle will be that of the method, 862 * with the receiver type (usually {@code refc}) prepended. 863 * The method and all its argument types must be accessible to the lookup object. 864 * <p> 865 * When called, the handle will treat the first argument as a receiver 866 * and dispatch on the receiver's type to determine which method 867 * implementation to enter. 868 * (The dispatching action is identical with that performed by an 869 * {@code invokevirtual} or {@code invokeinterface} instruction.) 870 * <p> 871 * The first argument will be of type {@code refc} if the lookup 872 * class has full privileges to access the member. Otherwise 873 * the member must be {@code protected} and the first argument 874 * will be restricted in type to the lookup class. 875 * <p> 876 * The returned method handle will have 877 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 878 * the method's variable arity modifier bit ({@code 0x0080}) is set. 879 * <p> 880 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 881 * instructions and method handles produced by {@code findVirtual}, 882 * if the class is {@code MethodHandle} and the name string is 883 * {@code invokeExact} or {@code invoke}, the resulting 884 * method handle is equivalent to one produced by 885 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 886 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 887 * with the same {@code type} argument. 888 * <p> 889 * If the class is {@code VarHandle} and the name string corresponds to 890 * the name of a signature-polymorphic access mode method, the resulting 891 * method handle is equivalent to one produced by 892 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with 893 * the access mode corresponding to the name string and with the same 894 * {@code type} arguments. 895 * <p> 896 * <b>Example:</b> 897 * <blockquote><pre>{@code 898 import static java.lang.invoke.MethodHandles.*; 899 import static java.lang.invoke.MethodType.*; 900 ... 901 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 902 "concat", methodType(String.class, String.class)); 903 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 904 "hashCode", methodType(int.class)); 905 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 906 "hashCode", methodType(int.class)); 907 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 908 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 909 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 910 // interface method: 911 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 912 "subSequence", methodType(CharSequence.class, int.class, int.class)); 913 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 914 // constructor "internal method" must be accessed differently: 915 MethodType MT_newString = methodType(void.class); //()V for new String() 916 try { assertEquals("impossible", lookup() 917 .findVirtual(String.class, "<init>", MT_newString)); 918 } catch (NoSuchMethodException ex) { } // OK 919 MethodHandle MH_newString = publicLookup() 920 .findConstructor(String.class, MT_newString); 921 assertEquals("", (String) MH_newString.invokeExact()); 922 * }</pre></blockquote> 923 * 924 * @param refc the class or interface from which the method is accessed 925 * @param name the name of the method 926 * @param type the type of the method, with the receiver argument omitted 927 * @return the desired method handle 928 * @throws NoSuchMethodException if the method does not exist 929 * @throws IllegalAccessException if access checking fails, 930 * or if the method is {@code static}, 931 * or if the method is {@code private} method of interface, 932 * or if the method's variable arity modifier bit 933 * is set and {@code asVarargsCollector} fails 934 * @exception SecurityException if a security manager is present and it 935 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 936 * @throws NullPointerException if any argument is null 937 */ 938 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 939 if (refc == MethodHandle.class) { 940 MethodHandle mh = findVirtualForMH(name, type); 941 if (mh != null) return mh; 942 } else if (refc == VarHandle.class) { 943 MethodHandle mh = findVirtualForVH(name, type); 944 if (mh != null) return mh; 945 } 946 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 947 MemberName method = resolveOrFail(refKind, refc, name, type); 948 return getDirectMethod(refKind, refc, method, findBoundCallerClass(method)); 949 } 950 private MethodHandle findVirtualForMH(String name, MethodType type) { 951 // these names require special lookups because of the implicit MethodType argument 952 if ("invoke".equals(name)) 953 return invoker(type); 954 if ("invokeExact".equals(name)) 955 return exactInvoker(type); 956 assert(!MemberName.isMethodHandleInvokeName(name)); 957 return null; 958 } 959 private MethodHandle findVirtualForVH(String name, MethodType type) { 960 try { 961 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); 962 } catch (IllegalArgumentException e) { 963 return null; 964 } 965 } 966 967 /** 968 * Produces a method handle which creates an object and initializes it, using 969 * the constructor of the specified type. 970 * The parameter types of the method handle will be those of the constructor, 971 * while the return type will be a reference to the constructor's class. 972 * The constructor and all its argument types must be accessible to the lookup object. 973 * <p> 974 * The requested type must have a return type of {@code void}. 975 * (This is consistent with the JVM's treatment of constructor type descriptors.) 976 * <p> 977 * The returned method handle will have 978 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 979 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 980 * <p> 981 * If the returned method handle is invoked, the constructor's class will 982 * be initialized, if it has not already been initialized. 983 * <p><b>Example:</b> 984 * <blockquote><pre>{@code 985 import static java.lang.invoke.MethodHandles.*; 986 import static java.lang.invoke.MethodType.*; 987 ... 988 MethodHandle MH_newArrayList = publicLookup().findConstructor( 989 ArrayList.class, methodType(void.class, Collection.class)); 990 Collection orig = Arrays.asList("x", "y"); 991 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 992 assert(orig != copy); 993 assertEquals(orig, copy); 994 // a variable-arity constructor: 995 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 996 ProcessBuilder.class, methodType(void.class, String[].class)); 997 ProcessBuilder pb = (ProcessBuilder) 998 MH_newProcessBuilder.invoke("x", "y", "z"); 999 assertEquals("[x, y, z]", pb.command().toString()); 1000 * }</pre></blockquote> 1001 * @param refc the class or interface from which the method is accessed 1002 * @param type the type of the method, with the receiver argument omitted, and a void return type 1003 * @return the desired method handle 1004 * @throws NoSuchMethodException if the constructor does not exist 1005 * @throws IllegalAccessException if access checking fails 1006 * or if the method's variable arity modifier bit 1007 * is set and {@code asVarargsCollector} fails 1008 * @exception SecurityException if a security manager is present and it 1009 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1010 * @throws NullPointerException if any argument is null 1011 */ 1012 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1013 if (refc.isArray()) { 1014 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 1015 } 1016 String name = "<init>"; 1017 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 1018 return getDirectConstructor(refc, ctor); 1019 } 1020 1021 /** 1022 * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static 1023 * initializer of the class is not run. 1024 * <p> 1025 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class 1026 * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to 1027 * load the requested class, and then determines whether the class is accessible to this lookup object. 1028 * 1029 * @param targetName the fully qualified name of the class to be looked up. 1030 * @return the requested class. 1031 * @exception SecurityException if a security manager is present and it 1032 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1033 * @throws LinkageError if the linkage fails 1034 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. 1035 * @throws IllegalAccessException if the class is not accessible, using the allowed access 1036 * modes. 1037 * @exception SecurityException if a security manager is present and it 1038 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1039 * @since 9 1040 */ 1041 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { 1042 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); 1043 return accessClass(targetClass); 1044 } 1045 1046 /** 1047 * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The 1048 * static initializer of the class is not run. 1049 * <p> 1050 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the 1051 * {@linkplain #lookupModes() lookup modes}. 1052 * 1053 * @param targetClass the class to be access-checked 1054 * 1055 * @return the class that has been access-checked 1056 * 1057 * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access 1058 * modes. 1059 * @exception SecurityException if a security manager is present and it 1060 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1061 * @since 9 1062 */ 1063 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { 1064 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) { 1065 throw new MemberName(targetClass).makeAccessException("access violation", this); 1066 } 1067 checkSecurityManager(targetClass, null); 1068 return targetClass; 1069 } 1070 1071 /** 1072 * Produces an early-bound method handle for a virtual method. 1073 * It will bypass checks for overriding methods on the receiver, 1074 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1075 * instruction from within the explicitly specified {@code specialCaller}. 1076 * The type of the method handle will be that of the method, 1077 * with a suitably restricted receiver type prepended. 1078 * (The receiver type will be {@code specialCaller} or a subtype.) 1079 * The method and all its argument types must be accessible 1080 * to the lookup object. 1081 * <p> 1082 * Before method resolution, 1083 * if the explicitly specified caller class is not identical with the 1084 * lookup class, or if this lookup object does not have 1085 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1086 * privileges, the access fails. 1087 * <p> 1088 * The returned method handle will have 1089 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1090 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1091 * <p style="font-size:smaller;"> 1092 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 1093 * even though the {@code invokespecial} instruction can refer to them 1094 * in special circumstances. Use {@link #findConstructor findConstructor} 1095 * to access instance initialization methods in a safe manner.)</em> 1096 * <p><b>Example:</b> 1097 * <blockquote><pre>{@code 1098 import static java.lang.invoke.MethodHandles.*; 1099 import static java.lang.invoke.MethodType.*; 1100 ... 1101 static class Listie extends ArrayList { 1102 public String toString() { return "[wee Listie]"; } 1103 static Lookup lookup() { return MethodHandles.lookup(); } 1104 } 1105 ... 1106 // no access to constructor via invokeSpecial: 1107 MethodHandle MH_newListie = Listie.lookup() 1108 .findConstructor(Listie.class, methodType(void.class)); 1109 Listie l = (Listie) MH_newListie.invokeExact(); 1110 try { assertEquals("impossible", Listie.lookup().findSpecial( 1111 Listie.class, "<init>", methodType(void.class), Listie.class)); 1112 } catch (NoSuchMethodException ex) { } // OK 1113 // access to super and self methods via invokeSpecial: 1114 MethodHandle MH_super = Listie.lookup().findSpecial( 1115 ArrayList.class, "toString" , methodType(String.class), Listie.class); 1116 MethodHandle MH_this = Listie.lookup().findSpecial( 1117 Listie.class, "toString" , methodType(String.class), Listie.class); 1118 MethodHandle MH_duper = Listie.lookup().findSpecial( 1119 Object.class, "toString" , methodType(String.class), Listie.class); 1120 assertEquals("[]", (String) MH_super.invokeExact(l)); 1121 assertEquals(""+l, (String) MH_this.invokeExact(l)); 1122 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 1123 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 1124 String.class, "toString", methodType(String.class), Listie.class)); 1125 } catch (IllegalAccessException ex) { } // OK 1126 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 1127 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 1128 * }</pre></blockquote> 1129 * 1130 * @param refc the class or interface from which the method is accessed 1131 * @param name the name of the method (which must not be "<init>") 1132 * @param type the type of the method, with the receiver argument omitted 1133 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 1134 * @return the desired method handle 1135 * @throws NoSuchMethodException if the method does not exist 1136 * @throws IllegalAccessException if access checking fails, 1137 * or if the method is {@code static}, 1138 * or if the method's variable arity modifier bit 1139 * is set and {@code asVarargsCollector} fails 1140 * @exception SecurityException if a security manager is present and it 1141 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1142 * @throws NullPointerException if any argument is null 1143 */ 1144 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 1145 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 1146 checkSpecialCaller(specialCaller, refc); 1147 Lookup specialLookup = this.in(specialCaller); 1148 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 1149 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1150 } 1151 1152 /** 1153 * Produces a method handle giving read access to a non-static field. 1154 * The type of the method handle will have a return type of the field's 1155 * value type. 1156 * The method handle's single argument will be the instance containing 1157 * the field. 1158 * Access checking is performed immediately on behalf of the lookup class. 1159 * @param refc the class or interface from which the method is accessed 1160 * @param name the field's name 1161 * @param type the field's type 1162 * @return a method handle which can load values from the field 1163 * @throws NoSuchFieldException if the field does not exist 1164 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1165 * @exception SecurityException if a security manager is present and it 1166 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1167 * @throws NullPointerException if any argument is null 1168 * @see #findVarHandle(Class, String, Class) 1169 */ 1170 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1171 MemberName field = resolveOrFail(REF_getField, refc, name, type); 1172 return getDirectField(REF_getField, refc, field); 1173 } 1174 1175 /** 1176 * Produces a method handle giving write access to a non-static field. 1177 * The type of the method handle will have a void return type. 1178 * The method handle will take two arguments, the instance containing 1179 * the field, and the value to be stored. 1180 * The second argument will be of the field's value type. 1181 * Access checking is performed immediately on behalf of the lookup class. 1182 * @param refc the class or interface from which the method is accessed 1183 * @param name the field's name 1184 * @param type the field's type 1185 * @return a method handle which can store values into the field 1186 * @throws NoSuchFieldException if the field does not exist 1187 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1188 * @exception SecurityException if a security manager is present and it 1189 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1190 * @throws NullPointerException if any argument is null 1191 * @see #findVarHandle(Class, String, Class) 1192 */ 1193 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1194 MemberName field = resolveOrFail(REF_putField, refc, name, type); 1195 return getDirectField(REF_putField, refc, field); 1196 } 1197 1198 /** 1199 * Produces a VarHandle giving access to non-static fields of type 1200 * {@code T} declared by a receiver class of type {@code R}, supporting 1201 * shape {@code (R : T)}. 1202 * <p> 1203 * Access checking is performed immediately on behalf of the lookup 1204 * class. 1205 * <p> 1206 * Certain access modes of the returned VarHandle are unsupported under 1207 * the following conditions: 1208 * <ul> 1209 * <li>if the field is declared {@code final}, then the write, atomic 1210 * update, and numeric atomic update access modes are unsupported. 1211 * <li>if the field type is anything other than {@code byte}, 1212 * {@code short}, {@code char}, {@code int} or {@code long}, 1213 * {@code float}, or {@code double} then numeric atomic update 1214 * access modes are unsupported. 1215 * </ul> 1216 * <p> 1217 * If the field is declared {@code volatile} then the returned VarHandle 1218 * will override access to the field (effectively ignore the 1219 * {@code volatile} declaration) in accordance to it's specified 1220 * access modes. 1221 * <p> 1222 * If the field type is {@code float} or {@code double} then numeric 1223 * and atomic update access modes compare values using their bitwise 1224 * representation (see {@link Float#floatToRawIntBits} and 1225 * {@link Double#doubleToRawLongBits}, respectively). 1226 * @apiNote 1227 * Bitwise comparison of {@code float} values or {@code double} values, 1228 * as performed by the numeric and atomic update access modes, differ 1229 * from the primitive {@code ==} operator and the {@link Float#equals} 1230 * and {@link Double#equals} methods, specifically with respect to 1231 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1232 * Care should be taken when performing a compare and set or a compare 1233 * and exchange operation with such values since the operation may 1234 * unexpectedly fail. 1235 * There are many possible NaN values that are considered to be 1236 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1237 * provided by Java can distinguish between them. Operation failure can 1238 * occur if the expected or witness value is a NaN value and it is 1239 * transformed (perhaps in a platform specific manner) into another NaN 1240 * value, and thus has a different bitwise representation (see 1241 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1242 * details). 1243 * The values {@code -0.0} and {@code +0.0} have different bitwise 1244 * representations but are considered equal when using the primitive 1245 * {@code ==} operator. Operation failure can occur if, for example, a 1246 * numeric algorithm computes an expected value to be say {@code -0.0} 1247 * and previously computed the witness value to be say {@code +0.0}. 1248 * @param recv the receiver class, of type {@code R}, that declares the 1249 * non-static field 1250 * @param name the field's name 1251 * @param type the field's type, of type {@code T} 1252 * @return a VarHandle giving access to non-static fields. 1253 * @throws NoSuchFieldException if the field does not exist 1254 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1255 * @exception SecurityException if a security manager is present and it 1256 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1257 * @throws NullPointerException if any argument is null 1258 * @since 9 1259 */ 1260 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1261 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 1262 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 1263 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 1264 } 1265 1266 /** 1267 * Produces a method handle giving read access to a static field. 1268 * The type of the method handle will have a return type of the field's 1269 * value type. 1270 * The method handle will take no arguments. 1271 * Access checking is performed immediately on behalf of the lookup class. 1272 * <p> 1273 * If the returned method handle is invoked, the field's class will 1274 * be initialized, if it has not already been initialized. 1275 * @param refc the class or interface from which the method is accessed 1276 * @param name the field's name 1277 * @param type the field's type 1278 * @return a method handle which can load values from the field 1279 * @throws NoSuchFieldException if the field does not exist 1280 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1281 * @exception SecurityException if a security manager is present and it 1282 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1283 * @throws NullPointerException if any argument is null 1284 */ 1285 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1286 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 1287 return getDirectField(REF_getStatic, refc, field); 1288 } 1289 1290 /** 1291 * Produces a method handle giving write access to a static field. 1292 * The type of the method handle will have a void return type. 1293 * The method handle will take a single 1294 * argument, of the field's value type, the value to be stored. 1295 * Access checking is performed immediately on behalf of the lookup class. 1296 * <p> 1297 * If the returned method handle is invoked, the field's class will 1298 * be initialized, if it has not already been initialized. 1299 * @param refc the class or interface from which the method is accessed 1300 * @param name the field's name 1301 * @param type the field's type 1302 * @return a method handle which can store values into the field 1303 * @throws NoSuchFieldException if the field does not exist 1304 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1305 * @exception SecurityException if a security manager is present and it 1306 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1307 * @throws NullPointerException if any argument is null 1308 */ 1309 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1310 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 1311 return getDirectField(REF_putStatic, refc, field); 1312 } 1313 1314 /** 1315 * Produces a VarHandle giving access to a static field of type 1316 * {@code T} declared by a given declaring class, supporting shape 1317 * {@code ((empty) : T)}. 1318 * <p> 1319 * Access checking is performed immediately on behalf of the lookup 1320 * class. 1321 * <p> 1322 * If the returned VarHandle is operated on, the declaring class will be 1323 * initialized, if it has not already been initialized. 1324 * <p> 1325 * Certain access modes of the returned VarHandle are unsupported under 1326 * the following conditions: 1327 * <ul> 1328 * <li>if the field is declared {@code final}, then the write, atomic 1329 * update, and numeric atomic update access modes are unsupported. 1330 * <li>if the field type is anything other than {@code byte}, 1331 * {@code short}, {@code char}, {@code int} or {@code long}, 1332 * {@code float}, or {@code double}, then numeric atomic update 1333 * access modes are unsupported. 1334 * </ul> 1335 * <p> 1336 * If the field is declared {@code volatile} then the returned VarHandle 1337 * will override access to the field (effectively ignore the 1338 * {@code volatile} declaration) in accordance to it's specified 1339 * access modes. 1340 * <p> 1341 * If the field type is {@code float} or {@code double} then numeric 1342 * and atomic update access modes compare values using their bitwise 1343 * representation (see {@link Float#floatToRawIntBits} and 1344 * {@link Double#doubleToRawLongBits}, respectively). 1345 * @apiNote 1346 * Bitwise comparison of {@code float} values or {@code double} values, 1347 * as performed by the numeric and atomic update access modes, differ 1348 * from the primitive {@code ==} operator and the {@link Float#equals} 1349 * and {@link Double#equals} methods, specifically with respect to 1350 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1351 * Care should be taken when performing a compare and set or a compare 1352 * and exchange operation with such values since the operation may 1353 * unexpectedly fail. 1354 * There are many possible NaN values that are considered to be 1355 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1356 * provided by Java can distinguish between them. Operation failure can 1357 * occur if the expected or witness value is a NaN value and it is 1358 * transformed (perhaps in a platform specific manner) into another NaN 1359 * value, and thus has a different bitwise representation (see 1360 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1361 * details). 1362 * The values {@code -0.0} and {@code +0.0} have different bitwise 1363 * representations but are considered equal when using the primitive 1364 * {@code ==} operator. Operation failure can occur if, for example, a 1365 * numeric algorithm computes an expected value to be say {@code -0.0} 1366 * and previously computed the witness value to be say {@code +0.0}. 1367 * @param decl the class that declares the static field 1368 * @param name the field's name 1369 * @param type the field's type, of type {@code T} 1370 * @return a VarHandle giving access to a static field 1371 * @throws NoSuchFieldException if the field does not exist 1372 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1373 * @exception SecurityException if a security manager is present and it 1374 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1375 * @throws NullPointerException if any argument is null 1376 * @since 9 1377 */ 1378 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1379 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 1380 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 1381 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 1382 } 1383 1384 /** 1385 * Produces an early-bound method handle for a non-static method. 1386 * The receiver must have a supertype {@code defc} in which a method 1387 * of the given name and type is accessible to the lookup class. 1388 * The method and all its argument types must be accessible to the lookup object. 1389 * The type of the method handle will be that of the method, 1390 * without any insertion of an additional receiver parameter. 1391 * The given receiver will be bound into the method handle, 1392 * so that every call to the method handle will invoke the 1393 * requested method on the given receiver. 1394 * <p> 1395 * The returned method handle will have 1396 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1397 * the method's variable arity modifier bit ({@code 0x0080}) is set 1398 * <em>and</em> the trailing array argument is not the only argument. 1399 * (If the trailing array argument is the only argument, 1400 * the given receiver value will be bound to it.) 1401 * <p> 1402 * This is equivalent to the following code: 1403 * <blockquote><pre>{@code 1404 import static java.lang.invoke.MethodHandles.*; 1405 import static java.lang.invoke.MethodType.*; 1406 ... 1407 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 1408 MethodHandle mh1 = mh0.bindTo(receiver); 1409 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 1410 return mh1; 1411 * }</pre></blockquote> 1412 * where {@code defc} is either {@code receiver.getClass()} or a super 1413 * type of that class, in which the requested method is accessible 1414 * to the lookup class. 1415 * (Note that {@code bindTo} does not preserve variable arity.) 1416 * @param receiver the object from which the method is accessed 1417 * @param name the name of the method 1418 * @param type the type of the method, with the receiver argument omitted 1419 * @return the desired method handle 1420 * @throws NoSuchMethodException if the method does not exist 1421 * @throws IllegalAccessException if access checking fails 1422 * or if the method's variable arity modifier bit 1423 * is set and {@code asVarargsCollector} fails 1424 * @exception SecurityException if a security manager is present and it 1425 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1426 * @throws NullPointerException if any argument is null 1427 * @see MethodHandle#bindTo 1428 * @see #findVirtual 1429 */ 1430 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1431 Class<? extends Object> refc = receiver.getClass(); // may get NPE 1432 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 1433 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1434 return mh.bindArgumentL(0, receiver).setVarargs(method); 1435 } 1436 1437 /** 1438 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1439 * to <i>m</i>, if the lookup class has permission. 1440 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 1441 * If <i>m</i> is virtual, overriding is respected on every call. 1442 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 1443 * The type of the method handle will be that of the method, 1444 * with the receiver type prepended (but only if it is non-static). 1445 * If the method's {@code accessible} flag is not set, 1446 * access checking is performed immediately on behalf of the lookup class. 1447 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 1448 * <p> 1449 * The returned method handle will have 1450 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1451 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1452 * <p> 1453 * If <i>m</i> is static, and 1454 * if the returned method handle is invoked, the method's class will 1455 * be initialized, if it has not already been initialized. 1456 * @param m the reflected method 1457 * @return a method handle which can invoke the reflected method 1458 * @throws IllegalAccessException if access checking fails 1459 * or if the method's variable arity modifier bit 1460 * is set and {@code asVarargsCollector} fails 1461 * @throws NullPointerException if the argument is null 1462 */ 1463 public MethodHandle unreflect(Method m) throws IllegalAccessException { 1464 if (m.getDeclaringClass() == MethodHandle.class) { 1465 MethodHandle mh = unreflectForMH(m); 1466 if (mh != null) return mh; 1467 } 1468 if (m.getDeclaringClass() == VarHandle.class) { 1469 MethodHandle mh = unreflectForVH(m); 1470 if (mh != null) return mh; 1471 } 1472 MemberName method = new MemberName(m); 1473 byte refKind = method.getReferenceKind(); 1474 if (refKind == REF_invokeSpecial) 1475 refKind = REF_invokeVirtual; 1476 assert(method.isMethod()); 1477 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 1478 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1479 } 1480 private MethodHandle unreflectForMH(Method m) { 1481 // these names require special lookups because they throw UnsupportedOperationException 1482 if (MemberName.isMethodHandleInvokeName(m.getName())) 1483 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 1484 return null; 1485 } 1486 private MethodHandle unreflectForVH(Method m) { 1487 // these names require special lookups because they throw UnsupportedOperationException 1488 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 1489 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 1490 return null; 1491 } 1492 1493 /** 1494 * Produces a method handle for a reflected method. 1495 * It will bypass checks for overriding methods on the receiver, 1496 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1497 * instruction from within the explicitly specified {@code specialCaller}. 1498 * The type of the method handle will be that of the method, 1499 * with a suitably restricted receiver type prepended. 1500 * (The receiver type will be {@code specialCaller} or a subtype.) 1501 * If the method's {@code accessible} flag is not set, 1502 * access checking is performed immediately on behalf of the lookup class, 1503 * as if {@code invokespecial} instruction were being linked. 1504 * <p> 1505 * Before method resolution, 1506 * if the explicitly specified caller class is not identical with the 1507 * lookup class, or if this lookup object does not have 1508 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1509 * privileges, the access fails. 1510 * <p> 1511 * The returned method handle will have 1512 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1513 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1514 * @param m the reflected method 1515 * @param specialCaller the class nominally calling the method 1516 * @return a method handle which can invoke the reflected method 1517 * @throws IllegalAccessException if access checking fails, 1518 * or if the method is {@code static}, 1519 * or if the method's variable arity modifier bit 1520 * is set and {@code asVarargsCollector} fails 1521 * @throws NullPointerException if any argument is null 1522 */ 1523 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 1524 checkSpecialCaller(specialCaller, null); 1525 Lookup specialLookup = this.in(specialCaller); 1526 MemberName method = new MemberName(m, true); 1527 assert(method.isMethod()); 1528 // ignore m.isAccessible: this is a new kind of access 1529 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1530 } 1531 1532 /** 1533 * Produces a method handle for a reflected constructor. 1534 * The type of the method handle will be that of the constructor, 1535 * with the return type changed to the declaring class. 1536 * The method handle will perform a {@code newInstance} operation, 1537 * creating a new instance of the constructor's class on the 1538 * arguments passed to the method handle. 1539 * <p> 1540 * If the constructor's {@code accessible} flag is not set, 1541 * access checking is performed immediately on behalf of the lookup class. 1542 * <p> 1543 * The returned method handle will have 1544 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1545 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1546 * <p> 1547 * If the returned method handle is invoked, the constructor's class will 1548 * be initialized, if it has not already been initialized. 1549 * @param c the reflected constructor 1550 * @return a method handle which can invoke the reflected constructor 1551 * @throws IllegalAccessException if access checking fails 1552 * or if the method's variable arity modifier bit 1553 * is set and {@code asVarargsCollector} fails 1554 * @throws NullPointerException if the argument is null 1555 */ 1556 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 1557 MemberName ctor = new MemberName(c); 1558 assert(ctor.isConstructor()); 1559 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 1560 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 1561 } 1562 1563 /** 1564 * Produces a method handle giving read access to a reflected field. 1565 * The type of the method handle will have a return type of the field's 1566 * value type. 1567 * If the field is static, the method handle will take no arguments. 1568 * Otherwise, its single argument will be the instance containing 1569 * the field. 1570 * If the field's {@code accessible} flag is not set, 1571 * access checking is performed immediately on behalf of the lookup class. 1572 * <p> 1573 * If the field is static, and 1574 * if the returned method handle is invoked, the field's class will 1575 * be initialized, if it has not already been initialized. 1576 * @param f the reflected field 1577 * @return a method handle which can load values from the reflected field 1578 * @throws IllegalAccessException if access checking fails 1579 * @throws NullPointerException if the argument is null 1580 */ 1581 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1582 return unreflectField(f, false); 1583 } 1584 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 1585 MemberName field = new MemberName(f, isSetter); 1586 assert(isSetter 1587 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 1588 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 1589 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 1590 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 1591 } 1592 1593 /** 1594 * Produces a method handle giving write access to a reflected field. 1595 * The type of the method handle will have a void return type. 1596 * If the field is static, the method handle will take a single 1597 * argument, of the field's value type, the value to be stored. 1598 * Otherwise, the two arguments will be the instance containing 1599 * the field, and the value to be stored. 1600 * If the field's {@code accessible} flag is not set, 1601 * access checking is performed immediately on behalf of the lookup class. 1602 * <p> 1603 * If the field is static, and 1604 * if the returned method handle is invoked, the field's class will 1605 * be initialized, if it has not already been initialized. 1606 * @param f the reflected field 1607 * @return a method handle which can store values into the reflected field 1608 * @throws IllegalAccessException if access checking fails 1609 * @throws NullPointerException if the argument is null 1610 */ 1611 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1612 return unreflectField(f, true); 1613 } 1614 1615 /** 1616 * Produces a VarHandle that accesses fields of type {@code T} declared 1617 * by a class of type {@code R}, as described by the given reflected 1618 * field. 1619 * If the field is non-static the VarHandle supports a shape of 1620 * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}. 1621 * <p> 1622 * Access checking is performed immediately on behalf of the lookup 1623 * class, regardless of the value of the field's {@code accessible} 1624 * flag. 1625 * <p> 1626 * If the field is static, and if the returned VarHandle is operated 1627 * on, the field's declaring class will be initialized, if it has not 1628 * already been initialized. 1629 * <p> 1630 * Certain access modes of the returned VarHandle are unsupported under 1631 * the following conditions: 1632 * <ul> 1633 * <li>if the field is declared {@code final}, then the write, atomic 1634 * update, and numeric atomic update access modes are unsupported. 1635 * <li>if the field type is anything other than {@code byte}, 1636 * {@code short}, {@code char}, {@code int} or {@code long}, 1637 * {@code float}, or {@code double} then numeric atomic update 1638 * access modes are unsupported. 1639 * </ul> 1640 * <p> 1641 * If the field is declared {@code volatile} then the returned VarHandle 1642 * will override access to the field (effectively ignore the 1643 * {@code volatile} declaration) in accordance to it's specified 1644 * access modes. 1645 * <p> 1646 * If the field type is {@code float} or {@code double} then numeric 1647 * and atomic update access modes compare values using their bitwise 1648 * representation (see {@link Float#floatToRawIntBits} and 1649 * {@link Double#doubleToRawLongBits}, respectively). 1650 * @apiNote 1651 * Bitwise comparison of {@code float} values or {@code double} values, 1652 * as performed by the numeric and atomic update access modes, differ 1653 * from the primitive {@code ==} operator and the {@link Float#equals} 1654 * and {@link Double#equals} methods, specifically with respect to 1655 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1656 * Care should be taken when performing a compare and set or a compare 1657 * and exchange operation with such values since the operation may 1658 * unexpectedly fail. 1659 * There are many possible NaN values that are considered to be 1660 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1661 * provided by Java can distinguish between them. Operation failure can 1662 * occur if the expected or witness value is a NaN value and it is 1663 * transformed (perhaps in a platform specific manner) into another NaN 1664 * value, and thus has a different bitwise representation (see 1665 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1666 * details). 1667 * The values {@code -0.0} and {@code +0.0} have different bitwise 1668 * representations but are considered equal when using the primitive 1669 * {@code ==} operator. Operation failure can occur if, for example, a 1670 * numeric algorithm computes an expected value to be say {@code -0.0} 1671 * and previously computed the witness value to be say {@code +0.0}. 1672 * @param f the reflected field, with a field of type {@code T}, and 1673 * a declaring class of type {@code R} 1674 * @return a VarHandle giving access to non-static fields or a static 1675 * field 1676 * @throws IllegalAccessException if access checking fails 1677 * @throws NullPointerException if the argument is null 1678 * @since 9 1679 */ 1680 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 1681 MemberName getField = new MemberName(f, false); 1682 MemberName putField = new MemberName(f, true); 1683 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 1684 f.getDeclaringClass(), getField, putField); 1685 } 1686 1687 /** 1688 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1689 * created by this lookup object or a similar one. 1690 * Security and access checks are performed to ensure that this lookup object 1691 * is capable of reproducing the target method handle. 1692 * This means that the cracking may fail if target is a direct method handle 1693 * but was created by an unrelated lookup object. 1694 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 1695 * and was created by a lookup object for a different class. 1696 * @param target a direct method handle to crack into symbolic reference components 1697 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 1698 * @exception SecurityException if a security manager is present and it 1699 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1700 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 1701 * @exception NullPointerException if the target is {@code null} 1702 * @see MethodHandleInfo 1703 * @since 1.8 1704 */ 1705 public MethodHandleInfo revealDirect(MethodHandle target) { 1706 MemberName member = target.internalMemberName(); 1707 if (member == null || (!member.isResolved() && 1708 !member.isMethodHandleInvoke() && 1709 !member.isVarHandleMethodInvoke())) 1710 throw newIllegalArgumentException("not a direct method handle"); 1711 Class<?> defc = member.getDeclaringClass(); 1712 byte refKind = member.getReferenceKind(); 1713 assert(MethodHandleNatives.refKindIsValid(refKind)); 1714 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 1715 // Devirtualized method invocation is usually formally virtual. 1716 // To avoid creating extra MemberName objects for this common case, 1717 // we encode this extra degree of freedom using MH.isInvokeSpecial. 1718 refKind = REF_invokeVirtual; 1719 if (refKind == REF_invokeVirtual && defc.isInterface()) 1720 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 1721 refKind = REF_invokeInterface; 1722 // Check SM permissions and member access before cracking. 1723 try { 1724 checkAccess(refKind, defc, member); 1725 checkSecurityManager(defc, member); 1726 } catch (IllegalAccessException ex) { 1727 throw new IllegalArgumentException(ex); 1728 } 1729 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 1730 Class<?> callerClass = target.internalCallerClass(); 1731 if (!hasPrivateAccess() || callerClass != lookupClass()) 1732 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 1733 } 1734 // Produce the handle to the results. 1735 return new InfoFromMemberName(this, member, refKind); 1736 } 1737 1738 /// Helper methods, all package-private. 1739 1740 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1741 checkSymbolicClass(refc); // do this before attempting to resolve 1742 Objects.requireNonNull(name); 1743 Objects.requireNonNull(type); 1744 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1745 NoSuchFieldException.class); 1746 } 1747 1748 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1749 checkSymbolicClass(refc); // do this before attempting to resolve 1750 Objects.requireNonNull(name); 1751 Objects.requireNonNull(type); 1752 checkMethodName(refKind, name); // NPE check on name 1753 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1754 NoSuchMethodException.class); 1755 } 1756 1757 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 1758 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 1759 Objects.requireNonNull(member.getName()); 1760 Objects.requireNonNull(member.getType()); 1761 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), 1762 ReflectiveOperationException.class); 1763 } 1764 1765 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 1766 Objects.requireNonNull(refc); 1767 Class<?> caller = lookupClassOrNull(); 1768 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) 1769 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 1770 } 1771 1772 /** Check name for an illegal leading "<" character. */ 1773 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 1774 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 1775 throw new NoSuchMethodException("illegal method name: "+name); 1776 } 1777 1778 1779 /** 1780 * Find my trustable caller class if m is a caller sensitive method. 1781 * If this lookup object has private access, then the caller class is the lookupClass. 1782 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 1783 */ 1784 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { 1785 Class<?> callerClass = null; 1786 if (MethodHandleNatives.isCallerSensitive(m)) { 1787 // Only lookups with private access are allowed to resolve caller-sensitive methods 1788 if (hasPrivateAccess()) { 1789 callerClass = lookupClass; 1790 } else { 1791 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 1792 } 1793 } 1794 return callerClass; 1795 } 1796 1797 private boolean hasPrivateAccess() { 1798 return (allowedModes & PRIVATE) != 0; 1799 } 1800 1801 /** 1802 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 1803 * Determines a trustable caller class to compare with refc, the symbolic reference class. 1804 * If this lookup object has private access, then the caller class is the lookupClass. 1805 */ 1806 void checkSecurityManager(Class<?> refc, MemberName m) { 1807 SecurityManager smgr = System.getSecurityManager(); 1808 if (smgr == null) return; 1809 if (allowedModes == TRUSTED) return; 1810 1811 // Step 1: 1812 boolean fullPowerLookup = hasPrivateAccess(); 1813 if (!fullPowerLookup || 1814 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 1815 ReflectUtil.checkPackageAccess(refc); 1816 } 1817 1818 if (m == null) { // findClass or accessClass 1819 // Step 2b: 1820 if (!fullPowerLookup) { 1821 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1822 } 1823 return; 1824 } 1825 1826 // Step 2a: 1827 if (m.isPublic()) return; 1828 if (!fullPowerLookup) { 1829 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 1830 } 1831 1832 // Step 3: 1833 Class<?> defc = m.getDeclaringClass(); 1834 if (!fullPowerLookup && defc != refc) { 1835 ReflectUtil.checkPackageAccess(defc); 1836 } 1837 } 1838 1839 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1840 boolean wantStatic = (refKind == REF_invokeStatic); 1841 String message; 1842 if (m.isConstructor()) 1843 message = "expected a method, not a constructor"; 1844 else if (!m.isMethod()) 1845 message = "expected a method"; 1846 else if (wantStatic != m.isStatic()) 1847 message = wantStatic ? "expected a static method" : "expected a non-static method"; 1848 else 1849 { checkAccess(refKind, refc, m); return; } 1850 throw m.makeAccessException(message, this); 1851 } 1852 1853 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1854 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 1855 String message; 1856 if (wantStatic != m.isStatic()) 1857 message = wantStatic ? "expected a static field" : "expected a non-static field"; 1858 else 1859 { checkAccess(refKind, refc, m); return; } 1860 throw m.makeAccessException(message, this); 1861 } 1862 1863 /** Check public/protected/private bits on the symbolic reference class and its member. */ 1864 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1865 assert(m.referenceKindIsConsistentWith(refKind) && 1866 MethodHandleNatives.refKindIsValid(refKind) && 1867 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 1868 int allowedModes = this.allowedModes; 1869 if (allowedModes == TRUSTED) return; 1870 int mods = m.getModifiers(); 1871 if (Modifier.isProtected(mods) && 1872 refKind == REF_invokeVirtual && 1873 m.getDeclaringClass() == Object.class && 1874 m.getName().equals("clone") && 1875 refc.isArray()) { 1876 // The JVM does this hack also. 1877 // (See ClassVerifier::verify_invoke_instructions 1878 // and LinkResolver::check_method_accessability.) 1879 // Because the JVM does not allow separate methods on array types, 1880 // there is no separate method for int[].clone. 1881 // All arrays simply inherit Object.clone. 1882 // But for access checking logic, we make Object.clone 1883 // (normally protected) appear to be public. 1884 // Later on, when the DirectMethodHandle is created, 1885 // its leading argument will be restricted to the 1886 // requested array type. 1887 // N.B. The return type is not adjusted, because 1888 // that is *not* the bytecode behavior. 1889 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 1890 } 1891 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 1892 // cannot "new" a protected ctor in a different package 1893 mods ^= Modifier.PROTECTED; 1894 } 1895 if (Modifier.isFinal(mods) && 1896 MethodHandleNatives.refKindIsSetter(refKind)) 1897 throw m.makeAccessException("unexpected set of a final field", this); 1898 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1899 if ((requestedModes & allowedModes) != 0) { 1900 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 1901 mods, lookupClass(), allowedModes)) 1902 return; 1903 } else { 1904 // Protected members can also be checked as if they were package-private. 1905 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1906 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 1907 return; 1908 } 1909 throw m.makeAccessException(accessFailedMessage(refc, m), this); 1910 } 1911 1912 String accessFailedMessage(Class<?> refc, MemberName m) { 1913 Class<?> defc = m.getDeclaringClass(); 1914 int mods = m.getModifiers(); 1915 // check the class first: 1916 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1917 (defc == refc || 1918 Modifier.isPublic(refc.getModifiers()))); 1919 if (!classOK && (allowedModes & PACKAGE) != 0) { 1920 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1921 (defc == refc || 1922 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1923 } 1924 if (!classOK) 1925 return "class is not public"; 1926 if (Modifier.isPublic(mods)) 1927 return "access to public member failed"; // (how?, module not readable?) 1928 if (Modifier.isPrivate(mods)) 1929 return "member is private"; 1930 if (Modifier.isProtected(mods)) 1931 return "member is protected"; 1932 return "member is private to package"; 1933 } 1934 1935 private static final boolean ALLOW_NESTMATE_ACCESS = false; 1936 1937 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 1938 int allowedModes = this.allowedModes; 1939 if (allowedModes == TRUSTED) return; 1940 if (!hasPrivateAccess() 1941 || (specialCaller != lookupClass() 1942 // ensure non-abstract methods in superinterfaces can be special-invoked 1943 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)) 1944 && !(ALLOW_NESTMATE_ACCESS && 1945 VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) 1946 throw new MemberName(specialCaller). 1947 makeAccessException("no private access for invokespecial", this); 1948 } 1949 1950 private boolean restrictProtectedReceiver(MemberName method) { 1951 // The accessing class only has the right to use a protected member 1952 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 1953 if (!method.isProtected() || method.isStatic() 1954 || allowedModes == TRUSTED 1955 || method.getDeclaringClass() == lookupClass() 1956 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) 1957 || (ALLOW_NESTMATE_ACCESS && 1958 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) 1959 return false; 1960 return true; 1961 } 1962 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 1963 assert(!method.isStatic()); 1964 // receiver type of mh is too wide; narrow to caller 1965 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 1966 throw method.makeAccessException("caller class must be a subclass below the method", caller); 1967 } 1968 MethodType rawType = mh.type(); 1969 if (rawType.parameterType(0) == caller) return mh; 1970 MethodType narrowType = rawType.changeParameterType(0, caller); 1971 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 1972 assert(mh.viewAsTypeChecks(narrowType, true)); 1973 return mh.copyWith(narrowType, mh.form); 1974 } 1975 1976 /** Check access and get the requested method. */ 1977 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1978 final boolean doRestrict = true; 1979 final boolean checkSecurity = true; 1980 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1981 } 1982 /** Check access and get the requested method, eliding receiver narrowing rules. */ 1983 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1984 final boolean doRestrict = false; 1985 final boolean checkSecurity = true; 1986 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1987 } 1988 /** Check access and get the requested method, eliding security manager checks. */ 1989 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1990 final boolean doRestrict = true; 1991 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1992 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1993 } 1994 /** Common code for all methods; do not call directly except from immediately above. */ 1995 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 1996 boolean checkSecurity, 1997 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { 1998 checkMethod(refKind, refc, method); 1999 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2000 if (checkSecurity) 2001 checkSecurityManager(refc, method); 2002 assert(!method.isMethodHandleInvoke()); 2003 2004 if (refKind == REF_invokeSpecial && 2005 refc != lookupClass() && 2006 !refc.isInterface() && 2007 refc != lookupClass().getSuperclass() && 2008 refc.isAssignableFrom(lookupClass())) { 2009 assert(!method.getName().equals("<init>")); // not this code path 2010 // Per JVMS 6.5, desc. of invokespecial instruction: 2011 // If the method is in a superclass of the LC, 2012 // and if our original search was above LC.super, 2013 // repeat the search (symbolic lookup) from LC.super 2014 // and continue with the direct superclass of that class, 2015 // and so forth, until a match is found or no further superclasses exist. 2016 // FIXME: MemberName.resolve should handle this instead. 2017 Class<?> refcAsSuper = lookupClass(); 2018 MemberName m2; 2019 do { 2020 refcAsSuper = refcAsSuper.getSuperclass(); 2021 m2 = new MemberName(refcAsSuper, 2022 method.getName(), 2023 method.getMethodType(), 2024 REF_invokeSpecial); 2025 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 2026 } while (m2 == null && // no method is found yet 2027 refc != refcAsSuper); // search up to refc 2028 if (m2 == null) throw new InternalError(method.toString()); 2029 method = m2; 2030 refc = refcAsSuper; 2031 // redo basic checks 2032 checkMethod(refKind, refc, method); 2033 } 2034 2035 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); 2036 MethodHandle mh = dmh; 2037 // Optionally narrow the receiver argument to refc using restrictReceiver. 2038 if (doRestrict && 2039 (refKind == REF_invokeSpecial || 2040 (MethodHandleNatives.refKindHasReceiver(refKind) && 2041 restrictProtectedReceiver(method)))) { 2042 mh = restrictReceiver(method, dmh, lookupClass()); 2043 } 2044 mh = maybeBindCaller(method, mh, callerClass); 2045 mh = mh.setVarargs(method); 2046 return mh; 2047 } 2048 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 2049 Class<?> callerClass) 2050 throws IllegalAccessException { 2051 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 2052 return mh; 2053 Class<?> hostClass = lookupClass; 2054 if (!hasPrivateAccess()) // caller must have private access 2055 hostClass = callerClass; // callerClass came from a security manager style stack walk 2056 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 2057 // Note: caller will apply varargs after this step happens. 2058 return cbmh; 2059 } 2060 /** Check access and get the requested field. */ 2061 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2062 final boolean checkSecurity = true; 2063 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2064 } 2065 /** Check access and get the requested field, eliding security manager checks. */ 2066 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2067 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2068 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2069 } 2070 /** Common code for all fields; do not call directly except from immediately above. */ 2071 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 2072 boolean checkSecurity) throws IllegalAccessException { 2073 checkField(refKind, refc, field); 2074 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2075 if (checkSecurity) 2076 checkSecurityManager(refc, field); 2077 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 2078 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 2079 restrictProtectedReceiver(field)); 2080 if (doRestrict) 2081 return restrictReceiver(field, dmh, lookupClass()); 2082 return dmh; 2083 } 2084 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 2085 Class<?> refc, MemberName getField, MemberName putField) 2086 throws IllegalAccessException { 2087 final boolean checkSecurity = true; 2088 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2089 } 2090 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 2091 Class<?> refc, MemberName getField, MemberName putField) 2092 throws IllegalAccessException { 2093 final boolean checkSecurity = false; 2094 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2095 } 2096 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 2097 Class<?> refc, MemberName getField, MemberName putField, 2098 boolean checkSecurity) throws IllegalAccessException { 2099 assert getField.isStatic() == putField.isStatic(); 2100 assert getField.isGetter() && putField.isSetter(); 2101 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 2102 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 2103 2104 checkField(getRefKind, refc, getField); 2105 if (checkSecurity) 2106 checkSecurityManager(refc, getField); 2107 2108 if (!putField.isFinal()) { 2109 // A VarHandle does not support updates to final fields, any 2110 // such VarHandle to a final field will be read-only and 2111 // therefore the following write-based accessibility checks are 2112 // only required for non-final fields 2113 checkField(putRefKind, refc, putField); 2114 if (checkSecurity) 2115 checkSecurityManager(refc, putField); 2116 } 2117 2118 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 2119 restrictProtectedReceiver(getField)); 2120 if (doRestrict) { 2121 assert !getField.isStatic(); 2122 // receiver type of VarHandle is too wide; narrow to caller 2123 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 2124 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 2125 } 2126 refc = lookupClass(); 2127 } 2128 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); 2129 } 2130 /** Check access and get the requested constructor. */ 2131 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2132 final boolean checkSecurity = true; 2133 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2134 } 2135 /** Check access and get the requested constructor, eliding security manager checks. */ 2136 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2137 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2138 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2139 } 2140 /** Common code for all constructors; do not call directly except from immediately above. */ 2141 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 2142 boolean checkSecurity) throws IllegalAccessException { 2143 assert(ctor.isConstructor()); 2144 checkAccess(REF_newInvokeSpecial, refc, ctor); 2145 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2146 if (checkSecurity) 2147 checkSecurityManager(refc, ctor); 2148 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 2149 return DirectMethodHandle.make(ctor).setVarargs(ctor); 2150 } 2151 2152 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 2153 */ 2154 /*non-public*/ 2155 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 2156 if (!(type instanceof Class || type instanceof MethodType)) 2157 throw new InternalError("unresolved MemberName"); 2158 MemberName member = new MemberName(refKind, defc, name, type); 2159 MethodHandle mh = LOOKASIDE_TABLE.get(member); 2160 if (mh != null) { 2161 checkSymbolicClass(defc); 2162 return mh; 2163 } 2164 // Treat MethodHandle.invoke and invokeExact specially. 2165 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 2166 mh = findVirtualForMH(member.getName(), member.getMethodType()); 2167 if (mh != null) { 2168 return mh; 2169 } 2170 } 2171 MemberName resolved = resolveOrFail(refKind, member); 2172 mh = getDirectMethodForConstant(refKind, defc, resolved); 2173 if (mh instanceof DirectMethodHandle 2174 && canBeCached(refKind, defc, resolved)) { 2175 MemberName key = mh.internalMemberName(); 2176 if (key != null) { 2177 key = key.asNormalOriginal(); 2178 } 2179 if (member.equals(key)) { // better safe than sorry 2180 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 2181 } 2182 } 2183 return mh; 2184 } 2185 private 2186 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 2187 if (refKind == REF_invokeSpecial) { 2188 return false; 2189 } 2190 if (!Modifier.isPublic(defc.getModifiers()) || 2191 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 2192 !member.isPublic() || 2193 member.isCallerSensitive()) { 2194 return false; 2195 } 2196 ClassLoader loader = defc.getClassLoader(); 2197 if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { 2198 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 2199 boolean found = false; 2200 while (sysl != null) { 2201 if (loader == sysl) { found = true; break; } 2202 sysl = sysl.getParent(); 2203 } 2204 if (!found) { 2205 return false; 2206 } 2207 } 2208 try { 2209 MemberName resolved2 = publicLookup().resolveOrFail(refKind, 2210 new MemberName(refKind, defc, member.getName(), member.getType())); 2211 checkSecurityManager(defc, resolved2); 2212 } catch (ReflectiveOperationException | SecurityException ex) { 2213 return false; 2214 } 2215 return true; 2216 } 2217 private 2218 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 2219 throws ReflectiveOperationException { 2220 if (MethodHandleNatives.refKindIsField(refKind)) { 2221 return getDirectFieldNoSecurityManager(refKind, defc, member); 2222 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 2223 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 2224 } else if (refKind == REF_newInvokeSpecial) { 2225 return getDirectConstructorNoSecurityManager(defc, member); 2226 } 2227 // oops 2228 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 2229 } 2230 2231 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 2232 } 2233 2234 /** 2235 * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class 2236 * in an <em>unnamed module</em>. 2237 * 2238 * @see Lookup#publicLookup 2239 */ 2240 private static class LookupHelper { 2241 private static final String UNNAMED = "Unnamed"; 2242 private static final String OBJECT = "java/lang/Object"; 2243 2244 private static Class<?> createClass() { 2245 try { 2246 ClassWriter cw = new ClassWriter(0); 2247 cw.visit(Opcodes.V1_8, 2248 Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, 2249 UNNAMED, 2250 null, 2251 OBJECT, 2252 null); 2253 cw.visitSource(UNNAMED, null); 2254 cw.visitEnd(); 2255 byte[] bytes = cw.toByteArray(); 2256 ClassLoader loader = new ClassLoader(null) { 2257 @Override 2258 protected Class<?> findClass(String cn) throws ClassNotFoundException { 2259 if (cn.equals(UNNAMED)) 2260 return super.defineClass(UNNAMED, bytes, 0, bytes.length); 2261 throw new ClassNotFoundException(cn); 2262 } 2263 }; 2264 return loader.loadClass(UNNAMED); 2265 } catch (Exception e) { 2266 throw new InternalError(e); 2267 } 2268 } 2269 2270 private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass(); 2271 2272 /** 2273 * Lookup that is trusted minimally. It can only be used to create 2274 * method handles to publicly accessible members in exported packages. 2275 * 2276 * @see MethodHandles#publicLookup 2277 */ 2278 static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC); 2279 } 2280 2281 /** 2282 * Produces a method handle constructing arrays of a desired type. 2283 * The return type of the method handle will be the array type. 2284 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2285 * @param arrayClass an array type 2286 * @return a method handle which can create arrays of the given type 2287 * @throws NullPointerException if the argument is {@code null} 2288 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2289 * @see java.lang.reflect.Array#newInstance(Class, int) 2290 * @since 9 2291 */ 2292 public static 2293 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2294 if (!arrayClass.isArray()) { 2295 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2296 } 2297 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2298 bindTo(arrayClass.getComponentType()); 2299 return ani.asType(ani.type().changeReturnType(arrayClass)); 2300 } 2301 2302 /** 2303 * Produces a method handle returning the length of an array. 2304 * The type of the method handle will have {@code int} as return type, 2305 * and its sole argument will be the array type. 2306 * @param arrayClass an array type 2307 * @return a method handle which can retrieve the length of an array of the given array type 2308 * @throws NullPointerException if the argument is {@code null} 2309 * @throws IllegalArgumentException if arrayClass is not an array type 2310 * @since 9 2311 */ 2312 public static 2313 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 2314 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 2315 } 2316 2317 /** 2318 * Produces a method handle giving read access to elements of an array. 2319 * The type of the method handle will have a return type of the array's 2320 * element type. Its first argument will be the array type, 2321 * and the second will be {@code int}. 2322 * @param arrayClass an array type 2323 * @return a method handle which can load values from the given array type 2324 * @throws NullPointerException if the argument is null 2325 * @throws IllegalArgumentException if arrayClass is not an array type 2326 */ 2327 public static 2328 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2329 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 2330 } 2331 2332 /** 2333 * Produces a method handle giving write access to elements of an array. 2334 * The type of the method handle will have a void return type. 2335 * Its last argument will be the array's element type. 2336 * The first and second arguments will be the array type and int. 2337 * @param arrayClass the class of an array 2338 * @return a method handle which can store values into the array type 2339 * @throws NullPointerException if the argument is null 2340 * @throws IllegalArgumentException if arrayClass is not an array type 2341 */ 2342 public static 2343 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2344 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 2345 } 2346 2347 /** 2348 * 2349 * Produces a VarHandle giving access to elements of an array type 2350 * {@code T[]}, supporting shape {@code (T[], int : T)}. 2351 * <p> 2352 * Certain access modes of the returned VarHandle are unsupported under 2353 * the following conditions: 2354 * <ul> 2355 * <li>if the component type is anything other than {@code byte}, 2356 * {@code short}, {@code char}, {@code int} or {@code long}, 2357 * {@code float}, or {@code double} then numeric atomic update access 2358 * modes are unsupported. 2359 * </ul> 2360 * <p> 2361 * If the component type is {@code float} or {@code double} then numeric 2362 * and atomic update access modes compare values using their bitwise 2363 * representation (see {@link Float#floatToRawIntBits} and 2364 * {@link Double#doubleToRawLongBits}, respectively). 2365 * @apiNote 2366 * Bitwise comparison of {@code float} values or {@code double} values, 2367 * as performed by the numeric and atomic update access modes, differ 2368 * from the primitive {@code ==} operator and the {@link Float#equals} 2369 * and {@link Double#equals} methods, specifically with respect to 2370 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2371 * Care should be taken when performing a compare and set or a compare 2372 * and exchange operation with such values since the operation may 2373 * unexpectedly fail. 2374 * There are many possible NaN values that are considered to be 2375 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2376 * provided by Java can distinguish between them. Operation failure can 2377 * occur if the expected or witness value is a NaN value and it is 2378 * transformed (perhaps in a platform specific manner) into another NaN 2379 * value, and thus has a different bitwise representation (see 2380 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2381 * details). 2382 * The values {@code -0.0} and {@code +0.0} have different bitwise 2383 * representations but are considered equal when using the primitive 2384 * {@code ==} operator. Operation failure can occur if, for example, a 2385 * numeric algorithm computes an expected value to be say {@code -0.0} 2386 * and previously computed the witness value to be say {@code +0.0}. 2387 * @param arrayClass the class of an array, of type {@code T[]} 2388 * @return a VarHandle giving access to elements of an array 2389 * @throws NullPointerException if the arrayClass is null 2390 * @throws IllegalArgumentException if arrayClass is not an array type 2391 * @since 9 2392 */ 2393 public static 2394 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2395 return VarHandles.makeArrayElementHandle(arrayClass); 2396 } 2397 2398 /** 2399 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2400 * viewed as if it were a different primitive array type, such as 2401 * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is 2402 * {@code (byte[], int : T)}, where the {@code int} coordinate type 2403 * corresponds to an argument that is an index in a {@code byte[]} array, 2404 * and {@code T} is the component type of the given view array class. The 2405 * returned VarHandle accesses bytes at an index in a {@code byte[]} array, 2406 * composing bytes to or from a value of {@code T} according to the given 2407 * endianness. 2408 * <p> 2409 * The supported component types (variables types) are {@code short}, 2410 * {@code char}, {@code int}, {@code long}, {@code float} and 2411 * {@code double}. 2412 * <p> 2413 * Access of bytes at a given index will result in an 2414 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2415 * or greater than the {@code byte[]} array length minus the size (in bytes) 2416 * of {@code T}. 2417 * <p> 2418 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2419 * with respect to the underlying memory address, {@code A} say, associated 2420 * with the array and index. 2421 * If access is misaligned then access for anything other than the 2422 * {@code get} and {@code set} access modes will result in an 2423 * {@code IllegalStateException}. In such cases atomic access is only 2424 * guaranteed with respect to the largest power of two that divides the GCD 2425 * of {@code A} and the size (in bytes) of {@code T}. 2426 * If access is aligned then following access modes are supported and are 2427 * guaranteed to support atomic access: 2428 * <ul> 2429 * <li>read write access modes for all {@code T}; 2430 * <li>atomic update access modes for {@code int}, {@code long}, 2431 * {@code float} or {@code double}. 2432 * (Future major platform releases of the JDK may support additional 2433 * types for certain currently unsupported access modes.) 2434 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2435 * (Future major platform releases of the JDK may support additional 2436 * numeric types for certain currently unsupported access modes.) 2437 * </ul> 2438 * <p> 2439 * Misaligned access, and therefore atomicity guarantees, may be determined 2440 * for {@code byte[]} arrays without operating on a specific array. Given 2441 * an {@code index}, {@code T} and it's corresponding boxed type, 2442 * {@code T_BOX}, misalignment may be determined as follows: 2443 * <pre>{@code 2444 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2445 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2446 * alignmentOffset(0, sizeOfT); 2447 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2448 * boolean isMisaligned = misalignedAtIndex != 0; 2449 * }</pre> 2450 * <p> 2451 * If the variable type is {@code float} or {@code double} then atomic 2452 * update access modes compare values using their bitwise representation 2453 * (see {@link Float#floatToRawIntBits} and 2454 * {@link Double#doubleToRawLongBits}, respectively). 2455 * @param viewArrayClass the view array class, with a component type of 2456 * type {@code T} 2457 * @param byteOrder the endianness of the view array elements, as 2458 * stored in the underlying {@code byte} array 2459 * @return a VarHandle giving access to elements of a {@code byte[]} array 2460 * viewed as if elements corresponding to the components type of the view 2461 * array class 2462 * @throws NullPointerException if viewArrayClass or byteOrder is null 2463 * @throws IllegalArgumentException if viewArrayClass is not an array type 2464 * @throws UnsupportedOperationException if the component type of 2465 * viewArrayClass is not supported as a variable type 2466 * @since 9 2467 */ 2468 public static 2469 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2470 ByteOrder byteOrder) throws IllegalArgumentException { 2471 Objects.requireNonNull(byteOrder); 2472 return VarHandles.byteArrayViewHandle(viewArrayClass, 2473 byteOrder == ByteOrder.BIG_ENDIAN); 2474 } 2475 2476 /** 2477 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2478 * viewed as if it were an array of elements of a different primitive 2479 * component type to that of {@code byte}, such as {@code int[]} or 2480 * {@code long[]}. The shape of the resulting VarHandle is 2481 * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type 2482 * corresponds to an argument that is an index in a {@code ByteBuffer}, and 2483 * {@code T} is the component type of the given view array class. The 2484 * returned VarHandle accesses bytes at an index in a {@code ByteBuffer}, 2485 * composing bytes to or from a value of {@code T} according to the given 2486 * endianness. 2487 * <p> 2488 * The supported component types (variables types) are {@code short}, 2489 * {@code char}, {@code int}, {@code long}, {@code float} and 2490 * {@code double}. 2491 * <p> 2492 * Access will result in a {@code ReadOnlyBufferException} for anything 2493 * other than the read access modes if the {@code ByteBuffer} is read-only. 2494 * <p> 2495 * Access of bytes at a given index will result in an 2496 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2497 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2498 * {@code T}. 2499 * <p> 2500 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2501 * with respect to the underlying memory address, {@code A} say, associated 2502 * with the {@code ByteBuffer} and index. 2503 * If access is misaligned then access for anything other than the 2504 * {@code get} and {@code set} access modes will result in an 2505 * {@code IllegalStateException}. In such cases atomic access is only 2506 * guaranteed with respect to the largest power of two that divides the GCD 2507 * of {@code A} and the size (in bytes) of {@code T}. 2508 * If access is aligned then following access modes are supported and are 2509 * guaranteed to support atomic access: 2510 * <ul> 2511 * <li>read write access modes for all {@code T}; 2512 * <li>atomic update access modes for {@code int}, {@code long}, 2513 * {@code float} or {@code double}. 2514 * (Future major platform releases of the JDK may support additional 2515 * types for certain currently unsupported access modes.) 2516 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2517 * (Future major platform releases of the JDK may support additional 2518 * numeric types for certain currently unsupported access modes.) 2519 * </ul> 2520 * <p> 2521 * Misaligned access, and therefore atomicity guarantees, may be determined 2522 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2523 * {@code index}, {@code T} and it's corresponding boxed type, 2524 * {@code T_BOX}, as follows: 2525 * <pre>{@code 2526 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2527 * ByteBuffer bb = ... 2528 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2529 * boolean isMisaligned = misalignedAtIndex != 0; 2530 * }</pre> 2531 * <p> 2532 * If the variable type is {@code float} or {@code double} then atomic 2533 * update access modes compare values using their bitwise representation 2534 * (see {@link Float#floatToRawIntBits} and 2535 * {@link Double#doubleToRawLongBits}, respectively). 2536 * @param viewArrayClass the view array class, with a component type of 2537 * type {@code T} 2538 * @param byteOrder the endianness of the view array elements, as 2539 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2540 * endianness of a {@code ByteBuffer}) 2541 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2542 * viewed as if elements corresponding to the components type of the view 2543 * array class 2544 * @throws NullPointerException if viewArrayClass or byteOrder is null 2545 * @throws IllegalArgumentException if viewArrayClass is not an array type 2546 * @throws UnsupportedOperationException if the component type of 2547 * viewArrayClass is not supported as a variable type 2548 * @since 9 2549 */ 2550 public static 2551 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2552 ByteOrder byteOrder) throws IllegalArgumentException { 2553 Objects.requireNonNull(byteOrder); 2554 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 2555 byteOrder == ByteOrder.BIG_ENDIAN); 2556 } 2557 2558 2559 /// method handle invocation (reflective style) 2560 2561 /** 2562 * Produces a method handle which will invoke any method handle of the 2563 * given {@code type}, with a given number of trailing arguments replaced by 2564 * a single trailing {@code Object[]} array. 2565 * The resulting invoker will be a method handle with the following 2566 * arguments: 2567 * <ul> 2568 * <li>a single {@code MethodHandle} target 2569 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2570 * <li>an {@code Object[]} array containing trailing arguments 2571 * </ul> 2572 * <p> 2573 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2574 * the indicated {@code type}. 2575 * That is, if the target is exactly of the given {@code type}, it will behave 2576 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2577 * is used to convert the target to the required {@code type}. 2578 * <p> 2579 * The type of the returned invoker will not be the given {@code type}, but rather 2580 * will have all parameters except the first {@code leadingArgCount} 2581 * replaced by a single array of type {@code Object[]}, which will be 2582 * the final parameter. 2583 * <p> 2584 * Before invoking its target, the invoker will spread the final array, apply 2585 * reference casts as necessary, and unbox and widen primitive arguments. 2586 * If, when the invoker is called, the supplied array argument does 2587 * not have the correct number of elements, the invoker will throw 2588 * an {@link IllegalArgumentException} instead of invoking the target. 2589 * <p> 2590 * This method is equivalent to the following code (though it may be more efficient): 2591 * <blockquote><pre>{@code 2592 MethodHandle invoker = MethodHandles.invoker(type); 2593 int spreadArgCount = type.parameterCount() - leadingArgCount; 2594 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2595 return invoker; 2596 * }</pre></blockquote> 2597 * This method throws no reflective or security exceptions. 2598 * @param type the desired target type 2599 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2600 * @return a method handle suitable for invoking any method handle of the given type 2601 * @throws NullPointerException if {@code type} is null 2602 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2603 * the range from 0 to {@code type.parameterCount()} inclusive, 2604 * or if the resulting method handle's type would have 2605 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2606 */ 2607 public static 2608 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2609 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2610 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2611 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 2612 return type.invokers().spreadInvoker(leadingArgCount); 2613 } 2614 2615 /** 2616 * Produces a special <em>invoker method handle</em> which can be used to 2617 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2618 * The resulting invoker will have a type which is 2619 * exactly equal to the desired type, except that it will accept 2620 * an additional leading argument of type {@code MethodHandle}. 2621 * <p> 2622 * This method is equivalent to the following code (though it may be more efficient): 2623 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2624 * 2625 * <p style="font-size:smaller;"> 2626 * <em>Discussion:</em> 2627 * Invoker method handles can be useful when working with variable method handles 2628 * of unknown types. 2629 * For example, to emulate an {@code invokeExact} call to a variable method 2630 * handle {@code M}, extract its type {@code T}, 2631 * look up the invoker method {@code X} for {@code T}, 2632 * and call the invoker method, as {@code X.invoke(T, A...)}. 2633 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2634 * is unknown.) 2635 * If spreading, collecting, or other argument transformations are required, 2636 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2637 * method handle values, as long as they are compatible with the type of {@code X}. 2638 * <p style="font-size:smaller;"> 2639 * <em>(Note: The invoker method is not available via the Core Reflection API. 2640 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2641 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2642 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2643 * <p> 2644 * This method throws no reflective or security exceptions. 2645 * @param type the desired target type 2646 * @return a method handle suitable for invoking any method handle of the given type 2647 * @throws IllegalArgumentException if the resulting method handle's type would have 2648 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2649 */ 2650 public static 2651 MethodHandle exactInvoker(MethodType type) { 2652 return type.invokers().exactInvoker(); 2653 } 2654 2655 /** 2656 * Produces a special <em>invoker method handle</em> which can be used to 2657 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2658 * The resulting invoker will have a type which is 2659 * exactly equal to the desired type, except that it will accept 2660 * an additional leading argument of type {@code MethodHandle}. 2661 * <p> 2662 * Before invoking its target, if the target differs from the expected type, 2663 * the invoker will apply reference casts as 2664 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 2665 * Similarly, the return value will be converted as necessary. 2666 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 2667 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 2668 * <p> 2669 * This method is equivalent to the following code (though it may be more efficient): 2670 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 2671 * <p style="font-size:smaller;"> 2672 * <em>Discussion:</em> 2673 * A {@linkplain MethodType#genericMethodType general method type} is one which 2674 * mentions only {@code Object} arguments and return values. 2675 * An invoker for such a type is capable of calling any method handle 2676 * of the same arity as the general type. 2677 * <p style="font-size:smaller;"> 2678 * <em>(Note: The invoker method is not available via the Core Reflection API. 2679 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2680 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2681 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2682 * <p> 2683 * This method throws no reflective or security exceptions. 2684 * @param type the desired target type 2685 * @return a method handle suitable for invoking any method handle convertible to the given type 2686 * @throws IllegalArgumentException if the resulting method handle's type would have 2687 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2688 */ 2689 public static 2690 MethodHandle invoker(MethodType type) { 2691 return type.invokers().genericInvoker(); 2692 } 2693 2694 /** 2695 * Produces a special <em>invoker method handle</em> which can be used to 2696 * invoke a signature-polymorphic access mode method on any VarHandle whose 2697 * associated access mode type is compatible with the given type. 2698 * The resulting invoker will have a type which is exactly equal to the 2699 * desired given type, except that it will accept an additional leading 2700 * argument of type {@code VarHandle}. 2701 * 2702 * @param accessMode the VarHandle access mode 2703 * @param type the desired target type 2704 * @return a method handle suitable for invoking an access mode method of 2705 * any VarHandle whose access mode type is of the given type. 2706 * @since 9 2707 */ 2708 static public 2709 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2710 return type.invokers().varHandleMethodExactInvoker(accessMode); 2711 } 2712 2713 /** 2714 * Produces a special <em>invoker method handle</em> which can be used to 2715 * invoke a signature-polymorphic access mode method on any VarHandle whose 2716 * associated access mode type is compatible with the given type. 2717 * The resulting invoker will have a type which is exactly equal to the 2718 * desired given type, except that it will accept an additional leading 2719 * argument of type {@code VarHandle}. 2720 * <p> 2721 * Before invoking its target, if the access mode type differs from the 2722 * desired given type, the invoker will apply reference casts as necessary 2723 * and box, unbox, or widen primitive values, as if by 2724 * {@link MethodHandle#asType asType}. Similarly, the return value will be 2725 * converted as necessary. 2726 * <p> 2727 * This method is equivalent to the following code (though it may be more 2728 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 2729 * 2730 * @param accessMode the VarHandle access mode 2731 * @param type the desired target type 2732 * @return a method handle suitable for invoking an access mode method of 2733 * any VarHandle whose access mode type is convertible to the given 2734 * type. 2735 * @since 9 2736 */ 2737 static public 2738 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2739 return type.invokers().varHandleMethodInvoker(accessMode); 2740 } 2741 2742 static /*non-public*/ 2743 MethodHandle basicInvoker(MethodType type) { 2744 return type.invokers().basicInvoker(); 2745 } 2746 2747 /// method handle modification (creation from other method handles) 2748 2749 /** 2750 * Produces a method handle which adapts the type of the 2751 * given method handle to a new type by pairwise argument and return type conversion. 2752 * The original type and new type must have the same number of arguments. 2753 * The resulting method handle is guaranteed to report a type 2754 * which is equal to the desired new type. 2755 * <p> 2756 * If the original type and new type are equal, returns target. 2757 * <p> 2758 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 2759 * and some additional conversions are also applied if those conversions fail. 2760 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 2761 * if possible, before or instead of any conversions done by {@code asType}: 2762 * <ul> 2763 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 2764 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 2765 * (This treatment of interfaces follows the usage of the bytecode verifier.) 2766 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 2767 * the boolean is converted to a byte value, 1 for true, 0 for false. 2768 * (This treatment follows the usage of the bytecode verifier.) 2769 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 2770 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 2771 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 2772 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 2773 * then a Java casting conversion (JLS 5.5) is applied. 2774 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 2775 * widening and/or narrowing.) 2776 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 2777 * conversion will be applied at runtime, possibly followed 2778 * by a Java casting conversion (JLS 5.5) on the primitive value, 2779 * possibly followed by a conversion from byte to boolean by testing 2780 * the low-order bit. 2781 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2782 * and if the reference is null at runtime, a zero value is introduced. 2783 * </ul> 2784 * @param target the method handle to invoke after arguments are retyped 2785 * @param newType the expected type of the new method handle 2786 * @return a method handle which delegates to the target after performing 2787 * any necessary argument conversions, and arranges for any 2788 * necessary return value conversions 2789 * @throws NullPointerException if either argument is null 2790 * @throws WrongMethodTypeException if the conversion cannot be made 2791 * @see MethodHandle#asType 2792 */ 2793 public static 2794 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2795 explicitCastArgumentsChecks(target, newType); 2796 // use the asTypeCache when possible: 2797 MethodType oldType = target.type(); 2798 if (oldType == newType) return target; 2799 if (oldType.explicitCastEquivalentToAsType(newType)) { 2800 return target.asFixedArity().asType(newType); 2801 } 2802 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 2803 } 2804 2805 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 2806 if (target.type().parameterCount() != newType.parameterCount()) { 2807 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 2808 } 2809 } 2810 2811 /** 2812 * Produces a method handle which adapts the calling sequence of the 2813 * given method handle to a new type, by reordering the arguments. 2814 * The resulting method handle is guaranteed to report a type 2815 * which is equal to the desired new type. 2816 * <p> 2817 * The given array controls the reordering. 2818 * Call {@code #I} the number of incoming parameters (the value 2819 * {@code newType.parameterCount()}, and call {@code #O} the number 2820 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2821 * Then the length of the reordering array must be {@code #O}, 2822 * and each element must be a non-negative number less than {@code #I}. 2823 * For every {@code N} less than {@code #O}, the {@code N}-th 2824 * outgoing argument will be taken from the {@code I}-th incoming 2825 * argument, where {@code I} is {@code reorder[N]}. 2826 * <p> 2827 * No argument or return value conversions are applied. 2828 * The type of each incoming argument, as determined by {@code newType}, 2829 * must be identical to the type of the corresponding outgoing parameter 2830 * or parameters in the target method handle. 2831 * The return type of {@code newType} must be identical to the return 2832 * type of the original target. 2833 * <p> 2834 * The reordering array need not specify an actual permutation. 2835 * An incoming argument will be duplicated if its index appears 2836 * more than once in the array, and an incoming argument will be dropped 2837 * if its index does not appear in the array. 2838 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2839 * incoming arguments which are not mentioned in the reordering array 2840 * may be of any type, as determined only by {@code newType}. 2841 * <blockquote><pre>{@code 2842 import static java.lang.invoke.MethodHandles.*; 2843 import static java.lang.invoke.MethodType.*; 2844 ... 2845 MethodType intfn1 = methodType(int.class, int.class); 2846 MethodType intfn2 = methodType(int.class, int.class, int.class); 2847 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2848 assert(sub.type().equals(intfn2)); 2849 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2850 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2851 assert((int)rsub.invokeExact(1, 100) == 99); 2852 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2853 assert(add.type().equals(intfn2)); 2854 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2855 assert(twice.type().equals(intfn1)); 2856 assert((int)twice.invokeExact(21) == 42); 2857 * }</pre></blockquote> 2858 * <p> 2859 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 2860 * variable-arity method handle}, even if the original target method handle was. 2861 * @param target the method handle to invoke after arguments are reordered 2862 * @param newType the expected type of the new method handle 2863 * @param reorder an index array which controls the reordering 2864 * @return a method handle which delegates to the target after it 2865 * drops unused arguments and moves and/or duplicates the other arguments 2866 * @throws NullPointerException if any argument is null 2867 * @throws IllegalArgumentException if the index array length is not equal to 2868 * the arity of the target, or if any index array element 2869 * not a valid index for a parameter of {@code newType}, 2870 * or if two corresponding parameter types in 2871 * {@code target.type()} and {@code newType} are not identical, 2872 */ 2873 public static 2874 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2875 reorder = reorder.clone(); // get a private copy 2876 MethodType oldType = target.type(); 2877 permuteArgumentChecks(reorder, newType, oldType); 2878 // first detect dropped arguments and handle them separately 2879 int[] originalReorder = reorder; 2880 BoundMethodHandle result = target.rebind(); 2881 LambdaForm form = result.form; 2882 int newArity = newType.parameterCount(); 2883 // Normalize the reordering into a real permutation, 2884 // by removing duplicates and adding dropped elements. 2885 // This somewhat improves lambda form caching, as well 2886 // as simplifying the transform by breaking it up into steps. 2887 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 2888 if (ddIdx > 0) { 2889 // We found a duplicated entry at reorder[ddIdx]. 2890 // Example: (x,y,z)->asList(x,y,z) 2891 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 2892 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 2893 // The starred element corresponds to the argument 2894 // deleted by the dupArgumentForm transform. 2895 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 2896 boolean killFirst = false; 2897 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 2898 // Set killFirst if the dup is larger than an intervening position. 2899 // This will remove at least one inversion from the permutation. 2900 if (dupVal > val) killFirst = true; 2901 } 2902 if (!killFirst) { 2903 srcPos = dstPos; 2904 dstPos = ddIdx; 2905 } 2906 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 2907 assert (reorder[srcPos] == reorder[dstPos]); 2908 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 2909 // contract the reordering by removing the element at dstPos 2910 int tailPos = dstPos + 1; 2911 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 2912 reorder = Arrays.copyOf(reorder, reorder.length - 1); 2913 } else { 2914 int dropVal = ~ddIdx, insPos = 0; 2915 while (insPos < reorder.length && reorder[insPos] < dropVal) { 2916 // Find first element of reorder larger than dropVal. 2917 // This is where we will insert the dropVal. 2918 insPos += 1; 2919 } 2920 Class<?> ptype = newType.parameterType(dropVal); 2921 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 2922 oldType = oldType.insertParameterTypes(insPos, ptype); 2923 // expand the reordering by inserting an element at insPos 2924 int tailPos = insPos + 1; 2925 reorder = Arrays.copyOf(reorder, reorder.length + 1); 2926 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 2927 reorder[insPos] = dropVal; 2928 } 2929 assert (permuteArgumentChecks(reorder, newType, oldType)); 2930 } 2931 assert (reorder.length == newArity); // a perfect permutation 2932 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 2933 form = form.editor().permuteArgumentsForm(1, reorder); 2934 if (newType == result.type() && form == result.internalForm()) 2935 return result; 2936 return result.copyWith(newType, form); 2937 } 2938 2939 /** 2940 * Return an indication of any duplicate or omission in reorder. 2941 * If the reorder contains a duplicate entry, return the index of the second occurrence. 2942 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 2943 * Otherwise, return zero. 2944 * If an element not in [0..newArity-1] is encountered, return reorder.length. 2945 */ 2946 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 2947 final int BIT_LIMIT = 63; // max number of bits in bit mask 2948 if (newArity < BIT_LIMIT) { 2949 long mask = 0; 2950 for (int i = 0; i < reorder.length; i++) { 2951 int arg = reorder[i]; 2952 if (arg >= newArity) { 2953 return reorder.length; 2954 } 2955 long bit = 1L << arg; 2956 if ((mask & bit) != 0) { 2957 return i; // >0 indicates a dup 2958 } 2959 mask |= bit; 2960 } 2961 if (mask == (1L << newArity) - 1) { 2962 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 2963 return 0; 2964 } 2965 // find first zero 2966 long zeroBit = Long.lowestOneBit(~mask); 2967 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 2968 assert(zeroPos <= newArity); 2969 if (zeroPos == newArity) { 2970 return 0; 2971 } 2972 return ~zeroPos; 2973 } else { 2974 // same algorithm, different bit set 2975 BitSet mask = new BitSet(newArity); 2976 for (int i = 0; i < reorder.length; i++) { 2977 int arg = reorder[i]; 2978 if (arg >= newArity) { 2979 return reorder.length; 2980 } 2981 if (mask.get(arg)) { 2982 return i; // >0 indicates a dup 2983 } 2984 mask.set(arg); 2985 } 2986 int zeroPos = mask.nextClearBit(0); 2987 assert(zeroPos <= newArity); 2988 if (zeroPos == newArity) { 2989 return 0; 2990 } 2991 return ~zeroPos; 2992 } 2993 } 2994 2995 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 2996 if (newType.returnType() != oldType.returnType()) 2997 throw newIllegalArgumentException("return types do not match", 2998 oldType, newType); 2999 if (reorder.length == oldType.parameterCount()) { 3000 int limit = newType.parameterCount(); 3001 boolean bad = false; 3002 for (int j = 0; j < reorder.length; j++) { 3003 int i = reorder[j]; 3004 if (i < 0 || i >= limit) { 3005 bad = true; break; 3006 } 3007 Class<?> src = newType.parameterType(i); 3008 Class<?> dst = oldType.parameterType(j); 3009 if (src != dst) 3010 throw newIllegalArgumentException("parameter types do not match after reorder", 3011 oldType, newType); 3012 } 3013 if (!bad) return true; 3014 } 3015 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 3016 } 3017 3018 /** 3019 * Produces a method handle of the requested return type which returns the given 3020 * constant value every time it is invoked. 3021 * <p> 3022 * Before the method handle is returned, the passed-in value is converted to the requested type. 3023 * If the requested type is primitive, widening primitive conversions are attempted, 3024 * else reference conversions are attempted. 3025 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 3026 * @param type the return type of the desired method handle 3027 * @param value the value to return 3028 * @return a method handle of the given return type and no arguments, which always returns the given value 3029 * @throws NullPointerException if the {@code type} argument is null 3030 * @throws ClassCastException if the value cannot be converted to the required return type 3031 * @throws IllegalArgumentException if the given type is {@code void.class} 3032 */ 3033 public static 3034 MethodHandle constant(Class<?> type, Object value) { 3035 if (type.isPrimitive()) { 3036 if (type == void.class) 3037 throw newIllegalArgumentException("void type"); 3038 Wrapper w = Wrapper.forPrimitiveType(type); 3039 value = w.convert(value, type); 3040 if (w.zero().equals(value)) 3041 return zero(w, type); 3042 return insertArguments(identity(type), 0, value); 3043 } else { 3044 if (value == null) 3045 return zero(Wrapper.OBJECT, type); 3046 return identity(type).bindTo(value); 3047 } 3048 } 3049 3050 /** 3051 * Produces a method handle which returns its sole argument when invoked. 3052 * @param type the type of the sole parameter and return value of the desired method handle 3053 * @return a unary method handle which accepts and returns the given type 3054 * @throws NullPointerException if the argument is null 3055 * @throws IllegalArgumentException if the given type is {@code void.class} 3056 */ 3057 public static 3058 MethodHandle identity(Class<?> type) { 3059 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 3060 int pos = btw.ordinal(); 3061 MethodHandle ident = IDENTITY_MHS[pos]; 3062 if (ident == null) { 3063 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 3064 } 3065 if (ident.type().returnType() == type) 3066 return ident; 3067 // something like identity(Foo.class); do not bother to intern these 3068 assert (btw == Wrapper.OBJECT); 3069 return makeIdentity(type); 3070 } 3071 3072 /** 3073 * Produces a constant method handle of the requested return type which 3074 * returns the default value for that type every time it is invoked. 3075 * The resulting constant method handle will have no side effects. 3076 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 3077 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 3078 * since {@code explicitCastArguments} converts {@code null} to default values. 3079 * @param type the expected return type of the desired method handle 3080 * @return a constant method handle that takes no arguments 3081 * and returns the default value of the given type (or void, if the type is void) 3082 * @throws NullPointerException if the argument is null 3083 * @see MethodHandles#constant 3084 * @see MethodHandles#empty 3085 * @see MethodHandles#explicitCastArguments 3086 * @since 9 3087 */ 3088 public static MethodHandle zero(Class<?> type) { 3089 Objects.requireNonNull(type); 3090 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 3091 } 3092 3093 private static MethodHandle identityOrVoid(Class<?> type) { 3094 return type == void.class ? zero(type) : identity(type); 3095 } 3096 3097 /** 3098 * Produces a method handle of the requested type which ignores any arguments, does nothing, 3099 * and returns a suitable default depending on the return type. 3100 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 3101 * <p>The returned method handle is equivalent to 3102 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 3103 * <p> 3104 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 3105 * {@code guardWithTest(pred, target, empty(target.type())}. 3106 * @param type the type of the desired method handle 3107 * @return a constant method handle of the given type, which returns a default value of the given return type 3108 * @throws NullPointerException if the argument is null 3109 * @see MethodHandles#zero 3110 * @see MethodHandles#constant 3111 * @since 9 3112 */ 3113 public static MethodHandle empty(MethodType type) { 3114 Objects.requireNonNull(type); 3115 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 3116 } 3117 3118 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 3119 private static MethodHandle makeIdentity(Class<?> ptype) { 3120 MethodType mtype = methodType(ptype, ptype); 3121 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 3122 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 3123 } 3124 3125 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 3126 int pos = btw.ordinal(); 3127 MethodHandle zero = ZERO_MHS[pos]; 3128 if (zero == null) { 3129 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 3130 } 3131 if (zero.type().returnType() == rtype) 3132 return zero; 3133 assert(btw == Wrapper.OBJECT); 3134 return makeZero(rtype); 3135 } 3136 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 3137 private static MethodHandle makeZero(Class<?> rtype) { 3138 MethodType mtype = methodType(rtype); 3139 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 3140 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 3141 } 3142 3143 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 3144 // Simulate a CAS, to avoid racy duplication of results. 3145 MethodHandle prev = cache[pos]; 3146 if (prev != null) return prev; 3147 return cache[pos] = value; 3148 } 3149 3150 /** 3151 * Provides a target method handle with one or more <em>bound arguments</em> 3152 * in advance of the method handle's invocation. 3153 * The formal parameters to the target corresponding to the bound 3154 * arguments are called <em>bound parameters</em>. 3155 * Returns a new method handle which saves away the bound arguments. 3156 * When it is invoked, it receives arguments for any non-bound parameters, 3157 * binds the saved arguments to their corresponding parameters, 3158 * and calls the original target. 3159 * <p> 3160 * The type of the new method handle will drop the types for the bound 3161 * parameters from the original target type, since the new method handle 3162 * will no longer require those arguments to be supplied by its callers. 3163 * <p> 3164 * Each given argument object must match the corresponding bound parameter type. 3165 * If a bound parameter type is a primitive, the argument object 3166 * must be a wrapper, and will be unboxed to produce the primitive value. 3167 * <p> 3168 * The {@code pos} argument selects which parameters are to be bound. 3169 * It may range between zero and <i>N-L</i> (inclusively), 3170 * where <i>N</i> is the arity of the target method handle 3171 * and <i>L</i> is the length of the values array. 3172 * <p> 3173 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3174 * variable-arity method handle}, even if the original target method handle was. 3175 * @param target the method handle to invoke after the argument is inserted 3176 * @param pos where to insert the argument (zero for the first) 3177 * @param values the series of arguments to insert 3178 * @return a method handle which inserts an additional argument, 3179 * before calling the original method handle 3180 * @throws NullPointerException if the target or the {@code values} array is null 3181 * @see MethodHandle#bindTo 3182 */ 3183 public static 3184 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3185 int insCount = values.length; 3186 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3187 if (insCount == 0) return target; 3188 BoundMethodHandle result = target.rebind(); 3189 for (int i = 0; i < insCount; i++) { 3190 Object value = values[i]; 3191 Class<?> ptype = ptypes[pos+i]; 3192 if (ptype.isPrimitive()) { 3193 result = insertArgumentPrimitive(result, pos, ptype, value); 3194 } else { 3195 value = ptype.cast(value); // throw CCE if needed 3196 result = result.bindArgumentL(pos, value); 3197 } 3198 } 3199 return result; 3200 } 3201 3202 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3203 Class<?> ptype, Object value) { 3204 Wrapper w = Wrapper.forPrimitiveType(ptype); 3205 // perform unboxing and/or primitive conversion 3206 value = w.convert(value, ptype); 3207 switch (w) { 3208 case INT: return result.bindArgumentI(pos, (int)value); 3209 case LONG: return result.bindArgumentJ(pos, (long)value); 3210 case FLOAT: return result.bindArgumentF(pos, (float)value); 3211 case DOUBLE: return result.bindArgumentD(pos, (double)value); 3212 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3213 } 3214 } 3215 3216 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3217 MethodType oldType = target.type(); 3218 int outargs = oldType.parameterCount(); 3219 int inargs = outargs - insCount; 3220 if (inargs < 0) 3221 throw newIllegalArgumentException("too many values to insert"); 3222 if (pos < 0 || pos > inargs) 3223 throw newIllegalArgumentException("no argument type to append"); 3224 return oldType.ptypes(); 3225 } 3226 3227 /** 3228 * Produces a method handle which will discard some dummy arguments 3229 * before calling some other specified <i>target</i> method handle. 3230 * The type of the new method handle will be the same as the target's type, 3231 * except it will also include the dummy argument types, 3232 * at some given position. 3233 * <p> 3234 * The {@code pos} argument may range between zero and <i>N</i>, 3235 * where <i>N</i> is the arity of the target. 3236 * If {@code pos} is zero, the dummy arguments will precede 3237 * the target's real arguments; if {@code pos} is <i>N</i> 3238 * they will come after. 3239 * <p> 3240 * <b>Example:</b> 3241 * <blockquote><pre>{@code 3242 import static java.lang.invoke.MethodHandles.*; 3243 import static java.lang.invoke.MethodType.*; 3244 ... 3245 MethodHandle cat = lookup().findVirtual(String.class, 3246 "concat", methodType(String.class, String.class)); 3247 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3248 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3249 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3250 assertEquals(bigType, d0.type()); 3251 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3252 * }</pre></blockquote> 3253 * <p> 3254 * This method is also equivalent to the following code: 3255 * <blockquote><pre> 3256 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3257 * </pre></blockquote> 3258 * @param target the method handle to invoke after the arguments are dropped 3259 * @param valueTypes the type(s) of the argument(s) to drop 3260 * @param pos position of first argument to drop (zero for the leftmost) 3261 * @return a method handle which drops arguments of the given types, 3262 * before calling the original method handle 3263 * @throws NullPointerException if the target is null, 3264 * or if the {@code valueTypes} list or any of its elements is null 3265 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3266 * or if {@code pos} is negative or greater than the arity of the target, 3267 * or if the new method handle's type would have too many parameters 3268 */ 3269 public static 3270 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3271 return dropArguments0(target, pos, copyTypes(valueTypes)); 3272 } 3273 3274 private static List<Class<?>> copyTypes(List<Class<?>> types) { 3275 Object[] a = types.toArray(); 3276 return Arrays.asList(Arrays.copyOf(a, a.length, Class[].class)); 3277 } 3278 3279 private static 3280 MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3281 MethodType oldType = target.type(); // get NPE 3282 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3283 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3284 if (dropped == 0) return target; 3285 BoundMethodHandle result = target.rebind(); 3286 LambdaForm lform = result.form; 3287 int insertFormArg = 1 + pos; 3288 for (Class<?> ptype : valueTypes) { 3289 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3290 } 3291 result = result.copyWith(newType, lform); 3292 return result; 3293 } 3294 3295 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3296 int dropped = valueTypes.size(); 3297 MethodType.checkSlotCount(dropped); 3298 int outargs = oldType.parameterCount(); 3299 int inargs = outargs + dropped; 3300 if (pos < 0 || pos > outargs) 3301 throw newIllegalArgumentException("no argument type to remove" 3302 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3303 ); 3304 return dropped; 3305 } 3306 3307 /** 3308 * Produces a method handle which will discard some dummy arguments 3309 * before calling some other specified <i>target</i> method handle. 3310 * The type of the new method handle will be the same as the target's type, 3311 * except it will also include the dummy argument types, 3312 * at some given position. 3313 * <p> 3314 * The {@code pos} argument may range between zero and <i>N</i>, 3315 * where <i>N</i> is the arity of the target. 3316 * If {@code pos} is zero, the dummy arguments will precede 3317 * the target's real arguments; if {@code pos} is <i>N</i> 3318 * they will come after. 3319 * @apiNote 3320 * <blockquote><pre>{@code 3321 import static java.lang.invoke.MethodHandles.*; 3322 import static java.lang.invoke.MethodType.*; 3323 ... 3324 MethodHandle cat = lookup().findVirtual(String.class, 3325 "concat", methodType(String.class, String.class)); 3326 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3327 MethodHandle d0 = dropArguments(cat, 0, String.class); 3328 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3329 MethodHandle d1 = dropArguments(cat, 1, String.class); 3330 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3331 MethodHandle d2 = dropArguments(cat, 2, String.class); 3332 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3333 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3334 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3335 * }</pre></blockquote> 3336 * <p> 3337 * This method is also equivalent to the following code: 3338 * <blockquote><pre> 3339 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3340 * </pre></blockquote> 3341 * @param target the method handle to invoke after the arguments are dropped 3342 * @param valueTypes the type(s) of the argument(s) to drop 3343 * @param pos position of first argument to drop (zero for the leftmost) 3344 * @return a method handle which drops arguments of the given types, 3345 * before calling the original method handle 3346 * @throws NullPointerException if the target is null, 3347 * or if the {@code valueTypes} array or any of its elements is null 3348 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3349 * or if {@code pos} is negative or greater than the arity of the target, 3350 * or if the new method handle's type would have 3351 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3352 */ 3353 public static 3354 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3355 return dropArguments(target, pos, Arrays.asList(valueTypes)); 3356 } 3357 3358 // private version which allows caller some freedom with error handling 3359 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3360 boolean nullOnFailure) { 3361 newTypes = copyTypes(newTypes); 3362 List<Class<?>> oldTypes = target.type().parameterList(); 3363 int match = oldTypes.size(); 3364 if (skip != 0) { 3365 if (skip < 0 || skip > match) { 3366 throw newIllegalArgumentException("illegal skip", skip, target); 3367 } 3368 oldTypes = oldTypes.subList(skip, match); 3369 match -= skip; 3370 } 3371 List<Class<?>> addTypes = newTypes; 3372 int add = addTypes.size(); 3373 if (pos != 0) { 3374 if (pos < 0 || pos > add) { 3375 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3376 } 3377 addTypes = addTypes.subList(pos, add); 3378 add -= pos; assert(addTypes.size() == add); 3379 } 3380 // Do not add types which already match the existing arguments. 3381 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3382 if (nullOnFailure) { 3383 return null; 3384 } 3385 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3386 } 3387 addTypes = addTypes.subList(match, add); 3388 add -= match; assert(addTypes.size() == add); 3389 // newTypes: ( P*[pos], M*[match], A*[add] ) 3390 // target: ( S*[skip], M*[match] ) 3391 MethodHandle adapter = target; 3392 if (add > 0) { 3393 adapter = dropArguments0(adapter, skip+ match, addTypes); 3394 } 3395 // adapter: (S*[skip], M*[match], A*[add] ) 3396 if (pos > 0) { 3397 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); 3398 } 3399 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3400 return adapter; 3401 } 3402 3403 /** 3404 * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments. 3405 * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored. 3406 * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list, 3407 * at the given position. 3408 * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding 3409 * positions of the target method handle's parameters, as if by {@link #dropArguments}. 3410 * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip}, 3411 * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the 3412 * target list.) 3413 * The target's return type will be unchanged. 3414 * @apiNote 3415 * Two method handles whose argument lists are "effectively identical" (i.e., identical 3416 * in a common prefix) may be mutually converted to a common type 3417 * by two calls to {@code dropArgumentsToMatch}, as follows: 3418 * <blockquote><pre>{@code 3419 import static java.lang.invoke.MethodHandles.*; 3420 import static java.lang.invoke.MethodType.*; 3421 ... 3422 ... 3423 MethodHandle h0 = constant(boolean.class, true); 3424 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3425 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3426 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3427 if (h1.type().parameterCount() < h2.type().parameterCount()) 3428 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3429 else 3430 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3431 MethodHandle h3 = guardWithTest(h0, h1, h2); 3432 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3433 * }</pre></blockquote> 3434 * @param target the method handle to adapt 3435 * @param skip number of targets parameters to disregard (they will be unchanged) 3436 * @param newTypes the desired argument list of the method handle 3437 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3438 * @return a possibly adapted method handle 3439 * @throws NullPointerException if either argument is null 3440 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 3441 * or if {@code skip} is negative or greater than the arity of the target, 3442 * or if {@code pos} is negative or greater than the newTypes list size, 3443 * or if the non-skipped target parameter types match the new types at {@code pos} 3444 * @since 9 3445 */ 3446 public static 3447 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3448 Objects.requireNonNull(target); 3449 Objects.requireNonNull(newTypes); 3450 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3451 } 3452 3453 /** 3454 * Adapts a target method handle by pre-processing 3455 * one or more of its arguments, each with its own unary filter function, 3456 * and then calling the target with each pre-processed argument 3457 * replaced by the result of its corresponding filter function. 3458 * <p> 3459 * The pre-processing is performed by one or more method handles, 3460 * specified in the elements of the {@code filters} array. 3461 * The first element of the filter array corresponds to the {@code pos} 3462 * argument of the target, and so on in sequence. 3463 * <p> 3464 * Null arguments in the array are treated as identity functions, 3465 * and the corresponding arguments left unchanged. 3466 * (If there are no non-null elements in the array, the original target is returned.) 3467 * Each filter is applied to the corresponding argument of the adapter. 3468 * <p> 3469 * If a filter {@code F} applies to the {@code N}th argument of 3470 * the target, then {@code F} must be a method handle which 3471 * takes exactly one argument. The type of {@code F}'s sole argument 3472 * replaces the corresponding argument type of the target 3473 * in the resulting adapted method handle. 3474 * The return type of {@code F} must be identical to the corresponding 3475 * parameter type of the target. 3476 * <p> 3477 * It is an error if there are elements of {@code filters} 3478 * (null or not) 3479 * which do not correspond to argument positions in the target. 3480 * <p><b>Example:</b> 3481 * <blockquote><pre>{@code 3482 import static java.lang.invoke.MethodHandles.*; 3483 import static java.lang.invoke.MethodType.*; 3484 ... 3485 MethodHandle cat = lookup().findVirtual(String.class, 3486 "concat", methodType(String.class, String.class)); 3487 MethodHandle upcase = lookup().findVirtual(String.class, 3488 "toUpperCase", methodType(String.class)); 3489 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3490 MethodHandle f0 = filterArguments(cat, 0, upcase); 3491 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3492 MethodHandle f1 = filterArguments(cat, 1, upcase); 3493 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3494 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3495 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3496 * }</pre></blockquote> 3497 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3498 * denotes the return type of both the {@code target} and resulting adapter. 3499 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3500 * of the parameters and arguments that precede and follow the filter position 3501 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3502 * values of the filtered parameters and arguments; they also represent the 3503 * return types of the {@code filter[i]} handles. The latter accept arguments 3504 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3505 * the resulting adapter. 3506 * <blockquote><pre>{@code 3507 * T target(P... p, A[i]... a[i], B... b); 3508 * A[i] filter[i](V[i]); 3509 * T adapter(P... p, V[i]... v[i], B... b) { 3510 * return target(p..., filter[i](v[i])..., b...); 3511 * } 3512 * }</pre></blockquote> 3513 * <p> 3514 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3515 * variable-arity method handle}, even if the original target method handle was. 3516 * 3517 * @param target the method handle to invoke after arguments are filtered 3518 * @param pos the position of the first argument to filter 3519 * @param filters method handles to call initially on filtered arguments 3520 * @return method handle which incorporates the specified argument filtering logic 3521 * @throws NullPointerException if the target is null 3522 * or if the {@code filters} array is null 3523 * @throws IllegalArgumentException if a non-null element of {@code filters} 3524 * does not match a corresponding argument type of target as described above, 3525 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3526 * or if the resulting method handle's type would have 3527 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3528 */ 3529 public static 3530 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3531 filterArgumentsCheckArity(target, pos, filters); 3532 MethodHandle adapter = target; 3533 int curPos = pos-1; // pre-incremented 3534 for (MethodHandle filter : filters) { 3535 curPos += 1; 3536 if (filter == null) continue; // ignore null elements of filters 3537 adapter = filterArgument(adapter, curPos, filter); 3538 } 3539 return adapter; 3540 } 3541 3542 /*non-public*/ static 3543 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3544 filterArgumentChecks(target, pos, filter); 3545 MethodType targetType = target.type(); 3546 MethodType filterType = filter.type(); 3547 BoundMethodHandle result = target.rebind(); 3548 Class<?> newParamType = filterType.parameterType(0); 3549 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3550 MethodType newType = targetType.changeParameterType(pos, newParamType); 3551 result = result.copyWithExtendL(newType, lform, filter); 3552 return result; 3553 } 3554 3555 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3556 MethodType targetType = target.type(); 3557 int maxPos = targetType.parameterCount(); 3558 if (pos + filters.length > maxPos) 3559 throw newIllegalArgumentException("too many filters"); 3560 } 3561 3562 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3563 MethodType targetType = target.type(); 3564 MethodType filterType = filter.type(); 3565 if (filterType.parameterCount() != 1 3566 || filterType.returnType() != targetType.parameterType(pos)) 3567 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3568 } 3569 3570 /** 3571 * Adapts a target method handle by pre-processing 3572 * a sub-sequence of its arguments with a filter (another method handle). 3573 * The pre-processed arguments are replaced by the result (if any) of the 3574 * filter function. 3575 * The target is then called on the modified (usually shortened) argument list. 3576 * <p> 3577 * If the filter returns a value, the target must accept that value as 3578 * its argument in position {@code pos}, preceded and/or followed by 3579 * any arguments not passed to the filter. 3580 * If the filter returns void, the target must accept all arguments 3581 * not passed to the filter. 3582 * No arguments are reordered, and a result returned from the filter 3583 * replaces (in order) the whole subsequence of arguments originally 3584 * passed to the adapter. 3585 * <p> 3586 * The argument types (if any) of the filter 3587 * replace zero or one argument types of the target, at position {@code pos}, 3588 * in the resulting adapted method handle. 3589 * The return type of the filter (if any) must be identical to the 3590 * argument type of the target at position {@code pos}, and that target argument 3591 * is supplied by the return value of the filter. 3592 * <p> 3593 * In all cases, {@code pos} must be greater than or equal to zero, and 3594 * {@code pos} must also be less than or equal to the target's arity. 3595 * <p><b>Example:</b> 3596 * <blockquote><pre>{@code 3597 import static java.lang.invoke.MethodHandles.*; 3598 import static java.lang.invoke.MethodType.*; 3599 ... 3600 MethodHandle deepToString = publicLookup() 3601 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 3602 3603 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 3604 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 3605 3606 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 3607 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 3608 3609 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 3610 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 3611 assertEquals("[top, [up, down], strange]", 3612 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 3613 3614 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 3615 assertEquals("[top, [up, down], [strange]]", 3616 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 3617 3618 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 3619 assertEquals("[top, [[up, down, strange], charm], bottom]", 3620 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 3621 * }</pre></blockquote> 3622 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3623 * represents the return type of the {@code target} and resulting adapter. 3624 * {@code V}/{@code v} stand for the return type and value of the 3625 * {@code filter}, which are also found in the signature and arguments of 3626 * the {@code target}, respectively, unless {@code V} is {@code void}. 3627 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 3628 * and values preceding and following the collection position, {@code pos}, 3629 * in the {@code target}'s signature. They also turn up in the resulting 3630 * adapter's signature and arguments, where they surround 3631 * {@code B}/{@code b}, which represent the parameter types and arguments 3632 * to the {@code filter} (if any). 3633 * <blockquote><pre>{@code 3634 * T target(A...,V,C...); 3635 * V filter(B...); 3636 * T adapter(A... a,B... b,C... c) { 3637 * V v = filter(b...); 3638 * return target(a...,v,c...); 3639 * } 3640 * // and if the filter has no arguments: 3641 * T target2(A...,V,C...); 3642 * V filter2(); 3643 * T adapter2(A... a,C... c) { 3644 * V v = filter2(); 3645 * return target2(a...,v,c...); 3646 * } 3647 * // and if the filter has a void return: 3648 * T target3(A...,C...); 3649 * void filter3(B...); 3650 * T adapter3(A... a,B... b,C... c) { 3651 * filter3(b...); 3652 * return target3(a...,c...); 3653 * } 3654 * }</pre></blockquote> 3655 * <p> 3656 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 3657 * one which first "folds" the affected arguments, and then drops them, in separate 3658 * steps as follows: 3659 * <blockquote><pre>{@code 3660 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 3661 * mh = MethodHandles.foldArguments(mh, coll); //step 1 3662 * }</pre></blockquote> 3663 * If the target method handle consumes no arguments besides than the result 3664 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 3665 * is equivalent to {@code filterReturnValue(coll, mh)}. 3666 * If the filter method handle {@code coll} consumes one argument and produces 3667 * a non-void result, then {@code collectArguments(mh, N, coll)} 3668 * is equivalent to {@code filterArguments(mh, N, coll)}. 3669 * Other equivalences are possible but would require argument permutation. 3670 * <p> 3671 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3672 * variable-arity method handle}, even if the original target method handle was. 3673 * 3674 * @param target the method handle to invoke after filtering the subsequence of arguments 3675 * @param pos the position of the first adapter argument to pass to the filter, 3676 * and/or the target argument which receives the result of the filter 3677 * @param filter method handle to call on the subsequence of arguments 3678 * @return method handle which incorporates the specified argument subsequence filtering logic 3679 * @throws NullPointerException if either argument is null 3680 * @throws IllegalArgumentException if the return type of {@code filter} 3681 * is non-void and is not the same as the {@code pos} argument of the target, 3682 * or if {@code pos} is not between 0 and the target's arity, inclusive, 3683 * or if the resulting method handle's type would have 3684 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3685 * @see MethodHandles#foldArguments 3686 * @see MethodHandles#filterArguments 3687 * @see MethodHandles#filterReturnValue 3688 */ 3689 public static 3690 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 3691 MethodType newType = collectArgumentsChecks(target, pos, filter); 3692 MethodType collectorType = filter.type(); 3693 BoundMethodHandle result = target.rebind(); 3694 LambdaForm lform; 3695 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 3696 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 3697 if (lform != null) { 3698 return result.copyWith(newType, lform); 3699 } 3700 } 3701 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 3702 return result.copyWithExtendL(newType, lform, filter); 3703 } 3704 3705 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3706 MethodType targetType = target.type(); 3707 MethodType filterType = filter.type(); 3708 Class<?> rtype = filterType.returnType(); 3709 List<Class<?>> filterArgs = filterType.parameterList(); 3710 if (rtype == void.class) { 3711 return targetType.insertParameterTypes(pos, filterArgs); 3712 } 3713 if (rtype != targetType.parameterType(pos)) { 3714 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3715 } 3716 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 3717 } 3718 3719 /** 3720 * Adapts a target method handle by post-processing 3721 * its return value (if any) with a filter (another method handle). 3722 * The result of the filter is returned from the adapter. 3723 * <p> 3724 * If the target returns a value, the filter must accept that value as 3725 * its only argument. 3726 * If the target returns void, the filter must accept no arguments. 3727 * <p> 3728 * The return type of the filter 3729 * replaces the return type of the target 3730 * in the resulting adapted method handle. 3731 * The argument type of the filter (if any) must be identical to the 3732 * return type of the target. 3733 * <p><b>Example:</b> 3734 * <blockquote><pre>{@code 3735 import static java.lang.invoke.MethodHandles.*; 3736 import static java.lang.invoke.MethodType.*; 3737 ... 3738 MethodHandle cat = lookup().findVirtual(String.class, 3739 "concat", methodType(String.class, String.class)); 3740 MethodHandle length = lookup().findVirtual(String.class, 3741 "length", methodType(int.class)); 3742 System.out.println((String) cat.invokeExact("x", "y")); // xy 3743 MethodHandle f0 = filterReturnValue(cat, length); 3744 System.out.println((int) f0.invokeExact("x", "y")); // 2 3745 * }</pre></blockquote> 3746 * <p>Here is pseudocode for the resulting adapter. In the code, 3747 * {@code T}/{@code t} represent the result type and value of the 3748 * {@code target}; {@code V}, the result type of the {@code filter}; and 3749 * {@code A}/{@code a}, the types and values of the parameters and arguments 3750 * of the {@code target} as well as the resulting adapter. 3751 * <blockquote><pre>{@code 3752 * T target(A...); 3753 * V filter(T); 3754 * V adapter(A... a) { 3755 * T t = target(a...); 3756 * return filter(t); 3757 * } 3758 * // and if the target has a void return: 3759 * void target2(A...); 3760 * V filter2(); 3761 * V adapter2(A... a) { 3762 * target2(a...); 3763 * return filter2(); 3764 * } 3765 * // and if the filter has a void return: 3766 * T target3(A...); 3767 * void filter3(V); 3768 * void adapter3(A... a) { 3769 * T t = target3(a...); 3770 * filter3(t); 3771 * } 3772 * }</pre></blockquote> 3773 * <p> 3774 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3775 * variable-arity method handle}, even if the original target method handle was. 3776 * @param target the method handle to invoke before filtering the return value 3777 * @param filter method handle to call on the return value 3778 * @return method handle which incorporates the specified return value filtering logic 3779 * @throws NullPointerException if either argument is null 3780 * @throws IllegalArgumentException if the argument list of {@code filter} 3781 * does not match the return type of target as described above 3782 */ 3783 public static 3784 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 3785 MethodType targetType = target.type(); 3786 MethodType filterType = filter.type(); 3787 filterReturnValueChecks(targetType, filterType); 3788 BoundMethodHandle result = target.rebind(); 3789 BasicType rtype = BasicType.basicType(filterType.returnType()); 3790 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 3791 MethodType newType = targetType.changeReturnType(filterType.returnType()); 3792 result = result.copyWithExtendL(newType, lform, filter); 3793 return result; 3794 } 3795 3796 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 3797 Class<?> rtype = targetType.returnType(); 3798 int filterValues = filterType.parameterCount(); 3799 if (filterValues == 0 3800 ? (rtype != void.class) 3801 : (rtype != filterType.parameterType(0) || filterValues != 1)) 3802 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3803 } 3804 3805 /** 3806 * Adapts a target method handle by pre-processing 3807 * some of its arguments, and then calling the target with 3808 * the result of the pre-processing, inserted into the original 3809 * sequence of arguments. 3810 * <p> 3811 * The pre-processing is performed by {@code combiner}, a second method handle. 3812 * Of the arguments passed to the adapter, the first {@code N} arguments 3813 * are copied to the combiner, which is then called. 3814 * (Here, {@code N} is defined as the parameter count of the combiner.) 3815 * After this, control passes to the target, with any result 3816 * from the combiner inserted before the original {@code N} incoming 3817 * arguments. 3818 * <p> 3819 * If the combiner returns a value, the first parameter type of the target 3820 * must be identical with the return type of the combiner, and the next 3821 * {@code N} parameter types of the target must exactly match the parameters 3822 * of the combiner. 3823 * <p> 3824 * If the combiner has a void return, no result will be inserted, 3825 * and the first {@code N} parameter types of the target 3826 * must exactly match the parameters of the combiner. 3827 * <p> 3828 * The resulting adapter is the same type as the target, except that the 3829 * first parameter type is dropped, 3830 * if it corresponds to the result of the combiner. 3831 * <p> 3832 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 3833 * that either the combiner or the target does not wish to receive. 3834 * If some of the incoming arguments are destined only for the combiner, 3835 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 3836 * arguments will not need to be live on the stack on entry to the 3837 * target.) 3838 * <p><b>Example:</b> 3839 * <blockquote><pre>{@code 3840 import static java.lang.invoke.MethodHandles.*; 3841 import static java.lang.invoke.MethodType.*; 3842 ... 3843 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 3844 "println", methodType(void.class, String.class)) 3845 .bindTo(System.out); 3846 MethodHandle cat = lookup().findVirtual(String.class, 3847 "concat", methodType(String.class, String.class)); 3848 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 3849 MethodHandle catTrace = foldArguments(cat, trace); 3850 // also prints "boo": 3851 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 3852 * }</pre></blockquote> 3853 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3854 * represents the result type of the {@code target} and resulting adapter. 3855 * {@code V}/{@code v} represent the type and value of the parameter and argument 3856 * of {@code target} that precedes the folding position; {@code V} also is 3857 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 3858 * types and values of the {@code N} parameters and arguments at the folding 3859 * position. {@code B}/{@code b} represent the types and values of the 3860 * {@code target} parameters and arguments that follow the folded parameters 3861 * and arguments. 3862 * <blockquote><pre>{@code 3863 * // there are N arguments in A... 3864 * T target(V, A[N]..., B...); 3865 * V combiner(A...); 3866 * T adapter(A... a, B... b) { 3867 * V v = combiner(a...); 3868 * return target(v, a..., b...); 3869 * } 3870 * // and if the combiner has a void return: 3871 * T target2(A[N]..., B...); 3872 * void combiner2(A...); 3873 * T adapter2(A... a, B... b) { 3874 * combiner2(a...); 3875 * return target2(a..., b...); 3876 * } 3877 * }</pre></blockquote> 3878 * <p> 3879 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3880 * variable-arity method handle}, even if the original target method handle was. 3881 * @param target the method handle to invoke after arguments are combined 3882 * @param combiner method handle to call initially on the incoming arguments 3883 * @return method handle which incorporates the specified argument folding logic 3884 * @throws NullPointerException if either argument is null 3885 * @throws IllegalArgumentException if {@code combiner}'s return type 3886 * is non-void and not the same as the first argument type of 3887 * the target, or if the initial {@code N} argument types 3888 * of the target 3889 * (skipping one matching the {@code combiner}'s return type) 3890 * are not identical with the argument types of {@code combiner} 3891 */ 3892 public static 3893 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 3894 return foldArguments(target, 0, combiner); 3895 } 3896 3897 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 3898 int foldArgs = combinerType.parameterCount(); 3899 Class<?> rtype = combinerType.returnType(); 3900 int foldVals = rtype == void.class ? 0 : 1; 3901 int afterInsertPos = foldPos + foldVals; 3902 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 3903 if (ok && !(combinerType.parameterList() 3904 .equals(targetType.parameterList().subList(afterInsertPos, 3905 afterInsertPos + foldArgs)))) 3906 ok = false; 3907 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 3908 ok = false; 3909 if (!ok) 3910 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3911 return rtype; 3912 } 3913 3914 /** 3915 * Makes a method handle which adapts a target method handle, 3916 * by guarding it with a test, a boolean-valued method handle. 3917 * If the guard fails, a fallback handle is called instead. 3918 * All three method handles must have the same corresponding 3919 * argument and return types, except that the return type 3920 * of the test must be boolean, and the test is allowed 3921 * to have fewer arguments than the other two method handles. 3922 * <p> 3923 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3924 * represents the uniform result type of the three involved handles; 3925 * {@code A}/{@code a}, the types and values of the {@code target} 3926 * parameters and arguments that are consumed by the {@code test}; and 3927 * {@code B}/{@code b}, those types and values of the {@code target} 3928 * parameters and arguments that are not consumed by the {@code test}. 3929 * <blockquote><pre>{@code 3930 * boolean test(A...); 3931 * T target(A...,B...); 3932 * T fallback(A...,B...); 3933 * T adapter(A... a,B... b) { 3934 * if (test(a...)) 3935 * return target(a..., b...); 3936 * else 3937 * return fallback(a..., b...); 3938 * } 3939 * }</pre></blockquote> 3940 * Note that the test arguments ({@code a...} in the pseudocode) cannot 3941 * be modified by execution of the test, and so are passed unchanged 3942 * from the caller to the target or fallback as appropriate. 3943 * @param test method handle used for test, must return boolean 3944 * @param target method handle to call if test passes 3945 * @param fallback method handle to call if test fails 3946 * @return method handle which incorporates the specified if/then/else logic 3947 * @throws NullPointerException if any argument is null 3948 * @throws IllegalArgumentException if {@code test} does not return boolean, 3949 * or if all three method types do not match (with the return 3950 * type of {@code test} changed to match that of the target). 3951 */ 3952 public static 3953 MethodHandle guardWithTest(MethodHandle test, 3954 MethodHandle target, 3955 MethodHandle fallback) { 3956 MethodType gtype = test.type(); 3957 MethodType ttype = target.type(); 3958 MethodType ftype = fallback.type(); 3959 if (!ttype.equals(ftype)) 3960 throw misMatchedTypes("target and fallback types", ttype, ftype); 3961 if (gtype.returnType() != boolean.class) 3962 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 3963 List<Class<?>> targs = ttype.parameterList(); 3964 test = dropArgumentsToMatch(test, 0, targs, 0, true); 3965 if (test == null) { 3966 throw misMatchedTypes("target and test types", ttype, gtype); 3967 } 3968 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 3969 } 3970 3971 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 3972 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 3973 } 3974 3975 /** 3976 * Makes a method handle which adapts a target method handle, 3977 * by running it inside an exception handler. 3978 * If the target returns normally, the adapter returns that value. 3979 * If an exception matching the specified type is thrown, the fallback 3980 * handle is called instead on the exception, plus the original arguments. 3981 * <p> 3982 * The target and handler must have the same corresponding 3983 * argument and return types, except that handler may omit trailing arguments 3984 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 3985 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 3986 * <p> 3987 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3988 * represents the return type of the {@code target} and {@code handler}, 3989 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 3990 * the types and values of arguments to the resulting handle consumed by 3991 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 3992 * resulting handle discarded by {@code handler}. 3993 * <blockquote><pre>{@code 3994 * T target(A..., B...); 3995 * T handler(ExType, A...); 3996 * T adapter(A... a, B... b) { 3997 * try { 3998 * return target(a..., b...); 3999 * } catch (ExType ex) { 4000 * return handler(ex, a...); 4001 * } 4002 * } 4003 * }</pre></blockquote> 4004 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4005 * be modified by execution of the target, and so are passed unchanged 4006 * from the caller to the handler, if the handler is invoked. 4007 * <p> 4008 * The target and handler must return the same type, even if the handler 4009 * always throws. (This might happen, for instance, because the handler 4010 * is simulating a {@code finally} clause). 4011 * To create such a throwing handler, compose the handler creation logic 4012 * with {@link #throwException throwException}, 4013 * in order to create a method handle of the correct return type. 4014 * @param target method handle to call 4015 * @param exType the type of exception which the handler will catch 4016 * @param handler method handle to call if a matching exception is thrown 4017 * @return method handle which incorporates the specified try/catch logic 4018 * @throws NullPointerException if any argument is null 4019 * @throws IllegalArgumentException if {@code handler} does not accept 4020 * the given exception type, or if the method handle types do 4021 * not match in their return types and their 4022 * corresponding parameters 4023 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 4024 */ 4025 public static 4026 MethodHandle catchException(MethodHandle target, 4027 Class<? extends Throwable> exType, 4028 MethodHandle handler) { 4029 MethodType ttype = target.type(); 4030 MethodType htype = handler.type(); 4031 if (!Throwable.class.isAssignableFrom(exType)) 4032 throw new ClassCastException(exType.getName()); 4033 if (htype.parameterCount() < 1 || 4034 !htype.parameterType(0).isAssignableFrom(exType)) 4035 throw newIllegalArgumentException("handler does not accept exception type "+exType); 4036 if (htype.returnType() != ttype.returnType()) 4037 throw misMatchedTypes("target and handler return types", ttype, htype); 4038 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 4039 if (handler == null) { 4040 throw misMatchedTypes("target and handler types", ttype, htype); 4041 } 4042 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 4043 } 4044 4045 /** 4046 * Produces a method handle which will throw exceptions of the given {@code exType}. 4047 * The method handle will accept a single argument of {@code exType}, 4048 * and immediately throw it as an exception. 4049 * The method type will nominally specify a return of {@code returnType}. 4050 * The return type may be anything convenient: It doesn't matter to the 4051 * method handle's behavior, since it will never return normally. 4052 * @param returnType the return type of the desired method handle 4053 * @param exType the parameter type of the desired method handle 4054 * @return method handle which can throw the given exceptions 4055 * @throws NullPointerException if either argument is null 4056 */ 4057 public static 4058 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 4059 if (!Throwable.class.isAssignableFrom(exType)) 4060 throw new ClassCastException(exType.getName()); 4061 return MethodHandleImpl.throwException(methodType(returnType, exType)); 4062 } 4063 4064 /** 4065 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 4066 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 4067 * delivers the loop's result, which is the return value of the resulting handle. 4068 * <p> 4069 * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop 4070 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 4071 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 4072 * terms of method handles, each clause will determine four actions:<ul> 4073 * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local. 4074 * <li>When a clause executes, an update step for the iteration variable. 4075 * <li>When a clause executes, a predicate execution to test for loop exit. 4076 * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 4077 * </ul> 4078 * <p> 4079 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 4080 * this case. See below for a detailed description. 4081 * <p> 4082 * Each clause function, with the exception of clause initializers, is able to observe the entire loop state, 4083 * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop 4084 * parameters. Most clause functions will not need all of this information, but they will be formally connected as 4085 * if by {@link #dropArguments}. 4086 * <p> 4087 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 4088 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 4089 * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met 4090 * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means 4091 * that they must be identical, or else one list must be a proper prefix of the other. 4092 * <p> 4093 * <em>Step 0: Determine clause structure.</em><ol type="a"> 4094 * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element. 4095 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4096 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4097 * four. Padding takes place by appending elements to the array. 4098 * <li>Clauses with all {@code null}s are disregarded. 4099 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4100 * </ol> 4101 * <p> 4102 * <em>Step 1A: Determine iteration variables.</em><ol type="a"> 4103 * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type. 4104 * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else 4105 * use the common return type (they must be identical). 4106 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4107 * <li>This list of types is called the "common prefix". 4108 * </ol> 4109 * <p> 4110 * <em>Step 1B: Determine loop parameters.</em><ul> 4111 * <li><b>If at least one init function is given,</b><ol type="a"> 4112 * <li>Examine init function parameter lists. 4113 * <li>Omitted init functions are deemed to have {@code null} parameter lists. 4114 * <li>All init function parameter lists must be effectively identical. 4115 * <li>The longest parameter list (which is necessarily unique) is called the "common suffix". 4116 * </ol> 4117 * <li><b>If no init function is given,</b><ol type="a"> 4118 * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix". 4119 * <li>The longest of these suffixes is taken as the "common suffix". 4120 * </ol></ul> 4121 * <p> 4122 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4123 * <li>Examine fini function return types, disregarding omitted fini functions. 4124 * <li>If there are no fini functions, use {@code void} as the loop return type. 4125 * <li>Otherwise, use the common return type of the fini functions; they must all be identical. 4126 * </ol> 4127 * <p> 4128 * <em>Step 1D: Check other types.</em><ol type="a"> 4129 * <li>There must be at least one non-omitted pred function. 4130 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4131 * </ol> 4132 * <p> 4133 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4134 * <li>The parameter list for the resulting loop handle will be the "common suffix". 4135 * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter 4136 * lists are already effectively identical to the common suffix.) 4137 * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix 4138 * followed by the common suffix, called the "common parameter sequence". 4139 * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter 4140 * sequence. 4141 * </ol> 4142 * <p> 4143 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4144 * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate 4145 * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a 4146 * function which does nothing and returns {@code void}; it can be obtained from another constant function by 4147 * {@linkplain MethodHandle#asType type conversion}.) 4148 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4149 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4150 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4151 * <li>If a pred function is omitted, the corresponding fini function must also be omitted. 4152 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4153 * as this clause is concerned.) 4154 * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the 4155 * loop return type. 4156 * </ol> 4157 * <p> 4158 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4159 * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some 4160 * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by 4161 * {@linkplain #dropArguments dropping arguments}. 4162 * <li>At this point, every non-init function parameter list is effectively identical to the common parameter 4163 * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end 4164 * of the list by {@linkplain #dropArguments dropping arguments}. 4165 * </ol> 4166 * <p> 4167 * <em>Final observations.</em><ol type="a"> 4168 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4169 * <li>All init functions have a common parameter type list, which the final loop handle will also have. 4170 * <li>All fini functions have a common return type, which the final loop handle will also have. 4171 * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of 4172 * (non-{@code void}) iteration variables followed by loop parameters. 4173 * <li>Each pair of init and step functions agrees in their return types. 4174 * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the 4175 * common prefix. 4176 * </ol> 4177 * <p> 4178 * <em>Loop execution.</em><ol type="a"> 4179 * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to 4180 * every clause function. These locals are loop invariant. 4181 * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values 4182 * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity 4183 * functions, as noted above). 4184 * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of 4185 * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order). 4186 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4187 * returns {@code false}. 4188 * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The 4189 * updated value is immediately visible to all subsequent function calls. 4190 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4191 * is returned from the loop as a whole. 4192 * </ol> 4193 * <p> 4194 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values 4195 * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the 4196 * result types of finalizers as well as of the resulting loop. 4197 * <blockquote><pre>{@code 4198 * V... init...(A...); 4199 * boolean pred...(V..., A...); 4200 * V... step...(V..., A...); 4201 * R fini...(V..., A...); 4202 * R loop(A... a) { 4203 * V... v... = init...(a...); 4204 * for (;;) { 4205 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4206 * v = s(v..., a...); 4207 * if (!p(v..., a...)) { 4208 * return f(v..., a...); 4209 * } 4210 * } 4211 * } 4212 * } 4213 * }</pre></blockquote> 4214 * <p> 4215 * @apiNote Example: 4216 * <blockquote><pre>{@code 4217 * // iterative implementation of the factorial function as a loop handle 4218 * static int one(int k) { return 1; } 4219 * static int inc(int i, int acc, int k) { return i + 1; } 4220 * static int mult(int i, int acc, int k) { return i * acc; } 4221 * static boolean pred(int i, int acc, int k) { return i < k; } 4222 * static int fin(int i, int acc, int k) { return acc; } 4223 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4224 * // null initializer for counter, should initialize to 0 4225 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4226 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4227 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4228 * assertEquals(120, loop.invoke(5)); 4229 * }</pre></blockquote> 4230 * 4231 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4232 * 4233 * @return a method handle embodying the looping behavior as defined by the arguments. 4234 * 4235 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4236 * 4237 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4238 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4239 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4240 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4241 * @since 9 4242 */ 4243 public static MethodHandle loop(MethodHandle[]... clauses) { 4244 // Step 0: determine clause structure. 4245 checkLoop0(clauses); 4246 4247 List<MethodHandle> init = new ArrayList<>(); 4248 List<MethodHandle> step = new ArrayList<>(); 4249 List<MethodHandle> pred = new ArrayList<>(); 4250 List<MethodHandle> fini = new ArrayList<>(); 4251 4252 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4253 init.add(clause[0]); // all clauses have at least length 1 4254 step.add(clause.length <= 1 ? null : clause[1]); 4255 pred.add(clause.length <= 2 ? null : clause[2]); 4256 fini.add(clause.length <= 3 ? null : clause[3]); 4257 }); 4258 4259 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4260 final int nclauses = init.size(); 4261 4262 // Step 1A: determine iteration variables. 4263 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4264 for (int i = 0; i < nclauses; ++i) { 4265 MethodHandle in = init.get(i); 4266 MethodHandle st = step.get(i); 4267 if (in == null && st == null) { 4268 iterationVariableTypes.add(void.class); 4269 } else if (in != null && st != null) { 4270 checkLoop1a(i, in, st); 4271 iterationVariableTypes.add(in.type().returnType()); 4272 } else { 4273 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4274 } 4275 } 4276 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4277 collect(Collectors.toList()); 4278 4279 // Step 1B: determine loop parameters. 4280 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4281 checkLoop1b(init, commonSuffix); 4282 4283 // Step 1C: determine loop return type. 4284 // Step 1D: check other types. 4285 final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type). 4286 map(MethodType::returnType).findFirst().orElse(void.class); 4287 checkLoop1cd(pred, fini, loopReturnType); 4288 4289 // Step 2: determine parameter lists. 4290 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4291 commonParameterSequence.addAll(commonSuffix); 4292 checkLoop2(step, pred, fini, commonParameterSequence); 4293 4294 // Step 3: fill in omitted functions. 4295 for (int i = 0; i < nclauses; ++i) { 4296 Class<?> t = iterationVariableTypes.get(i); 4297 if (init.get(i) == null) { 4298 init.set(i, empty(methodType(t, commonSuffix))); 4299 } 4300 if (step.get(i) == null) { 4301 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 4302 } 4303 if (pred.get(i) == null) { 4304 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); 4305 } 4306 if (fini.get(i) == null) { 4307 fini.set(i, empty(methodType(t, commonParameterSequence))); 4308 } 4309 } 4310 4311 // Step 4: fill in missing parameter types. 4312 List<MethodHandle> finit = fillParameterTypes(init, commonSuffix); 4313 List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence); 4314 List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence); 4315 List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence); 4316 4317 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 4318 allMatch(pl -> pl.equals(commonSuffix)); 4319 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 4320 allMatch(pl -> pl.equals(commonParameterSequence)); 4321 4322 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 4323 } 4324 4325 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 4326 return hs.stream().map(h -> { 4327 int pc = h.type().parameterCount(); 4328 int tpsize = targetParams.size(); 4329 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; 4330 }).collect(Collectors.toList()); 4331 } 4332 4333 /** 4334 * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for 4335 * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4336 * <p> 4337 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4338 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4339 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4340 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4341 * generic loop combinator}. 4342 * <p> 4343 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4344 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4345 * passed to the loop. 4346 * <blockquote><pre>{@code 4347 * V init(A); 4348 * boolean pred(V, A); 4349 * V body(V, A); 4350 * V whileLoop(A a) { 4351 * V v = init(a); 4352 * while (pred(v, a)) { 4353 * v = body(v, a); 4354 * } 4355 * return v; 4356 * } 4357 * }</pre></blockquote> 4358 * <p> 4359 * @apiNote Example: 4360 * <blockquote><pre>{@code 4361 * // implement the zip function for lists as a loop handle 4362 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 4363 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 4364 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 4365 * zip.add(a.next()); 4366 * zip.add(b.next()); 4367 * return zip; 4368 * } 4369 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 4370 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 4371 * List<String> a = Arrays.asList("a", "b", "c", "d"); 4372 * List<String> b = Arrays.asList("e", "f", "g", "h"); 4373 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 4374 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 4375 * }</pre></blockquote> 4376 * 4377 * <p> 4378 * @implSpec The implementation of this method is equivalent to: 4379 * <blockquote><pre>{@code 4380 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4381 * MethodHandle[] 4382 * checkExit = {null, null, pred, identity(init.type().returnType())}, 4383 * varBody = {init, body}; 4384 * return loop(checkExit, varBody); 4385 * } 4386 * }</pre></blockquote> 4387 * 4388 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4389 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4390 * {@code void}. 4391 * @param pred condition for the loop, which may not be {@code null}. 4392 * @param body body of the loop, which may not be {@code null}. 4393 * 4394 * @return the value of the loop variable as the loop terminates. 4395 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4396 * 4397 * @see MethodHandles#loop(MethodHandle[][]) 4398 * @since 9 4399 */ 4400 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4401 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4402 identity(init.type().returnType()); 4403 MethodHandle[] checkExit = {null, null, pred, fin}; 4404 MethodHandle[] varBody = {init, body}; 4405 return loop(checkExit, varBody); 4406 } 4407 4408 /** 4409 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper 4410 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4411 * <p> 4412 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4413 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4414 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4415 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4416 * generic loop combinator}. 4417 * <p> 4418 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4419 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4420 * passed to the loop. 4421 * <blockquote><pre>{@code 4422 * V init(A); 4423 * boolean pred(V, A); 4424 * V body(V, A); 4425 * V doWhileLoop(A a) { 4426 * V v = init(a); 4427 * do { 4428 * v = body(v, a); 4429 * } while (pred(v, a)); 4430 * return v; 4431 * } 4432 * }</pre></blockquote> 4433 * <p> 4434 * @apiNote Example: 4435 * <blockquote><pre>{@code 4436 * // int i = 0; while (i < limit) { ++i; } return i; => limit 4437 * static int zero(int limit) { return 0; } 4438 * static int step(int i, int limit) { return i + 1; } 4439 * static boolean pred(int i, int limit) { return i < limit; } 4440 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 4441 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 4442 * assertEquals(23, loop.invoke(23)); 4443 * }</pre></blockquote> 4444 * 4445 * <p> 4446 * @implSpec The implementation of this method is equivalent to: 4447 * <blockquote><pre>{@code 4448 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4449 * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) }; 4450 * return loop(clause); 4451 * } 4452 * }</pre></blockquote> 4453 * 4454 * 4455 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4456 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4457 * {@code void}. 4458 * @param pred condition for the loop, which may not be {@code null}. 4459 * @param body body of the loop, which may not be {@code null}. 4460 * 4461 * @return the value of the loop variable as the loop terminates. 4462 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4463 * 4464 * @see MethodHandles#loop(MethodHandle[][]) 4465 * @since 9 4466 */ 4467 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4468 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4469 identity(init.type().returnType()); 4470 MethodHandle[] clause = {init, body, pred, fin}; 4471 return loop(clause); 4472 } 4473 4474 /** 4475 * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the 4476 * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must 4477 * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional 4478 * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop 4479 * combinator}. 4480 * <p> 4481 * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code 4482 * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code 4483 * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter, 4484 * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described 4485 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4486 * <p> 4487 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4488 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4489 * passed to the loop. 4490 * <blockquote><pre>{@code 4491 * int iterations(A); 4492 * V init(A); 4493 * V body(int, V, A); 4494 * V countedLoop(A a) { 4495 * int end = iterations(a); 4496 * V v = init(a); 4497 * for (int i = 0; i < end; ++i) { 4498 * v = body(i, v, a); 4499 * } 4500 * return v; 4501 * } 4502 * }</pre></blockquote> 4503 * <p> 4504 * @apiNote Example: 4505 * <blockquote><pre>{@code 4506 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 4507 * // => a variation on a well known theme 4508 * static String start(String arg) { return arg; } 4509 * static String step(int counter, String v, String arg) { return "na " + v; } 4510 * // assume MH_start and MH_step are handles to the two methods above 4511 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 4512 * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step); 4513 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 4514 * }</pre></blockquote> 4515 * 4516 * <p> 4517 * @implSpec The implementation of this method is equivalent to: 4518 * <blockquote><pre>{@code 4519 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4520 * return countedLoop(null, iterations, init, body); // null => constant zero 4521 * } 4522 * }</pre></blockquote> 4523 * 4524 * @param iterations a handle to return the number of iterations this loop should run. 4525 * @param init initializer for additional loop state. This determines the loop's result type. 4526 * Passing {@code null} or a {@code void} init function will make the loop's result type 4527 * {@code void}. 4528 * @param body the body of the loop, which must not be {@code null}. 4529 * It must accept an initial {@code int} parameter (for the counter), and then any 4530 * additional loop-local variable plus loop parameters. 4531 * 4532 * @return a method handle representing the loop. 4533 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4534 * 4535 * @since 9 4536 */ 4537 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4538 return countedLoop(null, iterations, init, body); 4539 } 4540 4541 /** 4542 * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be 4543 * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the 4544 * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code 4545 * body} function in each iteration; it has to accept an initial {@code int} parameter 4546 * for that. The result of the loop execution is the final value of the additional local state 4547 * obtained by running {@code init}. 4548 * This is a 4549 * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4550 * <p> 4551 * The constraints for the {@code init} and {@code body} handles are the same as for {@link 4552 * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles 4553 * must return an {@code int} and accept the same parameters as {@code init}. 4554 * <p> 4555 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4556 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4557 * passed to the loop. 4558 * <blockquote><pre>{@code 4559 * int start(A); 4560 * int end(A); 4561 * V init(A); 4562 * V body(int, V, A); 4563 * V countedLoop(A a) { 4564 * int s = start(a); 4565 * int e = end(a); 4566 * V v = init(a); 4567 * for (int i = s; i < e; ++i) { 4568 * v = body(i, v, a); 4569 * } 4570 * return v; 4571 * } 4572 * }</pre></blockquote> 4573 * 4574 * <p> 4575 * @implSpec The implementation of this method is equivalent to: 4576 * <blockquote><pre>{@code 4577 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4578 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 4579 * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int, 4580 * // assume MH_decrement is a handle to x-1 of type int 4581 * MethodHandle[] 4582 * indexVar = {start, MH_increment}, // i = start; i = i+1 4583 * loopLimit = {end, null, MH_lessThan, returnVar }, // i<end 4584 * bodyClause = {init, 4585 * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v) 4586 * return loop(indexVar, loopLimit, bodyClause); 4587 * } 4588 * }</pre></blockquote> 4589 * 4590 * @param start a handle to return the start value of the loop counter. 4591 * If it is {@code null}, a constant zero is assumed. 4592 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}). 4593 * @param init initializer for additional loop state. This determines the loop's result type. 4594 * Passing {@code null} or a {@code void} init function will make the loop's result type 4595 * {@code void}. 4596 * @param body the body of the loop, which must not be {@code null}. 4597 * It must accept an initial {@code int} parameter (for the counter), and then any 4598 * additional loop-local variable plus loop parameters. 4599 * 4600 * @return a method handle representing the loop. 4601 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4602 * 4603 * @since 9 4604 */ 4605 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4606 Class<?> resultType; 4607 MethodHandle actualInit; 4608 if (init == null) { 4609 resultType = body == null ? void.class : body.type().returnType(); 4610 actualInit = empty(methodType(resultType)); 4611 } else { 4612 resultType = init.type().returnType(); 4613 actualInit = init; 4614 } 4615 MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType); 4616 MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body; 4617 MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class); 4618 MethodHandle actualEnd = end == null ? constant(int.class, 0) : end; 4619 MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)}; 4620 MethodHandle[] loopLimit = {actualEnd, null, 4621 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar}; 4622 MethodHandle[] bodyClause = {actualInit, 4623 filterArgument(dropArguments(actualBody, 1, int.class), 0, 4624 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))}; 4625 return loop(indexVar, loopLimit, bodyClause); 4626 } 4627 4628 /** 4629 * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}. 4630 * The iterator will be produced by the evaluation of the {@code iterator} handle. 4631 * This handle must have {@link java.util.Iterator} as its return type. 4632 * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead, 4633 * and will be applied to a leading argument of the loop handle. 4634 * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter. 4635 * The result of the loop execution is the final value of the additional local state 4636 * obtained by running {@code init}. 4637 * <p> 4638 * This is a convenience wrapper for the 4639 * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body} 4640 * handle follow directly from those described for the latter. 4641 * <p> 4642 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4643 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 4644 * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop. 4645 * <blockquote><pre>{@code 4646 * Iterator<T> iterator(A); // defaults to Iterable::iterator 4647 * V init(A); 4648 * V body(T,V,A); 4649 * V iteratedLoop(A a) { 4650 * Iterator<T> it = iterator(a); 4651 * V v = init(a); 4652 * for (T t : it) { 4653 * v = body(t, v, a); 4654 * } 4655 * return v; 4656 * } 4657 * }</pre></blockquote> 4658 * <p> 4659 * The type {@code T} may be either a primitive or reference. 4660 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type 4661 * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} 4662 * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method. 4663 * Therefore, if an iterator of the wrong type appears as the loop is executed, 4664 * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}. 4665 * <p> 4666 * @apiNote Example: 4667 * <blockquote><pre>{@code 4668 * // reverse a list 4669 * static List<String> reverseStep(String e, List<String> r, List<String> l) { 4670 * r.add(0, e); 4671 * return r; 4672 * } 4673 * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); } 4674 * // assume MH_reverseStep, MH_newArrayList are handles to the above methods 4675 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 4676 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 4677 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 4678 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 4679 * }</pre></blockquote> 4680 * <p> 4681 * @implSpec The implementation of this method is equivalent to (excluding error handling): 4682 * <blockquote><pre>{@code 4683 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4684 * // assume MH_next and MH_hasNext are handles to methods of Iterator 4685 * Class<?> itype = iterator.type().returnType(); 4686 * Class<?> ttype = body.type().parameterType(0); 4687 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype); 4688 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 4689 * MethodHandle[] 4690 * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext) 4691 * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a); 4692 * return loop(iterVar, bodyClause); 4693 * } 4694 * }</pre></blockquote> 4695 * 4696 * @param iterator a handle to return the iterator to start the loop. 4697 * The handle must have {@link java.util.Iterator} as its return type. 4698 * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first 4699 * incoming value. 4700 * @param init initializer for additional loop state. This determines the loop's result type. 4701 * Passing {@code null} or a {@code void} init function will make the loop's result type 4702 * {@code void}. 4703 * @param body the body of the loop, which must not be {@code null}. 4704 * It must accept an initial {@code T} parameter (for the iterated values), and then any 4705 * additional loop-local variable plus loop parameters. 4706 * 4707 * @return a method handle embodying the iteration loop functionality. 4708 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4709 * 4710 * @since 9 4711 */ 4712 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4713 checkIteratedLoop(iterator, body); 4714 Class<?> resultType = init == null ? 4715 body == null ? void.class : body.type().returnType() : 4716 init.type().returnType(); 4717 boolean voidResult = resultType == void.class; 4718 4719 MethodHandle initIterator; 4720 if (iterator == null) { 4721 MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 4722 initIterator = initit.asType(initit.type().changeParameterType(0, 4723 body.type().parameterType(voidResult ? 1 : 2))); 4724 } else { 4725 initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class)); 4726 } 4727 4728 Class<?> ttype = body.type().parameterType(0); 4729 4730 MethodHandle returnVar = 4731 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class); 4732 MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 4733 MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype)); 4734 4735 MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), 4736 returnVar}; 4737 MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)}; 4738 4739 return loop(iterVar, bodyClause); 4740 } 4741 4742 /** 4743 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 4744 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 4745 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 4746 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 4747 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 4748 * {@code try-finally} handle. 4749 * <p> 4750 * The {@code cleanup} handle will be passed one or two additional leading arguments. 4751 * The first is the exception thrown during the 4752 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 4753 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 4754 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 4755 * The second argument is not present if the {@code target} handle has a {@code void} return type. 4756 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 4757 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 4758 * <p> 4759 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 4760 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 4761 * two extra leading parameters:<ul> 4762 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 4763 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 4764 * the result from the execution of the {@code target} handle. 4765 * This parameter is not present if the {@code target} returns {@code void}. 4766 * </ul> 4767 * <p> 4768 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 4769 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 4770 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 4771 * the cleanup. 4772 * <blockquote><pre>{@code 4773 * V target(A..., B...); 4774 * V cleanup(Throwable, V, A...); 4775 * V adapter(A... a, B... b) { 4776 * V result = (zero value for V); 4777 * Throwable throwable = null; 4778 * try { 4779 * result = target(a..., b...); 4780 * } catch (Throwable t) { 4781 * throwable = t; 4782 * throw t; 4783 * } finally { 4784 * result = cleanup(throwable, result, a...); 4785 * } 4786 * return result; 4787 * } 4788 * }</pre></blockquote> 4789 * <p> 4790 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4791 * be modified by execution of the target, and so are passed unchanged 4792 * from the caller to the cleanup, if it is invoked. 4793 * <p> 4794 * The target and cleanup must return the same type, even if the cleanup 4795 * always throws. 4796 * To create such a throwing cleanup, compose the cleanup logic 4797 * with {@link #throwException throwException}, 4798 * in order to create a method handle of the correct return type. 4799 * <p> 4800 * Note that {@code tryFinally} never converts exceptions into normal returns. 4801 * In rare cases where exceptions must be converted in that way, first wrap 4802 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 4803 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 4804 * 4805 * @param target the handle whose execution is to be wrapped in a {@code try} block. 4806 * @param cleanup the handle that is invoked in the finally block. 4807 * 4808 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 4809 * @throws NullPointerException if any argument is null 4810 * @throws IllegalArgumentException if {@code cleanup} does not accept 4811 * the required leading arguments, or if the method handle types do 4812 * not match in their return types and their 4813 * corresponding trailing parameters 4814 * 4815 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 4816 * @since 9 4817 */ 4818 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 4819 List<Class<?>> targetParamTypes = target.type().parameterList(); 4820 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 4821 Class<?> rtype = target.type().returnType(); 4822 4823 checkTryFinally(target, cleanup); 4824 4825 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 4826 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 4827 // target parameter list. 4828 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 4829 4830 return MethodHandleImpl.makeTryFinally(target, cleanup, rtype, targetParamTypes); 4831 } 4832 4833 /** 4834 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 4835 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 4836 * before the folded arguments. 4837 * <p> 4838 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 4839 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 4840 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 4841 * 0. 4842 * <p> 4843 * @apiNote Example: 4844 * <blockquote><pre>{@code 4845 import static java.lang.invoke.MethodHandles.*; 4846 import static java.lang.invoke.MethodType.*; 4847 ... 4848 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4849 "println", methodType(void.class, String.class)) 4850 .bindTo(System.out); 4851 MethodHandle cat = lookup().findVirtual(String.class, 4852 "concat", methodType(String.class, String.class)); 4853 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4854 MethodHandle catTrace = foldArguments(cat, 1, trace); 4855 // also prints "jum": 4856 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4857 * }</pre></blockquote> 4858 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4859 * represents the result type of the {@code target} and resulting adapter. 4860 * {@code V}/{@code v} represent the type and value of the parameter and argument 4861 * of {@code target} that precedes the folding position; {@code V} also is 4862 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4863 * types and values of the {@code N} parameters and arguments at the folding 4864 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 4865 * and values of the {@code target} parameters and arguments that precede and 4866 * follow the folded parameters and arguments starting at {@code pos}, 4867 * respectively. 4868 * <blockquote><pre>{@code 4869 * // there are N arguments in A... 4870 * T target(Z..., V, A[N]..., B...); 4871 * V combiner(A...); 4872 * T adapter(Z... z, A... a, B... b) { 4873 * V v = combiner(a...); 4874 * return target(z..., v, a..., b...); 4875 * } 4876 * // and if the combiner has a void return: 4877 * T target2(Z..., A[N]..., B...); 4878 * void combiner2(A...); 4879 * T adapter2(Z... z, A... a, B... b) { 4880 * combiner2(a...); 4881 * return target2(z..., a..., b...); 4882 * } 4883 * }</pre></blockquote> 4884 * <p> 4885 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4886 * variable-arity method handle}, even if the original target method handle was. 4887 * 4888 * @param target the method handle to invoke after arguments are combined 4889 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 4890 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4891 * @param combiner method handle to call initially on the incoming arguments 4892 * @return method handle which incorporates the specified argument folding logic 4893 * @throws NullPointerException if either argument is null 4894 * @throws IllegalArgumentException if {@code combiner}'s return type 4895 * is non-void and not the same as the argument type at position {@code pos} of 4896 * the target signature, or if the {@code N} argument types at position {@code pos} 4897 * of the target signature 4898 * (skipping one matching the {@code combiner}'s return type) 4899 * are not identical with the argument types of {@code combiner} 4900 * 4901 * @see #foldArguments(MethodHandle, MethodHandle) 4902 * @since 9 4903 */ 4904 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 4905 MethodType targetType = target.type(); 4906 MethodType combinerType = combiner.type(); 4907 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 4908 BoundMethodHandle result = target.rebind(); 4909 boolean dropResult = rtype == void.class; 4910 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 4911 MethodType newType = targetType; 4912 if (!dropResult) { 4913 newType = newType.dropParameterTypes(pos, pos + 1); 4914 } 4915 result = result.copyWithExtendL(newType, lform, combiner); 4916 return result; 4917 } 4918 4919 4920 private static void checkLoop0(MethodHandle[][] clauses) { 4921 if (clauses == null || clauses.length == 0) { 4922 throw newIllegalArgumentException("null or no clauses passed"); 4923 } 4924 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 4925 throw newIllegalArgumentException("null clauses are not allowed"); 4926 } 4927 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 4928 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 4929 } 4930 } 4931 4932 private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) { 4933 if (in.type().returnType() != st.type().returnType()) { 4934 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 4935 st.type().returnType()); 4936 } 4937 } 4938 4939 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 4940 final List<Class<?>> empty = List.of(); 4941 final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList()); 4942 if (nonNullInits.isEmpty()) { 4943 final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull). 4944 // take only those that can contribute to a common suffix because they are longer than the prefix 4945 map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList). 4946 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4947 return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size()); 4948 } else { 4949 return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList). 4950 reduce((p, q) -> p.size() >= q.size() ? p : q).get(); 4951 } 4952 } 4953 4954 private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 4955 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList). 4956 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) { 4957 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 4958 " (common suffix: " + commonSuffix + ")"); 4959 } 4960 } 4961 4962 private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 4963 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4964 anyMatch(t -> t != loopReturnType)) { 4965 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 4966 loopReturnType + ")"); 4967 } 4968 4969 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 4970 throw newIllegalArgumentException("no predicate found", pred); 4971 } 4972 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4973 anyMatch(t -> t != boolean.class)) { 4974 throw newIllegalArgumentException("predicates must have boolean return type", pred); 4975 } 4976 } 4977 4978 private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 4979 final int cpSize = commonParameterSequence.size(); 4980 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 4981 map(MethodType::parameterList). 4982 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) { 4983 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 4984 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 4985 } 4986 } 4987 4988 private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) { 4989 if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) { 4990 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 4991 } 4992 if (null == body) { 4993 throw newIllegalArgumentException("iterated loop body must not be null"); 4994 } 4995 } 4996 4997 private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) { 4998 Class<?> rtype = target.type().returnType(); 4999 if (rtype != cleanup.type().returnType()) { 5000 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 5001 } 5002 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 5003 if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) { 5004 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 5005 } 5006 if (rtype != void.class && cleanupParamTypes.get(1) != rtype) { 5007 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 5008 } 5009 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 5010 // target parameter list. 5011 int cleanupArgIndex = rtype == void.class ? 1 : 2; 5012 List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()); 5013 List<Class<?>> targetParamTypes = target.type().parameterList(); 5014 if (targetParamTypes.size() < cleanupArgSuffix.size() || 5015 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) { 5016 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 5017 cleanup.type(), target.type()); 5018 } 5019 } 5020 5021 }