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