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