1 /* 2 * Copyright (c) 2008, 2014, 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 java.lang.reflect.*; 29 import java.util.BitSet; 30 import java.util.List; 31 import java.util.Arrays; 32 33 import sun.invoke.util.ValueConversions; 34 import sun.invoke.util.VerifyAccess; 35 import sun.invoke.util.Wrapper; 36 import sun.reflect.CallerSensitive; 37 import sun.reflect.Reflection; 38 import sun.reflect.misc.ReflectUtil; 39 import sun.security.util.SecurityConstants; 40 import java.lang.invoke.LambdaForm.BasicType; 41 import static java.lang.invoke.LambdaForm.BasicType.*; 42 import static java.lang.invoke.MethodHandleStatics.*; 43 import static java.lang.invoke.MethodHandleImpl.Intrinsic; 44 import static java.lang.invoke.MethodHandleNatives.Constants.*; 45 import java.util.concurrent.ConcurrentHashMap; 46 47 /** 48 * This class consists exclusively of static methods that operate on or return 49 * method handles. They fall into several categories: 50 * <ul> 51 * <li>Lookup methods which help create method handles for methods and fields. 52 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 53 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 54 * </ul> 55 * 56 * @author John Rose, JSR 292 EG 57 * @since 1.7 58 */ 59 public class MethodHandles { 60 61 private MethodHandles() { } // do not instantiate 62 63 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 64 static { MethodHandleImpl.initStatics(); } 65 // See IMPL_LOOKUP below. 66 67 //// Method handle creation from ordinary methods. 68 69 /** 70 * Returns a {@link Lookup lookup object} with 71 * full capabilities to emulate all supported bytecode behaviors of the caller. 72 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. 73 * Factory methods on the lookup object can create 74 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 75 * for any member that the caller has access to via bytecodes, 76 * including protected and private fields and methods. 77 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 78 * Do not store it in place where untrusted code can access it. 79 * <p> 80 * This method is caller sensitive, which means that it may return different 81 * values to different callers. 82 * <p> 83 * For any given caller class {@code C}, the lookup object returned by this call 84 * has equivalent capabilities to any lookup object 85 * supplied by the JVM to the bootstrap method of an 86 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> 87 * executing in the same caller class {@code C}. 88 * @return a lookup object for the caller of this method, with private access 89 */ 90 @CallerSensitive 91 public static Lookup lookup() { 92 return new Lookup(Reflection.getCallerClass()); 93 } 94 95 /** 96 * Returns a {@link Lookup lookup object} which is trusted minimally. 97 * It can only be used to create method handles to 98 * publicly accessible fields and methods. 99 * <p> 100 * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class} 101 * of this lookup object will be {@link java.lang.Object}. 102 * 103 * <p style="font-size:smaller;"> 104 * <em>Discussion:</em> 105 * The lookup class can be changed to any other class {@code C} using an expression of the form 106 * {@link Lookup#in publicLookup().in(C.class)}. 107 * Since all classes have equal access to public names, 108 * such a change would confer no new access rights. 109 * A public lookup object is always subject to 110 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 111 * Also, it cannot access 112 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 113 * @return a lookup object which is trusted minimally 114 */ 115 public static Lookup publicLookup() { 116 return Lookup.PUBLIC_LOOKUP; 117 } 118 119 /** 120 * Performs an unchecked "crack" of a 121 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 122 * The result is as if the user had obtained a lookup object capable enough 123 * to crack the target method handle, called 124 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 125 * on the target to obtain its symbolic reference, and then called 126 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 127 * to resolve the symbolic reference to a member. 128 * <p> 129 * If there is a security manager, its {@code checkPermission} method 130 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 131 * @param <T> the desired type of the result, either {@link Member} or a subtype 132 * @param target a direct method handle to crack into symbolic reference components 133 * @param expected a class object representing the desired result type {@code T} 134 * @return a reference to the method, constructor, or field object 135 * @exception SecurityException if the caller is not privileged to call {@code setAccessible} 136 * @exception NullPointerException if either argument is {@code null} 137 * @exception IllegalArgumentException if the target is not a direct method handle 138 * @exception ClassCastException if the member is not of the expected type 139 * @since 1.8 140 */ 141 public static <T extends Member> T 142 reflectAs(Class<T> expected, MethodHandle target) { 143 SecurityManager smgr = System.getSecurityManager(); 144 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION); 145 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup 146 return lookup.revealDirect(target).reflectAs(expected, lookup); 147 } 148 // Copied from AccessibleObject, as used by Method.setAccessible, etc.: 149 static final private java.security.Permission ACCESS_PERMISSION = 150 new ReflectPermission("suppressAccessChecks"); 151 152 /** 153 * A <em>lookup object</em> is a factory for creating method handles, 154 * when the creation requires access checking. 155 * Method handles do not perform 156 * access checks when they are called, but rather when they are created. 157 * Therefore, method handle access 158 * restrictions must be enforced when a method handle is created. 159 * The caller class against which those restrictions are enforced 160 * is known as the {@linkplain #lookupClass lookup class}. 161 * <p> 162 * A lookup class which needs to create method handles will call 163 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. 164 * When the {@code Lookup} factory object is created, the identity of the lookup class is 165 * determined, and securely stored in the {@code Lookup} object. 166 * The lookup class (or its delegates) may then use factory methods 167 * on the {@code Lookup} object to create method handles for access-checked members. 168 * This includes all methods, constructors, and fields which are allowed to the lookup class, 169 * even private ones. 170 * 171 * <h1><a name="lookups"></a>Lookup Factory Methods</h1> 172 * The factory methods on a {@code Lookup} object correspond to all major 173 * use cases for methods, constructors, and fields. 174 * Each method handle created by a factory method is the functional 175 * equivalent of a particular <em>bytecode behavior</em>. 176 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) 177 * Here is a summary of the correspondence between these factory methods and 178 * the behavior the resulting method handles: 179 * <table border=1 cellpadding=5 summary="lookup method behaviors"> 180 * <tr> 181 * <th><a name="equiv"></a>lookup expression</th> 182 * <th>member</th> 183 * <th>bytecode behavior</th> 184 * </tr> 185 * <tr> 186 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> 187 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 188 * </tr> 189 * <tr> 190 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> 191 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> 192 * </tr> 193 * <tr> 194 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> 195 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 196 * </tr> 197 * <tr> 198 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> 199 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 200 * </tr> 201 * <tr> 202 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> 203 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 204 * </tr> 205 * <tr> 206 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> 207 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 208 * </tr> 209 * <tr> 210 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> 211 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 212 * </tr> 213 * <tr> 214 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> 215 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 216 * </tr> 217 * <tr> 218 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> 219 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 220 * </tr> 221 * <tr> 222 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> 223 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 224 * </tr> 225 * <tr> 226 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 227 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 228 * </tr> 229 * <tr> 230 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> 231 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 232 * </tr> 233 * <tr> 234 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 235 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 236 * </tr> 237 * </table> 238 * 239 * Here, the type {@code C} is the class or interface being searched for a member, 240 * documented as a parameter named {@code refc} in the lookup methods. 241 * The method type {@code MT} is composed from the return type {@code T} 242 * and the sequence of argument types {@code A*}. 243 * The constructor also has a sequence of argument types {@code A*} and 244 * is deemed to return the newly-created object of type {@code C}. 245 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 246 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 247 * if it is present, it is always the leading argument to the method handle invocation. 248 * (In the case of some {@code protected} members, {@code this} may be 249 * restricted in type to the lookup class; see below.) 250 * The name {@code arg} stands for all the other method handle arguments. 251 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 252 * stands for a null reference if the accessed method or field is static, 253 * and {@code this} otherwise. 254 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 255 * for reflective objects corresponding to the given members. 256 * <p> 257 * In cases where the given member is of variable arity (i.e., a method or constructor) 258 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 259 * In all other cases, the returned method handle will be of fixed arity. 260 * <p style="font-size:smaller;"> 261 * <em>Discussion:</em> 262 * The equivalence between looked-up method handles and underlying 263 * class members and bytecode behaviors 264 * can break down in a few ways: 265 * <ul style="font-size:smaller;"> 266 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 267 * the lookup can still succeed, even when there is no equivalent 268 * Java expression or bytecoded constant. 269 * <li>Likewise, if {@code T} or {@code MT} 270 * is not symbolically accessible from the lookup class's loader, 271 * the lookup can still succeed. 272 * For example, lookups for {@code MethodHandle.invokeExact} and 273 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 274 * <li>If there is a security manager installed, it can forbid the lookup 275 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 276 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 277 * constant is not subject to security manager checks. 278 * <li>If the looked-up method has a 279 * <a href="MethodHandle.html#maxarity">very large arity</a>, 280 * the method handle creation may fail, due to the method handle 281 * type having too many parameters. 282 * </ul> 283 * 284 * <h1><a name="access"></a>Access checking</h1> 285 * Access checks are applied in the factory methods of {@code Lookup}, 286 * when a method handle is created. 287 * This is a key difference from the Core Reflection API, since 288 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 289 * performs access checking against every caller, on every call. 290 * <p> 291 * All access checks start from a {@code Lookup} object, which 292 * compares its recorded lookup class against all requests to 293 * create method handles. 294 * A single {@code Lookup} object can be used to create any number 295 * of access-checked method handles, all checked against a single 296 * lookup class. 297 * <p> 298 * A {@code Lookup} object can be shared with other trusted code, 299 * such as a metaobject protocol. 300 * A shared {@code Lookup} object delegates the capability 301 * to create method handles on private members of the lookup class. 302 * Even if privileged code uses the {@code Lookup} object, 303 * the access checking is confined to the privileges of the 304 * original lookup class. 305 * <p> 306 * A lookup can fail, because 307 * the containing class is not accessible to the lookup class, or 308 * because the desired class member is missing, or because the 309 * desired class member is not accessible to the lookup class, or 310 * because the lookup object is not trusted enough to access the member. 311 * In any of these cases, a {@code ReflectiveOperationException} will be 312 * thrown from the attempted lookup. The exact class will be one of 313 * the following: 314 * <ul> 315 * <li>NoSuchMethodException — if a method is requested but does not exist 316 * <li>NoSuchFieldException — if a field is requested but does not exist 317 * <li>IllegalAccessException — if the member exists but an access check fails 318 * </ul> 319 * <p> 320 * In general, the conditions under which a method handle may be 321 * looked up for a method {@code M} are no more restrictive than the conditions 322 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 323 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 324 * a method handle lookup will generally raise a corresponding 325 * checked exception, such as {@code NoSuchMethodException}. 326 * And the effect of invoking the method handle resulting from the lookup 327 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 328 * to executing the compiled, verified, and resolved call to {@code M}. 329 * The same point is true of fields and constructors. 330 * <p style="font-size:smaller;"> 331 * <em>Discussion:</em> 332 * Access checks only apply to named and reflected methods, 333 * constructors, and fields. 334 * Other method handle creation methods, such as 335 * {@link MethodHandle#asType MethodHandle.asType}, 336 * do not require any access checks, and are used 337 * independently of any {@code Lookup} object. 338 * <p> 339 * If the desired member is {@code protected}, the usual JVM rules apply, 340 * including the requirement that the lookup class must be either be in the 341 * same package as the desired member, or must inherit that member. 342 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) 343 * In addition, if the desired member is a non-static field or method 344 * in a different package, the resulting method handle may only be applied 345 * to objects of the lookup class or one of its subclasses. 346 * This requirement is enforced by narrowing the type of the leading 347 * {@code this} parameter from {@code C} 348 * (which will necessarily be a superclass of the lookup class) 349 * to the lookup class itself. 350 * <p> 351 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 352 * that the receiver argument must match both the resolved method <em>and</em> 353 * the current class. Again, this requirement is enforced by narrowing the 354 * type of the leading parameter to the resulting method handle. 355 * (See the Java Virtual Machine Specification, section 4.10.1.9.) 356 * <p> 357 * The JVM represents constructors and static initializer blocks as internal methods 358 * with special names ({@code "<init>"} and {@code "<clinit>"}). 359 * The internal syntax of invocation instructions allows them to refer to such internal 360 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 361 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 362 * <p> 363 * In some cases, access between nested classes is obtained by the Java compiler by creating 364 * an wrapper method to access a private method of another class 365 * in the same top-level declaration. 366 * For example, a nested class {@code C.D} 367 * can access private members within other related classes such as 368 * {@code C}, {@code C.D.E}, or {@code C.B}, 369 * but the Java compiler may need to generate wrapper methods in 370 * those related classes. In such cases, a {@code Lookup} object on 371 * {@code C.E} would be unable to those private members. 372 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 373 * which can transform a lookup on {@code C.E} into one on any of those other 374 * classes, without special elevation of privilege. 375 * <p> 376 * The accesses permitted to a given lookup object may be limited, 377 * according to its set of {@link #lookupModes lookupModes}, 378 * to a subset of members normally accessible to the lookup class. 379 * For example, the {@link MethodHandles#publicLookup publicLookup} 380 * method produces a lookup object which is only allowed to access 381 * public members in public classes. 382 * The caller sensitive method {@link MethodHandles#lookup lookup} 383 * produces a lookup object with full capabilities relative to 384 * its caller class, to emulate all supported bytecode behaviors. 385 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 386 * with fewer access modes than the original lookup object. 387 * 388 * <p style="font-size:smaller;"> 389 * <a name="privacc"></a> 390 * <em>Discussion of private access:</em> 391 * We say that a lookup has <em>private access</em> 392 * if its {@linkplain #lookupModes lookup modes} 393 * include the possibility of accessing {@code private} members. 394 * As documented in the relevant methods elsewhere, 395 * only lookups with private access possess the following capabilities: 396 * <ul style="font-size:smaller;"> 397 * <li>access private fields, methods, and constructors of the lookup class 398 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 399 * such as {@code Class.forName} 400 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 401 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 402 * for classes accessible to the lookup class 403 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 404 * within the same package member 405 * </ul> 406 * <p style="font-size:smaller;"> 407 * Each of these permissions is a consequence of the fact that a lookup object 408 * with private access can be securely traced back to an originating class, 409 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 410 * can be reliably determined and emulated by method handles. 411 * 412 * <h1><a name="secmgr"></a>Security manager interactions</h1> 413 * Although bytecode instructions can only refer to classes in 414 * a related class loader, this API can search for methods in any 415 * class, as long as a reference to its {@code Class} object is 416 * available. Such cross-loader references are also possible with the 417 * Core Reflection API, and are impossible to bytecode instructions 418 * such as {@code invokestatic} or {@code getfield}. 419 * There is a {@linkplain java.lang.SecurityManager security manager API} 420 * to allow applications to check such cross-loader references. 421 * These checks apply to both the {@code MethodHandles.Lookup} API 422 * and the Core Reflection API 423 * (as found on {@link java.lang.Class Class}). 424 * <p> 425 * If a security manager is present, member lookups are subject to 426 * additional checks. 427 * From one to three calls are made to the security manager. 428 * Any of these calls can refuse access by throwing a 429 * {@link java.lang.SecurityException SecurityException}. 430 * Define {@code smgr} as the security manager, 431 * {@code lookc} as the lookup class of the current lookup object, 432 * {@code refc} as the containing class in which the member 433 * is being sought, and {@code defc} as the class in which the 434 * member is actually defined. 435 * The value {@code lookc} is defined as <em>not present</em> 436 * if the current lookup object does not have 437 * <a href="MethodHandles.Lookup.html#privacc">private access</a>. 438 * The calls are made according to the following rules: 439 * <ul> 440 * <li><b>Step 1:</b> 441 * If {@code lookc} is not present, or if its class loader is not 442 * the same as or an ancestor of the class loader of {@code refc}, 443 * then {@link SecurityManager#checkPackageAccess 444 * smgr.checkPackageAccess(refcPkg)} is called, 445 * where {@code refcPkg} is the package of {@code refc}. 446 * <li><b>Step 2:</b> 447 * If the retrieved member is not public and 448 * {@code lookc} is not present, then 449 * {@link SecurityManager#checkPermission smgr.checkPermission} 450 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 451 * <li><b>Step 3:</b> 452 * If the retrieved member is not public, 453 * and if {@code lookc} is not present, 454 * and if {@code defc} and {@code refc} are different, 455 * then {@link SecurityManager#checkPackageAccess 456 * smgr.checkPackageAccess(defcPkg)} is called, 457 * where {@code defcPkg} is the package of {@code defc}. 458 * </ul> 459 * Security checks are performed after other access checks have passed. 460 * Therefore, the above rules presuppose a member that is public, 461 * or else that is being accessed from a lookup class that has 462 * rights to access the member. 463 * 464 * <h1><a name="callsens"></a>Caller sensitive methods</h1> 465 * A small number of Java methods have a special property called caller sensitivity. 466 * A <em>caller-sensitive</em> method can behave differently depending on the 467 * identity of its immediate caller. 468 * <p> 469 * If a method handle for a caller-sensitive method is requested, 470 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 471 * but they take account of the lookup class in a special way. 472 * The resulting method handle behaves as if it were called 473 * from an instruction contained in the lookup class, 474 * so that the caller-sensitive method detects the lookup class. 475 * (By contrast, the invoker of the method handle is disregarded.) 476 * Thus, in the case of caller-sensitive methods, 477 * different lookup classes may give rise to 478 * differently behaving method handles. 479 * <p> 480 * In cases where the lookup object is 481 * {@link MethodHandles#publicLookup() publicLookup()}, 482 * or some other lookup object without 483 * <a href="MethodHandles.Lookup.html#privacc">private access</a>, 484 * the lookup class is disregarded. 485 * In such cases, no caller-sensitive method handle can be created, 486 * access is forbidden, and the lookup fails with an 487 * {@code IllegalAccessException}. 488 * <p style="font-size:smaller;"> 489 * <em>Discussion:</em> 490 * For example, the caller-sensitive method 491 * {@link java.lang.Class#forName(String) Class.forName(x)} 492 * can return varying classes or throw varying exceptions, 493 * depending on the class loader of the class that calls it. 494 * A public lookup of {@code Class.forName} will fail, because 495 * there is no reasonable way to determine its bytecode behavior. 496 * <p style="font-size:smaller;"> 497 * If an application caches method handles for broad sharing, 498 * it should use {@code publicLookup()} to create them. 499 * If there is a lookup of {@code Class.forName}, it will fail, 500 * and the application must take appropriate action in that case. 501 * It may be that a later lookup, perhaps during the invocation of a 502 * bootstrap method, can incorporate the specific identity 503 * of the caller, making the method accessible. 504 * <p style="font-size:smaller;"> 505 * The function {@code MethodHandles.lookup} is caller sensitive 506 * so that there can be a secure foundation for lookups. 507 * Nearly all other methods in the JSR 292 API rely on lookup 508 * objects to check access requests. 509 */ 510 public static final 511 class Lookup { 512 /** The class on behalf of whom the lookup is being performed. */ 513 private final Class<?> lookupClass; 514 515 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 516 private final int allowedModes; 517 518 /** A single-bit mask representing {@code public} access, 519 * which may contribute to the result of {@link #lookupModes lookupModes}. 520 * The value, {@code 0x01}, happens to be the same as the value of the 521 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 522 */ 523 public static final int PUBLIC = Modifier.PUBLIC; 524 525 /** A single-bit mask representing {@code private} access, 526 * which may contribute to the result of {@link #lookupModes lookupModes}. 527 * The value, {@code 0x02}, happens to be the same as the value of the 528 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 529 */ 530 public static final int PRIVATE = Modifier.PRIVATE; 531 532 /** A single-bit mask representing {@code protected} access, 533 * which may contribute to the result of {@link #lookupModes lookupModes}. 534 * The value, {@code 0x04}, happens to be the same as the value of the 535 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 536 */ 537 public static final int PROTECTED = Modifier.PROTECTED; 538 539 /** A single-bit mask representing {@code package} access (default access), 540 * which may contribute to the result of {@link #lookupModes lookupModes}. 541 * The value is {@code 0x08}, which does not correspond meaningfully to 542 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 543 */ 544 public static final int PACKAGE = Modifier.STATIC; 545 546 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE); 547 private static final int TRUSTED = -1; 548 549 private static int fixmods(int mods) { 550 mods &= (ALL_MODES - PACKAGE); 551 return (mods != 0) ? mods : PACKAGE; 552 } 553 554 /** Tells which class is performing the lookup. It is this class against 555 * which checks are performed for visibility and access permissions. 556 * <p> 557 * The class implies a maximum level of access permission, 558 * but the permissions may be additionally limited by the bitmask 559 * {@link #lookupModes lookupModes}, which controls whether non-public members 560 * can be accessed. 561 * @return the lookup class, on behalf of which this lookup object finds members 562 */ 563 public Class<?> lookupClass() { 564 return lookupClass; 565 } 566 567 // This is just for calling out to MethodHandleImpl. 568 private Class<?> lookupClassOrNull() { 569 return (allowedModes == TRUSTED) ? null : lookupClass; 570 } 571 572 /** Tells which access-protection classes of members this lookup object can produce. 573 * The result is a bit-mask of the bits 574 * {@linkplain #PUBLIC PUBLIC (0x01)}, 575 * {@linkplain #PRIVATE PRIVATE (0x02)}, 576 * {@linkplain #PROTECTED PROTECTED (0x04)}, 577 * and {@linkplain #PACKAGE PACKAGE (0x08)}. 578 * <p> 579 * A freshly-created lookup object 580 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} 581 * has all possible bits set, since the caller class can access all its own members. 582 * A lookup object on a new lookup class 583 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 584 * may have some mode bits set to zero. 585 * The purpose of this is to restrict access via the new lookup object, 586 * so that it can access only names which can be reached by the original 587 * lookup object, and also by the new lookup class. 588 * @return the lookup modes, which limit the kinds of access performed by this lookup object 589 */ 590 public int lookupModes() { 591 return allowedModes & ALL_MODES; 592 } 593 594 /** Embody the current class (the lookupClass) as a lookup class 595 * for method handle creation. 596 * Must be called by from a method in this package, 597 * which in turn is called by a method not in this package. 598 */ 599 Lookup(Class<?> lookupClass) { 600 this(lookupClass, ALL_MODES); 601 // make sure we haven't accidentally picked up a privileged class: 602 checkUnprivilegedlookupClass(lookupClass, ALL_MODES); 603 } 604 605 private Lookup(Class<?> lookupClass, int allowedModes) { 606 this.lookupClass = lookupClass; 607 this.allowedModes = allowedModes; 608 } 609 610 /** 611 * Creates a lookup on the specified new lookup class. 612 * The resulting object will report the specified 613 * class as its own {@link #lookupClass lookupClass}. 614 * <p> 615 * However, the resulting {@code Lookup} object is guaranteed 616 * to have no more access capabilities than the original. 617 * In particular, access capabilities can be lost as follows:<ul> 618 * <li>If the new lookup class differs from the old one, 619 * protected members will not be accessible by virtue of inheritance. 620 * (Protected members may continue to be accessible because of package sharing.) 621 * <li>If the new lookup class is in a different package 622 * than the old one, protected and default (package) members will not be accessible. 623 * <li>If the new lookup class is not within the same package member 624 * as the old one, private members will not be accessible. 625 * <li>If the new lookup class is not accessible to the old lookup class, 626 * then no members, not even public members, will be accessible. 627 * (In all other cases, public members will continue to be accessible.) 628 * </ul> 629 * 630 * @param requestedLookupClass the desired lookup class for the new lookup object 631 * @return a lookup object which reports the desired lookup class 632 * @throws NullPointerException if the argument is null 633 */ 634 public Lookup in(Class<?> requestedLookupClass) { 635 requestedLookupClass.getClass(); // null check 636 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 637 return new Lookup(requestedLookupClass, ALL_MODES); 638 if (requestedLookupClass == this.lookupClass) 639 return this; // keep same capabilities 640 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); 641 if ((newModes & PACKAGE) != 0 642 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 643 newModes &= ~(PACKAGE|PRIVATE); 644 } 645 // Allow nestmate lookups to be created without special privilege: 646 if ((newModes & PRIVATE) != 0 647 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 648 newModes &= ~PRIVATE; 649 } 650 if ((newModes & PUBLIC) != 0 651 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { 652 // The requested class it not accessible from the lookup class. 653 // No permissions. 654 newModes = 0; 655 } 656 checkUnprivilegedlookupClass(requestedLookupClass, newModes); 657 return new Lookup(requestedLookupClass, newModes); 658 } 659 660 // Make sure outer class is initialized first. 661 static { IMPL_NAMES.getClass(); } 662 663 /** Version of lookup which is trusted minimally. 664 * It can only be used to create method handles to 665 * publicly accessible members. 666 */ 667 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC); 668 669 /** Package-private version of lookup which is trusted. */ 670 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); 671 672 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { 673 String name = lookupClass.getName(); 674 if (name.startsWith("java.lang.invoke.")) 675 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 676 677 // For caller-sensitive MethodHandles.lookup() 678 // disallow lookup more restricted packages 679 if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) { 680 if (name.startsWith("java.") || 681 (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) { 682 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); 683 } 684 } 685 } 686 687 /** 688 * Displays the name of the class from which lookups are to be made. 689 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 690 * If there are restrictions on the access permitted to this lookup, 691 * this is indicated by adding a suffix to the class name, consisting 692 * of a slash and a keyword. The keyword represents the strongest 693 * allowed access, and is chosen as follows: 694 * <ul> 695 * <li>If no access is allowed, the suffix is "/noaccess". 696 * <li>If only public access is allowed, the suffix is "/public". 697 * <li>If only public and package access are allowed, the suffix is "/package". 698 * <li>If only public, package, and private access are allowed, the suffix is "/private". 699 * </ul> 700 * If none of the above cases apply, it is the case that full 701 * access (public, package, private, and protected) is allowed. 702 * In this case, no suffix is added. 703 * This is true only of an object obtained originally from 704 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 705 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 706 * always have restricted access, and will display a suffix. 707 * <p> 708 * (It may seem strange that protected access should be 709 * stronger than private access. Viewed independently from 710 * package access, protected access is the first to be lost, 711 * because it requires a direct subclass relationship between 712 * caller and callee.) 713 * @see #in 714 */ 715 @Override 716 public String toString() { 717 String cname = lookupClass.getName(); 718 switch (allowedModes) { 719 case 0: // no privileges 720 return cname + "/noaccess"; 721 case PUBLIC: 722 return cname + "/public"; 723 case PUBLIC|PACKAGE: 724 return cname + "/package"; 725 case ALL_MODES & ~PROTECTED: 726 return cname + "/private"; 727 case ALL_MODES: 728 return cname; 729 case TRUSTED: 730 return "/trusted"; // internal only; not exported 731 default: // Should not happen, but it's a bitfield... 732 cname = cname + "/" + Integer.toHexString(allowedModes); 733 assert(false) : cname; 734 return cname; 735 } 736 } 737 738 /** 739 * Produces a method handle for a static method. 740 * The type of the method handle will be that of the method. 741 * (Since static methods do not take receivers, there is no 742 * additional receiver argument inserted into the method handle type, 743 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 744 * The method and all its argument types must be accessible to the lookup object. 745 * <p> 746 * The returned method handle will have 747 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 748 * the method's variable arity modifier bit ({@code 0x0080}) is set. 749 * <p> 750 * If the returned method handle is invoked, the method's class will 751 * be initialized, if it has not already been initialized. 752 * <p><b>Example:</b> 753 * <blockquote><pre>{@code 754 import static java.lang.invoke.MethodHandles.*; 755 import static java.lang.invoke.MethodType.*; 756 ... 757 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 758 "asList", methodType(List.class, Object[].class)); 759 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 760 * }</pre></blockquote> 761 * @param refc the class from which the method is accessed 762 * @param name the name of the method 763 * @param type the type of the method 764 * @return the desired method handle 765 * @throws NoSuchMethodException if the method does not exist 766 * @throws IllegalAccessException if access checking fails, 767 * or if the method is not {@code static}, 768 * or if the method's variable arity modifier bit 769 * is set and {@code asVarargsCollector} fails 770 * @exception SecurityException if a security manager is present and it 771 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 772 * @throws NullPointerException if any argument is null 773 */ 774 public 775 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 776 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); 777 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method)); 778 } 779 780 /** 781 * Produces a method handle for a virtual method. 782 * The type of the method handle will be that of the method, 783 * with the receiver type (usually {@code refc}) prepended. 784 * The method and all its argument types must be accessible to the lookup object. 785 * <p> 786 * When called, the handle will treat the first argument as a receiver 787 * and dispatch on the receiver's type to determine which method 788 * implementation to enter. 789 * (The dispatching action is identical with that performed by an 790 * {@code invokevirtual} or {@code invokeinterface} instruction.) 791 * <p> 792 * The first argument will be of type {@code refc} if the lookup 793 * class has full privileges to access the member. Otherwise 794 * the member must be {@code protected} and the first argument 795 * will be restricted in type to the lookup class. 796 * <p> 797 * The returned method handle will have 798 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 799 * the method's variable arity modifier bit ({@code 0x0080}) is set. 800 * <p> 801 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 802 * instructions and method handles produced by {@code findVirtual}, 803 * if the class is {@code MethodHandle} and the name string is 804 * {@code invokeExact} or {@code invoke}, the resulting 805 * method handle is equivalent to one produced by 806 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 807 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 808 * with the same {@code type} argument. 809 * 810 * <b>Example:</b> 811 * <blockquote><pre>{@code 812 import static java.lang.invoke.MethodHandles.*; 813 import static java.lang.invoke.MethodType.*; 814 ... 815 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 816 "concat", methodType(String.class, String.class)); 817 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 818 "hashCode", methodType(int.class)); 819 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 820 "hashCode", methodType(int.class)); 821 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 822 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 823 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 824 // interface method: 825 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 826 "subSequence", methodType(CharSequence.class, int.class, int.class)); 827 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 828 // constructor "internal method" must be accessed differently: 829 MethodType MT_newString = methodType(void.class); //()V for new String() 830 try { assertEquals("impossible", lookup() 831 .findVirtual(String.class, "<init>", MT_newString)); 832 } catch (NoSuchMethodException ex) { } // OK 833 MethodHandle MH_newString = publicLookup() 834 .findConstructor(String.class, MT_newString); 835 assertEquals("", (String) MH_newString.invokeExact()); 836 * }</pre></blockquote> 837 * 838 * @param refc the class or interface from which the method is accessed 839 * @param name the name of the method 840 * @param type the type of the method, with the receiver argument omitted 841 * @return the desired method handle 842 * @throws NoSuchMethodException if the method does not exist 843 * @throws IllegalAccessException if access checking fails, 844 * or if the method is {@code static} 845 * or if the method's variable arity modifier bit 846 * is set and {@code asVarargsCollector} fails 847 * @exception SecurityException if a security manager is present and it 848 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 849 * @throws NullPointerException if any argument is null 850 */ 851 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 852 if (refc == MethodHandle.class) { 853 MethodHandle mh = findVirtualForMH(name, type); 854 if (mh != null) return mh; 855 } 856 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); 857 MemberName method = resolveOrFail(refKind, refc, name, type); 858 return getDirectMethod(refKind, refc, method, findBoundCallerClass(method)); 859 } 860 private MethodHandle findVirtualForMH(String name, MethodType type) { 861 // these names require special lookups because of the implicit MethodType argument 862 if ("invoke".equals(name)) 863 return invoker(type); 864 if ("invokeExact".equals(name)) 865 return exactInvoker(type); 866 if ("invokeBasic".equals(name)) 867 return basicInvoker(type); 868 assert(!MemberName.isMethodHandleInvokeName(name)); 869 return null; 870 } 871 872 /** 873 * Produces a method handle which creates an object and initializes it, using 874 * the constructor of the specified type. 875 * The parameter types of the method handle will be those of the constructor, 876 * while the return type will be a reference to the constructor's class. 877 * The constructor and all its argument types must be accessible to the lookup object. 878 * <p> 879 * The requested type must have a return type of {@code void}. 880 * (This is consistent with the JVM's treatment of constructor type descriptors.) 881 * <p> 882 * The returned method handle will have 883 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 884 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 885 * <p> 886 * If the returned method handle is invoked, the constructor's class will 887 * be initialized, if it has not already been initialized. 888 * <p><b>Example:</b> 889 * <blockquote><pre>{@code 890 import static java.lang.invoke.MethodHandles.*; 891 import static java.lang.invoke.MethodType.*; 892 ... 893 MethodHandle MH_newArrayList = publicLookup().findConstructor( 894 ArrayList.class, methodType(void.class, Collection.class)); 895 Collection orig = Arrays.asList("x", "y"); 896 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 897 assert(orig != copy); 898 assertEquals(orig, copy); 899 // a variable-arity constructor: 900 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 901 ProcessBuilder.class, methodType(void.class, String[].class)); 902 ProcessBuilder pb = (ProcessBuilder) 903 MH_newProcessBuilder.invoke("x", "y", "z"); 904 assertEquals("[x, y, z]", pb.command().toString()); 905 * }</pre></blockquote> 906 * @param refc the class or interface from which the method is accessed 907 * @param type the type of the method, with the receiver argument omitted, and a void return type 908 * @return the desired method handle 909 * @throws NoSuchMethodException if the constructor does not exist 910 * @throws IllegalAccessException if access checking fails 911 * or if the method's variable arity modifier bit 912 * is set and {@code asVarargsCollector} fails 913 * @exception SecurityException if a security manager is present and it 914 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 915 * @throws NullPointerException if any argument is null 916 */ 917 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 918 String name = "<init>"; 919 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); 920 return getDirectConstructor(refc, ctor); 921 } 922 923 /** 924 * Produces an early-bound method handle for a virtual method. 925 * It will bypass checks for overriding methods on the receiver, 926 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 927 * instruction from within the explicitly specified {@code specialCaller}. 928 * The type of the method handle will be that of the method, 929 * with a suitably restricted receiver type prepended. 930 * (The receiver type will be {@code specialCaller} or a subtype.) 931 * The method and all its argument types must be accessible 932 * to the lookup object. 933 * <p> 934 * Before method resolution, 935 * if the explicitly specified caller class is not identical with the 936 * lookup class, or if this lookup object does not have 937 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 938 * privileges, the access fails. 939 * <p> 940 * The returned method handle will have 941 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 942 * the method's variable arity modifier bit ({@code 0x0080}) is set. 943 * <p style="font-size:smaller;"> 944 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 945 * even though the {@code invokespecial} instruction can refer to them 946 * in special circumstances. Use {@link #findConstructor findConstructor} 947 * to access instance initialization methods in a safe manner.)</em> 948 * <p><b>Example:</b> 949 * <blockquote><pre>{@code 950 import static java.lang.invoke.MethodHandles.*; 951 import static java.lang.invoke.MethodType.*; 952 ... 953 static class Listie extends ArrayList { 954 public String toString() { return "[wee Listie]"; } 955 static Lookup lookup() { return MethodHandles.lookup(); } 956 } 957 ... 958 // no access to constructor via invokeSpecial: 959 MethodHandle MH_newListie = Listie.lookup() 960 .findConstructor(Listie.class, methodType(void.class)); 961 Listie l = (Listie) MH_newListie.invokeExact(); 962 try { assertEquals("impossible", Listie.lookup().findSpecial( 963 Listie.class, "<init>", methodType(void.class), Listie.class)); 964 } catch (NoSuchMethodException ex) { } // OK 965 // access to super and self methods via invokeSpecial: 966 MethodHandle MH_super = Listie.lookup().findSpecial( 967 ArrayList.class, "toString" , methodType(String.class), Listie.class); 968 MethodHandle MH_this = Listie.lookup().findSpecial( 969 Listie.class, "toString" , methodType(String.class), Listie.class); 970 MethodHandle MH_duper = Listie.lookup().findSpecial( 971 Object.class, "toString" , methodType(String.class), Listie.class); 972 assertEquals("[]", (String) MH_super.invokeExact(l)); 973 assertEquals(""+l, (String) MH_this.invokeExact(l)); 974 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 975 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 976 String.class, "toString", methodType(String.class), Listie.class)); 977 } catch (IllegalAccessException ex) { } // OK 978 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 979 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 980 * }</pre></blockquote> 981 * 982 * @param refc the class or interface from which the method is accessed 983 * @param name the name of the method (which must not be "<init>") 984 * @param type the type of the method, with the receiver argument omitted 985 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 986 * @return the desired method handle 987 * @throws NoSuchMethodException if the method does not exist 988 * @throws IllegalAccessException if access checking fails 989 * or if the method's variable arity modifier bit 990 * is set and {@code asVarargsCollector} fails 991 * @exception SecurityException if a security manager is present and it 992 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 993 * @throws NullPointerException if any argument is null 994 */ 995 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 996 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 997 checkSpecialCaller(specialCaller); 998 Lookup specialLookup = this.in(specialCaller); 999 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); 1000 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1001 } 1002 1003 /** 1004 * Produces a method handle giving read access to a non-static field. 1005 * The type of the method handle will have a return type of the field's 1006 * value type. 1007 * The method handle's single argument will be the instance containing 1008 * the field. 1009 * Access checking is performed immediately on behalf of the lookup class. 1010 * @param refc the class or interface from which the method is accessed 1011 * @param name the field's name 1012 * @param type the field's type 1013 * @return a method handle which can load values from the field 1014 * @throws NoSuchFieldException if the field does not exist 1015 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1016 * @exception SecurityException if a security manager is present and it 1017 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1018 * @throws NullPointerException if any argument is null 1019 */ 1020 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1021 MemberName field = resolveOrFail(REF_getField, refc, name, type); 1022 return getDirectField(REF_getField, refc, field); 1023 } 1024 1025 /** 1026 * Produces a method handle giving write access to a non-static field. 1027 * The type of the method handle will have a void return type. 1028 * The method handle will take two arguments, the instance containing 1029 * the field, and the value to be stored. 1030 * The second argument will be of the field's value type. 1031 * Access checking is performed immediately on behalf of the lookup class. 1032 * @param refc the class or interface from which the method is accessed 1033 * @param name the field's name 1034 * @param type the field's type 1035 * @return a method handle which can store values into the field 1036 * @throws NoSuchFieldException if the field does not exist 1037 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1038 * @exception SecurityException if a security manager is present and it 1039 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1040 * @throws NullPointerException if any argument is null 1041 */ 1042 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1043 MemberName field = resolveOrFail(REF_putField, refc, name, type); 1044 return getDirectField(REF_putField, refc, field); 1045 } 1046 1047 /** 1048 * Produces a method handle giving read access to a static field. 1049 * The type of the method handle will have a return type of the field's 1050 * value type. 1051 * The method handle will take no arguments. 1052 * Access checking is performed immediately on behalf of the lookup class. 1053 * <p> 1054 * If the returned method handle is invoked, the field's class will 1055 * be initialized, if it has not already been initialized. 1056 * @param refc the class or interface from which the method is accessed 1057 * @param name the field's name 1058 * @param type the field's type 1059 * @return a method handle which can load values from the field 1060 * @throws NoSuchFieldException if the field does not exist 1061 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1062 * @exception SecurityException if a security manager is present and it 1063 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1064 * @throws NullPointerException if any argument is null 1065 */ 1066 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1067 MemberName field = resolveOrFail(REF_getStatic, refc, name, type); 1068 return getDirectField(REF_getStatic, refc, field); 1069 } 1070 1071 /** 1072 * Produces a method handle giving write access to a static field. 1073 * The type of the method handle will have a void return type. 1074 * The method handle will take a single 1075 * argument, of the field's value type, the value to be stored. 1076 * Access checking is performed immediately on behalf of the lookup class. 1077 * <p> 1078 * If the returned method handle is invoked, the field's class will 1079 * be initialized, if it has not already been initialized. 1080 * @param refc the class or interface from which the method is accessed 1081 * @param name the field's name 1082 * @param type the field's type 1083 * @return a method handle which can store values into the field 1084 * @throws NoSuchFieldException if the field does not exist 1085 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1086 * @exception SecurityException if a security manager is present and it 1087 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1088 * @throws NullPointerException if any argument is null 1089 */ 1090 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1091 MemberName field = resolveOrFail(REF_putStatic, refc, name, type); 1092 return getDirectField(REF_putStatic, refc, field); 1093 } 1094 1095 /** 1096 * Produces an early-bound method handle for a non-static method. 1097 * The receiver must have a supertype {@code defc} in which a method 1098 * of the given name and type is accessible to the lookup class. 1099 * The method and all its argument types must be accessible to the lookup object. 1100 * The type of the method handle will be that of the method, 1101 * without any insertion of an additional receiver parameter. 1102 * The given receiver will be bound into the method handle, 1103 * so that every call to the method handle will invoke the 1104 * requested method on the given receiver. 1105 * <p> 1106 * The returned method handle will have 1107 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1108 * the method's variable arity modifier bit ({@code 0x0080}) is set 1109 * <em>and</em> the trailing array argument is not the only argument. 1110 * (If the trailing array argument is the only argument, 1111 * the given receiver value will be bound to it.) 1112 * <p> 1113 * This is equivalent to the following code: 1114 * <blockquote><pre>{@code 1115 import static java.lang.invoke.MethodHandles.*; 1116 import static java.lang.invoke.MethodType.*; 1117 ... 1118 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 1119 MethodHandle mh1 = mh0.bindTo(receiver); 1120 MethodType mt1 = mh1.type(); 1121 if (mh0.isVarargsCollector()) 1122 mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1)); 1123 return mh1; 1124 * }</pre></blockquote> 1125 * where {@code defc} is either {@code receiver.getClass()} or a super 1126 * type of that class, in which the requested method is accessible 1127 * to the lookup class. 1128 * (Note that {@code bindTo} does not preserve variable arity.) 1129 * @param receiver the object from which the method is accessed 1130 * @param name the name of the method 1131 * @param type the type of the method, with the receiver argument omitted 1132 * @return the desired method handle 1133 * @throws NoSuchMethodException if the method does not exist 1134 * @throws IllegalAccessException if access checking fails 1135 * or if the method's variable arity modifier bit 1136 * is set and {@code asVarargsCollector} fails 1137 * @exception SecurityException if a security manager is present and it 1138 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1139 * @throws NullPointerException if any argument is null 1140 * @see MethodHandle#bindTo 1141 * @see #findVirtual 1142 */ 1143 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1144 Class<? extends Object> refc = receiver.getClass(); // may get NPE 1145 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); 1146 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); 1147 return mh.bindArgumentL(0, receiver).setVarargs(method); 1148 } 1149 1150 /** 1151 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1152 * to <i>m</i>, if the lookup class has permission. 1153 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 1154 * If <i>m</i> is virtual, overriding is respected on every call. 1155 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 1156 * The type of the method handle will be that of the method, 1157 * with the receiver type prepended (but only if it is non-static). 1158 * If the method's {@code accessible} flag is not set, 1159 * access checking is performed immediately on behalf of the lookup class. 1160 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 1161 * <p> 1162 * The returned method handle will have 1163 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1164 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1165 * <p> 1166 * If <i>m</i> is static, and 1167 * if the returned method handle is invoked, the method's class will 1168 * be initialized, if it has not already been initialized. 1169 * @param m the reflected method 1170 * @return a method handle which can invoke the reflected method 1171 * @throws IllegalAccessException if access checking fails 1172 * or if the method's variable arity modifier bit 1173 * is set and {@code asVarargsCollector} fails 1174 * @throws NullPointerException if the argument is null 1175 */ 1176 public MethodHandle unreflect(Method m) throws IllegalAccessException { 1177 if (m.getDeclaringClass() == MethodHandle.class) { 1178 MethodHandle mh = unreflectForMH(m); 1179 if (mh != null) return mh; 1180 } 1181 MemberName method = MemberName.make(m); 1182 byte refKind = method.getReferenceKind(); 1183 if (refKind == REF_invokeSpecial) 1184 refKind = REF_invokeVirtual; 1185 assert(method.isMethod()); 1186 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; 1187 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1188 } 1189 private MethodHandle unreflectForMH(Method m) { 1190 // these names require special lookups because they throw UnsupportedOperationException 1191 if (MemberName.isMethodHandleInvokeName(m.getName())) 1192 return MethodHandleImpl.fakeMethodHandleInvoke(MemberName.make(m)); 1193 return null; 1194 } 1195 1196 /** 1197 * Produces a method handle for a reflected method. 1198 * It will bypass checks for overriding methods on the receiver, 1199 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1200 * instruction from within the explicitly specified {@code specialCaller}. 1201 * The type of the method handle will be that of the method, 1202 * with a suitably restricted receiver type prepended. 1203 * (The receiver type will be {@code specialCaller} or a subtype.) 1204 * If the method's {@code accessible} flag is not set, 1205 * access checking is performed immediately on behalf of the lookup class, 1206 * as if {@code invokespecial} instruction were being linked. 1207 * <p> 1208 * Before method resolution, 1209 * if the explicitly specified caller class is not identical with the 1210 * lookup class, or if this lookup object does not have 1211 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1212 * privileges, the access fails. 1213 * <p> 1214 * The returned method handle will have 1215 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1216 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1217 * @param m the reflected method 1218 * @param specialCaller the class nominally calling the method 1219 * @return a method handle which can invoke the reflected method 1220 * @throws IllegalAccessException if access checking fails 1221 * or if the method's variable arity modifier bit 1222 * is set and {@code asVarargsCollector} fails 1223 * @throws NullPointerException if any argument is null 1224 */ 1225 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 1226 checkSpecialCaller(specialCaller); 1227 Lookup specialLookup = this.in(specialCaller); 1228 MemberName method = MemberName.make(m, true); 1229 assert(method.isMethod()); 1230 // ignore m.isAccessible: this is a new kind of access 1231 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); 1232 } 1233 1234 /** 1235 * Produces a method handle for a reflected constructor. 1236 * The type of the method handle will be that of the constructor, 1237 * with the return type changed to the declaring class. 1238 * The method handle will perform a {@code newInstance} operation, 1239 * creating a new instance of the constructor's class on the 1240 * arguments passed to the method handle. 1241 * <p> 1242 * If the constructor's {@code accessible} flag is not set, 1243 * access checking is performed immediately on behalf of the lookup class. 1244 * <p> 1245 * The returned method handle will have 1246 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1247 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1248 * <p> 1249 * If the returned method handle is invoked, the constructor's class will 1250 * be initialized, if it has not already been initialized. 1251 * @param c the reflected constructor 1252 * @return a method handle which can invoke the reflected constructor 1253 * @throws IllegalAccessException if access checking fails 1254 * or if the method's variable arity modifier bit 1255 * is set and {@code asVarargsCollector} fails 1256 * @throws NullPointerException if the argument is null 1257 */ 1258 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 1259 MemberName ctor = MemberName.make(c); 1260 assert(ctor.isConstructor()); 1261 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; 1262 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); 1263 } 1264 1265 /** 1266 * Produces a method handle giving read access to a reflected field. 1267 * The type of the method handle will have a return type of the field's 1268 * value type. 1269 * If the field is static, the method handle will take no arguments. 1270 * Otherwise, its single argument will be the instance containing 1271 * the field. 1272 * If the field's {@code accessible} flag is not set, 1273 * access checking is performed immediately on behalf of the lookup class. 1274 * <p> 1275 * If the field is static, and 1276 * if the returned method handle is invoked, the field's class will 1277 * be initialized, if it has not already been initialized. 1278 * @param f the reflected field 1279 * @return a method handle which can load values from the reflected field 1280 * @throws IllegalAccessException if access checking fails 1281 * @throws NullPointerException if the argument is null 1282 */ 1283 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1284 return unreflectField(f, false); 1285 } 1286 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { 1287 MemberName field = MemberName.make(f, isSetter); 1288 assert(isSetter 1289 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) 1290 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); 1291 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; 1292 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); 1293 } 1294 1295 /** 1296 * Produces a method handle giving write access to a reflected field. 1297 * The type of the method handle will have a void return type. 1298 * If the field is static, the method handle will take a single 1299 * argument, of the field's value type, the value to be stored. 1300 * Otherwise, the two arguments will be the instance containing 1301 * the field, and the value to be stored. 1302 * If the field's {@code accessible} flag is not set, 1303 * access checking is performed immediately on behalf of the lookup class. 1304 * <p> 1305 * If the field is static, and 1306 * if the returned method handle is invoked, the field's class will 1307 * be initialized, if it has not already been initialized. 1308 * @param f the reflected field 1309 * @return a method handle which can store values into the reflected field 1310 * @throws IllegalAccessException if access checking fails 1311 * @throws NullPointerException if the argument is null 1312 */ 1313 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1314 return unreflectField(f, true); 1315 } 1316 1317 /** 1318 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1319 * created by this lookup object or a similar one. 1320 * Security and access checks are performed to ensure that this lookup object 1321 * is capable of reproducing the target method handle. 1322 * This means that the cracking may fail if target is a direct method handle 1323 * but was created by an unrelated lookup object. 1324 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 1325 * and was created by a lookup object for a different class. 1326 * @param target a direct method handle to crack into symbolic reference components 1327 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 1328 * @exception SecurityException if a security manager is present and it 1329 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1330 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 1331 * @exception NullPointerException if the target is {@code null} 1332 * @see MethodHandleInfo 1333 * @since 1.8 1334 */ 1335 public MethodHandleInfo revealDirect(MethodHandle target) { 1336 MemberName member = target.internalMemberName(); 1337 if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke())) 1338 throw newIllegalArgumentException("not a direct method handle"); 1339 Class<?> defc = member.getDeclaringClass(); 1340 byte refKind = member.getReferenceKind(); 1341 assert(MethodHandleNatives.refKindIsValid(refKind)); 1342 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) 1343 // Devirtualized method invocation is usually formally virtual. 1344 // To avoid creating extra MemberName objects for this common case, 1345 // we encode this extra degree of freedom using MH.isInvokeSpecial. 1346 refKind = REF_invokeVirtual; 1347 if (refKind == REF_invokeVirtual && defc.isInterface()) 1348 // Symbolic reference is through interface but resolves to Object method (toString, etc.) 1349 refKind = REF_invokeInterface; 1350 // Check SM permissions and member access before cracking. 1351 try { 1352 checkAccess(refKind, defc, member); 1353 checkSecurityManager(defc, member); 1354 } catch (IllegalAccessException ex) { 1355 throw new IllegalArgumentException(ex); 1356 } 1357 if (allowedModes != TRUSTED && member.isCallerSensitive()) { 1358 Class<?> callerClass = target.internalCallerClass(); 1359 if (!hasPrivateAccess() || callerClass != lookupClass()) 1360 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); 1361 } 1362 // Produce the handle to the results. 1363 return new InfoFromMemberName(this, member, refKind); 1364 } 1365 1366 /// Helper methods, all package-private. 1367 1368 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1369 checkSymbolicClass(refc); // do this before attempting to resolve 1370 name.getClass(); // NPE 1371 type.getClass(); // NPE 1372 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1373 NoSuchFieldException.class); 1374 } 1375 1376 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1377 checkSymbolicClass(refc); // do this before attempting to resolve 1378 name.getClass(); // NPE 1379 type.getClass(); // NPE 1380 checkMethodName(refKind, name); // NPE check on name 1381 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), 1382 NoSuchMethodException.class); 1383 } 1384 1385 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { 1386 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve 1387 member.getName().getClass(); // NPE 1388 member.getType().getClass(); // NPE 1389 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), 1390 ReflectiveOperationException.class); 1391 } 1392 1393 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { 1394 refc.getClass(); // NPE 1395 Class<?> caller = lookupClassOrNull(); 1396 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) 1397 throw new MemberName(refc).makeAccessException("symbolic reference class is not public", this); 1398 } 1399 1400 /** Check name for an illegal leading "<" character. */ 1401 void checkMethodName(byte refKind, String name) throws NoSuchMethodException { 1402 if (name.startsWith("<") && refKind != REF_newInvokeSpecial) 1403 throw new NoSuchMethodException("illegal method name: "+name); 1404 } 1405 1406 1407 /** 1408 * Find my trustable caller class if m is a caller sensitive method. 1409 * If this lookup object has private access, then the caller class is the lookupClass. 1410 * Otherwise, if m is caller-sensitive, throw IllegalAccessException. 1411 */ 1412 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { 1413 Class<?> callerClass = null; 1414 if (MethodHandleNatives.isCallerSensitive(m)) { 1415 // Only lookups with private access are allowed to resolve caller-sensitive methods 1416 if (hasPrivateAccess()) { 1417 callerClass = lookupClass; 1418 } else { 1419 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); 1420 } 1421 } 1422 return callerClass; 1423 } 1424 1425 private boolean hasPrivateAccess() { 1426 return (allowedModes & PRIVATE) != 0; 1427 } 1428 1429 /** 1430 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. 1431 * Determines a trustable caller class to compare with refc, the symbolic reference class. 1432 * If this lookup object has private access, then the caller class is the lookupClass. 1433 */ 1434 void checkSecurityManager(Class<?> refc, MemberName m) { 1435 SecurityManager smgr = System.getSecurityManager(); 1436 if (smgr == null) return; 1437 if (allowedModes == TRUSTED) return; 1438 1439 // Step 1: 1440 boolean fullPowerLookup = hasPrivateAccess(); 1441 if (!fullPowerLookup || 1442 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { 1443 ReflectUtil.checkPackageAccess(refc); 1444 } 1445 1446 // Step 2: 1447 if (m.isPublic()) return; 1448 if (!fullPowerLookup) { 1449 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); 1450 } 1451 1452 // Step 3: 1453 Class<?> defc = m.getDeclaringClass(); 1454 if (!fullPowerLookup && defc != refc) { 1455 ReflectUtil.checkPackageAccess(defc); 1456 } 1457 } 1458 1459 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1460 boolean wantStatic = (refKind == REF_invokeStatic); 1461 String message; 1462 if (m.isConstructor()) 1463 message = "expected a method, not a constructor"; 1464 else if (!m.isMethod()) 1465 message = "expected a method"; 1466 else if (wantStatic != m.isStatic()) 1467 message = wantStatic ? "expected a static method" : "expected a non-static method"; 1468 else 1469 { checkAccess(refKind, refc, m); return; } 1470 throw m.makeAccessException(message, this); 1471 } 1472 1473 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1474 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); 1475 String message; 1476 if (wantStatic != m.isStatic()) 1477 message = wantStatic ? "expected a static field" : "expected a non-static field"; 1478 else 1479 { checkAccess(refKind, refc, m); return; } 1480 throw m.makeAccessException(message, this); 1481 } 1482 1483 /** Check public/protected/private bits on the symbolic reference class and its member. */ 1484 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { 1485 assert(m.referenceKindIsConsistentWith(refKind) && 1486 MethodHandleNatives.refKindIsValid(refKind) && 1487 (MethodHandleNatives.refKindIsField(refKind) == m.isField())); 1488 int allowedModes = this.allowedModes; 1489 if (allowedModes == TRUSTED) return; 1490 int mods = m.getModifiers(); 1491 if (Modifier.isProtected(mods) && 1492 refKind == REF_invokeVirtual && 1493 m.getDeclaringClass() == Object.class && 1494 m.getName().equals("clone") && 1495 refc.isArray()) { 1496 // The JVM does this hack also. 1497 // (See ClassVerifier::verify_invoke_instructions 1498 // and LinkResolver::check_method_accessability.) 1499 // Because the JVM does not allow separate methods on array types, 1500 // there is no separate method for int[].clone. 1501 // All arrays simply inherit Object.clone. 1502 // But for access checking logic, we make Object.clone 1503 // (normally protected) appear to be public. 1504 // Later on, when the DirectMethodHandle is created, 1505 // its leading argument will be restricted to the 1506 // requested array type. 1507 // N.B. The return type is not adjusted, because 1508 // that is *not* the bytecode behavior. 1509 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 1510 } 1511 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { 1512 // cannot "new" a protected ctor in a different package 1513 mods ^= Modifier.PROTECTED; 1514 } 1515 if (Modifier.isFinal(mods) && 1516 MethodHandleNatives.refKindIsSetter(refKind)) 1517 throw m.makeAccessException("unexpected set of a final field", this); 1518 if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0) 1519 return; // common case 1520 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1521 if ((requestedModes & allowedModes) != 0) { 1522 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), 1523 mods, lookupClass(), allowedModes)) 1524 return; 1525 } else { 1526 // Protected members can also be checked as if they were package-private. 1527 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1528 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) 1529 return; 1530 } 1531 throw m.makeAccessException(accessFailedMessage(refc, m), this); 1532 } 1533 1534 String accessFailedMessage(Class<?> refc, MemberName m) { 1535 Class<?> defc = m.getDeclaringClass(); 1536 int mods = m.getModifiers(); 1537 // check the class first: 1538 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1539 (defc == refc || 1540 Modifier.isPublic(refc.getModifiers()))); 1541 if (!classOK && (allowedModes & PACKAGE) != 0) { 1542 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1543 (defc == refc || 1544 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1545 } 1546 if (!classOK) 1547 return "class is not public"; 1548 if (Modifier.isPublic(mods)) 1549 return "access to public member failed"; // (how?) 1550 if (Modifier.isPrivate(mods)) 1551 return "member is private"; 1552 if (Modifier.isProtected(mods)) 1553 return "member is protected"; 1554 return "member is private to package"; 1555 } 1556 1557 private static final boolean ALLOW_NESTMATE_ACCESS = false; 1558 1559 private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException { 1560 int allowedModes = this.allowedModes; 1561 if (allowedModes == TRUSTED) return; 1562 if (!hasPrivateAccess() 1563 || (specialCaller != lookupClass() 1564 && !(ALLOW_NESTMATE_ACCESS && 1565 VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) 1566 throw new MemberName(specialCaller). 1567 makeAccessException("no private access for invokespecial", this); 1568 } 1569 1570 private boolean restrictProtectedReceiver(MemberName method) { 1571 // The accessing class only has the right to use a protected member 1572 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. 1573 if (!method.isProtected() || method.isStatic() 1574 || allowedModes == TRUSTED 1575 || method.getDeclaringClass() == lookupClass() 1576 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) 1577 || (ALLOW_NESTMATE_ACCESS && 1578 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) 1579 return false; 1580 return true; 1581 } 1582 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { 1583 assert(!method.isStatic()); 1584 // receiver type of mh is too wide; narrow to caller 1585 if (!method.getDeclaringClass().isAssignableFrom(caller)) { 1586 throw method.makeAccessException("caller class must be a subclass below the method", caller); 1587 } 1588 MethodType rawType = mh.type(); 1589 if (rawType.parameterType(0) == caller) return mh; 1590 MethodType narrowType = rawType.changeParameterType(0, caller); 1591 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness 1592 assert(mh.viewAsTypeChecks(narrowType, true)); 1593 return mh.copyWith(narrowType, mh.form); 1594 } 1595 1596 /** Check access and get the requested method. */ 1597 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1598 final boolean doRestrict = true; 1599 final boolean checkSecurity = true; 1600 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1601 } 1602 /** Check access and get the requested method, eliding receiver narrowing rules. */ 1603 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1604 final boolean doRestrict = false; 1605 final boolean checkSecurity = true; 1606 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1607 } 1608 /** Check access and get the requested method, eliding security manager checks. */ 1609 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { 1610 final boolean doRestrict = true; 1611 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1612 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); 1613 } 1614 /** Common code for all methods; do not call directly except from immediately above. */ 1615 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, 1616 boolean checkSecurity, 1617 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { 1618 checkMethod(refKind, refc, method); 1619 // Optionally check with the security manager; this isn't needed for unreflect* calls. 1620 if (checkSecurity) 1621 checkSecurityManager(refc, method); 1622 assert(!method.isMethodHandleInvoke()); 1623 1624 if (refKind == REF_invokeSpecial && 1625 refc != lookupClass() && 1626 !refc.isInterface() && 1627 refc != lookupClass().getSuperclass() && 1628 refc.isAssignableFrom(lookupClass())) { 1629 assert(!method.getName().equals("<init>")); // not this code path 1630 // Per JVMS 6.5, desc. of invokespecial instruction: 1631 // If the method is in a superclass of the LC, 1632 // and if our original search was above LC.super, 1633 // repeat the search (symbolic lookup) from LC.super 1634 // and continue with the direct superclass of that class, 1635 // and so forth, until a match is found or no further superclasses exist. 1636 // FIXME: MemberName.resolve should handle this instead. 1637 Class<?> refcAsSuper = lookupClass(); 1638 MemberName m2; 1639 do { 1640 refcAsSuper = refcAsSuper.getSuperclass(); 1641 m2 = new MemberName(refcAsSuper, 1642 method.getName(), 1643 method.getMethodType(), 1644 REF_invokeSpecial); 1645 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 1646 } while (m2 == null && // no method is found yet 1647 refc != refcAsSuper); // search up to refc 1648 if (m2 == null) throw new InternalError(method.toString()); 1649 method = m2; 1650 refc = refcAsSuper; 1651 // redo basic checks 1652 checkMethod(refKind, refc, method); 1653 } 1654 1655 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); 1656 MethodHandle mh = dmh; 1657 // Optionally narrow the receiver argument to refc using restrictReceiver. 1658 if (doRestrict && 1659 (refKind == REF_invokeSpecial || 1660 (MethodHandleNatives.refKindHasReceiver(refKind) && 1661 restrictProtectedReceiver(method)))) { 1662 mh = restrictReceiver(method, dmh, lookupClass()); 1663 } 1664 mh = maybeBindCaller(method, mh, callerClass); 1665 mh = mh.setVarargs(method); 1666 return mh; 1667 } 1668 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 1669 Class<?> callerClass) 1670 throws IllegalAccessException { 1671 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 1672 return mh; 1673 Class<?> hostClass = lookupClass; 1674 if (!hasPrivateAccess()) // caller must have private access 1675 hostClass = callerClass; // callerClass came from a security manager style stack walk 1676 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 1677 // Note: caller will apply varargs after this step happens. 1678 return cbmh; 1679 } 1680 /** Check access and get the requested field. */ 1681 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 1682 final boolean checkSecurity = true; 1683 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 1684 } 1685 /** Check access and get the requested field, eliding security manager checks. */ 1686 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 1687 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1688 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 1689 } 1690 /** Common code for all fields; do not call directly except from immediately above. */ 1691 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 1692 boolean checkSecurity) throws IllegalAccessException { 1693 checkField(refKind, refc, field); 1694 // Optionally check with the security manager; this isn't needed for unreflect* calls. 1695 if (checkSecurity) 1696 checkSecurityManager(refc, field); 1697 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); 1698 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 1699 restrictProtectedReceiver(field)); 1700 if (doRestrict) 1701 return restrictReceiver(field, dmh, lookupClass()); 1702 return dmh; 1703 } 1704 /** Check access and get the requested constructor. */ 1705 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 1706 final boolean checkSecurity = true; 1707 return getDirectConstructorCommon(refc, ctor, checkSecurity); 1708 } 1709 /** Check access and get the requested constructor, eliding security manager checks. */ 1710 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 1711 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1712 return getDirectConstructorCommon(refc, ctor, checkSecurity); 1713 } 1714 /** Common code for all constructors; do not call directly except from immediately above. */ 1715 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 1716 boolean checkSecurity) throws IllegalAccessException { 1717 assert(ctor.isConstructor()); 1718 checkAccess(REF_newInvokeSpecial, refc, ctor); 1719 // Optionally check with the security manager; this isn't needed for unreflect* calls. 1720 if (checkSecurity) 1721 checkSecurityManager(refc, ctor); 1722 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 1723 return DirectMethodHandle.make(ctor).setVarargs(ctor); 1724 } 1725 1726 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 1727 */ 1728 /*non-public*/ 1729 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 1730 if (!(type instanceof Class || type instanceof MethodType)) 1731 throw new InternalError("unresolved MemberName"); 1732 MemberName member = new MemberName(refKind, defc, name, type); 1733 MethodHandle mh = LOOKASIDE_TABLE.get(member); 1734 if (mh != null) { 1735 checkSymbolicClass(defc); 1736 return mh; 1737 } 1738 // Treat MethodHandle.invoke and invokeExact specially. 1739 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 1740 mh = findVirtualForMH(member.getName(), member.getMethodType()); 1741 if (mh != null) { 1742 return mh; 1743 } 1744 } 1745 MemberName resolved = resolveOrFail(refKind, member); 1746 mh = getDirectMethodForConstant(refKind, defc, resolved); 1747 if (mh instanceof DirectMethodHandle 1748 && canBeCached(refKind, defc, resolved)) { 1749 MemberName key = mh.internalMemberName(); 1750 if (key != null) { 1751 key = key.asNormalOriginal(); 1752 } 1753 if (member.equals(key)) { // better safe than sorry 1754 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 1755 } 1756 } 1757 return mh; 1758 } 1759 private 1760 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 1761 if (refKind == REF_invokeSpecial) { 1762 return false; 1763 } 1764 if (!Modifier.isPublic(defc.getModifiers()) || 1765 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 1766 !member.isPublic() || 1767 member.isCallerSensitive()) { 1768 return false; 1769 } 1770 ClassLoader loader = defc.getClassLoader(); 1771 if (!sun.misc.VM.isSystemDomainLoader(loader)) { 1772 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 1773 boolean found = false; 1774 while (sysl != null) { 1775 if (loader == sysl) { found = true; break; } 1776 sysl = sysl.getParent(); 1777 } 1778 if (!found) { 1779 return false; 1780 } 1781 } 1782 try { 1783 MemberName resolved2 = publicLookup().resolveOrFail(refKind, 1784 new MemberName(refKind, defc, member.getName(), member.getType())); 1785 checkSecurityManager(defc, resolved2); 1786 } catch (ReflectiveOperationException | SecurityException ex) { 1787 return false; 1788 } 1789 return true; 1790 } 1791 private 1792 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 1793 throws ReflectiveOperationException { 1794 if (MethodHandleNatives.refKindIsField(refKind)) { 1795 return getDirectFieldNoSecurityManager(refKind, defc, member); 1796 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 1797 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 1798 } else if (refKind == REF_newInvokeSpecial) { 1799 return getDirectConstructorNoSecurityManager(defc, member); 1800 } 1801 // oops 1802 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 1803 } 1804 1805 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 1806 } 1807 1808 /** 1809 * Produces a method handle giving read access to elements of an array. 1810 * The type of the method handle will have a return type of the array's 1811 * element type. Its first argument will be the array type, 1812 * and the second will be {@code int}. 1813 * @param arrayClass an array type 1814 * @return a method handle which can load values from the given array type 1815 * @throws NullPointerException if the argument is null 1816 * @throws IllegalArgumentException if arrayClass is not an array type 1817 */ 1818 public static 1819 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 1820 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false); 1821 } 1822 1823 /** 1824 * Produces a method handle giving write access to elements of an array. 1825 * The type of the method handle will have a void return type. 1826 * Its last argument will be the array's element type. 1827 * The first and second arguments will be the array type and int. 1828 * @param arrayClass the class of an array 1829 * @return a method handle which can store values into the array type 1830 * @throws NullPointerException if the argument is null 1831 * @throws IllegalArgumentException if arrayClass is not an array type 1832 */ 1833 public static 1834 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 1835 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true); 1836 } 1837 1838 /// method handle invocation (reflective style) 1839 1840 /** 1841 * Produces a method handle which will invoke any method handle of the 1842 * given {@code type}, with a given number of trailing arguments replaced by 1843 * a single trailing {@code Object[]} array. 1844 * The resulting invoker will be a method handle with the following 1845 * arguments: 1846 * <ul> 1847 * <li>a single {@code MethodHandle} target 1848 * <li>zero or more leading values (counted by {@code leadingArgCount}) 1849 * <li>an {@code Object[]} array containing trailing arguments 1850 * </ul> 1851 * <p> 1852 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 1853 * the indicated {@code type}. 1854 * That is, if the target is exactly of the given {@code type}, it will behave 1855 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 1856 * is used to convert the target to the required {@code type}. 1857 * <p> 1858 * The type of the returned invoker will not be the given {@code type}, but rather 1859 * will have all parameters except the first {@code leadingArgCount} 1860 * replaced by a single array of type {@code Object[]}, which will be 1861 * the final parameter. 1862 * <p> 1863 * Before invoking its target, the invoker will spread the final array, apply 1864 * reference casts as necessary, and unbox and widen primitive arguments. 1865 * If, when the invoker is called, the supplied array argument does 1866 * not have the correct number of elements, the invoker will throw 1867 * an {@link IllegalArgumentException} instead of invoking the target. 1868 * <p> 1869 * This method is equivalent to the following code (though it may be more efficient): 1870 * <blockquote><pre>{@code 1871 MethodHandle invoker = MethodHandles.invoker(type); 1872 int spreadArgCount = type.parameterCount() - leadingArgCount; 1873 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 1874 return invoker; 1875 * }</pre></blockquote> 1876 * This method throws no reflective or security exceptions. 1877 * @param type the desired target type 1878 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 1879 * @return a method handle suitable for invoking any method handle of the given type 1880 * @throws NullPointerException if {@code type} is null 1881 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 1882 * the range from 0 to {@code type.parameterCount()} inclusive, 1883 * or if the resulting method handle's type would have 1884 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1885 */ 1886 static public 1887 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 1888 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 1889 throw newIllegalArgumentException("bad argument count", leadingArgCount); 1890 type = type.asSpreaderType(Object[].class, type.parameterCount() - leadingArgCount); 1891 return type.invokers().spreadInvoker(leadingArgCount); 1892 } 1893 1894 /** 1895 * Produces a special <em>invoker method handle</em> which can be used to 1896 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 1897 * The resulting invoker will have a type which is 1898 * exactly equal to the desired type, except that it will accept 1899 * an additional leading argument of type {@code MethodHandle}. 1900 * <p> 1901 * This method is equivalent to the following code (though it may be more efficient): 1902 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 1903 * 1904 * <p style="font-size:smaller;"> 1905 * <em>Discussion:</em> 1906 * Invoker method handles can be useful when working with variable method handles 1907 * of unknown types. 1908 * For example, to emulate an {@code invokeExact} call to a variable method 1909 * handle {@code M}, extract its type {@code T}, 1910 * look up the invoker method {@code X} for {@code T}, 1911 * and call the invoker method, as {@code X.invoke(T, A...)}. 1912 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 1913 * is unknown.) 1914 * If spreading, collecting, or other argument transformations are required, 1915 * they can be applied once to the invoker {@code X} and reused on many {@code M} 1916 * method handle values, as long as they are compatible with the type of {@code X}. 1917 * <p style="font-size:smaller;"> 1918 * <em>(Note: The invoker method is not available via the Core Reflection API. 1919 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 1920 * on the declared {@code invokeExact} or {@code invoke} method will raise an 1921 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 1922 * <p> 1923 * This method throws no reflective or security exceptions. 1924 * @param type the desired target type 1925 * @return a method handle suitable for invoking any method handle of the given type 1926 * @throws IllegalArgumentException if the resulting method handle's type would have 1927 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1928 */ 1929 static public 1930 MethodHandle exactInvoker(MethodType type) { 1931 return type.invokers().exactInvoker(); 1932 } 1933 1934 /** 1935 * Produces a special <em>invoker method handle</em> which can be used to 1936 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 1937 * The resulting invoker will have a type which is 1938 * exactly equal to the desired type, except that it will accept 1939 * an additional leading argument of type {@code MethodHandle}. 1940 * <p> 1941 * Before invoking its target, if the target differs from the expected type, 1942 * the invoker will apply reference casts as 1943 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 1944 * Similarly, the return value will be converted as necessary. 1945 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 1946 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 1947 * <p> 1948 * This method is equivalent to the following code (though it may be more efficient): 1949 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 1950 * <p style="font-size:smaller;"> 1951 * <em>Discussion:</em> 1952 * A {@linkplain MethodType#genericMethodType general method type} is one which 1953 * mentions only {@code Object} arguments and return values. 1954 * An invoker for such a type is capable of calling any method handle 1955 * of the same arity as the general type. 1956 * <p style="font-size:smaller;"> 1957 * <em>(Note: The invoker method is not available via the Core Reflection API. 1958 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 1959 * on the declared {@code invokeExact} or {@code invoke} method will raise an 1960 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 1961 * <p> 1962 * This method throws no reflective or security exceptions. 1963 * @param type the desired target type 1964 * @return a method handle suitable for invoking any method handle convertible to the given type 1965 * @throws IllegalArgumentException if the resulting method handle's type would have 1966 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1967 */ 1968 static public 1969 MethodHandle invoker(MethodType type) { 1970 return type.invokers().genericInvoker(); 1971 } 1972 1973 static /*non-public*/ 1974 MethodHandle basicInvoker(MethodType type) { 1975 return type.invokers().basicInvoker(); 1976 } 1977 1978 /// method handle modification (creation from other method handles) 1979 1980 /** 1981 * Produces a method handle which adapts the type of the 1982 * given method handle to a new type by pairwise argument and return type conversion. 1983 * The original type and new type must have the same number of arguments. 1984 * The resulting method handle is guaranteed to report a type 1985 * which is equal to the desired new type. 1986 * <p> 1987 * If the original type and new type are equal, returns target. 1988 * <p> 1989 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 1990 * and some additional conversions are also applied if those conversions fail. 1991 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 1992 * if possible, before or instead of any conversions done by {@code asType}: 1993 * <ul> 1994 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 1995 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 1996 * (This treatment of interfaces follows the usage of the bytecode verifier.) 1997 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 1998 * the boolean is converted to a byte value, 1 for true, 0 for false. 1999 * (This treatment follows the usage of the bytecode verifier.) 2000 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 2001 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 2002 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 2003 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 2004 * then a Java casting conversion (JLS 5.5) is applied. 2005 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 2006 * widening and/or narrowing.) 2007 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 2008 * conversion will be applied at runtime, possibly followed 2009 * by a Java casting conversion (JLS 5.5) on the primitive value, 2010 * possibly followed by a conversion from byte to boolean by testing 2011 * the low-order bit. 2012 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2013 * and if the reference is null at runtime, a zero value is introduced. 2014 * </ul> 2015 * @param target the method handle to invoke after arguments are retyped 2016 * @param newType the expected type of the new method handle 2017 * @return a method handle which delegates to the target after performing 2018 * any necessary argument conversions, and arranges for any 2019 * necessary return value conversions 2020 * @throws NullPointerException if either argument is null 2021 * @throws WrongMethodTypeException if the conversion cannot be made 2022 * @see MethodHandle#asType 2023 */ 2024 public static 2025 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2026 explicitCastArgumentsChecks(target, newType); 2027 // use the asTypeCache when possible: 2028 MethodType oldType = target.type(); 2029 if (oldType == newType) return target; 2030 if (oldType.explicitCastEquivalentToAsType(newType)) { 2031 return target.asType(newType); 2032 } 2033 return MethodHandleImpl.makePairwiseConvert(target, newType, false); 2034 } 2035 2036 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 2037 if (target.type().parameterCount() != newType.parameterCount()) { 2038 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); 2039 } 2040 } 2041 2042 /** 2043 * Produces a method handle which adapts the calling sequence of the 2044 * given method handle to a new type, by reordering the arguments. 2045 * The resulting method handle is guaranteed to report a type 2046 * which is equal to the desired new type. 2047 * <p> 2048 * The given array controls the reordering. 2049 * Call {@code #I} the number of incoming parameters (the value 2050 * {@code newType.parameterCount()}, and call {@code #O} the number 2051 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2052 * Then the length of the reordering array must be {@code #O}, 2053 * and each element must be a non-negative number less than {@code #I}. 2054 * For every {@code N} less than {@code #O}, the {@code N}-th 2055 * outgoing argument will be taken from the {@code I}-th incoming 2056 * argument, where {@code I} is {@code reorder[N]}. 2057 * <p> 2058 * No argument or return value conversions are applied. 2059 * The type of each incoming argument, as determined by {@code newType}, 2060 * must be identical to the type of the corresponding outgoing parameter 2061 * or parameters in the target method handle. 2062 * The return type of {@code newType} must be identical to the return 2063 * type of the original target. 2064 * <p> 2065 * The reordering array need not specify an actual permutation. 2066 * An incoming argument will be duplicated if its index appears 2067 * more than once in the array, and an incoming argument will be dropped 2068 * if its index does not appear in the array. 2069 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2070 * incoming arguments which are not mentioned in the reordering array 2071 * are may be any type, as determined only by {@code newType}. 2072 * <blockquote><pre>{@code 2073 import static java.lang.invoke.MethodHandles.*; 2074 import static java.lang.invoke.MethodType.*; 2075 ... 2076 MethodType intfn1 = methodType(int.class, int.class); 2077 MethodType intfn2 = methodType(int.class, int.class, int.class); 2078 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2079 assert(sub.type().equals(intfn2)); 2080 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2081 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2082 assert((int)rsub.invokeExact(1, 100) == 99); 2083 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2084 assert(add.type().equals(intfn2)); 2085 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2086 assert(twice.type().equals(intfn1)); 2087 assert((int)twice.invokeExact(21) == 42); 2088 * }</pre></blockquote> 2089 * @param target the method handle to invoke after arguments are reordered 2090 * @param newType the expected type of the new method handle 2091 * @param reorder an index array which controls the reordering 2092 * @return a method handle which delegates to the target after it 2093 * drops unused arguments and moves and/or duplicates the other arguments 2094 * @throws NullPointerException if any argument is null 2095 * @throws IllegalArgumentException if the index array length is not equal to 2096 * the arity of the target, or if any index array element 2097 * not a valid index for a parameter of {@code newType}, 2098 * or if two corresponding parameter types in 2099 * {@code target.type()} and {@code newType} are not identical, 2100 */ 2101 public static 2102 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2103 reorder = reorder.clone(); // get a private copy 2104 MethodType oldType = target.type(); 2105 permuteArgumentChecks(reorder, newType, oldType); 2106 if (USE_LAMBDA_FORM_EDITOR) { 2107 // first detect dropped arguments and handle them separately 2108 int[] originalReorder = reorder; 2109 BoundMethodHandle result = target.rebind(); 2110 LambdaForm form = result.form; 2111 int newArity = newType.parameterCount(); 2112 // Normalize the reordering into a real permutation, 2113 // by removing duplicates and adding dropped elements. 2114 // This somewhat improves lambda form caching, as well 2115 // as simplifying the transform by breaking it up into steps. 2116 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { 2117 if (ddIdx > 0) { 2118 // We found a duplicated entry at reorder[ddIdx]. 2119 // Example: (x,y,z)->asList(x,y,z) 2120 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) 2121 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) 2122 // The starred element corresponds to the argument 2123 // deleted by the dupArgumentForm transform. 2124 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; 2125 boolean killFirst = false; 2126 for (int val; (val = reorder[--dstPos]) != dupVal; ) { 2127 // Set killFirst if the dup is larger than an intervening position. 2128 // This will remove at least one inversion from the permutation. 2129 if (dupVal > val) killFirst = true; 2130 } 2131 if (!killFirst) { 2132 srcPos = dstPos; 2133 dstPos = ddIdx; 2134 } 2135 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); 2136 assert (reorder[srcPos] == reorder[dstPos]); 2137 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); 2138 // contract the reordering by removing the element at dstPos 2139 int tailPos = dstPos + 1; 2140 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); 2141 reorder = Arrays.copyOf(reorder, reorder.length - 1); 2142 } else { 2143 int dropVal = ~ddIdx, insPos = 0; 2144 while (insPos < reorder.length && reorder[insPos] < dropVal) { 2145 // Find first element of reorder larger than dropVal. 2146 // This is where we will insert the dropVal. 2147 insPos += 1; 2148 } 2149 Class<?> ptype = newType.parameterType(dropVal); 2150 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); 2151 oldType = oldType.insertParameterTypes(insPos, ptype); 2152 // expand the reordering by inserting an element at insPos 2153 int tailPos = insPos + 1; 2154 reorder = Arrays.copyOf(reorder, reorder.length + 1); 2155 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); 2156 reorder[insPos] = dropVal; 2157 } 2158 assert (permuteArgumentChecks(reorder, newType, oldType)); 2159 } 2160 assert (reorder.length == newArity); // a perfect permutation 2161 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 2162 form = form.editor().permuteArgumentsForm(1, reorder); 2163 if (newType == result.type() && form == result.internalForm()) 2164 return result; 2165 return result.copyWith(newType, form); 2166 } else { 2167 // first detect dropped arguments and handle them separately 2168 MethodHandle originalTarget = target; 2169 int newArity = newType.parameterCount(); 2170 for (int dropIdx; (dropIdx = findFirstDrop(reorder, newArity)) >= 0; ) { 2171 // dropIdx is missing from reorder; add it in at the end 2172 int oldArity = reorder.length; 2173 target = dropArguments(target, oldArity, newType.parameterType(dropIdx)); 2174 reorder = Arrays.copyOf(reorder, oldArity + 1); 2175 reorder[oldArity] = dropIdx; 2176 } 2177 assert(target == originalTarget || permuteArgumentChecks(reorder, newType, target.type())); 2178 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 2179 BoundMethodHandle result = target.rebind(); 2180 LambdaForm form = result.form.permuteArguments(1, reorder, basicTypes(newType.parameterList())); 2181 return result.copyWith(newType, form); 2182 } 2183 } 2184 2185 /** Return the first value in [0..newArity-1] that is not present in reorder. */ 2186 private static int findFirstDrop(int[] reorder, int newArity) { 2187 final int BIT_LIMIT = 63; // max number of bits in bit mask 2188 if (newArity < BIT_LIMIT) { 2189 long mask = 0; 2190 for (int arg : reorder) { 2191 assert(arg < newArity); 2192 mask |= (1L << arg); 2193 } 2194 if (mask == (1L << newArity) - 1) { 2195 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 2196 return -1; 2197 } 2198 // find first zero 2199 long zeroBit = Long.lowestOneBit(~mask); 2200 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 2201 assert(zeroPos < newArity); 2202 return zeroPos; 2203 } else { 2204 BitSet mask = new BitSet(newArity); 2205 for (int arg : reorder) { 2206 assert (arg < newArity); 2207 mask.set(arg); 2208 } 2209 int zeroPos = mask.nextClearBit(0); 2210 assert(zeroPos <= newArity); 2211 if (zeroPos == newArity) 2212 return -1; 2213 return zeroPos; 2214 } 2215 } 2216 2217 /** 2218 * Return an indication of any duplicate or omission in reorder. 2219 * If the reorder contains a duplicate entry, return the index of the second occurrence. 2220 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. 2221 * Otherwise, return zero. 2222 * If an element not in [0..newArity-1] is encountered, return reorder.length. 2223 */ 2224 private static int findFirstDupOrDrop(int[] reorder, int newArity) { 2225 final int BIT_LIMIT = 63; // max number of bits in bit mask 2226 if (newArity < BIT_LIMIT) { 2227 long mask = 0; 2228 for (int i = 0; i < reorder.length; i++) { 2229 int arg = reorder[i]; 2230 if (arg >= newArity) { 2231 return reorder.length; 2232 } 2233 long bit = 1L << arg; 2234 if ((mask & bit) != 0) { 2235 return i; // >0 indicates a dup 2236 } 2237 mask |= bit; 2238 } 2239 if (mask == (1L << newArity) - 1) { 2240 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); 2241 return 0; 2242 } 2243 // find first zero 2244 long zeroBit = Long.lowestOneBit(~mask); 2245 int zeroPos = Long.numberOfTrailingZeros(zeroBit); 2246 assert(zeroPos <= newArity); 2247 if (zeroPos == newArity) { 2248 return 0; 2249 } 2250 return ~zeroPos; 2251 } else { 2252 // same algorithm, different bit set 2253 BitSet mask = new BitSet(newArity); 2254 for (int i = 0; i < reorder.length; i++) { 2255 int arg = reorder[i]; 2256 if (arg >= newArity) { 2257 return reorder.length; 2258 } 2259 if (mask.get(arg)) { 2260 return i; // >0 indicates a dup 2261 } 2262 mask.set(arg); 2263 } 2264 int zeroPos = mask.nextClearBit(0); 2265 assert(zeroPos <= newArity); 2266 if (zeroPos == newArity) { 2267 return 0; 2268 } 2269 return ~zeroPos; 2270 } 2271 } 2272 2273 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 2274 if (newType.returnType() != oldType.returnType()) 2275 throw newIllegalArgumentException("return types do not match", 2276 oldType, newType); 2277 if (reorder.length == oldType.parameterCount()) { 2278 int limit = newType.parameterCount(); 2279 boolean bad = false; 2280 for (int j = 0; j < reorder.length; j++) { 2281 int i = reorder[j]; 2282 if (i < 0 || i >= limit) { 2283 bad = true; break; 2284 } 2285 Class<?> src = newType.parameterType(i); 2286 Class<?> dst = oldType.parameterType(j); 2287 if (src != dst) 2288 throw newIllegalArgumentException("parameter types do not match after reorder", 2289 oldType, newType); 2290 } 2291 if (!bad) return true; 2292 } 2293 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 2294 } 2295 2296 /** 2297 * Produces a method handle of the requested return type which returns the given 2298 * constant value every time it is invoked. 2299 * <p> 2300 * Before the method handle is returned, the passed-in value is converted to the requested type. 2301 * If the requested type is primitive, widening primitive conversions are attempted, 2302 * else reference conversions are attempted. 2303 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 2304 * @param type the return type of the desired method handle 2305 * @param value the value to return 2306 * @return a method handle of the given return type and no arguments, which always returns the given value 2307 * @throws NullPointerException if the {@code type} argument is null 2308 * @throws ClassCastException if the value cannot be converted to the required return type 2309 * @throws IllegalArgumentException if the given type is {@code void.class} 2310 */ 2311 public static 2312 MethodHandle constant(Class<?> type, Object value) { 2313 if (type.isPrimitive()) { 2314 if (type == void.class) 2315 throw newIllegalArgumentException("void type"); 2316 Wrapper w = Wrapper.forPrimitiveType(type); 2317 value = w.convert(value, type); 2318 if (w.zero().equals(value)) 2319 return zero(w, type); 2320 return insertArguments(identity(type), 0, value); 2321 } else { 2322 if (value == null) 2323 return zero(Wrapper.OBJECT, type); 2324 return identity(type).bindTo(value); 2325 } 2326 } 2327 2328 /** 2329 * Produces a method handle which returns its sole argument when invoked. 2330 * @param type the type of the sole parameter and return value of the desired method handle 2331 * @return a unary method handle which accepts and returns the given type 2332 * @throws NullPointerException if the argument is null 2333 * @throws IllegalArgumentException if the given type is {@code void.class} 2334 */ 2335 public static 2336 MethodHandle identity(Class<?> type) { 2337 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 2338 int pos = btw.ordinal(); 2339 MethodHandle ident = IDENTITY_MHS[pos]; 2340 if (ident == null) { 2341 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 2342 } 2343 if (ident.type().returnType() == type) 2344 return ident; 2345 // something like identity(Foo.class); do not bother to intern these 2346 assert(btw == Wrapper.OBJECT); 2347 return makeIdentity(type); 2348 } 2349 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length]; 2350 private static MethodHandle makeIdentity(Class<?> ptype) { 2351 MethodType mtype = MethodType.methodType(ptype, ptype); 2352 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 2353 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 2354 } 2355 2356 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 2357 int pos = btw.ordinal(); 2358 MethodHandle zero = ZERO_MHS[pos]; 2359 if (zero == null) { 2360 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 2361 } 2362 if (zero.type().returnType() == rtype) 2363 return zero; 2364 assert(btw == Wrapper.OBJECT); 2365 return makeZero(rtype); 2366 } 2367 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length]; 2368 private static MethodHandle makeZero(Class<?> rtype) { 2369 MethodType mtype = MethodType.methodType(rtype); 2370 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 2371 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 2372 } 2373 2374 synchronized private static MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 2375 // Simulate a CAS, to avoid racy duplication of results. 2376 MethodHandle prev = cache[pos]; 2377 if (prev != null) return prev; 2378 return cache[pos] = value; 2379 } 2380 2381 /** 2382 * Provides a target method handle with one or more <em>bound arguments</em> 2383 * in advance of the method handle's invocation. 2384 * The formal parameters to the target corresponding to the bound 2385 * arguments are called <em>bound parameters</em>. 2386 * Returns a new method handle which saves away the bound arguments. 2387 * When it is invoked, it receives arguments for any non-bound parameters, 2388 * binds the saved arguments to their corresponding parameters, 2389 * and calls the original target. 2390 * <p> 2391 * The type of the new method handle will drop the types for the bound 2392 * parameters from the original target type, since the new method handle 2393 * will no longer require those arguments to be supplied by its callers. 2394 * <p> 2395 * Each given argument object must match the corresponding bound parameter type. 2396 * If a bound parameter type is a primitive, the argument object 2397 * must be a wrapper, and will be unboxed to produce the primitive value. 2398 * <p> 2399 * The {@code pos} argument selects which parameters are to be bound. 2400 * It may range between zero and <i>N-L</i> (inclusively), 2401 * where <i>N</i> is the arity of the target method handle 2402 * and <i>L</i> is the length of the values array. 2403 * @param target the method handle to invoke after the argument is inserted 2404 * @param pos where to insert the argument (zero for the first) 2405 * @param values the series of arguments to insert 2406 * @return a method handle which inserts an additional argument, 2407 * before calling the original method handle 2408 * @throws NullPointerException if the target or the {@code values} array is null 2409 * @see MethodHandle#bindTo 2410 */ 2411 public static 2412 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 2413 int insCount = values.length; 2414 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 2415 if (insCount == 0) return target; 2416 BoundMethodHandle result = target.rebind(); 2417 for (int i = 0; i < insCount; i++) { 2418 Object value = values[i]; 2419 Class<?> ptype = ptypes[pos+i]; 2420 if (ptype.isPrimitive()) { 2421 result = insertArgumentPrimitive(result, pos, ptype, value); 2422 } else { 2423 value = ptype.cast(value); // throw CCE if needed 2424 result = result.bindArgumentL(pos, value); 2425 } 2426 } 2427 return result; 2428 } 2429 2430 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 2431 Class<?> ptype, Object value) { 2432 Wrapper w = Wrapper.forPrimitiveType(ptype); 2433 // perform unboxing and/or primitive conversion 2434 value = w.convert(value, ptype); 2435 switch (w) { 2436 case INT: return result.bindArgumentI(pos, (int)value); 2437 case LONG: return result.bindArgumentJ(pos, (long)value); 2438 case FLOAT: return result.bindArgumentF(pos, (float)value); 2439 case DOUBLE: return result.bindArgumentD(pos, (double)value); 2440 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 2441 } 2442 } 2443 2444 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 2445 MethodType oldType = target.type(); 2446 int outargs = oldType.parameterCount(); 2447 int inargs = outargs - insCount; 2448 if (inargs < 0) 2449 throw newIllegalArgumentException("too many values to insert"); 2450 if (pos < 0 || pos > inargs) 2451 throw newIllegalArgumentException("no argument type to append"); 2452 return oldType.ptypes(); 2453 } 2454 2455 /** 2456 * Produces a method handle which will discard some dummy arguments 2457 * before calling some other specified <i>target</i> method handle. 2458 * The type of the new method handle will be the same as the target's type, 2459 * except it will also include the dummy argument types, 2460 * at some given position. 2461 * <p> 2462 * The {@code pos} argument may range between zero and <i>N</i>, 2463 * where <i>N</i> is the arity of the target. 2464 * If {@code pos} is zero, the dummy arguments will precede 2465 * the target's real arguments; if {@code pos} is <i>N</i> 2466 * they will come after. 2467 * <p> 2468 * <b>Example:</b> 2469 * <blockquote><pre>{@code 2470 import static java.lang.invoke.MethodHandles.*; 2471 import static java.lang.invoke.MethodType.*; 2472 ... 2473 MethodHandle cat = lookup().findVirtual(String.class, 2474 "concat", methodType(String.class, String.class)); 2475 assertEquals("xy", (String) cat.invokeExact("x", "y")); 2476 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 2477 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 2478 assertEquals(bigType, d0.type()); 2479 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 2480 * }</pre></blockquote> 2481 * <p> 2482 * This method is also equivalent to the following code: 2483 * <blockquote><pre> 2484 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 2485 * </pre></blockquote> 2486 * @param target the method handle to invoke after the arguments are dropped 2487 * @param valueTypes the type(s) of the argument(s) to drop 2488 * @param pos position of first argument to drop (zero for the leftmost) 2489 * @return a method handle which drops arguments of the given types, 2490 * before calling the original method handle 2491 * @throws NullPointerException if the target is null, 2492 * or if the {@code valueTypes} list or any of its elements is null 2493 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 2494 * or if {@code pos} is negative or greater than the arity of the target, 2495 * or if the new method handle's type would have too many parameters 2496 */ 2497 public static 2498 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 2499 MethodType oldType = target.type(); // get NPE 2500 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 2501 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 2502 if (dropped == 0) return target; 2503 BoundMethodHandle result = target.rebind(); 2504 LambdaForm lform = result.form; 2505 if (USE_LAMBDA_FORM_EDITOR) { 2506 int insertFormArg = 1 + pos; 2507 for (Class<?> ptype : valueTypes) { 2508 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 2509 } 2510 } else { 2511 lform = lform.addArguments(pos, valueTypes); 2512 } 2513 result = result.copyWith(newType, lform); 2514 return result; 2515 } 2516 2517 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 2518 int dropped = valueTypes.size(); 2519 MethodType.checkSlotCount(dropped); 2520 int outargs = oldType.parameterCount(); 2521 int inargs = outargs + dropped; 2522 if (pos < 0 || pos > outargs) 2523 throw newIllegalArgumentException("no argument type to remove" 2524 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 2525 ); 2526 return dropped; 2527 } 2528 2529 /** 2530 * Produces a method handle which will discard some dummy arguments 2531 * before calling some other specified <i>target</i> method handle. 2532 * The type of the new method handle will be the same as the target's type, 2533 * except it will also include the dummy argument types, 2534 * at some given position. 2535 * <p> 2536 * The {@code pos} argument may range between zero and <i>N</i>, 2537 * where <i>N</i> is the arity of the target. 2538 * If {@code pos} is zero, the dummy arguments will precede 2539 * the target's real arguments; if {@code pos} is <i>N</i> 2540 * they will come after. 2541 * <p> 2542 * <b>Example:</b> 2543 * <blockquote><pre>{@code 2544 import static java.lang.invoke.MethodHandles.*; 2545 import static java.lang.invoke.MethodType.*; 2546 ... 2547 MethodHandle cat = lookup().findVirtual(String.class, 2548 "concat", methodType(String.class, String.class)); 2549 assertEquals("xy", (String) cat.invokeExact("x", "y")); 2550 MethodHandle d0 = dropArguments(cat, 0, String.class); 2551 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 2552 MethodHandle d1 = dropArguments(cat, 1, String.class); 2553 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 2554 MethodHandle d2 = dropArguments(cat, 2, String.class); 2555 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 2556 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 2557 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 2558 * }</pre></blockquote> 2559 * <p> 2560 * This method is also equivalent to the following code: 2561 * <blockquote><pre> 2562 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 2563 * </pre></blockquote> 2564 * @param target the method handle to invoke after the arguments are dropped 2565 * @param valueTypes the type(s) of the argument(s) to drop 2566 * @param pos position of first argument to drop (zero for the leftmost) 2567 * @return a method handle which drops arguments of the given types, 2568 * before calling the original method handle 2569 * @throws NullPointerException if the target is null, 2570 * or if the {@code valueTypes} array or any of its elements is null 2571 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 2572 * or if {@code pos} is negative or greater than the arity of the target, 2573 * or if the new method handle's type would have 2574 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2575 */ 2576 public static 2577 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 2578 return dropArguments(target, pos, Arrays.asList(valueTypes)); 2579 } 2580 2581 /** 2582 * Adapts a target method handle by pre-processing 2583 * one or more of its arguments, each with its own unary filter function, 2584 * and then calling the target with each pre-processed argument 2585 * replaced by the result of its corresponding filter function. 2586 * <p> 2587 * The pre-processing is performed by one or more method handles, 2588 * specified in the elements of the {@code filters} array. 2589 * The first element of the filter array corresponds to the {@code pos} 2590 * argument of the target, and so on in sequence. 2591 * <p> 2592 * Null arguments in the array are treated as identity functions, 2593 * and the corresponding arguments left unchanged. 2594 * (If there are no non-null elements in the array, the original target is returned.) 2595 * Each filter is applied to the corresponding argument of the adapter. 2596 * <p> 2597 * If a filter {@code F} applies to the {@code N}th argument of 2598 * the target, then {@code F} must be a method handle which 2599 * takes exactly one argument. The type of {@code F}'s sole argument 2600 * replaces the corresponding argument type of the target 2601 * in the resulting adapted method handle. 2602 * The return type of {@code F} must be identical to the corresponding 2603 * parameter type of the target. 2604 * <p> 2605 * It is an error if there are elements of {@code filters} 2606 * (null or not) 2607 * which do not correspond to argument positions in the target. 2608 * <p><b>Example:</b> 2609 * <blockquote><pre>{@code 2610 import static java.lang.invoke.MethodHandles.*; 2611 import static java.lang.invoke.MethodType.*; 2612 ... 2613 MethodHandle cat = lookup().findVirtual(String.class, 2614 "concat", methodType(String.class, String.class)); 2615 MethodHandle upcase = lookup().findVirtual(String.class, 2616 "toUpperCase", methodType(String.class)); 2617 assertEquals("xy", (String) cat.invokeExact("x", "y")); 2618 MethodHandle f0 = filterArguments(cat, 0, upcase); 2619 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 2620 MethodHandle f1 = filterArguments(cat, 1, upcase); 2621 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 2622 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 2623 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 2624 * }</pre></blockquote> 2625 * <p> Here is pseudocode for the resulting adapter: 2626 * <blockquote><pre>{@code 2627 * V target(P... p, A[i]... a[i], B... b); 2628 * A[i] filter[i](V[i]); 2629 * T adapter(P... p, V[i]... v[i], B... b) { 2630 * return target(p..., f[i](v[i])..., b...); 2631 * } 2632 * }</pre></blockquote> 2633 * 2634 * @param target the method handle to invoke after arguments are filtered 2635 * @param pos the position of the first argument to filter 2636 * @param filters method handles to call initially on filtered arguments 2637 * @return method handle which incorporates the specified argument filtering logic 2638 * @throws NullPointerException if the target is null 2639 * or if the {@code filters} array is null 2640 * @throws IllegalArgumentException if a non-null element of {@code filters} 2641 * does not match a corresponding argument type of target as described above, 2642 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 2643 * or if the resulting method handle's type would have 2644 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2645 */ 2646 public static 2647 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 2648 filterArgumentsCheckArity(target, pos, filters); 2649 MethodHandle adapter = target; 2650 int curPos = pos-1; // pre-incremented 2651 for (MethodHandle filter : filters) { 2652 curPos += 1; 2653 if (filter == null) continue; // ignore null elements of filters 2654 adapter = filterArgument(adapter, curPos, filter); 2655 } 2656 return adapter; 2657 } 2658 2659 /*non-public*/ static 2660 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 2661 filterArgumentChecks(target, pos, filter); 2662 if (USE_LAMBDA_FORM_EDITOR) { 2663 MethodType targetType = target.type(); 2664 MethodType filterType = filter.type(); 2665 BoundMethodHandle result = target.rebind(); 2666 Class<?> newParamType = filterType.parameterType(0); 2667 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 2668 MethodType newType = targetType.changeParameterType(pos, newParamType); 2669 result = result.copyWithExtendL(newType, lform, filter); 2670 return result; 2671 } else { 2672 return MethodHandleImpl.makeCollectArguments(target, filter, pos, false); 2673 } 2674 } 2675 2676 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 2677 MethodType targetType = target.type(); 2678 int maxPos = targetType.parameterCount(); 2679 if (pos + filters.length > maxPos) 2680 throw newIllegalArgumentException("too many filters"); 2681 } 2682 2683 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 2684 MethodType targetType = target.type(); 2685 MethodType filterType = filter.type(); 2686 if (filterType.parameterCount() != 1 2687 || filterType.returnType() != targetType.parameterType(pos)) 2688 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 2689 } 2690 2691 /** 2692 * Adapts a target method handle by pre-processing 2693 * a sub-sequence of its arguments with a filter (another method handle). 2694 * The pre-processed arguments are replaced by the result (if any) of the 2695 * filter function. 2696 * The target is then called on the modified (usually shortened) argument list. 2697 * <p> 2698 * If the filter returns a value, the target must accept that value as 2699 * its argument in position {@code pos}, preceded and/or followed by 2700 * any arguments not passed to the filter. 2701 * If the filter returns void, the target must accept all arguments 2702 * not passed to the filter. 2703 * No arguments are reordered, and a result returned from the filter 2704 * replaces (in order) the whole subsequence of arguments originally 2705 * passed to the adapter. 2706 * <p> 2707 * The argument types (if any) of the filter 2708 * replace zero or one argument types of the target, at position {@code pos}, 2709 * in the resulting adapted method handle. 2710 * The return type of the filter (if any) must be identical to the 2711 * argument type of the target at position {@code pos}, and that target argument 2712 * is supplied by the return value of the filter. 2713 * <p> 2714 * In all cases, {@code pos} must be greater than or equal to zero, and 2715 * {@code pos} must also be less than or equal to the target's arity. 2716 * <p><b>Example:</b> 2717 * <blockquote><pre>{@code 2718 import static java.lang.invoke.MethodHandles.*; 2719 import static java.lang.invoke.MethodType.*; 2720 ... 2721 MethodHandle deepToString = publicLookup() 2722 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 2723 2724 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 2725 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 2726 2727 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 2728 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 2729 2730 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 2731 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 2732 assertEquals("[top, [up, down], strange]", 2733 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 2734 2735 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 2736 assertEquals("[top, [up, down], [strange]]", 2737 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 2738 2739 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 2740 assertEquals("[top, [[up, down, strange], charm], bottom]", 2741 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 2742 * }</pre></blockquote> 2743 * <p> Here is pseudocode for the resulting adapter: 2744 * <blockquote><pre>{@code 2745 * T target(A...,V,C...); 2746 * V filter(B...); 2747 * T adapter(A... a,B... b,C... c) { 2748 * V v = filter(b...); 2749 * return target(a...,v,c...); 2750 * } 2751 * // and if the filter has no arguments: 2752 * T target2(A...,V,C...); 2753 * V filter2(); 2754 * T adapter2(A... a,C... c) { 2755 * V v = filter2(); 2756 * return target2(a...,v,c...); 2757 * } 2758 * // and if the filter has a void return: 2759 * T target3(A...,C...); 2760 * void filter3(B...); 2761 * void adapter3(A... a,B... b,C... c) { 2762 * filter3(b...); 2763 * return target3(a...,c...); 2764 * } 2765 * }</pre></blockquote> 2766 * <p> 2767 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 2768 * one which first "folds" the affected arguments, and then drops them, in separate 2769 * steps as follows: 2770 * <blockquote><pre>{@code 2771 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 2772 * mh = MethodHandles.foldArguments(mh, coll); //step 1 2773 * }</pre></blockquote> 2774 * If the target method handle consumes no arguments besides than the result 2775 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 2776 * is equivalent to {@code filterReturnValue(coll, mh)}. 2777 * If the filter method handle {@code coll} consumes one argument and produces 2778 * a non-void result, then {@code collectArguments(mh, N, coll)} 2779 * is equivalent to {@code filterArguments(mh, N, coll)}. 2780 * Other equivalences are possible but would require argument permutation. 2781 * 2782 * @param target the method handle to invoke after filtering the subsequence of arguments 2783 * @param pos the position of the first adapter argument to pass to the filter, 2784 * and/or the target argument which receives the result of the filter 2785 * @param filter method handle to call on the subsequence of arguments 2786 * @return method handle which incorporates the specified argument subsequence filtering logic 2787 * @throws NullPointerException if either argument is null 2788 * @throws IllegalArgumentException if the return type of {@code filter} 2789 * is non-void and is not the same as the {@code pos} argument of the target, 2790 * or if {@code pos} is not between 0 and the target's arity, inclusive, 2791 * or if the resulting method handle's type would have 2792 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2793 * @see MethodHandles#foldArguments 2794 * @see MethodHandles#filterArguments 2795 * @see MethodHandles#filterReturnValue 2796 */ 2797 public static 2798 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 2799 MethodType newType = collectArgumentsChecks(target, pos, filter); 2800 if (USE_LAMBDA_FORM_EDITOR) { 2801 MethodType collectorType = filter.type(); 2802 BoundMethodHandle result = target.rebind(); 2803 LambdaForm lform; 2804 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { 2805 lform = result.editor().collectArgumentArrayForm(1 + pos, filter); 2806 if (lform != null) { 2807 return result.copyWith(newType, lform); 2808 } 2809 } 2810 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); 2811 return result.copyWithExtendL(newType, lform, filter); 2812 } else { 2813 return MethodHandleImpl.makeCollectArguments(target, filter, pos, false); 2814 } 2815 } 2816 2817 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 2818 MethodType targetType = target.type(); 2819 MethodType filterType = filter.type(); 2820 Class<?> rtype = filterType.returnType(); 2821 List<Class<?>> filterArgs = filterType.parameterList(); 2822 if (rtype == void.class) { 2823 return targetType.insertParameterTypes(pos, filterArgs); 2824 } 2825 if (rtype != targetType.parameterType(pos)) { 2826 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 2827 } 2828 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 2829 } 2830 2831 /** 2832 * Adapts a target method handle by post-processing 2833 * its return value (if any) with a filter (another method handle). 2834 * The result of the filter is returned from the adapter. 2835 * <p> 2836 * If the target returns a value, the filter must accept that value as 2837 * its only argument. 2838 * If the target returns void, the filter must accept no arguments. 2839 * <p> 2840 * The return type of the filter 2841 * replaces the return type of the target 2842 * in the resulting adapted method handle. 2843 * The argument type of the filter (if any) must be identical to the 2844 * return type of the target. 2845 * <p><b>Example:</b> 2846 * <blockquote><pre>{@code 2847 import static java.lang.invoke.MethodHandles.*; 2848 import static java.lang.invoke.MethodType.*; 2849 ... 2850 MethodHandle cat = lookup().findVirtual(String.class, 2851 "concat", methodType(String.class, String.class)); 2852 MethodHandle length = lookup().findVirtual(String.class, 2853 "length", methodType(int.class)); 2854 System.out.println((String) cat.invokeExact("x", "y")); // xy 2855 MethodHandle f0 = filterReturnValue(cat, length); 2856 System.out.println((int) f0.invokeExact("x", "y")); // 2 2857 * }</pre></blockquote> 2858 * <p> Here is pseudocode for the resulting adapter: 2859 * <blockquote><pre>{@code 2860 * V target(A...); 2861 * T filter(V); 2862 * T adapter(A... a) { 2863 * V v = target(a...); 2864 * return filter(v); 2865 * } 2866 * // and if the target has a void return: 2867 * void target2(A...); 2868 * T filter2(); 2869 * T adapter2(A... a) { 2870 * target2(a...); 2871 * return filter2(); 2872 * } 2873 * // and if the filter has a void return: 2874 * V target3(A...); 2875 * void filter3(V); 2876 * void adapter3(A... a) { 2877 * V v = target3(a...); 2878 * filter3(v); 2879 * } 2880 * }</pre></blockquote> 2881 * @param target the method handle to invoke before filtering the return value 2882 * @param filter method handle to call on the return value 2883 * @return method handle which incorporates the specified return value filtering logic 2884 * @throws NullPointerException if either argument is null 2885 * @throws IllegalArgumentException if the argument list of {@code filter} 2886 * does not match the return type of target as described above 2887 */ 2888 public static 2889 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 2890 MethodType targetType = target.type(); 2891 MethodType filterType = filter.type(); 2892 filterReturnValueChecks(targetType, filterType); 2893 if (USE_LAMBDA_FORM_EDITOR) { 2894 BoundMethodHandle result = target.rebind(); 2895 BasicType rtype = BasicType.basicType(filterType.returnType()); 2896 LambdaForm lform = result.editor().filterReturnForm(rtype, false); 2897 MethodType newType = targetType.changeReturnType(filterType.returnType()); 2898 result = result.copyWithExtendL(newType, lform, filter); 2899 return result; 2900 } else { 2901 return MethodHandleImpl.makeCollectArguments(filter, target, 0, false); 2902 } 2903 } 2904 2905 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 2906 Class<?> rtype = targetType.returnType(); 2907 int filterValues = filterType.parameterCount(); 2908 if (filterValues == 0 2909 ? (rtype != void.class) 2910 : (rtype != filterType.parameterType(0))) 2911 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 2912 } 2913 2914 /** 2915 * Adapts a target method handle by pre-processing 2916 * some of its arguments, and then calling the target with 2917 * the result of the pre-processing, inserted into the original 2918 * sequence of arguments. 2919 * <p> 2920 * The pre-processing is performed by {@code combiner}, a second method handle. 2921 * Of the arguments passed to the adapter, the first {@code N} arguments 2922 * are copied to the combiner, which is then called. 2923 * (Here, {@code N} is defined as the parameter count of the combiner.) 2924 * After this, control passes to the target, with any result 2925 * from the combiner inserted before the original {@code N} incoming 2926 * arguments. 2927 * <p> 2928 * If the combiner returns a value, the first parameter type of the target 2929 * must be identical with the return type of the combiner, and the next 2930 * {@code N} parameter types of the target must exactly match the parameters 2931 * of the combiner. 2932 * <p> 2933 * If the combiner has a void return, no result will be inserted, 2934 * and the first {@code N} parameter types of the target 2935 * must exactly match the parameters of the combiner. 2936 * <p> 2937 * The resulting adapter is the same type as the target, except that the 2938 * first parameter type is dropped, 2939 * if it corresponds to the result of the combiner. 2940 * <p> 2941 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 2942 * that either the combiner or the target does not wish to receive. 2943 * If some of the incoming arguments are destined only for the combiner, 2944 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 2945 * arguments will not need to be live on the stack on entry to the 2946 * target.) 2947 * <p><b>Example:</b> 2948 * <blockquote><pre>{@code 2949 import static java.lang.invoke.MethodHandles.*; 2950 import static java.lang.invoke.MethodType.*; 2951 ... 2952 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 2953 "println", methodType(void.class, String.class)) 2954 .bindTo(System.out); 2955 MethodHandle cat = lookup().findVirtual(String.class, 2956 "concat", methodType(String.class, String.class)); 2957 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 2958 MethodHandle catTrace = foldArguments(cat, trace); 2959 // also prints "boo": 2960 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 2961 * }</pre></blockquote> 2962 * <p> Here is pseudocode for the resulting adapter: 2963 * <blockquote><pre>{@code 2964 * // there are N arguments in A... 2965 * T target(V, A[N]..., B...); 2966 * V combiner(A...); 2967 * T adapter(A... a, B... b) { 2968 * V v = combiner(a...); 2969 * return target(v, a..., b...); 2970 * } 2971 * // and if the combiner has a void return: 2972 * T target2(A[N]..., B...); 2973 * void combiner2(A...); 2974 * T adapter2(A... a, B... b) { 2975 * combiner2(a...); 2976 * return target2(a..., b...); 2977 * } 2978 * }</pre></blockquote> 2979 * @param target the method handle to invoke after arguments are combined 2980 * @param combiner method handle to call initially on the incoming arguments 2981 * @return method handle which incorporates the specified argument folding logic 2982 * @throws NullPointerException if either argument is null 2983 * @throws IllegalArgumentException if {@code combiner}'s return type 2984 * is non-void and not the same as the first argument type of 2985 * the target, or if the initial {@code N} argument types 2986 * of the target 2987 * (skipping one matching the {@code combiner}'s return type) 2988 * are not identical with the argument types of {@code combiner} 2989 */ 2990 public static 2991 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 2992 int foldPos = 0; 2993 MethodType targetType = target.type(); 2994 MethodType combinerType = combiner.type(); 2995 Class<?> rtype = foldArgumentChecks(foldPos, targetType, combinerType); 2996 if (USE_LAMBDA_FORM_EDITOR) { 2997 BoundMethodHandle result = target.rebind(); 2998 boolean dropResult = (rtype == void.class); 2999 // Note: This may cache too many distinct LFs. Consider backing off to varargs code. 3000 LambdaForm lform = result.editor().foldArgumentsForm(1 + foldPos, dropResult, combinerType.basicType()); 3001 MethodType newType = targetType; 3002 if (!dropResult) 3003 newType = newType.dropParameterTypes(foldPos, foldPos + 1); 3004 result = result.copyWithExtendL(newType, lform, combiner); 3005 return result; 3006 } else { 3007 return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true); 3008 } 3009 } 3010 3011 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 3012 int foldArgs = combinerType.parameterCount(); 3013 Class<?> rtype = combinerType.returnType(); 3014 int foldVals = rtype == void.class ? 0 : 1; 3015 int afterInsertPos = foldPos + foldVals; 3016 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 3017 if (ok && !(combinerType.parameterList() 3018 .equals(targetType.parameterList().subList(afterInsertPos, 3019 afterInsertPos + foldArgs)))) 3020 ok = false; 3021 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(0)) 3022 ok = false; 3023 if (!ok) 3024 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3025 return rtype; 3026 } 3027 3028 /** 3029 * Makes a method handle which adapts a target method handle, 3030 * by guarding it with a test, a boolean-valued method handle. 3031 * If the guard fails, a fallback handle is called instead. 3032 * All three method handles must have the same corresponding 3033 * argument and return types, except that the return type 3034 * of the test must be boolean, and the test is allowed 3035 * to have fewer arguments than the other two method handles. 3036 * <p> Here is pseudocode for the resulting adapter: 3037 * <blockquote><pre>{@code 3038 * boolean test(A...); 3039 * T target(A...,B...); 3040 * T fallback(A...,B...); 3041 * T adapter(A... a,B... b) { 3042 * if (test(a...)) 3043 * return target(a..., b...); 3044 * else 3045 * return fallback(a..., b...); 3046 * } 3047 * }</pre></blockquote> 3048 * Note that the test arguments ({@code a...} in the pseudocode) cannot 3049 * be modified by execution of the test, and so are passed unchanged 3050 * from the caller to the target or fallback as appropriate. 3051 * @param test method handle used for test, must return boolean 3052 * @param target method handle to call if test passes 3053 * @param fallback method handle to call if test fails 3054 * @return method handle which incorporates the specified if/then/else logic 3055 * @throws NullPointerException if any argument is null 3056 * @throws IllegalArgumentException if {@code test} does not return boolean, 3057 * or if all three method types do not match (with the return 3058 * type of {@code test} changed to match that of the target). 3059 */ 3060 public static 3061 MethodHandle guardWithTest(MethodHandle test, 3062 MethodHandle target, 3063 MethodHandle fallback) { 3064 MethodType gtype = test.type(); 3065 MethodType ttype = target.type(); 3066 MethodType ftype = fallback.type(); 3067 if (!ttype.equals(ftype)) 3068 throw misMatchedTypes("target and fallback types", ttype, ftype); 3069 if (gtype.returnType() != boolean.class) 3070 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 3071 List<Class<?>> targs = ttype.parameterList(); 3072 List<Class<?>> gargs = gtype.parameterList(); 3073 if (!targs.equals(gargs)) { 3074 int gpc = gargs.size(), tpc = targs.size(); 3075 if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs)) 3076 throw misMatchedTypes("target and test types", ttype, gtype); 3077 test = dropArguments(test, gpc, targs.subList(gpc, tpc)); 3078 gtype = test.type(); 3079 } 3080 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 3081 } 3082 3083 static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) { 3084 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 3085 } 3086 3087 /** 3088 * Makes a method handle which adapts a target method handle, 3089 * by running it inside an exception handler. 3090 * If the target returns normally, the adapter returns that value. 3091 * If an exception matching the specified type is thrown, the fallback 3092 * handle is called instead on the exception, plus the original arguments. 3093 * <p> 3094 * The target and handler must have the same corresponding 3095 * argument and return types, except that handler may omit trailing arguments 3096 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 3097 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 3098 * <p> Here is pseudocode for the resulting adapter: 3099 * <blockquote><pre>{@code 3100 * T target(A..., B...); 3101 * T handler(ExType, A...); 3102 * T adapter(A... a, B... b) { 3103 * try { 3104 * return target(a..., b...); 3105 * } catch (ExType ex) { 3106 * return handler(ex, a...); 3107 * } 3108 * } 3109 * }</pre></blockquote> 3110 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 3111 * be modified by execution of the target, and so are passed unchanged 3112 * from the caller to the handler, if the handler is invoked. 3113 * <p> 3114 * The target and handler must return the same type, even if the handler 3115 * always throws. (This might happen, for instance, because the handler 3116 * is simulating a {@code finally} clause). 3117 * To create such a throwing handler, compose the handler creation logic 3118 * with {@link #throwException throwException}, 3119 * in order to create a method handle of the correct return type. 3120 * @param target method handle to call 3121 * @param exType the type of exception which the handler will catch 3122 * @param handler method handle to call if a matching exception is thrown 3123 * @return method handle which incorporates the specified try/catch logic 3124 * @throws NullPointerException if any argument is null 3125 * @throws IllegalArgumentException if {@code handler} does not accept 3126 * the given exception type, or if the method handle types do 3127 * not match in their return types and their 3128 * corresponding parameters 3129 */ 3130 public static 3131 MethodHandle catchException(MethodHandle target, 3132 Class<? extends Throwable> exType, 3133 MethodHandle handler) { 3134 MethodType ttype = target.type(); 3135 MethodType htype = handler.type(); 3136 if (htype.parameterCount() < 1 || 3137 !htype.parameterType(0).isAssignableFrom(exType)) 3138 throw newIllegalArgumentException("handler does not accept exception type "+exType); 3139 if (htype.returnType() != ttype.returnType()) 3140 throw misMatchedTypes("target and handler return types", ttype, htype); 3141 List<Class<?>> targs = ttype.parameterList(); 3142 List<Class<?>> hargs = htype.parameterList(); 3143 hargs = hargs.subList(1, hargs.size()); // omit leading parameter from handler 3144 if (!targs.equals(hargs)) { 3145 int hpc = hargs.size(), tpc = targs.size(); 3146 if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs)) 3147 throw misMatchedTypes("target and handler types", ttype, htype); 3148 handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc)); 3149 htype = handler.type(); 3150 } 3151 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 3152 } 3153 3154 /** 3155 * Produces a method handle which will throw exceptions of the given {@code exType}. 3156 * The method handle will accept a single argument of {@code exType}, 3157 * and immediately throw it as an exception. 3158 * The method type will nominally specify a return of {@code returnType}. 3159 * The return type may be anything convenient: It doesn't matter to the 3160 * method handle's behavior, since it will never return normally. 3161 * @param returnType the return type of the desired method handle 3162 * @param exType the parameter type of the desired method handle 3163 * @return method handle which can throw the given exceptions 3164 * @throws NullPointerException if either argument is null 3165 */ 3166 public static 3167 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 3168 if (!Throwable.class.isAssignableFrom(exType)) 3169 throw new ClassCastException(exType.getName()); 3170 return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType)); 3171 } 3172 }