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 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, numeric atomic update, and bitwise atomic update access 1211 * modes are unsupported. 1212 * <li>if the field type is anything other than {@code byte}, 1213 * {@code short}, {@code char}, {@code int}, {@code long}, 1214 * {@code float}, or {@code double} then numeric atomic update 1215 * access modes are unsupported. 1216 * <li>if the field type is anything other than {@code boolean}, 1217 * {@code byte}, {@code short}, {@code char}, {@code int} or 1218 * {@code long} then bitwise atomic update access modes are 1219 * unsupported. 1220 * </ul> 1221 * <p> 1222 * If the field is declared {@code volatile} then the returned VarHandle 1223 * will override access to the field (effectively ignore the 1224 * {@code volatile} declaration) in accordance to it's specified 1225 * access modes. 1226 * <p> 1227 * If the field type is {@code float} or {@code double} then numeric 1228 * and atomic update access modes compare values using their bitwise 1229 * representation (see {@link Float#floatToRawIntBits} and 1230 * {@link Double#doubleToRawLongBits}, respectively). 1231 * @apiNote 1232 * Bitwise comparison of {@code float} values or {@code double} values, 1233 * as performed by the numeric and atomic update access modes, differ 1234 * from the primitive {@code ==} operator and the {@link Float#equals} 1235 * and {@link Double#equals} methods, specifically with respect to 1236 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1237 * Care should be taken when performing a compare and set or a compare 1238 * and exchange operation with such values since the operation may 1239 * unexpectedly fail. 1240 * There are many possible NaN values that are considered to be 1241 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1242 * provided by Java can distinguish between them. Operation failure can 1243 * occur if the expected or witness value is a NaN value and it is 1244 * transformed (perhaps in a platform specific manner) into another NaN 1245 * value, and thus has a different bitwise representation (see 1246 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1247 * details). 1248 * The values {@code -0.0} and {@code +0.0} have different bitwise 1249 * representations but are considered equal when using the primitive 1250 * {@code ==} operator. Operation failure can occur if, for example, a 1251 * numeric algorithm computes an expected value to be say {@code -0.0} 1252 * and previously computed the witness value to be say {@code +0.0}. 1253 * @param recv the receiver class, of type {@code R}, that declares the 1254 * non-static field 1255 * @param name the field's name 1256 * @param type the field's type, of type {@code T} 1257 * @return a VarHandle giving access to non-static fields. 1258 * @throws NoSuchFieldException if the field does not exist 1259 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1260 * @exception SecurityException if a security manager is present and it 1261 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1262 * @throws NullPointerException if any argument is null 1263 * @since 9 1264 */ 1265 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1266 MemberName getField = resolveOrFail(REF_getField, recv, name, type); 1267 MemberName putField = resolveOrFail(REF_putField, recv, name, type); 1268 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); 1269 } 1270 1271 /** 1272 * Produces a method handle giving read access to a static field. 1273 * The type of the method handle will have a return type of the field's 1274 * value type. 1275 * The method handle will take no arguments. 1276 * Access checking is performed immediately on behalf of the lookup class. 1277 * <p> 1278 * If the returned method handle is invoked, the field's class will 1279 * be initialized, if it has not already been initialized. 1280 * @param refc the class or interface from which the method is accessed 1281 * @param name the field's name 1282 * @param type the field's type 1283 * @return a method handle which can load values from the field 1284 * @throws NoSuchFieldException if the field does not exist 1285 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1286 * @exception SecurityException if a security manager is present and it 1287 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1288 * @throws NullPointerException if any argument is null 1289 */ 1290 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1291 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 1292 return getDirectField(REF_getStatic, refc, field); 1293 } 1294 1295 /** 1296 * Produces a method handle giving write access to a static field. 1297 * The type of the method handle will have a void return type. 1298 * The method handle will take a single 1299 * argument, of the field's value type, the value to be stored. 1300 * Access checking is performed immediately on behalf of the lookup class. 1301 * <p> 1302 * If the returned method handle is invoked, the field's class will 1303 * be initialized, if it has not already been initialized. 1304 * @param refc the class or interface from which the method is accessed 1305 * @param name the field's name 1306 * @param type the field's type 1307 * @return a method handle which can store values into the field 1308 * @throws NoSuchFieldException if the field does not exist 1309 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1310 * @exception SecurityException if a security manager is present and it 1311 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1312 * @throws NullPointerException if any argument is null 1313 */ 1314 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1315 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 1316 return getDirectField(REF_putStatic, refc, field); 1317 } 1318 1319 /** 1320 * Produces a VarHandle giving access to a static field of type 1321 * {@code T} declared by a given declaring class, supporting shape 1322 * {@code ((empty) : T)}. 1323 * <p> 1324 * Access checking is performed immediately on behalf of the lookup 1325 * class. 1326 * <p> 1327 * If the returned VarHandle is operated on, the declaring class will be 1328 * initialized, if it has not already been initialized. 1329 * <p> 1330 * Certain access modes of the returned VarHandle are unsupported under 1331 * the following conditions: 1332 * <ul> 1333 * <li>if the field is declared {@code final}, then the write, atomic 1334 * update, numeric atomic update, and bitwise atomic update access 1335 * modes are unsupported. 1336 * <li>if the field type is anything other than {@code byte}, 1337 * {@code short}, {@code char}, {@code int}, {@code long}, 1338 * {@code float}, or {@code double}, then numeric atomic update 1339 * access modes are unsupported. 1340 * <li>if the field type is anything other than {@code boolean}, 1341 * {@code byte}, {@code short}, {@code char}, {@code int} or 1342 * {@code long} then bitwise atomic update access modes are 1343 * unsupported. 1344 * </ul> 1345 * <p> 1346 * If the field is declared {@code volatile} then the returned VarHandle 1347 * will override access to the field (effectively ignore the 1348 * {@code volatile} declaration) in accordance to it's specified 1349 * access modes. 1350 * <p> 1351 * If the field type is {@code float} or {@code double} then numeric 1352 * and atomic update access modes compare values using their bitwise 1353 * representation (see {@link Float#floatToRawIntBits} and 1354 * {@link Double#doubleToRawLongBits}, respectively). 1355 * @apiNote 1356 * Bitwise comparison of {@code float} values or {@code double} values, 1357 * as performed by the numeric and atomic update access modes, differ 1358 * from the primitive {@code ==} operator and the {@link Float#equals} 1359 * and {@link Double#equals} methods, specifically with respect to 1360 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1361 * Care should be taken when performing a compare and set or a compare 1362 * and exchange operation with such values since the operation may 1363 * unexpectedly fail. 1364 * There are many possible NaN values that are considered to be 1365 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1366 * provided by Java can distinguish between them. Operation failure can 1367 * occur if the expected or witness value is a NaN value and it is 1368 * transformed (perhaps in a platform specific manner) into another NaN 1369 * value, and thus has a different bitwise representation (see 1370 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1371 * details). 1372 * The values {@code -0.0} and {@code +0.0} have different bitwise 1373 * representations but are considered equal when using the primitive 1374 * {@code ==} operator. Operation failure can occur if, for example, a 1375 * numeric algorithm computes an expected value to be say {@code -0.0} 1376 * and previously computed the witness value to be say {@code +0.0}. 1377 * @param decl the class that declares the static field 1378 * @param name the field's name 1379 * @param type the field's type, of type {@code T} 1380 * @return a VarHandle giving access to a static field 1381 * @throws NoSuchFieldException if the field does not exist 1382 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1383 * @exception SecurityException if a security manager is present and it 1384 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1385 * @throws NullPointerException if any argument is null 1386 * @since 9 1387 */ 1388 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1389 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); 1390 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); 1391 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); 1392 } 1393 1394 /** 1395 * Produces an early-bound method handle for a non-static method. 1396 * The receiver must have a supertype {@code defc} in which a method 1397 * of the given name and type is accessible to the lookup class. 1398 * The method and all its argument types must be accessible to the lookup object. 1399 * The type of the method handle will be that of the method, 1400 * without any insertion of an additional receiver parameter. 1401 * The given receiver will be bound into the method handle, 1402 * so that every call to the method handle will invoke the 1403 * requested method on the given receiver. 1404 * <p> 1405 * The returned method handle will have 1406 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1407 * the method's variable arity modifier bit ({@code 0x0080}) is set 1408 * <em>and</em> the trailing array argument is not the only argument. 1409 * (If the trailing array argument is the only argument, 1410 * the given receiver value will be bound to it.) 1411 * <p> 1412 * This is equivalent to the following code: 1413 * <blockquote><pre>{@code 1414 import static java.lang.invoke.MethodHandles.*; 1415 import static java.lang.invoke.MethodType.*; 1416 ... 1417 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 1418 MethodHandle mh1 = mh0.bindTo(receiver); 1419 mh1 = mh1.withVarargs(mh0.isVarargsCollector()); 1420 return mh1; 1421 * }</pre></blockquote> 1422 * where {@code defc} is either {@code receiver.getClass()} or a super 1423 * type of that class, in which the requested method is accessible 1424 * to the lookup class. 1425 * (Note that {@code bindTo} does not preserve variable arity.) 1426 * @param receiver the object from which the method is accessed 1427 * @param name the name of the method 1428 * @param type the type of the method, with the receiver argument omitted 1429 * @return the desired method handle 1430 * @throws NoSuchMethodException if the method does not exist 1431 * @throws IllegalAccessException if access checking fails 1432 * or if the method's variable arity modifier bit 1433 * is set and {@code asVarargsCollector} fails 1434 * @exception SecurityException if a security manager is present and it 1435 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1436 * @throws NullPointerException if any argument is null 1437 * @see MethodHandle#bindTo 1438 * @see #findVirtual 1439 */ 1440 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1441 Class<? extends Object> refc = receiver.getClass(); // may get NPE 1442 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 1443 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1444 return mh.bindArgumentL(0, receiver).setVarargs(method); 1445 } 1446 1447 /** 1448 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1449 * to <i>m</i>, if the lookup class has permission. 1450 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 1451 * If <i>m</i> is virtual, overriding is respected on every call. 1452 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 1453 * The type of the method handle will be that of the method, 1454 * with the receiver type prepended (but only if it is non-static). 1455 * If the method's {@code accessible} flag is not set, 1456 * access checking is performed immediately on behalf of the lookup class. 1457 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 1458 * <p> 1459 * The returned method handle will have 1460 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1461 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1462 * <p> 1463 * If <i>m</i> is static, and 1464 * if the returned method handle is invoked, the method's class will 1465 * be initialized, if it has not already been initialized. 1466 * @param m the reflected method 1467 * @return a method handle which can invoke the reflected method 1468 * @throws IllegalAccessException if access checking fails 1469 * or if the method's variable arity modifier bit 1470 * is set and {@code asVarargsCollector} fails 1471 * @throws NullPointerException if the argument is null 1472 */ 1473 public MethodHandle unreflect(Method m) throws IllegalAccessException { 1474 if (m.getDeclaringClass() == MethodHandle.class) { 1475 MethodHandle mh = unreflectForMH(m); 1476 if (mh != null) return mh; 1477 } 1478 if (m.getDeclaringClass() == VarHandle.class) { 1479 MethodHandle mh = unreflectForVH(m); 1480 if (mh != null) return mh; 1481 } 1482 MemberName method = new MemberName(m); 1483 byte refKind = method.getReferenceKind(); 1484 if (refKind == REF_invokeSpecial) 1485 refKind = REF_invokeVirtual; 1486 assert(method.isMethod()); 1487 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 1488 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1489 } 1490 private MethodHandle unreflectForMH(Method m) { 1491 // these names require special lookups because they throw UnsupportedOperationException 1492 if (MemberName.isMethodHandleInvokeName(m.getName())) 1493 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); 1494 return null; 1495 } 1496 private MethodHandle unreflectForVH(Method m) { 1497 // these names require special lookups because they throw UnsupportedOperationException 1498 if (MemberName.isVarHandleMethodInvokeName(m.getName())) 1499 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); 1500 return null; 1501 } 1502 1503 /** 1504 * Produces a method handle for a reflected method. 1505 * It will bypass checks for overriding methods on the receiver, 1506 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1507 * instruction from within the explicitly specified {@code specialCaller}. 1508 * The type of the method handle will be that of the method, 1509 * with a suitably restricted receiver type prepended. 1510 * (The receiver type will be {@code specialCaller} or a subtype.) 1511 * If the method's {@code accessible} flag is not set, 1512 * access checking is performed immediately on behalf of the lookup class, 1513 * as if {@code invokespecial} instruction were being linked. 1514 * <p> 1515 * Before method resolution, 1516 * if the explicitly specified caller class is not identical with the 1517 * lookup class, or if this lookup object does not have 1518 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1519 * privileges, the access fails. 1520 * <p> 1521 * The returned method handle will have 1522 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1523 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1524 * @param m the reflected method 1525 * @param specialCaller the class nominally calling the method 1526 * @return a method handle which can invoke the reflected method 1527 * @throws IllegalAccessException if access checking fails, 1528 * or if the method is {@code static}, 1529 * or if the method's variable arity modifier bit 1530 * is set and {@code asVarargsCollector} fails 1531 * @throws NullPointerException if any argument is null 1532 */ 1533 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 1534 checkSpecialCaller(specialCaller, null); 1535 Lookup specialLookup = this.in(specialCaller); 1536 MemberName method = new MemberName(m, true); 1537 assert(method.isMethod()); 1538 // ignore m.isAccessible: this is a new kind of access 1539 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1540 } 1541 1542 /** 1543 * Produces a method handle for a reflected constructor. 1544 * The type of the method handle will be that of the constructor, 1545 * with the return type changed to the declaring class. 1546 * The method handle will perform a {@code newInstance} operation, 1547 * creating a new instance of the constructor's class on the 1548 * arguments passed to the method handle. 1549 * <p> 1550 * If the constructor's {@code accessible} flag is not set, 1551 * access checking is performed immediately on behalf of the lookup class. 1552 * <p> 1553 * The returned method handle will have 1554 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1555 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1556 * <p> 1557 * If the returned method handle is invoked, the constructor's class will 1558 * be initialized, if it has not already been initialized. 1559 * @param c the reflected constructor 1560 * @return a method handle which can invoke the reflected constructor 1561 * @throws IllegalAccessException if access checking fails 1562 * or if the method's variable arity modifier bit 1563 * is set and {@code asVarargsCollector} fails 1564 * @throws NullPointerException if the argument is null 1565 */ 1566 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 1567 MemberName ctor = new MemberName(c); 1568 assert(ctor.isConstructor()); 1569 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 1570 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 1571 } 1572 1573 /** 1574 * Produces a method handle giving read access to a reflected field. 1575 * The type of the method handle will have a return type of the field's 1576 * value type. 1577 * If the field is static, the method handle will take no arguments. 1578 * Otherwise, its single argument will be the instance containing 1579 * the field. 1580 * If the field's {@code accessible} flag is not set, 1581 * access checking is performed immediately on behalf of the lookup class. 1582 * <p> 1583 * If the field is static, and 1584 * if the returned method handle is invoked, the field's class will 1585 * be initialized, if it has not already been initialized. 1586 * @param f the reflected field 1587 * @return a method handle which can load values from the reflected field 1588 * @throws IllegalAccessException if access checking fails 1589 * @throws NullPointerException if the argument is null 1590 */ 1591 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1592 return unreflectField(f, false); 1593 } 1594 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 1595 MemberName field = new MemberName(f, isSetter); 1596 assert(isSetter 1597 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 1598 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 1599 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 1600 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 1601 } 1602 1603 /** 1604 * Produces a method handle giving write access to a reflected field. 1605 * The type of the method handle will have a void return type. 1606 * If the field is static, the method handle will take a single 1607 * argument, of the field's value type, the value to be stored. 1608 * Otherwise, the two arguments will be the instance containing 1609 * the field, and the value to be stored. 1610 * If the field's {@code accessible} flag is not set, 1611 * access checking is performed immediately on behalf of the lookup class. 1612 * <p> 1613 * If the field is static, and 1614 * if the returned method handle is invoked, the field's class will 1615 * be initialized, if it has not already been initialized. 1616 * @param f the reflected field 1617 * @return a method handle which can store values into the reflected field 1618 * @throws IllegalAccessException if access checking fails 1619 * @throws NullPointerException if the argument is null 1620 */ 1621 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1622 return unreflectField(f, true); 1623 } 1624 1625 /** 1626 * Produces a VarHandle that accesses fields of type {@code T} declared 1627 * by a class of type {@code R}, as described by the given reflected 1628 * field. 1629 * If the field is non-static the VarHandle supports a shape of 1630 * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}. 1631 * <p> 1632 * Access checking is performed immediately on behalf of the lookup 1633 * class, regardless of the value of the field's {@code accessible} 1634 * flag. 1635 * <p> 1636 * If the field is static, and if the returned VarHandle is operated 1637 * on, the field's declaring class will be initialized, if it has not 1638 * already been initialized. 1639 * <p> 1640 * Certain access modes of the returned VarHandle are unsupported under 1641 * the following conditions: 1642 * <ul> 1643 * <li>if the field is declared {@code final}, then the write, atomic 1644 * update, numeric atomic update, and bitwise atomic update access 1645 * modes are unsupported. 1646 * <li>if the field type is anything other than {@code byte}, 1647 * {@code short}, {@code char}, {@code int}, {@code long}, 1648 * {@code float}, or {@code double} then numeric atomic update 1649 * access modes are unsupported. 1650 * <li>if the field type is anything other than {@code boolean}, 1651 * {@code byte}, {@code short}, {@code char}, {@code int} or 1652 * {@code long} then bitwise atomic update access modes are 1653 * unsupported. 1654 * </ul> 1655 * <p> 1656 * If the field is declared {@code volatile} then the returned VarHandle 1657 * will override access to the field (effectively ignore the 1658 * {@code volatile} declaration) in accordance to it's specified 1659 * access modes. 1660 * <p> 1661 * If the field type is {@code float} or {@code double} then numeric 1662 * and atomic update access modes compare values using their bitwise 1663 * representation (see {@link Float#floatToRawIntBits} and 1664 * {@link Double#doubleToRawLongBits}, respectively). 1665 * @apiNote 1666 * Bitwise comparison of {@code float} values or {@code double} values, 1667 * as performed by the numeric and atomic update access modes, differ 1668 * from the primitive {@code ==} operator and the {@link Float#equals} 1669 * and {@link Double#equals} methods, specifically with respect to 1670 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1671 * Care should be taken when performing a compare and set or a compare 1672 * and exchange operation with such values since the operation may 1673 * unexpectedly fail. 1674 * There are many possible NaN values that are considered to be 1675 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1676 * provided by Java can distinguish between them. Operation failure can 1677 * occur if the expected or witness value is a NaN value and it is 1678 * transformed (perhaps in a platform specific manner) into another NaN 1679 * value, and thus has a different bitwise representation (see 1680 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1681 * details). 1682 * The values {@code -0.0} and {@code +0.0} have different bitwise 1683 * representations but are considered equal when using the primitive 1684 * {@code ==} operator. Operation failure can occur if, for example, a 1685 * numeric algorithm computes an expected value to be say {@code -0.0} 1686 * and previously computed the witness value to be say {@code +0.0}. 1687 * @param f the reflected field, with a field of type {@code T}, and 1688 * a declaring class of type {@code R} 1689 * @return a VarHandle giving access to non-static fields or a static 1690 * field 1691 * @throws IllegalAccessException if access checking fails 1692 * @throws NullPointerException if the argument is null 1693 * @since 9 1694 */ 1695 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 1696 MemberName getField = new MemberName(f, false); 1697 MemberName putField = new MemberName(f, true); 1698 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), 1699 f.getDeclaringClass(), getField, putField); 1700 } 1701 1702 /** 1703 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1704 * created by this lookup object or a similar one. 1705 * Security and access checks are performed to ensure that this lookup object 1706 * is capable of reproducing the target method handle. 1707 * This means that the cracking may fail if target is a direct method handle 1708 * but was created by an unrelated lookup object. 1709 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 1710 * and was created by a lookup object for a different class. 1711 * @param target a direct method handle to crack into symbolic reference components 1712 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 1713 * @exception SecurityException if a security manager is present and it 1714 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1715 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 1716 * @exception NullPointerException if the target is {@code null} 1717 * @see MethodHandleInfo 1718 * @since 1.8 1719 */ 1720 public MethodHandleInfo revealDirect(MethodHandle target) { 1721 MemberName member = target.internalMemberName(); 1722 if (member == null || (!member.isResolved() && 1723 !member.isMethodHandleInvoke() && 1724 !member.isVarHandleMethodInvoke())) 1725 throw newIllegalArgumentException("not a direct method handle"); 1726 Class<?> defc = member.getDeclaringClass(); 1727 byte refKind = member.getReferenceKind(); 1728 assert(MethodHandleNatives.refKindIsValid(refKind)); 1729 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 1730 // Devirtualized method invocation is usually formally virtual. 1731 // To avoid creating extra MemberName objects for this common case, 1732 // we encode this extra degree of freedom using MH.isInvokeSpecial. 1733 refKind = REF_invokeVirtual; 1734 if (refKind == REF_invokeVirtual && defc.isInterface()) 1735 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 1736 refKind = REF_invokeInterface; 1737 // Check SM permissions and member access before cracking. 1738 try { 1739 checkAccess(refKind, defc, member); 1740 checkSecurityManager(defc, member); 1741 } catch (IllegalAccessException ex) { 1742 throw new IllegalArgumentException(ex); 1743 } 1744 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 1745 Class<?> callerClass = target.internalCallerClass(); 1746 if (!hasPrivateAccess() || callerClass != lookupClass()) 1747 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 1748 } 1749 // Produce the handle to the results. 1750 return new InfoFromMemberName(this, member, refKind); 1751 } 1752 1753 /// Helper methods, all package-private. 1754 1755 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1756 checkSymbolicClass(refc); // do this before attempting to resolve 1757 Objects.requireNonNull(name); 1758 Objects.requireNonNull(type); 1759 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1760 NoSuchFieldException.class); 1761 } 1762 1763 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1764 checkSymbolicClass(refc); // do this before attempting to resolve 1765 Objects.requireNonNull(name); 1766 Objects.requireNonNull(type); 1767 checkMethodName(refKind, name); // NPE check on name 1768 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1769 NoSuchMethodException.class); 1770 } 1771 1772 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 1773 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 1774 Objects.requireNonNull(member.getName()); 1775 Objects.requireNonNull(member.getType()); 1776 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), 1777 ReflectiveOperationException.class); 1778 } 1779 1780 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 1781 Objects.requireNonNull(refc); 1782 Class<?> caller = lookupClassOrNull(); 1783 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) 1784 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); 1785 } 1786 1787 /** Check name for an illegal leading "<" character. */ 1788 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 1789 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 1790 throw new NoSuchMethodException("illegal method name: "+name); 1791 } 1792 1793 1794 /** 1795 * Find my trustable caller class if m is a caller sensitive method. 1796 * If this lookup object has private access, then the caller class is the lookupClass. 1797 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 1798 */ 1799 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { 1800 Class<?> callerClass = null; 1801 if (MethodHandleNatives.isCallerSensitive(m)) { 1802 // Only lookups with private access are allowed to resolve caller-sensitive methods 1803 if (hasPrivateAccess()) { 1804 callerClass = lookupClass; 1805 } else { 1806 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 1807 } 1808 } 1809 return callerClass; 1810 } 1811 1812 private boolean hasPrivateAccess() { 1813 return (allowedModes & PRIVATE) != 0; 1814 } 1815 1816 /** 1817 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 1818 * Determines a trustable caller class to compare with refc, the symbolic reference class. 1819 * If this lookup object has private access, then the caller class is the lookupClass. 1820 */ 1821 void checkSecurityManager(Class<?> refc, MemberName m) { 1822 SecurityManager smgr = System.getSecurityManager(); 1823 if (smgr == null) return; 1824 if (allowedModes == TRUSTED) return; 1825 1826 // Step 1: 1827 boolean fullPowerLookup = hasPrivateAccess(); 1828 if (!fullPowerLookup || 1829 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 1830 ReflectUtil.checkPackageAccess(refc); 1831 } 1832 1833 if (m == null) { // findClass or accessClass 1834 // Step 2b: 1835 if (!fullPowerLookup) { 1836 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1837 } 1838 return; 1839 } 1840 1841 // Step 2a: 1842 if (m.isPublic()) return; 1843 if (!fullPowerLookup) { 1844 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 1845 } 1846 1847 // Step 3: 1848 Class<?> defc = m.getDeclaringClass(); 1849 if (!fullPowerLookup && defc != refc) { 1850 ReflectUtil.checkPackageAccess(defc); 1851 } 1852 } 1853 1854 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1855 boolean wantStatic = (refKind == REF_invokeStatic); 1856 String message; 1857 if (m.isConstructor()) 1858 message = "expected a method, not a constructor"; 1859 else if (!m.isMethod()) 1860 message = "expected a method"; 1861 else if (wantStatic != m.isStatic()) 1862 message = wantStatic ? "expected a static method" : "expected a non-static method"; 1863 else 1864 { checkAccess(refKind, refc, m); return; } 1865 throw m.makeAccessException(message, this); 1866 } 1867 1868 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1869 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 1870 String message; 1871 if (wantStatic != m.isStatic()) 1872 message = wantStatic ? "expected a static field" : "expected a non-static field"; 1873 else 1874 { checkAccess(refKind, refc, m); return; } 1875 throw m.makeAccessException(message, this); 1876 } 1877 1878 /** Check public/protected/private bits on the symbolic reference class and its member. */ 1879 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1880 assert(m.referenceKindIsConsistentWith(refKind) && 1881 MethodHandleNatives.refKindIsValid(refKind) && 1882 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 1883 int allowedModes = this.allowedModes; 1884 if (allowedModes == TRUSTED) return; 1885 int mods = m.getModifiers(); 1886 if (Modifier.isProtected(mods) && 1887 refKind == REF_invokeVirtual && 1888 m.getDeclaringClass() == Object.class && 1889 m.getName().equals("clone") && 1890 refc.isArray()) { 1891 // The JVM does this hack also. 1892 // (See ClassVerifier::verify_invoke_instructions 1893 // and LinkResolver::check_method_accessability.) 1894 // Because the JVM does not allow separate methods on array types, 1895 // there is no separate method for int[].clone. 1896 // All arrays simply inherit Object.clone. 1897 // But for access checking logic, we make Object.clone 1898 // (normally protected) appear to be public. 1899 // Later on, when the DirectMethodHandle is created, 1900 // its leading argument will be restricted to the 1901 // requested array type. 1902 // N.B. The return type is not adjusted, because 1903 // that is *not* the bytecode behavior. 1904 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 1905 } 1906 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 1907 // cannot "new" a protected ctor in a different package 1908 mods ^= Modifier.PROTECTED; 1909 } 1910 if (Modifier.isFinal(mods) && 1911 MethodHandleNatives.refKindIsSetter(refKind)) 1912 throw m.makeAccessException("unexpected set of a final field", this); 1913 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1914 if ((requestedModes & allowedModes) != 0) { 1915 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 1916 mods, lookupClass(), allowedModes)) 1917 return; 1918 } else { 1919 // Protected members can also be checked as if they were package-private. 1920 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1921 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 1922 return; 1923 } 1924 throw m.makeAccessException(accessFailedMessage(refc, m), this); 1925 } 1926 1927 String accessFailedMessage(Class<?> refc, MemberName m) { 1928 Class<?> defc = m.getDeclaringClass(); 1929 int mods = m.getModifiers(); 1930 // check the class first: 1931 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1932 (defc == refc || 1933 Modifier.isPublic(refc.getModifiers()))); 1934 if (!classOK && (allowedModes & PACKAGE) != 0) { 1935 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1936 (defc == refc || 1937 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1938 } 1939 if (!classOK) 1940 return "class is not public"; 1941 if (Modifier.isPublic(mods)) 1942 return "access to public member failed"; // (how?, module not readable?) 1943 if (Modifier.isPrivate(mods)) 1944 return "member is private"; 1945 if (Modifier.isProtected(mods)) 1946 return "member is protected"; 1947 return "member is private to package"; 1948 } 1949 1950 private static final boolean ALLOW_NESTMATE_ACCESS = false; 1951 1952 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 1953 int allowedModes = this.allowedModes; 1954 if (allowedModes == TRUSTED) return; 1955 if (!hasPrivateAccess() 1956 || (specialCaller != lookupClass() 1957 // ensure non-abstract methods in superinterfaces can be special-invoked 1958 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)) 1959 && !(ALLOW_NESTMATE_ACCESS && 1960 VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) 1961 throw new MemberName(specialCaller). 1962 makeAccessException("no private access for invokespecial", this); 1963 } 1964 1965 private boolean restrictProtectedReceiver(MemberName method) { 1966 // The accessing class only has the right to use a protected member 1967 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 1968 if (!method.isProtected() || method.isStatic() 1969 || allowedModes == TRUSTED 1970 || method.getDeclaringClass() == lookupClass() 1971 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) 1972 || (ALLOW_NESTMATE_ACCESS && 1973 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) 1974 return false; 1975 return true; 1976 } 1977 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 1978 assert(!method.isStatic()); 1979 // receiver type of mh is too wide; narrow to caller 1980 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 1981 throw method.makeAccessException("caller class must be a subclass below the method", caller); 1982 } 1983 MethodType rawType = mh.type(); 1984 if (rawType.parameterType(0) == caller) return mh; 1985 MethodType narrowType = rawType.changeParameterType(0, caller); 1986 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 1987 assert(mh.viewAsTypeChecks(narrowType, true)); 1988 return mh.copyWith(narrowType, mh.form); 1989 } 1990 1991 /** Check access and get the requested method. */ 1992 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1993 final boolean doRestrict = true; 1994 final boolean checkSecurity = true; 1995 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1996 } 1997 /** Check access and get the requested method, eliding receiver narrowing rules. */ 1998 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1999 final boolean doRestrict = false; 2000 final boolean checkSecurity = true; 2001 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 2002 } 2003 /** Check access and get the requested method, eliding security manager checks. */ 2004 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 2005 final boolean doRestrict = true; 2006 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2007 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 2008 } 2009 /** Common code for all methods; do not call directly except from immediately above. */ 2010 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 2011 boolean checkSecurity, 2012 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { 2013 checkMethod(refKind, refc, method); 2014 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2015 if (checkSecurity) 2016 checkSecurityManager(refc, method); 2017 assert(!method.isMethodHandleInvoke()); 2018 2019 if (refKind == REF_invokeSpecial && 2020 refc != lookupClass() && 2021 !refc.isInterface() && 2022 refc != lookupClass().getSuperclass() && 2023 refc.isAssignableFrom(lookupClass())) { 2024 assert(!method.getName().equals("<init>")); // not this code path 2025 // Per JVMS 6.5, desc. of invokespecial instruction: 2026 // If the method is in a superclass of the LC, 2027 // and if our original search was above LC.super, 2028 // repeat the search (symbolic lookup) from LC.super 2029 // and continue with the direct superclass of that class, 2030 // and so forth, until a match is found or no further superclasses exist. 2031 // FIXME: MemberName.resolve should handle this instead. 2032 Class<?> refcAsSuper = lookupClass(); 2033 MemberName m2; 2034 do { 2035 refcAsSuper = refcAsSuper.getSuperclass(); 2036 m2 = new MemberName(refcAsSuper, 2037 method.getName(), 2038 method.getMethodType(), 2039 REF_invokeSpecial); 2040 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 2041 } while (m2 == null && // no method is found yet 2042 refc != refcAsSuper); // search up to refc 2043 if (m2 == null) throw new InternalError(method.toString()); 2044 method = m2; 2045 refc = refcAsSuper; 2046 // redo basic checks 2047 checkMethod(refKind, refc, method); 2048 } 2049 2050 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); 2051 MethodHandle mh = dmh; 2052 // Optionally narrow the receiver argument to refc using restrictReceiver. 2053 if (doRestrict && 2054 (refKind == REF_invokeSpecial || 2055 (MethodHandleNatives.refKindHasReceiver(refKind) && 2056 restrictProtectedReceiver(method)))) { 2057 mh = restrictReceiver(method, dmh, lookupClass()); 2058 } 2059 mh = maybeBindCaller(method, mh, callerClass); 2060 mh = mh.setVarargs(method); 2061 return mh; 2062 } 2063 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 2064 Class<?> callerClass) 2065 throws IllegalAccessException { 2066 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 2067 return mh; 2068 Class<?> hostClass = lookupClass; 2069 if (!hasPrivateAccess()) // caller must have private access 2070 hostClass = callerClass; // callerClass came from a security manager style stack walk 2071 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 2072 // Note: caller will apply varargs after this step happens. 2073 return cbmh; 2074 } 2075 /** Check access and get the requested field. */ 2076 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2077 final boolean checkSecurity = true; 2078 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2079 } 2080 /** Check access and get the requested field, eliding security manager checks. */ 2081 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 2082 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2083 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 2084 } 2085 /** Common code for all fields; do not call directly except from immediately above. */ 2086 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 2087 boolean checkSecurity) throws IllegalAccessException { 2088 checkField(refKind, refc, field); 2089 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2090 if (checkSecurity) 2091 checkSecurityManager(refc, field); 2092 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 2093 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 2094 restrictProtectedReceiver(field)); 2095 if (doRestrict) 2096 return restrictReceiver(field, dmh, lookupClass()); 2097 return dmh; 2098 } 2099 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, 2100 Class<?> refc, MemberName getField, MemberName putField) 2101 throws IllegalAccessException { 2102 final boolean checkSecurity = true; 2103 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2104 } 2105 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, 2106 Class<?> refc, MemberName getField, MemberName putField) 2107 throws IllegalAccessException { 2108 final boolean checkSecurity = false; 2109 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); 2110 } 2111 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, 2112 Class<?> refc, MemberName getField, MemberName putField, 2113 boolean checkSecurity) throws IllegalAccessException { 2114 assert getField.isStatic() == putField.isStatic(); 2115 assert getField.isGetter() && putField.isSetter(); 2116 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); 2117 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); 2118 2119 checkField(getRefKind, refc, getField); 2120 if (checkSecurity) 2121 checkSecurityManager(refc, getField); 2122 2123 if (!putField.isFinal()) { 2124 // A VarHandle does not support updates to final fields, any 2125 // such VarHandle to a final field will be read-only and 2126 // therefore the following write-based accessibility checks are 2127 // only required for non-final fields 2128 checkField(putRefKind, refc, putField); 2129 if (checkSecurity) 2130 checkSecurityManager(refc, putField); 2131 } 2132 2133 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && 2134 restrictProtectedReceiver(getField)); 2135 if (doRestrict) { 2136 assert !getField.isStatic(); 2137 // receiver type of VarHandle is too wide; narrow to caller 2138 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { 2139 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); 2140 } 2141 refc = lookupClass(); 2142 } 2143 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); 2144 } 2145 /** Check access and get the requested constructor. */ 2146 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2147 final boolean checkSecurity = true; 2148 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2149 } 2150 /** Check access and get the requested constructor, eliding security manager checks. */ 2151 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 2152 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 2153 return getDirectConstructorCommon(refc, ctor, checkSecurity); 2154 } 2155 /** Common code for all constructors; do not call directly except from immediately above. */ 2156 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 2157 boolean checkSecurity) throws IllegalAccessException { 2158 assert(ctor.isConstructor()); 2159 checkAccess(REF_newInvokeSpecial, refc, ctor); 2160 // Optionally check with the security manager; this isn't needed for unreflect* calls. 2161 if (checkSecurity) 2162 checkSecurityManager(refc, ctor); 2163 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 2164 return DirectMethodHandle.make(ctor).setVarargs(ctor); 2165 } 2166 2167 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 2168 */ 2169 /*non-public*/ 2170 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 2171 if (!(type instanceof Class || type instanceof MethodType)) 2172 throw new InternalError("unresolved MemberName"); 2173 MemberName member = new MemberName(refKind, defc, name, type); 2174 MethodHandle mh = LOOKASIDE_TABLE.get(member); 2175 if (mh != null) { 2176 checkSymbolicClass(defc); 2177 return mh; 2178 } 2179 // Treat MethodHandle.invoke and invokeExact specially. 2180 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 2181 mh = findVirtualForMH(member.getName(), member.getMethodType()); 2182 if (mh != null) { 2183 return mh; 2184 } 2185 } 2186 MemberName resolved = resolveOrFail(refKind, member); 2187 mh = getDirectMethodForConstant(refKind, defc, resolved); 2188 if (mh instanceof DirectMethodHandle 2189 && canBeCached(refKind, defc, resolved)) { 2190 MemberName key = mh.internalMemberName(); 2191 if (key != null) { 2192 key = key.asNormalOriginal(); 2193 } 2194 if (member.equals(key)) { // better safe than sorry 2195 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 2196 } 2197 } 2198 return mh; 2199 } 2200 private 2201 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 2202 if (refKind == REF_invokeSpecial) { 2203 return false; 2204 } 2205 if (!Modifier.isPublic(defc.getModifiers()) || 2206 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 2207 !member.isPublic() || 2208 member.isCallerSensitive()) { 2209 return false; 2210 } 2211 ClassLoader loader = defc.getClassLoader(); 2212 if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { 2213 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 2214 boolean found = false; 2215 while (sysl != null) { 2216 if (loader == sysl) { found = true; break; } 2217 sysl = sysl.getParent(); 2218 } 2219 if (!found) { 2220 return false; 2221 } 2222 } 2223 try { 2224 MemberName resolved2 = publicLookup().resolveOrFail(refKind, 2225 new MemberName(refKind, defc, member.getName(), member.getType())); 2226 checkSecurityManager(defc, resolved2); 2227 } catch (ReflectiveOperationException | SecurityException ex) { 2228 return false; 2229 } 2230 return true; 2231 } 2232 private 2233 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 2234 throws ReflectiveOperationException { 2235 if (MethodHandleNatives.refKindIsField(refKind)) { 2236 return getDirectFieldNoSecurityManager(refKind, defc, member); 2237 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 2238 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 2239 } else if (refKind == REF_newInvokeSpecial) { 2240 return getDirectConstructorNoSecurityManager(defc, member); 2241 } 2242 // oops 2243 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 2244 } 2245 2246 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 2247 } 2248 2249 /** 2250 * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class 2251 * in an <em>unnamed module</em>. 2252 * 2253 * @see Lookup#publicLookup 2254 */ 2255 private static class LookupHelper { 2256 private static final String UNNAMED = "Unnamed"; 2257 private static final String OBJECT = "java/lang/Object"; 2258 2259 private static Class<?> createClass() { 2260 try { 2261 ClassWriter cw = new ClassWriter(0); 2262 cw.visit(Opcodes.V1_8, 2263 Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, 2264 UNNAMED, 2265 null, 2266 OBJECT, 2267 null); 2268 cw.visitSource(UNNAMED, null); 2269 cw.visitEnd(); 2270 byte[] bytes = cw.toByteArray(); 2271 ClassLoader loader = new ClassLoader(null) { 2272 @Override 2273 protected Class<?> findClass(String cn) throws ClassNotFoundException { 2274 if (cn.equals(UNNAMED)) 2275 return super.defineClass(UNNAMED, bytes, 0, bytes.length); 2276 throw new ClassNotFoundException(cn); 2277 } 2278 }; 2279 return loader.loadClass(UNNAMED); 2280 } catch (Exception e) { 2281 throw new InternalError(e); 2282 } 2283 } 2284 2285 private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass(); 2286 2287 /** 2288 * Lookup that is trusted minimally. It can only be used to create 2289 * method handles to publicly accessible members in exported packages. 2290 * 2291 * @see MethodHandles#publicLookup 2292 */ 2293 static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC); 2294 } 2295 2296 /** 2297 * Produces a method handle constructing arrays of a desired type. 2298 * The return type of the method handle will be the array type. 2299 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2300 * @param arrayClass an array type 2301 * @return a method handle which can create arrays of the given type 2302 * @throws NullPointerException if the argument is {@code null} 2303 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2304 * @see java.lang.reflect.Array#newInstance(Class, int) 2305 * @since 9 2306 */ 2307 public static 2308 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2309 if (!arrayClass.isArray()) { 2310 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2311 } 2312 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2313 bindTo(arrayClass.getComponentType()); 2314 return ani.asType(ani.type().changeReturnType(arrayClass)); 2315 } 2316 2317 /** 2318 * Produces a method handle returning the length of an array. 2319 * The type of the method handle will have {@code int} as return type, 2320 * and its sole argument will be the array type. 2321 * @param arrayClass an array type 2322 * @return a method handle which can retrieve the length of an array of the given array type 2323 * @throws NullPointerException if the argument is {@code null} 2324 * @throws IllegalArgumentException if arrayClass is not an array type 2325 * @since 9 2326 */ 2327 public static 2328 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 2329 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 2330 } 2331 2332 /** 2333 * Produces a method handle giving read access to elements of an array. 2334 * The type of the method handle will have a return type of the array's 2335 * element type. Its first argument will be the array type, 2336 * and the second will be {@code int}. 2337 * @param arrayClass an array type 2338 * @return a method handle which can load values from the given 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 arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2344 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); 2345 } 2346 2347 /** 2348 * Produces a method handle giving write access to elements of an array. 2349 * The type of the method handle will have a void return type. 2350 * Its last argument will be the array's element type. 2351 * The first and second arguments will be the array type and int. 2352 * @param arrayClass the class of an array 2353 * @return a method handle which can store values into the array type 2354 * @throws NullPointerException if the argument is null 2355 * @throws IllegalArgumentException if arrayClass is not an array type 2356 */ 2357 public static 2358 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2359 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); 2360 } 2361 2362 /** 2363 * 2364 * Produces a VarHandle giving access to elements of an array type 2365 * {@code T[]}, supporting shape {@code (T[], int : T)}. 2366 * <p> 2367 * Certain access modes of the returned VarHandle are unsupported under 2368 * the following conditions: 2369 * <ul> 2370 * <li>if the component type is anything other than {@code byte}, 2371 * {@code short}, {@code char}, {@code int}, {@code long}, 2372 * {@code float}, or {@code double} then numeric atomic update access 2373 * modes are unsupported. 2374 * <li>if the field type is anything other than {@code boolean}, 2375 * {@code byte}, {@code short}, {@code char}, {@code int} or 2376 * {@code long} then bitwise atomic update access modes are 2377 * unsupported. 2378 * </ul> 2379 * <p> 2380 * If the component type is {@code float} or {@code double} then numeric 2381 * and atomic update access modes compare values using their bitwise 2382 * representation (see {@link Float#floatToRawIntBits} and 2383 * {@link Double#doubleToRawLongBits}, respectively). 2384 * @apiNote 2385 * Bitwise comparison of {@code float} values or {@code double} values, 2386 * as performed by the numeric and atomic update access modes, differ 2387 * from the primitive {@code ==} operator and the {@link Float#equals} 2388 * and {@link Double#equals} methods, specifically with respect to 2389 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2390 * Care should be taken when performing a compare and set or a compare 2391 * and exchange operation with such values since the operation may 2392 * unexpectedly fail. 2393 * There are many possible NaN values that are considered to be 2394 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2395 * provided by Java can distinguish between them. Operation failure can 2396 * occur if the expected or witness value is a NaN value and it is 2397 * transformed (perhaps in a platform specific manner) into another NaN 2398 * value, and thus has a different bitwise representation (see 2399 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2400 * details). 2401 * The values {@code -0.0} and {@code +0.0} have different bitwise 2402 * representations but are considered equal when using the primitive 2403 * {@code ==} operator. Operation failure can occur if, for example, a 2404 * numeric algorithm computes an expected value to be say {@code -0.0} 2405 * and previously computed the witness value to be say {@code +0.0}. 2406 * @param arrayClass the class of an array, of type {@code T[]} 2407 * @return a VarHandle giving access to elements of an array 2408 * @throws NullPointerException if the arrayClass is null 2409 * @throws IllegalArgumentException if arrayClass is not an array type 2410 * @since 9 2411 */ 2412 public static 2413 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2414 return VarHandles.makeArrayElementHandle(arrayClass); 2415 } 2416 2417 /** 2418 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2419 * viewed as if it were a different primitive array type, such as 2420 * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is 2421 * {@code (byte[], int : T)}, where the {@code int} coordinate type 2422 * corresponds to an argument that is an index in a {@code byte[]} array, 2423 * and {@code T} is the component type of the given view array class. The 2424 * returned VarHandle accesses bytes at an index in a {@code byte[]} array, 2425 * composing bytes to or from a value of {@code T} according to the given 2426 * endianness. 2427 * <p> 2428 * The supported component types (variables types) are {@code short}, 2429 * {@code char}, {@code int}, {@code long}, {@code float} and 2430 * {@code double}. 2431 * <p> 2432 * Access of bytes at a given index will result in an 2433 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2434 * or greater than the {@code byte[]} array length minus the size (in bytes) 2435 * of {@code T}. 2436 * <p> 2437 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2438 * with respect to the underlying memory address, {@code A} say, associated 2439 * with the array and index. 2440 * If access is misaligned then access for anything other than the 2441 * {@code get} and {@code set} access modes will result in an 2442 * {@code IllegalStateException}. In such cases atomic access is only 2443 * guaranteed with respect to the largest power of two that divides the GCD 2444 * of {@code A} and the size (in bytes) of {@code T}. 2445 * If access is aligned then following access modes are supported and are 2446 * guaranteed to support atomic access: 2447 * <ul> 2448 * <li>read write access modes for all {@code T}, with the exception of 2449 * access modes {@code get} and {@code set} for {@code long} and 2450 * {@code double} on 32-bit platforms. 2451 * <li>atomic update access modes for {@code int}, {@code long}, 2452 * {@code float} or {@code double}. 2453 * (Future major platform releases of the JDK may support additional 2454 * types for certain currently unsupported access modes.) 2455 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2456 * (Future major platform releases of the JDK may support additional 2457 * numeric types for certain currently unsupported access modes.) 2458 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2459 * (Future major platform releases of the JDK may support additional 2460 * numeric types for certain currently unsupported access modes.) 2461 * </ul> 2462 * <p> 2463 * Misaligned access, and therefore atomicity guarantees, may be determined 2464 * for {@code byte[]} arrays without operating on a specific array. Given 2465 * an {@code index}, {@code T} and it's corresponding boxed type, 2466 * {@code T_BOX}, misalignment may be determined as follows: 2467 * <pre>{@code 2468 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2469 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2470 * alignmentOffset(0, sizeOfT); 2471 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2472 * boolean isMisaligned = misalignedAtIndex != 0; 2473 * }</pre> 2474 * <p> 2475 * If the variable type is {@code float} or {@code double} then atomic 2476 * update access modes compare values using their bitwise representation 2477 * (see {@link Float#floatToRawIntBits} and 2478 * {@link Double#doubleToRawLongBits}, respectively). 2479 * @param viewArrayClass the view array class, with a component type of 2480 * type {@code T} 2481 * @param byteOrder the endianness of the view array elements, as 2482 * stored in the underlying {@code byte} array 2483 * @return a VarHandle giving access to elements of a {@code byte[]} array 2484 * viewed as if elements corresponding to the components type of the view 2485 * array class 2486 * @throws NullPointerException if viewArrayClass or byteOrder is null 2487 * @throws IllegalArgumentException if viewArrayClass is not an array type 2488 * @throws UnsupportedOperationException if the component type of 2489 * viewArrayClass is not supported as a variable type 2490 * @since 9 2491 */ 2492 public static 2493 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2494 ByteOrder byteOrder) throws IllegalArgumentException { 2495 Objects.requireNonNull(byteOrder); 2496 return VarHandles.byteArrayViewHandle(viewArrayClass, 2497 byteOrder == ByteOrder.BIG_ENDIAN); 2498 } 2499 2500 /** 2501 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2502 * viewed as if it were an array of elements of a different primitive 2503 * component type to that of {@code byte}, such as {@code int[]} or 2504 * {@code long[]}. The shape of the resulting VarHandle is 2505 * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type 2506 * corresponds to an argument that is an index in a {@code ByteBuffer}, and 2507 * {@code T} is the component type of the given view array class. The 2508 * returned VarHandle accesses bytes at an index in a {@code ByteBuffer}, 2509 * composing bytes to or from a value of {@code T} according to the given 2510 * endianness. 2511 * <p> 2512 * The supported component types (variables types) are {@code short}, 2513 * {@code char}, {@code int}, {@code long}, {@code float} and 2514 * {@code double}. 2515 * <p> 2516 * Access will result in a {@code ReadOnlyBufferException} for anything 2517 * other than the read access modes if the {@code ByteBuffer} is read-only. 2518 * <p> 2519 * Access of bytes at a given index will result in an 2520 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2521 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2522 * {@code T}. 2523 * <p> 2524 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2525 * with respect to the underlying memory address, {@code A} say, associated 2526 * with the {@code ByteBuffer} and index. 2527 * If access is misaligned then access for anything other than the 2528 * {@code get} and {@code set} access modes will result in an 2529 * {@code IllegalStateException}. In such cases atomic access is only 2530 * guaranteed with respect to the largest power of two that divides the GCD 2531 * of {@code A} and the size (in bytes) of {@code T}. 2532 * If access is aligned then following access modes are supported and are 2533 * guaranteed to support atomic access: 2534 * <ul> 2535 * <li>read write access modes for all {@code T}, with the exception of 2536 * access modes {@code get} and {@code set} for {@code long} and 2537 * {@code double} on 32-bit platforms. 2538 * <li>atomic update access modes for {@code int}, {@code long}, 2539 * {@code float} or {@code double}. 2540 * (Future major platform releases of the JDK may support additional 2541 * types for certain currently unsupported access modes.) 2542 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2543 * (Future major platform releases of the JDK may support additional 2544 * numeric types for certain currently unsupported access modes.) 2545 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2546 * (Future major platform releases of the JDK may support additional 2547 * numeric types for certain currently unsupported access modes.) 2548 * </ul> 2549 * <p> 2550 * Misaligned access, and therefore atomicity guarantees, may be determined 2551 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2552 * {@code index}, {@code T} and it's corresponding boxed type, 2553 * {@code T_BOX}, as follows: 2554 * <pre>{@code 2555 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2556 * ByteBuffer bb = ... 2557 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2558 * boolean isMisaligned = misalignedAtIndex != 0; 2559 * }</pre> 2560 * <p> 2561 * If the variable type is {@code float} or {@code double} then atomic 2562 * update access modes compare values using their bitwise representation 2563 * (see {@link Float#floatToRawIntBits} and 2564 * {@link Double#doubleToRawLongBits}, respectively). 2565 * @param viewArrayClass the view array class, with a component type of 2566 * type {@code T} 2567 * @param byteOrder the endianness of the view array elements, as 2568 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2569 * endianness of a {@code ByteBuffer}) 2570 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2571 * viewed as if elements corresponding to the components type of the view 2572 * array class 2573 * @throws NullPointerException if viewArrayClass or byteOrder is null 2574 * @throws IllegalArgumentException if viewArrayClass is not an array type 2575 * @throws UnsupportedOperationException if the component type of 2576 * viewArrayClass is not supported as a variable type 2577 * @since 9 2578 */ 2579 public static 2580 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2581 ByteOrder byteOrder) throws IllegalArgumentException { 2582 Objects.requireNonNull(byteOrder); 2583 return VarHandles.makeByteBufferViewHandle(viewArrayClass, 2584 byteOrder == ByteOrder.BIG_ENDIAN); 2585 } 2586 2587 2588 /// method handle invocation (reflective style) 2589 2590 /** 2591 * Produces a method handle which will invoke any method handle of the 2592 * given {@code type}, with a given number of trailing arguments replaced by 2593 * a single trailing {@code Object[]} array. 2594 * The resulting invoker will be a method handle with the following 2595 * arguments: 2596 * <ul> 2597 * <li>a single {@code MethodHandle} target 2598 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2599 * <li>an {@code Object[]} array containing trailing arguments 2600 * </ul> 2601 * <p> 2602 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2603 * the indicated {@code type}. 2604 * That is, if the target is exactly of the given {@code type}, it will behave 2605 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2606 * is used to convert the target to the required {@code type}. 2607 * <p> 2608 * The type of the returned invoker will not be the given {@code type}, but rather 2609 * will have all parameters except the first {@code leadingArgCount} 2610 * replaced by a single array of type {@code Object[]}, which will be 2611 * the final parameter. 2612 * <p> 2613 * Before invoking its target, the invoker will spread the final array, apply 2614 * reference casts as necessary, and unbox and widen primitive arguments. 2615 * If, when the invoker is called, the supplied array argument does 2616 * not have the correct number of elements, the invoker will throw 2617 * an {@link IllegalArgumentException} instead of invoking the target. 2618 * <p> 2619 * This method is equivalent to the following code (though it may be more efficient): 2620 * <blockquote><pre>{@code 2621 MethodHandle invoker = MethodHandles.invoker(type); 2622 int spreadArgCount = type.parameterCount() - leadingArgCount; 2623 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2624 return invoker; 2625 * }</pre></blockquote> 2626 * This method throws no reflective or security exceptions. 2627 * @param type the desired target type 2628 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2629 * @return a method handle suitable for invoking any method handle of the given type 2630 * @throws NullPointerException if {@code type} is null 2631 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2632 * the range from 0 to {@code type.parameterCount()} inclusive, 2633 * or if the resulting method handle's type would have 2634 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2635 */ 2636 public static 2637 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2638 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2639 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2640 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); 2641 return type.invokers().spreadInvoker(leadingArgCount); 2642 } 2643 2644 /** 2645 * Produces a special <em>invoker method handle</em> which can be used to 2646 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2647 * The resulting invoker will have a type which is 2648 * exactly equal to the desired type, except that it will accept 2649 * an additional leading argument of type {@code MethodHandle}. 2650 * <p> 2651 * This method is equivalent to the following code (though it may be more efficient): 2652 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2653 * 2654 * <p style="font-size:smaller;"> 2655 * <em>Discussion:</em> 2656 * Invoker method handles can be useful when working with variable method handles 2657 * of unknown types. 2658 * For example, to emulate an {@code invokeExact} call to a variable method 2659 * handle {@code M}, extract its type {@code T}, 2660 * look up the invoker method {@code X} for {@code T}, 2661 * and call the invoker method, as {@code X.invoke(T, A...)}. 2662 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2663 * is unknown.) 2664 * If spreading, collecting, or other argument transformations are required, 2665 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2666 * method handle values, as long as they are compatible with the type of {@code X}. 2667 * <p style="font-size:smaller;"> 2668 * <em>(Note: The invoker method is not available via the Core Reflection API. 2669 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2670 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2671 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2672 * <p> 2673 * This method throws no reflective or security exceptions. 2674 * @param type the desired target type 2675 * @return a method handle suitable for invoking any method handle of the given type 2676 * @throws IllegalArgumentException if the resulting method handle's type would have 2677 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2678 */ 2679 public static 2680 MethodHandle exactInvoker(MethodType type) { 2681 return type.invokers().exactInvoker(); 2682 } 2683 2684 /** 2685 * Produces a special <em>invoker method handle</em> which can be used to 2686 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2687 * The resulting invoker will have a type which is 2688 * exactly equal to the desired type, except that it will accept 2689 * an additional leading argument of type {@code MethodHandle}. 2690 * <p> 2691 * Before invoking its target, if the target differs from the expected type, 2692 * the invoker will apply reference casts as 2693 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 2694 * Similarly, the return value will be converted as necessary. 2695 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 2696 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 2697 * <p> 2698 * This method is equivalent to the following code (though it may be more efficient): 2699 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 2700 * <p style="font-size:smaller;"> 2701 * <em>Discussion:</em> 2702 * A {@linkplain MethodType#genericMethodType general method type} is one which 2703 * mentions only {@code Object} arguments and return values. 2704 * An invoker for such a type is capable of calling any method handle 2705 * of the same arity as the general type. 2706 * <p style="font-size:smaller;"> 2707 * <em>(Note: The invoker method is not available via the Core Reflection API. 2708 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2709 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2710 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2711 * <p> 2712 * This method throws no reflective or security exceptions. 2713 * @param type the desired target type 2714 * @return a method handle suitable for invoking any method handle convertible to the given type 2715 * @throws IllegalArgumentException if the resulting method handle's type would have 2716 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2717 */ 2718 public static 2719 MethodHandle invoker(MethodType type) { 2720 return type.invokers().genericInvoker(); 2721 } 2722 2723 /** 2724 * Produces a special <em>invoker method handle</em> which can be used to 2725 * invoke a signature-polymorphic access mode method on any VarHandle whose 2726 * associated access mode type is compatible with the given type. 2727 * The resulting invoker will have a type which is exactly equal to the 2728 * desired given type, except that it will accept an additional leading 2729 * argument of type {@code VarHandle}. 2730 * 2731 * @param accessMode the VarHandle access mode 2732 * @param type the desired target type 2733 * @return a method handle suitable for invoking an access mode method of 2734 * any VarHandle whose access mode type is of the given type. 2735 * @since 9 2736 */ 2737 static public 2738 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2739 return type.invokers().varHandleMethodExactInvoker(accessMode); 2740 } 2741 2742 /** 2743 * Produces a special <em>invoker method handle</em> which can be used to 2744 * invoke a signature-polymorphic access mode method on any VarHandle whose 2745 * associated access mode type is compatible with the given type. 2746 * The resulting invoker will have a type which is exactly equal to the 2747 * desired given type, except that it will accept an additional leading 2748 * argument of type {@code VarHandle}. 2749 * <p> 2750 * Before invoking its target, if the access mode type differs from the 2751 * desired given type, the invoker will apply reference casts as necessary 2752 * and box, unbox, or widen primitive values, as if by 2753 * {@link MethodHandle#asType asType}. Similarly, the return value will be 2754 * converted as necessary. 2755 * <p> 2756 * This method is equivalent to the following code (though it may be more 2757 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 2758 * 2759 * @param accessMode the VarHandle access mode 2760 * @param type the desired target type 2761 * @return a method handle suitable for invoking an access mode method of 2762 * any VarHandle whose access mode type is convertible to the given 2763 * type. 2764 * @since 9 2765 */ 2766 static public 2767 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2768 return type.invokers().varHandleMethodInvoker(accessMode); 2769 } 2770 2771 static /*non-public*/ 2772 MethodHandle basicInvoker(MethodType type) { 2773 return type.invokers().basicInvoker(); 2774 } 2775 2776 /// method handle modification (creation from other method handles) 2777 2778 /** 2779 * Produces a method handle which adapts the type of the 2780 * given method handle to a new type by pairwise argument and return type conversion. 2781 * The original type and new type must have the same number of arguments. 2782 * The resulting method handle is guaranteed to report a type 2783 * which is equal to the desired new type. 2784 * <p> 2785 * If the original type and new type are equal, returns target. 2786 * <p> 2787 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 2788 * and some additional conversions are also applied if those conversions fail. 2789 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 2790 * if possible, before or instead of any conversions done by {@code asType}: 2791 * <ul> 2792 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 2793 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 2794 * (This treatment of interfaces follows the usage of the bytecode verifier.) 2795 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 2796 * the boolean is converted to a byte value, 1 for true, 0 for false. 2797 * (This treatment follows the usage of the bytecode verifier.) 2798 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 2799 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 2800 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 2801 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 2802 * then a Java casting conversion (JLS 5.5) is applied. 2803 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 2804 * widening and/or narrowing.) 2805 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 2806 * conversion will be applied at runtime, possibly followed 2807 * by a Java casting conversion (JLS 5.5) on the primitive value, 2808 * possibly followed by a conversion from byte to boolean by testing 2809 * the low-order bit. 2810 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2811 * and if the reference is null at runtime, a zero value is introduced. 2812 * </ul> 2813 * @param target the method handle to invoke after arguments are retyped 2814 * @param newType the expected type of the new method handle 2815 * @return a method handle which delegates to the target after performing 2816 * any necessary argument conversions, and arranges for any 2817 * necessary return value conversions 2818 * @throws NullPointerException if either argument is null 2819 * @throws WrongMethodTypeException if the conversion cannot be made 2820 * @see MethodHandle#asType 2821 */ 2822 public static 2823 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2824 explicitCastArgumentsChecks(target, newType); 2825 // use the asTypeCache when possible: 2826 MethodType oldType = target.type(); 2827 if (oldType == newType) return target; 2828 if (oldType.explicitCastEquivalentToAsType(newType)) { 2829 return target.asFixedArity().asType(newType); 2830 } 2831 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 2832 } 2833 2834 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 2835 if (target.type().parameterCount() != newType.parameterCount()) { 2836 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 2837 } 2838 } 2839 2840 /** 2841 * Produces a method handle which adapts the calling sequence of the 2842 * given method handle to a new type, by reordering the arguments. 2843 * The resulting method handle is guaranteed to report a type 2844 * which is equal to the desired new type. 2845 * <p> 2846 * The given array controls the reordering. 2847 * Call {@code #I} the number of incoming parameters (the value 2848 * {@code newType.parameterCount()}, and call {@code #O} the number 2849 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2850 * Then the length of the reordering array must be {@code #O}, 2851 * and each element must be a non-negative number less than {@code #I}. 2852 * For every {@code N} less than {@code #O}, the {@code N}-th 2853 * outgoing argument will be taken from the {@code I}-th incoming 2854 * argument, where {@code I} is {@code reorder[N]}. 2855 * <p> 2856 * No argument or return value conversions are applied. 2857 * The type of each incoming argument, as determined by {@code newType}, 2858 * must be identical to the type of the corresponding outgoing parameter 2859 * or parameters in the target method handle. 2860 * The return type of {@code newType} must be identical to the return 2861 * type of the original target. 2862 * <p> 2863 * The reordering array need not specify an actual permutation. 2864 * An incoming argument will be duplicated if its index appears 2865 * more than once in the array, and an incoming argument will be dropped 2866 * if its index does not appear in the array. 2867 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2868 * incoming arguments which are not mentioned in the reordering array 2869 * may be of any type, as determined only by {@code newType}. 2870 * <blockquote><pre>{@code 2871 import static java.lang.invoke.MethodHandles.*; 2872 import static java.lang.invoke.MethodType.*; 2873 ... 2874 MethodType intfn1 = methodType(int.class, int.class); 2875 MethodType intfn2 = methodType(int.class, int.class, int.class); 2876 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2877 assert(sub.type().equals(intfn2)); 2878 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2879 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2880 assert((int)rsub.invokeExact(1, 100) == 99); 2881 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2882 assert(add.type().equals(intfn2)); 2883 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2884 assert(twice.type().equals(intfn1)); 2885 assert((int)twice.invokeExact(21) == 42); 2886 * }</pre></blockquote> 2887 * <p> 2888 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 2889 * variable-arity method handle}, even if the original target method handle was. 2890 * @param target the method handle to invoke after arguments are reordered 2891 * @param newType the expected type of the new method handle 2892 * @param reorder an index array which controls the reordering 2893 * @return a method handle which delegates to the target after it 2894 * drops unused arguments and moves and/or duplicates the other arguments 2895 * @throws NullPointerException if any argument is null 2896 * @throws IllegalArgumentException if the index array length is not equal to 2897 * the arity of the target, or if any index array element 2898 * not a valid index for a parameter of {@code newType}, 2899 * or if two corresponding parameter types in 2900 * {@code target.type()} and {@code newType} are not identical, 2901 */ 2902 public static 2903 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2904 reorder = reorder.clone(); // get a private copy 2905 MethodType oldType = target.type(); 2906 permuteArgumentChecks(reorder, newType, oldType); 2907 // first detect dropped arguments and handle them separately 2908 int[] originalReorder = reorder; 2909 BoundMethodHandle result = target.rebind(); 2910 LambdaForm form = result.form; 2911 int newArity = newType.parameterCount(); 2912 // Normalize the reordering into a real permutation, 2913 // by removing duplicates and adding dropped elements. 2914 // This somewhat improves lambda form caching, as well 2915 // as simplifying the transform by breaking it up into steps. 2916 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 2917 if (ddIdx > 0) { 2918 // We found a duplicated entry at reorder[ddIdx]. 2919 // Example: (x,y,z)->asList(x,y,z) 2920 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 2921 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 2922 // The starred element corresponds to the argument 2923 // deleted by the dupArgumentForm transform. 2924 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 2925 boolean killFirst = false; 2926 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 2927 // Set killFirst if the dup is larger than an intervening position. 2928 // This will remove at least one inversion from the permutation. 2929 if (dupVal > val) killFirst = true; 2930 } 2931 if (!killFirst) { 2932 srcPos = dstPos; 2933 dstPos = ddIdx; 2934 } 2935 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 2936 assert (reorder[srcPos] == reorder[dstPos]); 2937 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 2938 // contract the reordering by removing the element at dstPos 2939 int tailPos = dstPos + 1; 2940 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 2941 reorder = Arrays.copyOf(reorder, reorder.length - 1); 2942 } else { 2943 int dropVal = ~ddIdx, insPos = 0; 2944 while (insPos < reorder.length && reorder[insPos] < dropVal) { 2945 // Find first element of reorder larger than dropVal. 2946 // This is where we will insert the dropVal. 2947 insPos += 1; 2948 } 2949 Class<?> ptype = newType.parameterType(dropVal); 2950 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 2951 oldType = oldType.insertParameterTypes(insPos, ptype); 2952 // expand the reordering by inserting an element at insPos 2953 int tailPos = insPos + 1; 2954 reorder = Arrays.copyOf(reorder, reorder.length + 1); 2955 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 2956 reorder[insPos] = dropVal; 2957 } 2958 assert (permuteArgumentChecks(reorder, newType, oldType)); 2959 } 2960 assert (reorder.length == newArity); // a perfect permutation 2961 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 2962 form = form.editor().permuteArgumentsForm(1, reorder); 2963 if (newType == result.type() && form == result.internalForm()) 2964 return result; 2965 return result.copyWith(newType, form); 2966 } 2967 2968 /** 2969 * Return an indication of any duplicate or omission in reorder. 2970 * If the reorder contains a duplicate entry, return the index of the second occurrence. 2971 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 2972 * Otherwise, return zero. 2973 * If an element not in [0..newArity-1] is encountered, return reorder.length. 2974 */ 2975 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 2976 final int BIT_LIMIT = 63; // max number of bits in bit mask 2977 if (newArity < BIT_LIMIT) { 2978 long mask = 0; 2979 for (int i = 0; i < reorder.length; i++) { 2980 int arg = reorder[i]; 2981 if (arg >= newArity) { 2982 return reorder.length; 2983 } 2984 long bit = 1L << arg; 2985 if ((mask & bit) != 0) { 2986 return i; // >0 indicates a dup 2987 } 2988 mask |= bit; 2989 } 2990 if (mask == (1L << newArity) - 1) { 2991 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 2992 return 0; 2993 } 2994 // find first zero 2995 long zeroBit = Long.lowestOneBit(~mask); 2996 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 2997 assert(zeroPos <= newArity); 2998 if (zeroPos == newArity) { 2999 return 0; 3000 } 3001 return ~zeroPos; 3002 } else { 3003 // same algorithm, different bit set 3004 BitSet mask = new BitSet(newArity); 3005 for (int i = 0; i < reorder.length; i++) { 3006 int arg = reorder[i]; 3007 if (arg >= newArity) { 3008 return reorder.length; 3009 } 3010 if (mask.get(arg)) { 3011 return i; // >0 indicates a dup 3012 } 3013 mask.set(arg); 3014 } 3015 int zeroPos = mask.nextClearBit(0); 3016 assert(zeroPos <= newArity); 3017 if (zeroPos == newArity) { 3018 return 0; 3019 } 3020 return ~zeroPos; 3021 } 3022 } 3023 3024 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 3025 if (newType.returnType() != oldType.returnType()) 3026 throw newIllegalArgumentException("return types do not match", 3027 oldType, newType); 3028 if (reorder.length == oldType.parameterCount()) { 3029 int limit = newType.parameterCount(); 3030 boolean bad = false; 3031 for (int j = 0; j < reorder.length; j++) { 3032 int i = reorder[j]; 3033 if (i < 0 || i >= limit) { 3034 bad = true; break; 3035 } 3036 Class<?> src = newType.parameterType(i); 3037 Class<?> dst = oldType.parameterType(j); 3038 if (src != dst) 3039 throw newIllegalArgumentException("parameter types do not match after reorder", 3040 oldType, newType); 3041 } 3042 if (!bad) return true; 3043 } 3044 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 3045 } 3046 3047 /** 3048 * Produces a method handle of the requested return type which returns the given 3049 * constant value every time it is invoked. 3050 * <p> 3051 * Before the method handle is returned, the passed-in value is converted to the requested type. 3052 * If the requested type is primitive, widening primitive conversions are attempted, 3053 * else reference conversions are attempted. 3054 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 3055 * @param type the return type of the desired method handle 3056 * @param value the value to return 3057 * @return a method handle of the given return type and no arguments, which always returns the given value 3058 * @throws NullPointerException if the {@code type} argument is null 3059 * @throws ClassCastException if the value cannot be converted to the required return type 3060 * @throws IllegalArgumentException if the given type is {@code void.class} 3061 */ 3062 public static 3063 MethodHandle constant(Class<?> type, Object value) { 3064 if (type.isPrimitive()) { 3065 if (type == void.class) 3066 throw newIllegalArgumentException("void type"); 3067 Wrapper w = Wrapper.forPrimitiveType(type); 3068 value = w.convert(value, type); 3069 if (w.zero().equals(value)) 3070 return zero(w, type); 3071 return insertArguments(identity(type), 0, value); 3072 } else { 3073 if (value == null) 3074 return zero(Wrapper.OBJECT, type); 3075 return identity(type).bindTo(value); 3076 } 3077 } 3078 3079 /** 3080 * Produces a method handle which returns its sole argument when invoked. 3081 * @param type the type of the sole parameter and return value of the desired method handle 3082 * @return a unary method handle which accepts and returns the given type 3083 * @throws NullPointerException if the argument is null 3084 * @throws IllegalArgumentException if the given type is {@code void.class} 3085 */ 3086 public static 3087 MethodHandle identity(Class<?> type) { 3088 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 3089 int pos = btw.ordinal(); 3090 MethodHandle ident = IDENTITY_MHS[pos]; 3091 if (ident == null) { 3092 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 3093 } 3094 if (ident.type().returnType() == type) 3095 return ident; 3096 // something like identity(Foo.class); do not bother to intern these 3097 assert (btw == Wrapper.OBJECT); 3098 return makeIdentity(type); 3099 } 3100 3101 /** 3102 * Produces a constant method handle of the requested return type which 3103 * returns the default value for that type every time it is invoked. 3104 * The resulting constant method handle will have no side effects. 3105 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 3106 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 3107 * since {@code explicitCastArguments} converts {@code null} to default values. 3108 * @param type the expected return type of the desired method handle 3109 * @return a constant method handle that takes no arguments 3110 * and returns the default value of the given type (or void, if the type is void) 3111 * @throws NullPointerException if the argument is null 3112 * @see MethodHandles#constant 3113 * @see MethodHandles#empty 3114 * @see MethodHandles#explicitCastArguments 3115 * @since 9 3116 */ 3117 public static MethodHandle zero(Class<?> type) { 3118 Objects.requireNonNull(type); 3119 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 3120 } 3121 3122 private static MethodHandle identityOrVoid(Class<?> type) { 3123 return type == void.class ? zero(type) : identity(type); 3124 } 3125 3126 /** 3127 * Produces a method handle of the requested type which ignores any arguments, does nothing, 3128 * and returns a suitable default depending on the return type. 3129 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 3130 * <p>The returned method handle is equivalent to 3131 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 3132 * <p> 3133 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 3134 * {@code guardWithTest(pred, target, empty(target.type())}. 3135 * @param type the type of the desired method handle 3136 * @return a constant method handle of the given type, which returns a default value of the given return type 3137 * @throws NullPointerException if the argument is null 3138 * @see MethodHandles#zero 3139 * @see MethodHandles#constant 3140 * @since 9 3141 */ 3142 public static MethodHandle empty(MethodType type) { 3143 Objects.requireNonNull(type); 3144 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 3145 } 3146 3147 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; 3148 private static MethodHandle makeIdentity(Class<?> ptype) { 3149 MethodType mtype = methodType(ptype, ptype); 3150 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 3151 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 3152 } 3153 3154 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 3155 int pos = btw.ordinal(); 3156 MethodHandle zero = ZERO_MHS[pos]; 3157 if (zero == null) { 3158 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 3159 } 3160 if (zero.type().returnType() == rtype) 3161 return zero; 3162 assert(btw == Wrapper.OBJECT); 3163 return makeZero(rtype); 3164 } 3165 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; 3166 private static MethodHandle makeZero(Class<?> rtype) { 3167 MethodType mtype = methodType(rtype); 3168 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 3169 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 3170 } 3171 3172 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 3173 // Simulate a CAS, to avoid racy duplication of results. 3174 MethodHandle prev = cache[pos]; 3175 if (prev != null) return prev; 3176 return cache[pos] = value; 3177 } 3178 3179 /** 3180 * Provides a target method handle with one or more <em>bound arguments</em> 3181 * in advance of the method handle's invocation. 3182 * The formal parameters to the target corresponding to the bound 3183 * arguments are called <em>bound parameters</em>. 3184 * Returns a new method handle which saves away the bound arguments. 3185 * When it is invoked, it receives arguments for any non-bound parameters, 3186 * binds the saved arguments to their corresponding parameters, 3187 * and calls the original target. 3188 * <p> 3189 * The type of the new method handle will drop the types for the bound 3190 * parameters from the original target type, since the new method handle 3191 * will no longer require those arguments to be supplied by its callers. 3192 * <p> 3193 * Each given argument object must match the corresponding bound parameter type. 3194 * If a bound parameter type is a primitive, the argument object 3195 * must be a wrapper, and will be unboxed to produce the primitive value. 3196 * <p> 3197 * The {@code pos} argument selects which parameters are to be bound. 3198 * It may range between zero and <i>N-L</i> (inclusively), 3199 * where <i>N</i> is the arity of the target method handle 3200 * and <i>L</i> is the length of the values array. 3201 * <p> 3202 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3203 * variable-arity method handle}, even if the original target method handle was. 3204 * @param target the method handle to invoke after the argument is inserted 3205 * @param pos where to insert the argument (zero for the first) 3206 * @param values the series of arguments to insert 3207 * @return a method handle which inserts an additional argument, 3208 * before calling the original method handle 3209 * @throws NullPointerException if the target or the {@code values} array is null 3210 * @see MethodHandle#bindTo 3211 */ 3212 public static 3213 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3214 int insCount = values.length; 3215 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3216 if (insCount == 0) return target; 3217 BoundMethodHandle result = target.rebind(); 3218 for (int i = 0; i < insCount; i++) { 3219 Object value = values[i]; 3220 Class<?> ptype = ptypes[pos+i]; 3221 if (ptype.isPrimitive()) { 3222 result = insertArgumentPrimitive(result, pos, ptype, value); 3223 } else { 3224 value = ptype.cast(value); // throw CCE if needed 3225 result = result.bindArgumentL(pos, value); 3226 } 3227 } 3228 return result; 3229 } 3230 3231 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3232 Class<?> ptype, Object value) { 3233 Wrapper w = Wrapper.forPrimitiveType(ptype); 3234 // perform unboxing and/or primitive conversion 3235 value = w.convert(value, ptype); 3236 switch (w) { 3237 case INT: return result.bindArgumentI(pos, (int)value); 3238 case LONG: return result.bindArgumentJ(pos, (long)value); 3239 case FLOAT: return result.bindArgumentF(pos, (float)value); 3240 case DOUBLE: return result.bindArgumentD(pos, (double)value); 3241 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3242 } 3243 } 3244 3245 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3246 MethodType oldType = target.type(); 3247 int outargs = oldType.parameterCount(); 3248 int inargs = outargs - insCount; 3249 if (inargs < 0) 3250 throw newIllegalArgumentException("too many values to insert"); 3251 if (pos < 0 || pos > inargs) 3252 throw newIllegalArgumentException("no argument type to append"); 3253 return oldType.ptypes(); 3254 } 3255 3256 /** 3257 * Produces a method handle which will discard some dummy arguments 3258 * before calling some other specified <i>target</i> method handle. 3259 * The type of the new method handle will be the same as the target's type, 3260 * except it will also include the dummy argument types, 3261 * at some given position. 3262 * <p> 3263 * The {@code pos} argument may range between zero and <i>N</i>, 3264 * where <i>N</i> is the arity of the target. 3265 * If {@code pos} is zero, the dummy arguments will precede 3266 * the target's real arguments; if {@code pos} is <i>N</i> 3267 * they will come after. 3268 * <p> 3269 * <b>Example:</b> 3270 * <blockquote><pre>{@code 3271 import static java.lang.invoke.MethodHandles.*; 3272 import static java.lang.invoke.MethodType.*; 3273 ... 3274 MethodHandle cat = lookup().findVirtual(String.class, 3275 "concat", methodType(String.class, String.class)); 3276 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3277 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3278 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3279 assertEquals(bigType, d0.type()); 3280 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3281 * }</pre></blockquote> 3282 * <p> 3283 * This method is also equivalent to the following code: 3284 * <blockquote><pre> 3285 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3286 * </pre></blockquote> 3287 * @param target the method handle to invoke after the arguments are dropped 3288 * @param valueTypes the type(s) of the argument(s) to drop 3289 * @param pos position of first argument to drop (zero for the leftmost) 3290 * @return a method handle which drops arguments of the given types, 3291 * before calling the original method handle 3292 * @throws NullPointerException if the target is null, 3293 * or if the {@code valueTypes} list or any of its elements is null 3294 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3295 * or if {@code pos} is negative or greater than the arity of the target, 3296 * or if the new method handle's type would have too many parameters 3297 */ 3298 public static 3299 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3300 return dropArguments0(target, pos, copyTypes(valueTypes.toArray())); 3301 } 3302 3303 private static List<Class<?>> copyTypes(Object[] array) { 3304 return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class)); 3305 } 3306 3307 private static 3308 MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3309 MethodType oldType = target.type(); // get NPE 3310 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3311 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3312 if (dropped == 0) return target; 3313 BoundMethodHandle result = target.rebind(); 3314 LambdaForm lform = result.form; 3315 int insertFormArg = 1 + pos; 3316 for (Class<?> ptype : valueTypes) { 3317 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3318 } 3319 result = result.copyWith(newType, lform); 3320 return result; 3321 } 3322 3323 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3324 int dropped = valueTypes.size(); 3325 MethodType.checkSlotCount(dropped); 3326 int outargs = oldType.parameterCount(); 3327 int inargs = outargs + dropped; 3328 if (pos < 0 || pos > outargs) 3329 throw newIllegalArgumentException("no argument type to remove" 3330 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3331 ); 3332 return dropped; 3333 } 3334 3335 /** 3336 * Produces a method handle which will discard some dummy arguments 3337 * before calling some other specified <i>target</i> method handle. 3338 * The type of the new method handle will be the same as the target's type, 3339 * except it will also include the dummy argument types, 3340 * at some given position. 3341 * <p> 3342 * The {@code pos} argument may range between zero and <i>N</i>, 3343 * where <i>N</i> is the arity of the target. 3344 * If {@code pos} is zero, the dummy arguments will precede 3345 * the target's real arguments; if {@code pos} is <i>N</i> 3346 * they will come after. 3347 * @apiNote 3348 * <blockquote><pre>{@code 3349 import static java.lang.invoke.MethodHandles.*; 3350 import static java.lang.invoke.MethodType.*; 3351 ... 3352 MethodHandle cat = lookup().findVirtual(String.class, 3353 "concat", methodType(String.class, String.class)); 3354 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3355 MethodHandle d0 = dropArguments(cat, 0, String.class); 3356 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3357 MethodHandle d1 = dropArguments(cat, 1, String.class); 3358 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3359 MethodHandle d2 = dropArguments(cat, 2, String.class); 3360 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3361 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3362 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3363 * }</pre></blockquote> 3364 * <p> 3365 * This method is also equivalent to the following code: 3366 * <blockquote><pre> 3367 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3368 * </pre></blockquote> 3369 * @param target the method handle to invoke after the arguments are dropped 3370 * @param valueTypes the type(s) of the argument(s) to drop 3371 * @param pos position of first argument to drop (zero for the leftmost) 3372 * @return a method handle which drops arguments of the given types, 3373 * before calling the original method handle 3374 * @throws NullPointerException if the target is null, 3375 * or if the {@code valueTypes} array or any of its elements is null 3376 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3377 * or if {@code pos} is negative or greater than the arity of the target, 3378 * or if the new method handle's type would have 3379 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3380 */ 3381 public static 3382 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3383 return dropArguments0(target, pos, copyTypes(valueTypes)); 3384 } 3385 3386 // private version which allows caller some freedom with error handling 3387 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3388 boolean nullOnFailure) { 3389 newTypes = copyTypes(newTypes.toArray()); 3390 List<Class<?>> oldTypes = target.type().parameterList(); 3391 int match = oldTypes.size(); 3392 if (skip != 0) { 3393 if (skip < 0 || skip > match) { 3394 throw newIllegalArgumentException("illegal skip", skip, target); 3395 } 3396 oldTypes = oldTypes.subList(skip, match); 3397 match -= skip; 3398 } 3399 List<Class<?>> addTypes = newTypes; 3400 int add = addTypes.size(); 3401 if (pos != 0) { 3402 if (pos < 0 || pos > add) { 3403 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3404 } 3405 addTypes = addTypes.subList(pos, add); 3406 add -= pos; assert(addTypes.size() == add); 3407 } 3408 // Do not add types which already match the existing arguments. 3409 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3410 if (nullOnFailure) { 3411 return null; 3412 } 3413 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3414 } 3415 addTypes = addTypes.subList(match, add); 3416 add -= match; assert(addTypes.size() == add); 3417 // newTypes: ( P*[pos], M*[match], A*[add] ) 3418 // target: ( S*[skip], M*[match] ) 3419 MethodHandle adapter = target; 3420 if (add > 0) { 3421 adapter = dropArguments0(adapter, skip+ match, addTypes); 3422 } 3423 // adapter: (S*[skip], M*[match], A*[add] ) 3424 if (pos > 0) { 3425 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); 3426 } 3427 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3428 return adapter; 3429 } 3430 3431 /** 3432 * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments. 3433 * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored. 3434 * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list, 3435 * at the given position. 3436 * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding 3437 * positions of the target method handle's parameters, as if by {@link #dropArguments}. 3438 * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip}, 3439 * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the 3440 * target list.) 3441 * The target's return type will be unchanged. 3442 * @apiNote 3443 * Two method handles whose argument lists are "effectively identical" (i.e., identical 3444 * in a common prefix) may be mutually converted to a common type 3445 * by two calls to {@code dropArgumentsToMatch}, as follows: 3446 * <blockquote><pre>{@code 3447 import static java.lang.invoke.MethodHandles.*; 3448 import static java.lang.invoke.MethodType.*; 3449 ... 3450 ... 3451 MethodHandle h0 = constant(boolean.class, true); 3452 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3453 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3454 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3455 if (h1.type().parameterCount() < h2.type().parameterCount()) 3456 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3457 else 3458 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3459 MethodHandle h3 = guardWithTest(h0, h1, h2); 3460 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3461 * }</pre></blockquote> 3462 * @param target the method handle to adapt 3463 * @param skip number of targets parameters to disregard (they will be unchanged) 3464 * @param newTypes the desired argument list of the method handle 3465 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3466 * @return a possibly adapted method handle 3467 * @throws NullPointerException if either argument is null 3468 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 3469 * or if {@code skip} is negative or greater than the arity of the target, 3470 * or if {@code pos} is negative or greater than the newTypes list size, 3471 * or if the non-skipped target parameter types match the new types at {@code pos} 3472 * @since 9 3473 */ 3474 public static 3475 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3476 Objects.requireNonNull(target); 3477 Objects.requireNonNull(newTypes); 3478 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3479 } 3480 3481 /** 3482 * Adapts a target method handle by pre-processing 3483 * one or more of its arguments, each with its own unary filter function, 3484 * and then calling the target with each pre-processed argument 3485 * replaced by the result of its corresponding filter function. 3486 * <p> 3487 * The pre-processing is performed by one or more method handles, 3488 * specified in the elements of the {@code filters} array. 3489 * The first element of the filter array corresponds to the {@code pos} 3490 * argument of the target, and so on in sequence. 3491 * <p> 3492 * Null arguments in the array are treated as identity functions, 3493 * and the corresponding arguments left unchanged. 3494 * (If there are no non-null elements in the array, the original target is returned.) 3495 * Each filter is applied to the corresponding argument of the adapter. 3496 * <p> 3497 * If a filter {@code F} applies to the {@code N}th argument of 3498 * the target, then {@code F} must be a method handle which 3499 * takes exactly one argument. The type of {@code F}'s sole argument 3500 * replaces the corresponding argument type of the target 3501 * in the resulting adapted method handle. 3502 * The return type of {@code F} must be identical to the corresponding 3503 * parameter type of the target. 3504 * <p> 3505 * It is an error if there are elements of {@code filters} 3506 * (null or not) 3507 * which do not correspond to argument positions in the target. 3508 * <p><b>Example:</b> 3509 * <blockquote><pre>{@code 3510 import static java.lang.invoke.MethodHandles.*; 3511 import static java.lang.invoke.MethodType.*; 3512 ... 3513 MethodHandle cat = lookup().findVirtual(String.class, 3514 "concat", methodType(String.class, String.class)); 3515 MethodHandle upcase = lookup().findVirtual(String.class, 3516 "toUpperCase", methodType(String.class)); 3517 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3518 MethodHandle f0 = filterArguments(cat, 0, upcase); 3519 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3520 MethodHandle f1 = filterArguments(cat, 1, upcase); 3521 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3522 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3523 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3524 * }</pre></blockquote> 3525 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3526 * denotes the return type of both the {@code target} and resulting adapter. 3527 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3528 * of the parameters and arguments that precede and follow the filter position 3529 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3530 * values of the filtered parameters and arguments; they also represent the 3531 * return types of the {@code filter[i]} handles. The latter accept arguments 3532 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3533 * the resulting adapter. 3534 * <blockquote><pre>{@code 3535 * T target(P... p, A[i]... a[i], B... b); 3536 * A[i] filter[i](V[i]); 3537 * T adapter(P... p, V[i]... v[i], B... b) { 3538 * return target(p..., filter[i](v[i])..., b...); 3539 * } 3540 * }</pre></blockquote> 3541 * <p> 3542 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3543 * variable-arity method handle}, even if the original target method handle was. 3544 * 3545 * @param target the method handle to invoke after arguments are filtered 3546 * @param pos the position of the first argument to filter 3547 * @param filters method handles to call initially on filtered arguments 3548 * @return method handle which incorporates the specified argument filtering logic 3549 * @throws NullPointerException if the target is null 3550 * or if the {@code filters} array is null 3551 * @throws IllegalArgumentException if a non-null element of {@code filters} 3552 * does not match a corresponding argument type of target as described above, 3553 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3554 * or if the resulting method handle's type would have 3555 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3556 */ 3557 public static 3558 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3559 filterArgumentsCheckArity(target, pos, filters); 3560 MethodHandle adapter = target; 3561 int curPos = pos-1; // pre-incremented 3562 for (MethodHandle filter : filters) { 3563 curPos += 1; 3564 if (filter == null) continue; // ignore null elements of filters 3565 adapter = filterArgument(adapter, curPos, filter); 3566 } 3567 return adapter; 3568 } 3569 3570 /*non-public*/ static 3571 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3572 filterArgumentChecks(target, pos, filter); 3573 MethodType targetType = target.type(); 3574 MethodType filterType = filter.type(); 3575 BoundMethodHandle result = target.rebind(); 3576 Class<?> newParamType = filterType.parameterType(0); 3577 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3578 MethodType newType = targetType.changeParameterType(pos, newParamType); 3579 result = result.copyWithExtendL(newType, lform, filter); 3580 return result; 3581 } 3582 3583 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3584 MethodType targetType = target.type(); 3585 int maxPos = targetType.parameterCount(); 3586 if (pos + filters.length > maxPos) 3587 throw newIllegalArgumentException("too many filters"); 3588 } 3589 3590 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3591 MethodType targetType = target.type(); 3592 MethodType filterType = filter.type(); 3593 if (filterType.parameterCount() != 1 3594 || filterType.returnType() != targetType.parameterType(pos)) 3595 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3596 } 3597 3598 /** 3599 * Adapts a target method handle by pre-processing 3600 * a sub-sequence of its arguments with a filter (another method handle). 3601 * The pre-processed arguments are replaced by the result (if any) of the 3602 * filter function. 3603 * The target is then called on the modified (usually shortened) argument list. 3604 * <p> 3605 * If the filter returns a value, the target must accept that value as 3606 * its argument in position {@code pos}, preceded and/or followed by 3607 * any arguments not passed to the filter. 3608 * If the filter returns void, the target must accept all arguments 3609 * not passed to the filter. 3610 * No arguments are reordered, and a result returned from the filter 3611 * replaces (in order) the whole subsequence of arguments originally 3612 * passed to the adapter. 3613 * <p> 3614 * The argument types (if any) of the filter 3615 * replace zero or one argument types of the target, at position {@code pos}, 3616 * in the resulting adapted method handle. 3617 * The return type of the filter (if any) must be identical to the 3618 * argument type of the target at position {@code pos}, and that target argument 3619 * is supplied by the return value of the filter. 3620 * <p> 3621 * In all cases, {@code pos} must be greater than or equal to zero, and 3622 * {@code pos} must also be less than or equal to the target's arity. 3623 * <p><b>Example:</b> 3624 * <blockquote><pre>{@code 3625 import static java.lang.invoke.MethodHandles.*; 3626 import static java.lang.invoke.MethodType.*; 3627 ... 3628 MethodHandle deepToString = publicLookup() 3629 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 3630 3631 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 3632 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 3633 3634 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 3635 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 3636 3637 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 3638 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 3639 assertEquals("[top, [up, down], strange]", 3640 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 3641 3642 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 3643 assertEquals("[top, [up, down], [strange]]", 3644 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 3645 3646 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 3647 assertEquals("[top, [[up, down, strange], charm], bottom]", 3648 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 3649 * }</pre></blockquote> 3650 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3651 * represents the return type of the {@code target} and resulting adapter. 3652 * {@code V}/{@code v} stand for the return type and value of the 3653 * {@code filter}, which are also found in the signature and arguments of 3654 * the {@code target}, respectively, unless {@code V} is {@code void}. 3655 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types 3656 * and values preceding and following the collection position, {@code pos}, 3657 * in the {@code target}'s signature. They also turn up in the resulting 3658 * adapter's signature and arguments, where they surround 3659 * {@code B}/{@code b}, which represent the parameter types and arguments 3660 * to the {@code filter} (if any). 3661 * <blockquote><pre>{@code 3662 * T target(A...,V,C...); 3663 * V filter(B...); 3664 * T adapter(A... a,B... b,C... c) { 3665 * V v = filter(b...); 3666 * return target(a...,v,c...); 3667 * } 3668 * // and if the filter has no arguments: 3669 * T target2(A...,V,C...); 3670 * V filter2(); 3671 * T adapter2(A... a,C... c) { 3672 * V v = filter2(); 3673 * return target2(a...,v,c...); 3674 * } 3675 * // and if the filter has a void return: 3676 * T target3(A...,C...); 3677 * void filter3(B...); 3678 * T adapter3(A... a,B... b,C... c) { 3679 * filter3(b...); 3680 * return target3(a...,c...); 3681 * } 3682 * }</pre></blockquote> 3683 * <p> 3684 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 3685 * one which first "folds" the affected arguments, and then drops them, in separate 3686 * steps as follows: 3687 * <blockquote><pre>{@code 3688 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 3689 * mh = MethodHandles.foldArguments(mh, coll); //step 1 3690 * }</pre></blockquote> 3691 * If the target method handle consumes no arguments besides than the result 3692 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 3693 * is equivalent to {@code filterReturnValue(coll, mh)}. 3694 * If the filter method handle {@code coll} consumes one argument and produces 3695 * a non-void result, then {@code collectArguments(mh, N, coll)} 3696 * is equivalent to {@code filterArguments(mh, N, coll)}. 3697 * Other equivalences are possible but would require argument permutation. 3698 * <p> 3699 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3700 * variable-arity method handle}, even if the original target method handle was. 3701 * 3702 * @param target the method handle to invoke after filtering the subsequence of arguments 3703 * @param pos the position of the first adapter argument to pass to the filter, 3704 * and/or the target argument which receives the result of the filter 3705 * @param filter method handle to call on the subsequence of arguments 3706 * @return method handle which incorporates the specified argument subsequence filtering logic 3707 * @throws NullPointerException if either argument is null 3708 * @throws IllegalArgumentException if the return type of {@code filter} 3709 * is non-void and is not the same as the {@code pos} argument of the target, 3710 * or if {@code pos} is not between 0 and the target's arity, inclusive, 3711 * or if the resulting method handle's type would have 3712 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3713 * @see MethodHandles#foldArguments 3714 * @see MethodHandles#filterArguments 3715 * @see MethodHandles#filterReturnValue 3716 */ 3717 public static 3718 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 3719 MethodType newType = collectArgumentsChecks(target, pos, filter); 3720 MethodType collectorType = filter.type(); 3721 BoundMethodHandle result = target.rebind(); 3722 LambdaForm lform; 3723 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 3724 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 3725 if (lform != null) { 3726 return result.copyWith(newType, lform); 3727 } 3728 } 3729 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 3730 return result.copyWithExtendL(newType, lform, filter); 3731 } 3732 3733 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3734 MethodType targetType = target.type(); 3735 MethodType filterType = filter.type(); 3736 Class<?> rtype = filterType.returnType(); 3737 List<Class<?>> filterArgs = filterType.parameterList(); 3738 if (rtype == void.class) { 3739 return targetType.insertParameterTypes(pos, filterArgs); 3740 } 3741 if (rtype != targetType.parameterType(pos)) { 3742 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3743 } 3744 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 3745 } 3746 3747 /** 3748 * Adapts a target method handle by post-processing 3749 * its return value (if any) with a filter (another method handle). 3750 * The result of the filter is returned from the adapter. 3751 * <p> 3752 * If the target returns a value, the filter must accept that value as 3753 * its only argument. 3754 * If the target returns void, the filter must accept no arguments. 3755 * <p> 3756 * The return type of the filter 3757 * replaces the return type of the target 3758 * in the resulting adapted method handle. 3759 * The argument type of the filter (if any) must be identical to the 3760 * return type of the target. 3761 * <p><b>Example:</b> 3762 * <blockquote><pre>{@code 3763 import static java.lang.invoke.MethodHandles.*; 3764 import static java.lang.invoke.MethodType.*; 3765 ... 3766 MethodHandle cat = lookup().findVirtual(String.class, 3767 "concat", methodType(String.class, String.class)); 3768 MethodHandle length = lookup().findVirtual(String.class, 3769 "length", methodType(int.class)); 3770 System.out.println((String) cat.invokeExact("x", "y")); // xy 3771 MethodHandle f0 = filterReturnValue(cat, length); 3772 System.out.println((int) f0.invokeExact("x", "y")); // 2 3773 * }</pre></blockquote> 3774 * <p>Here is pseudocode for the resulting adapter. In the code, 3775 * {@code T}/{@code t} represent the result type and value of the 3776 * {@code target}; {@code V}, the result type of the {@code filter}; and 3777 * {@code A}/{@code a}, the types and values of the parameters and arguments 3778 * of the {@code target} as well as the resulting adapter. 3779 * <blockquote><pre>{@code 3780 * T target(A...); 3781 * V filter(T); 3782 * V adapter(A... a) { 3783 * T t = target(a...); 3784 * return filter(t); 3785 * } 3786 * // and if the target has a void return: 3787 * void target2(A...); 3788 * V filter2(); 3789 * V adapter2(A... a) { 3790 * target2(a...); 3791 * return filter2(); 3792 * } 3793 * // and if the filter has a void return: 3794 * T target3(A...); 3795 * void filter3(V); 3796 * void adapter3(A... a) { 3797 * T t = target3(a...); 3798 * filter3(t); 3799 * } 3800 * }</pre></blockquote> 3801 * <p> 3802 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3803 * variable-arity method handle}, even if the original target method handle was. 3804 * @param target the method handle to invoke before filtering the return value 3805 * @param filter method handle to call on the return value 3806 * @return method handle which incorporates the specified return value filtering logic 3807 * @throws NullPointerException if either argument is null 3808 * @throws IllegalArgumentException if the argument list of {@code filter} 3809 * does not match the return type of target as described above 3810 */ 3811 public static 3812 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 3813 MethodType targetType = target.type(); 3814 MethodType filterType = filter.type(); 3815 filterReturnValueChecks(targetType, filterType); 3816 BoundMethodHandle result = target.rebind(); 3817 BasicType rtype = BasicType.basicType(filterType.returnType()); 3818 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 3819 MethodType newType = targetType.changeReturnType(filterType.returnType()); 3820 result = result.copyWithExtendL(newType, lform, filter); 3821 return result; 3822 } 3823 3824 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 3825 Class<?> rtype = targetType.returnType(); 3826 int filterValues = filterType.parameterCount(); 3827 if (filterValues == 0 3828 ? (rtype != void.class) 3829 : (rtype != filterType.parameterType(0) || filterValues != 1)) 3830 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3831 } 3832 3833 /** 3834 * Adapts a target method handle by pre-processing 3835 * some of its arguments, and then calling the target with 3836 * the result of the pre-processing, inserted into the original 3837 * sequence of arguments. 3838 * <p> 3839 * The pre-processing is performed by {@code combiner}, a second method handle. 3840 * Of the arguments passed to the adapter, the first {@code N} arguments 3841 * are copied to the combiner, which is then called. 3842 * (Here, {@code N} is defined as the parameter count of the combiner.) 3843 * After this, control passes to the target, with any result 3844 * from the combiner inserted before the original {@code N} incoming 3845 * arguments. 3846 * <p> 3847 * If the combiner returns a value, the first parameter type of the target 3848 * must be identical with the return type of the combiner, and the next 3849 * {@code N} parameter types of the target must exactly match the parameters 3850 * of the combiner. 3851 * <p> 3852 * If the combiner has a void return, no result will be inserted, 3853 * and the first {@code N} parameter types of the target 3854 * must exactly match the parameters of the combiner. 3855 * <p> 3856 * The resulting adapter is the same type as the target, except that the 3857 * first parameter type is dropped, 3858 * if it corresponds to the result of the combiner. 3859 * <p> 3860 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 3861 * that either the combiner or the target does not wish to receive. 3862 * If some of the incoming arguments are destined only for the combiner, 3863 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 3864 * arguments will not need to be live on the stack on entry to the 3865 * target.) 3866 * <p><b>Example:</b> 3867 * <blockquote><pre>{@code 3868 import static java.lang.invoke.MethodHandles.*; 3869 import static java.lang.invoke.MethodType.*; 3870 ... 3871 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 3872 "println", methodType(void.class, String.class)) 3873 .bindTo(System.out); 3874 MethodHandle cat = lookup().findVirtual(String.class, 3875 "concat", methodType(String.class, String.class)); 3876 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 3877 MethodHandle catTrace = foldArguments(cat, trace); 3878 // also prints "boo": 3879 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 3880 * }</pre></blockquote> 3881 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3882 * represents the result type of the {@code target} and resulting adapter. 3883 * {@code V}/{@code v} represent the type and value of the parameter and argument 3884 * of {@code target} that precedes the folding position; {@code V} also is 3885 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 3886 * types and values of the {@code N} parameters and arguments at the folding 3887 * position. {@code B}/{@code b} represent the types and values of the 3888 * {@code target} parameters and arguments that follow the folded parameters 3889 * and arguments. 3890 * <blockquote><pre>{@code 3891 * // there are N arguments in A... 3892 * T target(V, A[N]..., B...); 3893 * V combiner(A...); 3894 * T adapter(A... a, B... b) { 3895 * V v = combiner(a...); 3896 * return target(v, a..., b...); 3897 * } 3898 * // and if the combiner has a void return: 3899 * T target2(A[N]..., B...); 3900 * void combiner2(A...); 3901 * T adapter2(A... a, B... b) { 3902 * combiner2(a...); 3903 * return target2(a..., b...); 3904 * } 3905 * }</pre></blockquote> 3906 * <p> 3907 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3908 * variable-arity method handle}, even if the original target method handle was. 3909 * @param target the method handle to invoke after arguments are combined 3910 * @param combiner method handle to call initially on the incoming arguments 3911 * @return method handle which incorporates the specified argument folding logic 3912 * @throws NullPointerException if either argument is null 3913 * @throws IllegalArgumentException if {@code combiner}'s return type 3914 * is non-void and not the same as the first argument type of 3915 * the target, or if the initial {@code N} argument types 3916 * of the target 3917 * (skipping one matching the {@code combiner}'s return type) 3918 * are not identical with the argument types of {@code combiner} 3919 */ 3920 public static 3921 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 3922 return foldArguments(target, 0, combiner); 3923 } 3924 3925 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 3926 int foldArgs = combinerType.parameterCount(); 3927 Class<?> rtype = combinerType.returnType(); 3928 int foldVals = rtype == void.class ? 0 : 1; 3929 int afterInsertPos = foldPos + foldVals; 3930 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 3931 if (ok) { 3932 for (int i = 0; i < foldArgs; i++) { 3933 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 3934 ok = false; 3935 break; 3936 } 3937 } 3938 } 3939 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 3940 ok = false; 3941 if (!ok) 3942 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3943 return rtype; 3944 } 3945 3946 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType, int ... argPos) { 3947 int foldArgs = combinerType.parameterCount(); 3948 if (argPos.length != foldArgs) { 3949 throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length); 3950 } 3951 Class<?> rtype = combinerType.returnType(); 3952 int foldVals = rtype == void.class ? 0 : 1; 3953 boolean ok = true; 3954 for (int i = 0; i < foldArgs; i++) { 3955 int arg = argPos[i]; 3956 if (arg < 0 || arg > targetType.parameterCount()) { 3957 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg); 3958 } 3959 if (combinerType.parameterType(i) != targetType.parameterType(arg)) { 3960 throw newIllegalArgumentException("target argument type at position " + arg 3961 + " must match combiner argument type at index " + i + ": " + targetType 3962 + " -> " + combinerType + ", map: " + Arrays.toString(argPos)); 3963 } 3964 } 3965 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) { 3966 ok = false; 3967 } 3968 if (!ok) 3969 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3970 return rtype; 3971 } 3972 3973 /** 3974 * Makes a method handle which adapts a target method handle, 3975 * by guarding it with a test, a boolean-valued method handle. 3976 * If the guard fails, a fallback handle is called instead. 3977 * All three method handles must have the same corresponding 3978 * argument and return types, except that the return type 3979 * of the test must be boolean, and the test is allowed 3980 * to have fewer arguments than the other two method handles. 3981 * <p> 3982 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3983 * represents the uniform result type of the three involved handles; 3984 * {@code A}/{@code a}, the types and values of the {@code target} 3985 * parameters and arguments that are consumed by the {@code test}; and 3986 * {@code B}/{@code b}, those types and values of the {@code target} 3987 * parameters and arguments that are not consumed by the {@code test}. 3988 * <blockquote><pre>{@code 3989 * boolean test(A...); 3990 * T target(A...,B...); 3991 * T fallback(A...,B...); 3992 * T adapter(A... a,B... b) { 3993 * if (test(a...)) 3994 * return target(a..., b...); 3995 * else 3996 * return fallback(a..., b...); 3997 * } 3998 * }</pre></blockquote> 3999 * Note that the test arguments ({@code a...} in the pseudocode) cannot 4000 * be modified by execution of the test, and so are passed unchanged 4001 * from the caller to the target or fallback as appropriate. 4002 * @param test method handle used for test, must return boolean 4003 * @param target method handle to call if test passes 4004 * @param fallback method handle to call if test fails 4005 * @return method handle which incorporates the specified if/then/else logic 4006 * @throws NullPointerException if any argument is null 4007 * @throws IllegalArgumentException if {@code test} does not return boolean, 4008 * or if all three method types do not match (with the return 4009 * type of {@code test} changed to match that of the target). 4010 */ 4011 public static 4012 MethodHandle guardWithTest(MethodHandle test, 4013 MethodHandle target, 4014 MethodHandle fallback) { 4015 MethodType gtype = test.type(); 4016 MethodType ttype = target.type(); 4017 MethodType ftype = fallback.type(); 4018 if (!ttype.equals(ftype)) 4019 throw misMatchedTypes("target and fallback types", ttype, ftype); 4020 if (gtype.returnType() != boolean.class) 4021 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 4022 List<Class<?>> targs = ttype.parameterList(); 4023 test = dropArgumentsToMatch(test, 0, targs, 0, true); 4024 if (test == null) { 4025 throw misMatchedTypes("target and test types", ttype, gtype); 4026 } 4027 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 4028 } 4029 4030 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 4031 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 4032 } 4033 4034 /** 4035 * Makes a method handle which adapts a target method handle, 4036 * by running it inside an exception handler. 4037 * If the target returns normally, the adapter returns that value. 4038 * If an exception matching the specified type is thrown, the fallback 4039 * handle is called instead on the exception, plus the original arguments. 4040 * <p> 4041 * The target and handler must have the same corresponding 4042 * argument and return types, except that handler may omit trailing arguments 4043 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 4044 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 4045 * <p> 4046 * Here is pseudocode for the resulting adapter. In the code, {@code T} 4047 * represents the return type of the {@code target} and {@code handler}, 4048 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 4049 * the types and values of arguments to the resulting handle consumed by 4050 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 4051 * resulting handle discarded by {@code handler}. 4052 * <blockquote><pre>{@code 4053 * T target(A..., B...); 4054 * T handler(ExType, A...); 4055 * T adapter(A... a, B... b) { 4056 * try { 4057 * return target(a..., b...); 4058 * } catch (ExType ex) { 4059 * return handler(ex, a...); 4060 * } 4061 * } 4062 * }</pre></blockquote> 4063 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4064 * be modified by execution of the target, and so are passed unchanged 4065 * from the caller to the handler, if the handler is invoked. 4066 * <p> 4067 * The target and handler must return the same type, even if the handler 4068 * always throws. (This might happen, for instance, because the handler 4069 * is simulating a {@code finally} clause). 4070 * To create such a throwing handler, compose the handler creation logic 4071 * with {@link #throwException throwException}, 4072 * in order to create a method handle of the correct return type. 4073 * @param target method handle to call 4074 * @param exType the type of exception which the handler will catch 4075 * @param handler method handle to call if a matching exception is thrown 4076 * @return method handle which incorporates the specified try/catch logic 4077 * @throws NullPointerException if any argument is null 4078 * @throws IllegalArgumentException if {@code handler} does not accept 4079 * the given exception type, or if the method handle types do 4080 * not match in their return types and their 4081 * corresponding parameters 4082 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 4083 */ 4084 public static 4085 MethodHandle catchException(MethodHandle target, 4086 Class<? extends Throwable> exType, 4087 MethodHandle handler) { 4088 MethodType ttype = target.type(); 4089 MethodType htype = handler.type(); 4090 if (!Throwable.class.isAssignableFrom(exType)) 4091 throw new ClassCastException(exType.getName()); 4092 if (htype.parameterCount() < 1 || 4093 !htype.parameterType(0).isAssignableFrom(exType)) 4094 throw newIllegalArgumentException("handler does not accept exception type "+exType); 4095 if (htype.returnType() != ttype.returnType()) 4096 throw misMatchedTypes("target and handler return types", ttype, htype); 4097 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 4098 if (handler == null) { 4099 throw misMatchedTypes("target and handler types", ttype, htype); 4100 } 4101 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 4102 } 4103 4104 /** 4105 * Produces a method handle which will throw exceptions of the given {@code exType}. 4106 * The method handle will accept a single argument of {@code exType}, 4107 * and immediately throw it as an exception. 4108 * The method type will nominally specify a return of {@code returnType}. 4109 * The return type may be anything convenient: It doesn't matter to the 4110 * method handle's behavior, since it will never return normally. 4111 * @param returnType the return type of the desired method handle 4112 * @param exType the parameter type of the desired method handle 4113 * @return method handle which can throw the given exceptions 4114 * @throws NullPointerException if either argument is null 4115 */ 4116 public static 4117 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 4118 if (!Throwable.class.isAssignableFrom(exType)) 4119 throw new ClassCastException(exType.getName()); 4120 return MethodHandleImpl.throwException(methodType(returnType, exType)); 4121 } 4122 4123 /** 4124 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 4125 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 4126 * delivers the loop's result, which is the return value of the resulting handle. 4127 * <p> 4128 * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop 4129 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 4130 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 4131 * terms of method handles, each clause will determine four actions:<ul> 4132 * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local. 4133 * <li>When a clause executes, an update step for the iteration variable. 4134 * <li>When a clause executes, a predicate execution to test for loop exit. 4135 * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 4136 * </ul> 4137 * <p> 4138 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 4139 * this case. See below for a detailed description. 4140 * <p> 4141 * Each clause function, with the exception of clause initializers, is able to observe the entire loop state, 4142 * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop 4143 * parameters. Most clause functions will not need all of this information, but they will be formally connected as 4144 * if by {@link #dropArguments}. 4145 * <p> 4146 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 4147 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 4148 * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met 4149 * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means 4150 * that they must be identical, or else one list must be a proper prefix of the other. 4151 * <p> 4152 * <em>Step 0: Determine clause structure.</em><ol type="a"> 4153 * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element. 4154 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4155 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4156 * four. Padding takes place by appending elements to the array. 4157 * <li>Clauses with all {@code null}s are disregarded. 4158 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4159 * </ol> 4160 * <p> 4161 * <em>Step 1A: Determine iteration variables.</em><ol type="a"> 4162 * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type. 4163 * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else 4164 * use the common return type (they must be identical). 4165 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4166 * <li>This list of types is called the "common prefix". 4167 * </ol> 4168 * <p> 4169 * <em>Step 1B: Determine loop parameters.</em><ul> 4170 * <li><b>If at least one init function is given,</b><ol type="a"> 4171 * <li>Examine init function parameter lists. 4172 * <li>Omitted init functions are deemed to have {@code null} parameter lists. 4173 * <li>All init function parameter lists must be effectively identical. 4174 * <li>The longest parameter list (which is necessarily unique) is called the "common suffix". 4175 * </ol> 4176 * <li><b>If no init function is given,</b><ol type="a"> 4177 * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix". 4178 * <li>The longest of these suffixes is taken as the "common suffix". 4179 * </ol></ul> 4180 * <p> 4181 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4182 * <li>Examine fini function return types, disregarding omitted fini functions. 4183 * <li>If there are no fini functions, use {@code void} as the loop return type. 4184 * <li>Otherwise, use the common return type of the fini functions; they must all be identical. 4185 * </ol> 4186 * <p> 4187 * <em>Step 1D: Check other types.</em><ol type="a"> 4188 * <li>There must be at least one non-omitted pred function. 4189 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4190 * </ol> 4191 * <p> 4192 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4193 * <li>The parameter list for the resulting loop handle will be the "common suffix". 4194 * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter 4195 * lists are already effectively identical to the common suffix.) 4196 * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix 4197 * followed by the common suffix, called the "common parameter sequence". 4198 * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter 4199 * sequence. 4200 * </ol> 4201 * <p> 4202 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4203 * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate 4204 * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a 4205 * function which does nothing and returns {@code void}; it can be obtained from another constant function by 4206 * {@linkplain MethodHandle#asType type conversion}.) 4207 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4208 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4209 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4210 * <li>If a pred function is omitted, the corresponding fini function must also be omitted. 4211 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4212 * as this clause is concerned.) 4213 * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the 4214 * loop return type. 4215 * </ol> 4216 * <p> 4217 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4218 * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some 4219 * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by 4220 * {@linkplain #dropArguments dropping arguments}. 4221 * <li>At this point, every non-init function parameter list is effectively identical to the common parameter 4222 * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end 4223 * of the list by {@linkplain #dropArguments dropping arguments}. 4224 * </ol> 4225 * <p> 4226 * <em>Final observations.</em><ol type="a"> 4227 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4228 * <li>All init functions have a common parameter type list, which the final loop handle will also have. 4229 * <li>All fini functions have a common return type, which the final loop handle will also have. 4230 * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of 4231 * (non-{@code void}) iteration variables followed by loop parameters. 4232 * <li>Each pair of init and step functions agrees in their return types. 4233 * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the 4234 * common prefix. 4235 * </ol> 4236 * <p> 4237 * <em>Loop execution.</em><ol type="a"> 4238 * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to 4239 * every clause function. These locals are loop invariant. 4240 * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values 4241 * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity 4242 * functions, as noted above). 4243 * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of 4244 * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order). 4245 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4246 * returns {@code false}. 4247 * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The 4248 * updated value is immediately visible to all subsequent function calls. 4249 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4250 * is returned from the loop as a whole. 4251 * </ol> 4252 * <p> 4253 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values 4254 * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the 4255 * result types of finalizers as well as of the resulting loop. 4256 * <blockquote><pre>{@code 4257 * V... init...(A...); 4258 * boolean pred...(V..., A...); 4259 * V... step...(V..., A...); 4260 * R fini...(V..., A...); 4261 * R loop(A... a) { 4262 * V... v... = init...(a...); 4263 * for (;;) { 4264 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4265 * v = s(v..., a...); 4266 * if (!p(v..., a...)) { 4267 * return f(v..., a...); 4268 * } 4269 * } 4270 * } 4271 * } 4272 * }</pre></blockquote> 4273 * <p> 4274 * @apiNote Example: 4275 * <blockquote><pre>{@code 4276 * // iterative implementation of the factorial function as a loop handle 4277 * static int one(int k) { return 1; } 4278 * static int inc(int i, int acc, int k) { return i + 1; } 4279 * static int mult(int i, int acc, int k) { return i * acc; } 4280 * static boolean pred(int i, int acc, int k) { return i < k; } 4281 * static int fin(int i, int acc, int k) { return acc; } 4282 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4283 * // null initializer for counter, should initialize to 0 4284 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4285 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4286 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4287 * assertEquals(120, loop.invoke(5)); 4288 * }</pre></blockquote> 4289 * 4290 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4291 * 4292 * @return a method handle embodying the looping behavior as defined by the arguments. 4293 * 4294 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4295 * 4296 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4297 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4298 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4299 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4300 * @since 9 4301 */ 4302 public static MethodHandle loop(MethodHandle[]... clauses) { 4303 // Step 0: determine clause structure. 4304 checkLoop0(clauses); 4305 4306 List<MethodHandle> init = new ArrayList<>(); 4307 List<MethodHandle> step = new ArrayList<>(); 4308 List<MethodHandle> pred = new ArrayList<>(); 4309 List<MethodHandle> fini = new ArrayList<>(); 4310 4311 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4312 init.add(clause[0]); // all clauses have at least length 1 4313 step.add(clause.length <= 1 ? null : clause[1]); 4314 pred.add(clause.length <= 2 ? null : clause[2]); 4315 fini.add(clause.length <= 3 ? null : clause[3]); 4316 }); 4317 4318 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4319 final int nclauses = init.size(); 4320 4321 // Step 1A: determine iteration variables. 4322 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4323 for (int i = 0; i < nclauses; ++i) { 4324 MethodHandle in = init.get(i); 4325 MethodHandle st = step.get(i); 4326 if (in == null && st == null) { 4327 iterationVariableTypes.add(void.class); 4328 } else if (in != null && st != null) { 4329 checkLoop1a(i, in, st); 4330 iterationVariableTypes.add(in.type().returnType()); 4331 } else { 4332 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4333 } 4334 } 4335 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4336 collect(Collectors.toList()); 4337 4338 // Step 1B: determine loop parameters. 4339 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4340 checkLoop1b(init, commonSuffix); 4341 4342 // Step 1C: determine loop return type. 4343 // Step 1D: check other types. 4344 final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type). 4345 map(MethodType::returnType).findFirst().orElse(void.class); 4346 checkLoop1cd(pred, fini, loopReturnType); 4347 4348 // Step 2: determine parameter lists. 4349 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4350 commonParameterSequence.addAll(commonSuffix); 4351 checkLoop2(step, pred, fini, commonParameterSequence); 4352 4353 // Step 3: fill in omitted functions. 4354 for (int i = 0; i < nclauses; ++i) { 4355 Class<?> t = iterationVariableTypes.get(i); 4356 if (init.get(i) == null) { 4357 init.set(i, empty(methodType(t, commonSuffix))); 4358 } 4359 if (step.get(i) == null) { 4360 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 4361 } 4362 if (pred.get(i) == null) { 4363 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); 4364 } 4365 if (fini.get(i) == null) { 4366 fini.set(i, empty(methodType(t, commonParameterSequence))); 4367 } 4368 } 4369 4370 // Step 4: fill in missing parameter types. 4371 List<MethodHandle> finit = fillParameterTypes(init, commonSuffix); 4372 List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence); 4373 List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence); 4374 List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence); 4375 4376 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 4377 allMatch(pl -> pl.equals(commonSuffix)); 4378 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 4379 allMatch(pl -> pl.equals(commonParameterSequence)); 4380 4381 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 4382 } 4383 4384 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 4385 return hs.stream().map(h -> { 4386 int pc = h.type().parameterCount(); 4387 int tpsize = targetParams.size(); 4388 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; 4389 }).collect(Collectors.toList()); 4390 } 4391 4392 /** 4393 * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for 4394 * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4395 * <p> 4396 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4397 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4398 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4399 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4400 * generic loop combinator}. 4401 * <p> 4402 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4403 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4404 * passed to the loop. 4405 * <blockquote><pre>{@code 4406 * V init(A); 4407 * boolean pred(V, A); 4408 * V body(V, A); 4409 * V whileLoop(A a) { 4410 * V v = init(a); 4411 * while (pred(v, a)) { 4412 * v = body(v, a); 4413 * } 4414 * return v; 4415 * } 4416 * }</pre></blockquote> 4417 * <p> 4418 * @apiNote Example: 4419 * <blockquote><pre>{@code 4420 * // implement the zip function for lists as a loop handle 4421 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 4422 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 4423 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 4424 * zip.add(a.next()); 4425 * zip.add(b.next()); 4426 * return zip; 4427 * } 4428 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 4429 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 4430 * List<String> a = Arrays.asList("a", "b", "c", "d"); 4431 * List<String> b = Arrays.asList("e", "f", "g", "h"); 4432 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 4433 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 4434 * }</pre></blockquote> 4435 * 4436 * <p> 4437 * @implSpec The implementation of this method is equivalent to: 4438 * <blockquote><pre>{@code 4439 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4440 * MethodHandle[] 4441 * checkExit = {null, null, pred, identity(init.type().returnType())}, 4442 * varBody = {init, body}; 4443 * return loop(checkExit, varBody); 4444 * } 4445 * }</pre></blockquote> 4446 * 4447 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4448 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4449 * {@code void}. 4450 * @param pred condition for the loop, which may not be {@code null}. 4451 * @param body body of the loop, which may not be {@code null}. 4452 * 4453 * @return the value of the loop variable as the loop terminates. 4454 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4455 * 4456 * @see MethodHandles#loop(MethodHandle[][]) 4457 * @since 9 4458 */ 4459 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4460 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4461 identity(init.type().returnType()); 4462 MethodHandle[] checkExit = {null, null, pred, fin}; 4463 MethodHandle[] varBody = {init, body}; 4464 return loop(checkExit, varBody); 4465 } 4466 4467 /** 4468 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper 4469 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4470 * <p> 4471 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. 4472 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle 4473 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code 4474 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) 4475 * generic loop combinator}. 4476 * <p> 4477 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4478 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4479 * passed to the loop. 4480 * <blockquote><pre>{@code 4481 * V init(A); 4482 * boolean pred(V, A); 4483 * V body(V, A); 4484 * V doWhileLoop(A a) { 4485 * V v = init(a); 4486 * do { 4487 * v = body(v, a); 4488 * } while (pred(v, a)); 4489 * return v; 4490 * } 4491 * }</pre></blockquote> 4492 * <p> 4493 * @apiNote Example: 4494 * <blockquote><pre>{@code 4495 * // int i = 0; while (i < limit) { ++i; } return i; => limit 4496 * static int zero(int limit) { return 0; } 4497 * static int step(int i, int limit) { return i + 1; } 4498 * static boolean pred(int i, int limit) { return i < limit; } 4499 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 4500 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 4501 * assertEquals(23, loop.invoke(23)); 4502 * }</pre></blockquote> 4503 * 4504 * <p> 4505 * @implSpec The implementation of this method is equivalent to: 4506 * <blockquote><pre>{@code 4507 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4508 * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) }; 4509 * return loop(clause); 4510 * } 4511 * }</pre></blockquote> 4512 * 4513 * 4514 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's 4515 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type 4516 * {@code void}. 4517 * @param pred condition for the loop, which may not be {@code null}. 4518 * @param body body of the loop, which may not be {@code null}. 4519 * 4520 * @return the value of the loop variable as the loop terminates. 4521 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4522 * 4523 * @see MethodHandles#loop(MethodHandle[][]) 4524 * @since 9 4525 */ 4526 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4527 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : 4528 identity(init.type().returnType()); 4529 MethodHandle[] clause = {init, body, pred, fin}; 4530 return loop(clause); 4531 } 4532 4533 /** 4534 * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the 4535 * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must 4536 * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional 4537 * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop 4538 * combinator}. 4539 * <p> 4540 * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code 4541 * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code 4542 * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter, 4543 * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described 4544 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4545 * <p> 4546 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4547 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4548 * passed to the loop. 4549 * <blockquote><pre>{@code 4550 * int iterations(A); 4551 * V init(A); 4552 * V body(int, V, A); 4553 * V countedLoop(A a) { 4554 * int end = iterations(a); 4555 * V v = init(a); 4556 * for (int i = 0; i < end; ++i) { 4557 * v = body(i, v, a); 4558 * } 4559 * return v; 4560 * } 4561 * }</pre></blockquote> 4562 * <p> 4563 * @apiNote Example: 4564 * <blockquote><pre>{@code 4565 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 4566 * // => a variation on a well known theme 4567 * static String start(String arg) { return arg; } 4568 * static String step(int counter, String v, String arg) { return "na " + v; } 4569 * // assume MH_start and MH_step are handles to the two methods above 4570 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 4571 * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step); 4572 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 4573 * }</pre></blockquote> 4574 * 4575 * <p> 4576 * @implSpec The implementation of this method is equivalent to: 4577 * <blockquote><pre>{@code 4578 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4579 * return countedLoop(null, iterations, init, body); // null => constant zero 4580 * } 4581 * }</pre></blockquote> 4582 * 4583 * @param iterations a handle to return the number of iterations this loop should run. 4584 * @param init initializer for additional loop state. This determines the loop's result type. 4585 * Passing {@code null} or a {@code void} init function will make the loop's result type 4586 * {@code void}. 4587 * @param body the body of the loop, which must not be {@code null}. 4588 * It must accept an initial {@code int} parameter (for the counter), and then any 4589 * additional loop-local variable plus loop parameters. 4590 * 4591 * @return a method handle representing the loop. 4592 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4593 * 4594 * @since 9 4595 */ 4596 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4597 return countedLoop(null, iterations, init, body); 4598 } 4599 4600 /** 4601 * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be 4602 * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the 4603 * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code 4604 * body} function in each iteration; it has to accept an initial {@code int} parameter 4605 * for that. The result of the loop execution is the final value of the additional local state 4606 * obtained by running {@code init}. 4607 * This is a 4608 * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. 4609 * <p> 4610 * The constraints for the {@code init} and {@code body} handles are the same as for {@link 4611 * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles 4612 * must return an {@code int} and accept the same parameters as {@code init}. 4613 * <p> 4614 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4615 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4616 * passed to the loop. 4617 * <blockquote><pre>{@code 4618 * int start(A); 4619 * int end(A); 4620 * V init(A); 4621 * V body(int, V, A); 4622 * V countedLoop(A a) { 4623 * int s = start(a); 4624 * int e = end(a); 4625 * V v = init(a); 4626 * for (int i = s; i < e; ++i) { 4627 * v = body(i, v, a); 4628 * } 4629 * return v; 4630 * } 4631 * }</pre></blockquote> 4632 * 4633 * <p> 4634 * @implSpec The implementation of this method is equivalent to: 4635 * <blockquote><pre>{@code 4636 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4637 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 4638 * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int, 4639 * // assume MH_decrement is a handle to x-1 of type int 4640 * MethodHandle[] 4641 * indexVar = {start, MH_increment}, // i = start; i = i+1 4642 * loopLimit = {end, null, 4643 * filterArgument(MH_lessThan, 0, MH_decrement), returnVar}, // i-1<end 4644 * bodyClause = {init, 4645 * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v) 4646 * return loop(indexVar, loopLimit, bodyClause); 4647 * } 4648 * }</pre></blockquote> 4649 * 4650 * @param start a handle to return the start value of the loop counter. 4651 * If it is {@code null}, a constant zero is assumed. 4652 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}). 4653 * @param init initializer for additional loop state. This determines the loop's result type. 4654 * Passing {@code null} or a {@code void} init function will make the loop's result type 4655 * {@code void}. 4656 * @param body the body of the loop, which must not be {@code null}. 4657 * It must accept an initial {@code int} parameter (for the counter), and then any 4658 * additional loop-local variable plus loop parameters. 4659 * 4660 * @return a method handle representing the loop. 4661 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4662 * 4663 * @since 9 4664 */ 4665 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4666 Class<?> resultType; 4667 MethodHandle actualInit; 4668 if (init == null) { 4669 resultType = body == null ? void.class : body.type().returnType(); 4670 actualInit = empty(methodType(resultType)); 4671 } else { 4672 resultType = init.type().returnType(); 4673 actualInit = init; 4674 } 4675 MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType); 4676 MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body; 4677 MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class); 4678 MethodHandle actualEnd = end == null ? constant(int.class, 0) : end; 4679 MethodHandle decr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter); 4680 MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)}; 4681 MethodHandle[] loopLimit = {actualEnd, null, 4682 filterArgument(MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), 0, decr), 4683 returnVar}; 4684 MethodHandle[] bodyClause = {actualInit, filterArgument(dropArguments(actualBody, 1, int.class), 0, decr)}; 4685 return loop(indexVar, loopLimit, bodyClause); 4686 } 4687 4688 /** 4689 * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}. 4690 * The iterator will be produced by the evaluation of the {@code iterator} handle. 4691 * This handle must have {@link java.util.Iterator} as its return type. 4692 * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead, 4693 * and will be applied to a leading argument of the loop handle. 4694 * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter. 4695 * The result of the loop execution is the final value of the additional local state 4696 * obtained by running {@code init}. 4697 * <p> 4698 * This is a convenience wrapper for the 4699 * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body} 4700 * handle follow directly from those described for the latter. 4701 * <p> 4702 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4703 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 4704 * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop. 4705 * <blockquote><pre>{@code 4706 * Iterator<T> iterator(A); // defaults to Iterable::iterator 4707 * V init(A); 4708 * V body(T,V,A); 4709 * V iteratedLoop(A a) { 4710 * Iterator<T> it = iterator(a); 4711 * V v = init(a); 4712 * for (T t : it) { 4713 * v = body(t, v, a); 4714 * } 4715 * return v; 4716 * } 4717 * }</pre></blockquote> 4718 * <p> 4719 * The type {@code T} may be either a primitive or reference. 4720 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type 4721 * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} 4722 * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method. 4723 * Therefore, if an iterator of the wrong type appears as the loop is executed, 4724 * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}. 4725 * <p> 4726 * @apiNote Example: 4727 * <blockquote><pre>{@code 4728 * // reverse a list 4729 * static List<String> reverseStep(String e, List<String> r, List<String> l) { 4730 * r.add(0, e); 4731 * return r; 4732 * } 4733 * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); } 4734 * // assume MH_reverseStep, MH_newArrayList are handles to the above methods 4735 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 4736 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 4737 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 4738 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 4739 * }</pre></blockquote> 4740 * <p> 4741 * @implSpec The implementation of this method is equivalent to (excluding error handling): 4742 * <blockquote><pre>{@code 4743 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4744 * // assume MH_next and MH_hasNext are handles to methods of Iterator 4745 * Class<?> itype = iterator.type().returnType(); 4746 * Class<?> ttype = body.type().parameterType(0); 4747 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype); 4748 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 4749 * MethodHandle[] 4750 * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext) 4751 * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a); 4752 * return loop(iterVar, bodyClause); 4753 * } 4754 * }</pre></blockquote> 4755 * 4756 * @param iterator a handle to return the iterator to start the loop. 4757 * The handle must have {@link java.util.Iterator} as its return type. 4758 * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first 4759 * incoming value. 4760 * @param init initializer for additional loop state. This determines the loop's result type. 4761 * Passing {@code null} or a {@code void} init function will make the loop's result type 4762 * {@code void}. 4763 * @param body the body of the loop, which must not be {@code null}. 4764 * It must accept an initial {@code T} parameter (for the iterated values), and then any 4765 * additional loop-local variable plus loop parameters. 4766 * 4767 * @return a method handle embodying the iteration loop functionality. 4768 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure 4769 * 4770 * @since 9 4771 */ 4772 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 4773 checkIteratedLoop(iterator, body); 4774 Class<?> resultType = init == null ? 4775 body == null ? void.class : body.type().returnType() : 4776 init.type().returnType(); 4777 boolean voidResult = resultType == void.class; 4778 4779 MethodHandle initIterator; 4780 if (iterator == null) { 4781 MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 4782 initIterator = initit.asType(initit.type().changeParameterType(0, 4783 body.type().parameterType(voidResult ? 1 : 2))); 4784 } else { 4785 initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class)); 4786 } 4787 4788 Class<?> ttype = body.type().parameterType(0); 4789 4790 MethodHandle returnVar = 4791 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class); 4792 MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 4793 MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype)); 4794 4795 MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), 4796 returnVar}; 4797 MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)}; 4798 4799 return loop(iterVar, bodyClause); 4800 } 4801 4802 /** 4803 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 4804 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 4805 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 4806 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 4807 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 4808 * {@code try-finally} handle. 4809 * <p> 4810 * The {@code cleanup} handle will be passed one or two additional leading arguments. 4811 * The first is the exception thrown during the 4812 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 4813 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 4814 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 4815 * The second argument is not present if the {@code target} handle has a {@code void} return type. 4816 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 4817 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 4818 * <p> 4819 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 4820 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 4821 * two extra leading parameters:<ul> 4822 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 4823 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 4824 * the result from the execution of the {@code target} handle. 4825 * This parameter is not present if the {@code target} returns {@code void}. 4826 * </ul> 4827 * <p> 4828 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 4829 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 4830 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 4831 * the cleanup. 4832 * <blockquote><pre>{@code 4833 * V target(A..., B...); 4834 * V cleanup(Throwable, V, A...); 4835 * V adapter(A... a, B... b) { 4836 * V result = (zero value for V); 4837 * Throwable throwable = null; 4838 * try { 4839 * result = target(a..., b...); 4840 * } catch (Throwable t) { 4841 * throwable = t; 4842 * throw t; 4843 * } finally { 4844 * result = cleanup(throwable, result, a...); 4845 * } 4846 * return result; 4847 * } 4848 * }</pre></blockquote> 4849 * <p> 4850 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 4851 * be modified by execution of the target, and so are passed unchanged 4852 * from the caller to the cleanup, if it is invoked. 4853 * <p> 4854 * The target and cleanup must return the same type, even if the cleanup 4855 * always throws. 4856 * To create such a throwing cleanup, compose the cleanup logic 4857 * with {@link #throwException throwException}, 4858 * in order to create a method handle of the correct return type. 4859 * <p> 4860 * Note that {@code tryFinally} never converts exceptions into normal returns. 4861 * In rare cases where exceptions must be converted in that way, first wrap 4862 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 4863 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 4864 * 4865 * @param target the handle whose execution is to be wrapped in a {@code try} block. 4866 * @param cleanup the handle that is invoked in the finally block. 4867 * 4868 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 4869 * @throws NullPointerException if any argument is null 4870 * @throws IllegalArgumentException if {@code cleanup} does not accept 4871 * the required leading arguments, or if the method handle types do 4872 * not match in their return types and their 4873 * corresponding trailing parameters 4874 * 4875 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 4876 * @since 9 4877 */ 4878 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 4879 List<Class<?>> targetParamTypes = target.type().parameterList(); 4880 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 4881 Class<?> rtype = target.type().returnType(); 4882 4883 checkTryFinally(target, cleanup); 4884 4885 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 4886 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 4887 // target parameter list. 4888 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 4889 4890 return MethodHandleImpl.makeTryFinally(target, cleanup, rtype, targetParamTypes); 4891 } 4892 4893 /** 4894 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 4895 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 4896 * before the folded arguments. 4897 * <p> 4898 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 4899 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 4900 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 4901 * 0. 4902 * <p> 4903 * @apiNote Example: 4904 * <blockquote><pre>{@code 4905 import static java.lang.invoke.MethodHandles.*; 4906 import static java.lang.invoke.MethodType.*; 4907 ... 4908 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 4909 "println", methodType(void.class, String.class)) 4910 .bindTo(System.out); 4911 MethodHandle cat = lookup().findVirtual(String.class, 4912 "concat", methodType(String.class, String.class)); 4913 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 4914 MethodHandle catTrace = foldArguments(cat, 1, trace); 4915 // also prints "jum": 4916 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 4917 * }</pre></blockquote> 4918 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 4919 * represents the result type of the {@code target} and resulting adapter. 4920 * {@code V}/{@code v} represent the type and value of the parameter and argument 4921 * of {@code target} that precedes the folding position; {@code V} also is 4922 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 4923 * types and values of the {@code N} parameters and arguments at the folding 4924 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 4925 * and values of the {@code target} parameters and arguments that precede and 4926 * follow the folded parameters and arguments starting at {@code pos}, 4927 * respectively. 4928 * <blockquote><pre>{@code 4929 * // there are N arguments in A... 4930 * T target(Z..., V, A[N]..., B...); 4931 * V combiner(A...); 4932 * T adapter(Z... z, A... a, B... b) { 4933 * V v = combiner(a...); 4934 * return target(z..., v, a..., b...); 4935 * } 4936 * // and if the combiner has a void return: 4937 * T target2(Z..., A[N]..., B...); 4938 * void combiner2(A...); 4939 * T adapter2(Z... z, A... a, B... b) { 4940 * combiner2(a...); 4941 * return target2(z..., a..., b...); 4942 * } 4943 * }</pre></blockquote> 4944 * <p> 4945 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 4946 * variable-arity method handle}, even if the original target method handle was. 4947 * 4948 * @param target the method handle to invoke after arguments are combined 4949 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 4950 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 4951 * @param combiner method handle to call initially on the incoming arguments 4952 * @return method handle which incorporates the specified argument folding logic 4953 * @throws NullPointerException if either argument is null 4954 * @throws IllegalArgumentException if {@code combiner}'s return type 4955 * is non-void and not the same as the argument type at position {@code pos} of 4956 * the target signature, or if the {@code N} argument types at position {@code pos} 4957 * of the target signature 4958 * (skipping one matching the {@code combiner}'s return type) 4959 * are not identical with the argument types of {@code combiner} 4960 * 4961 * @see #foldArguments(MethodHandle, MethodHandle) 4962 * @since 9 4963 */ 4964 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 4965 MethodType targetType = target.type(); 4966 MethodType combinerType = combiner.type(); 4967 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 4968 BoundMethodHandle result = target.rebind(); 4969 boolean dropResult = rtype == void.class; 4970 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 4971 MethodType newType = targetType; 4972 if (!dropResult) { 4973 newType = newType.dropParameterTypes(pos, pos + 1); 4974 } 4975 result = result.copyWithExtendL(newType, lform, combiner); 4976 return result; 4977 } 4978 4979 /** 4980 * 4981 * @param target 4982 * @param pos 4983 * @param combiner 4984 * @param argPositions 4985 * @return 4986 */ 4987 static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner, int ... argPositions) { 4988 MethodType targetType = target.type(); 4989 MethodType combinerType = combiner.type(); 4990 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType, argPositions); 4991 BoundMethodHandle result = target.rebind(); 4992 boolean dropResult = rtype == void.class; 4993 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType(), argPositions); 4994 MethodType newType = targetType; 4995 if (!dropResult) { 4996 newType = newType.dropParameterTypes(pos, pos + 1); 4997 } 4998 result = result.copyWithExtendL(newType, lform, combiner); 4999 return result; 5000 } 5001 5002 private static void checkLoop0(MethodHandle[][] clauses) { 5003 if (clauses == null || clauses.length == 0) { 5004 throw newIllegalArgumentException("null or no clauses passed"); 5005 } 5006 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 5007 throw newIllegalArgumentException("null clauses are not allowed"); 5008 } 5009 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 5010 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 5011 } 5012 } 5013 5014 private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) { 5015 if (in.type().returnType() != st.type().returnType()) { 5016 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 5017 st.type().returnType()); 5018 } 5019 } 5020 5021 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 5022 final List<Class<?>> empty = List.of(); 5023 final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList()); 5024 if (nonNullInits.isEmpty()) { 5025 final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull). 5026 // take only those that can contribute to a common suffix because they are longer than the prefix 5027 map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList). 5028 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 5029 return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size()); 5030 } else { 5031 return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList). 5032 reduce((p, q) -> p.size() >= q.size() ? p : q).get(); 5033 } 5034 } 5035 5036 private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 5037 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList). 5038 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) { 5039 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 5040 " (common suffix: " + commonSuffix + ")"); 5041 } 5042 } 5043 5044 private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 5045 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 5046 anyMatch(t -> t != loopReturnType)) { 5047 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 5048 loopReturnType + ")"); 5049 } 5050 5051 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 5052 throw newIllegalArgumentException("no predicate found", pred); 5053 } 5054 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 5055 anyMatch(t -> t != boolean.class)) { 5056 throw newIllegalArgumentException("predicates must have boolean return type", pred); 5057 } 5058 } 5059 5060 private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 5061 final int cpSize = commonParameterSequence.size(); 5062 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 5063 map(MethodType::parameterList). 5064 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) { 5065 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 5066 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 5067 } 5068 } 5069 5070 private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) { 5071 if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) { 5072 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 5073 } 5074 if (null == body) { 5075 throw newIllegalArgumentException("iterated loop body must not be null"); 5076 } 5077 } 5078 5079 private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) { 5080 Class<?> rtype = target.type().returnType(); 5081 if (rtype != cleanup.type().returnType()) { 5082 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 5083 } 5084 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); 5085 if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) { 5086 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 5087 } 5088 if (rtype != void.class && cleanupParamTypes.get(1) != rtype) { 5089 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 5090 } 5091 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 5092 // target parameter list. 5093 int cleanupArgIndex = rtype == void.class ? 1 : 2; 5094 List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()); 5095 List<Class<?>> targetParamTypes = target.type().parameterList(); 5096 if (targetParamTypes.size() < cleanupArgSuffix.size() || 5097 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) { 5098 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 5099 cleanup.type(), target.type()); 5100 } 5101 } 5102 5103 }