1 /* 2 * Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import java.lang.reflect.*; 29 import java.util.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 * 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 if (refKind == REF_invokeSpecial && 1616 refc != lookupClass() && 1617 !refc.isInterface() && 1618 refc != lookupClass().getSuperclass() && 1619 refc.isAssignableFrom(lookupClass())) { 1620 assert(!method.getName().equals("<init>")); // not this code path 1621 // Per JVMS 6.5, desc. of invokespecial instruction: 1622 // If the method is in a superclass of the LC, 1623 // and if our original search was above LC.super, 1624 // repeat the search (symbolic lookup) from LC.super 1625 // and continue with the direct superclass of that class, 1626 // and so forth, until a match is found or no further superclasses exist. 1627 // FIXME: MemberName.resolve should handle this instead. 1628 Class<?> refcAsSuper = lookupClass(); 1629 MemberName m2; 1630 do { 1631 refcAsSuper = refcAsSuper.getSuperclass(); 1632 m2 = new MemberName(refcAsSuper, 1633 method.getName(), 1634 method.getMethodType(), 1635 REF_invokeSpecial); 1636 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); 1637 } while (m2 == null && // no method is found yet 1638 refc != refcAsSuper); // search up to refc 1639 if (m2 == null) throw new InternalError(method.toString()); 1640 method = m2; 1641 refc = refcAsSuper; 1642 // redo basic checks 1643 checkMethod(refKind, refc, method); 1644 } 1645 1646 MethodHandle mh = DirectMethodHandle.make(refKind, refc, method); 1647 mh = maybeBindCaller(method, mh, callerClass); 1648 mh = mh.setVarargs(method); 1649 // Optionally narrow the receiver argument to refc using restrictReceiver. 1650 if (doRestrict && 1651 (refKind == REF_invokeSpecial || 1652 (MethodHandleNatives.refKindHasReceiver(refKind) && 1653 restrictProtectedReceiver(method)))) 1654 mh = restrictReceiver(method, mh, lookupClass()); 1655 return mh; 1656 } 1657 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, 1658 Class<?> callerClass) 1659 throws IllegalAccessException { 1660 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) 1661 return mh; 1662 Class<?> hostClass = lookupClass; 1663 if (!hasPrivateAccess()) // caller must have private access 1664 hostClass = callerClass; // callerClass came from a security manager style stack walk 1665 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); 1666 // Note: caller will apply varargs after this step happens. 1667 return cbmh; 1668 } 1669 /** Check access and get the requested field. */ 1670 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 1671 final boolean checkSecurity = true; 1672 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 1673 } 1674 /** Check access and get the requested field, eliding security manager checks. */ 1675 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { 1676 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1677 return getDirectFieldCommon(refKind, refc, field, checkSecurity); 1678 } 1679 /** Common code for all fields; do not call directly except from immediately above. */ 1680 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, 1681 boolean checkSecurity) throws IllegalAccessException { 1682 checkField(refKind, refc, field); 1683 // Optionally check with the security manager; this isn't needed for unreflect* calls. 1684 if (checkSecurity) 1685 checkSecurityManager(refc, field); 1686 MethodHandle mh = DirectMethodHandle.make(refc, field); 1687 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && 1688 restrictProtectedReceiver(field)); 1689 if (doRestrict) 1690 mh = restrictReceiver(field, mh, lookupClass()); 1691 return mh; 1692 } 1693 /** Check access and get the requested constructor. */ 1694 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { 1695 final boolean checkSecurity = true; 1696 return getDirectConstructorCommon(refc, ctor, checkSecurity); 1697 } 1698 /** Check access and get the requested constructor, eliding security manager checks. */ 1699 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { 1700 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants 1701 return getDirectConstructorCommon(refc, ctor, checkSecurity); 1702 } 1703 /** Common code for all constructors; do not call directly except from immediately above. */ 1704 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, 1705 boolean checkSecurity) throws IllegalAccessException { 1706 assert(ctor.isConstructor()); 1707 checkAccess(REF_newInvokeSpecial, refc, ctor); 1708 // Optionally check with the security manager; this isn't needed for unreflect* calls. 1709 if (checkSecurity) 1710 checkSecurityManager(refc, ctor); 1711 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here 1712 return DirectMethodHandle.make(ctor).setVarargs(ctor); 1713 } 1714 1715 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: 1716 */ 1717 /*non-public*/ 1718 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { 1719 if (!(type instanceof Class || type instanceof MethodType)) 1720 throw new InternalError("unresolved MemberName"); 1721 MemberName member = new MemberName(refKind, defc, name, type); 1722 MethodHandle mh = LOOKASIDE_TABLE.get(member); 1723 if (mh != null) { 1724 checkSymbolicClass(defc); 1725 return mh; 1726 } 1727 // Treat MethodHandle.invoke and invokeExact specially. 1728 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { 1729 mh = findVirtualForMH(member.getName(), member.getMethodType()); 1730 if (mh != null) { 1731 return mh; 1732 } 1733 } 1734 MemberName resolved = resolveOrFail(refKind, member); 1735 mh = getDirectMethodForConstant(refKind, defc, resolved); 1736 if (mh instanceof DirectMethodHandle 1737 && canBeCached(refKind, defc, resolved)) { 1738 MemberName key = mh.internalMemberName(); 1739 if (key != null) { 1740 key = key.asNormalOriginal(); 1741 } 1742 if (member.equals(key)) { // better safe than sorry 1743 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); 1744 } 1745 } 1746 return mh; 1747 } 1748 private 1749 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { 1750 if (refKind == REF_invokeSpecial) { 1751 return false; 1752 } 1753 if (!Modifier.isPublic(defc.getModifiers()) || 1754 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || 1755 !member.isPublic() || 1756 member.isCallerSensitive()) { 1757 return false; 1758 } 1759 ClassLoader loader = defc.getClassLoader(); 1760 if (!sun.misc.VM.isSystemDomainLoader(loader)) { 1761 ClassLoader sysl = ClassLoader.getSystemClassLoader(); 1762 boolean found = false; 1763 while (sysl != null) { 1764 if (loader == sysl) { found = true; break; } 1765 sysl = sysl.getParent(); 1766 } 1767 if (!found) { 1768 return false; 1769 } 1770 } 1771 try { 1772 MemberName resolved2 = publicLookup().resolveOrFail(refKind, 1773 new MemberName(refKind, defc, member.getName(), member.getType())); 1774 checkSecurityManager(defc, resolved2); 1775 } catch (ReflectiveOperationException | SecurityException ex) { 1776 return false; 1777 } 1778 return true; 1779 } 1780 private 1781 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) 1782 throws ReflectiveOperationException { 1783 if (MethodHandleNatives.refKindIsField(refKind)) { 1784 return getDirectFieldNoSecurityManager(refKind, defc, member); 1785 } else if (MethodHandleNatives.refKindIsMethod(refKind)) { 1786 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); 1787 } else if (refKind == REF_newInvokeSpecial) { 1788 return getDirectConstructorNoSecurityManager(defc, member); 1789 } 1790 // oops 1791 throw newIllegalArgumentException("bad MethodHandle constant #"+member); 1792 } 1793 1794 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); 1795 } 1796 1797 /** 1798 * Produces a method handle giving read access to elements of an array. 1799 * The type of the method handle will have a return type of the array's 1800 * element type. Its first argument will be the array type, 1801 * and the second will be {@code int}. 1802 * @param arrayClass an array type 1803 * @return a method handle which can load values from the given array type 1804 * @throws NullPointerException if the argument is null 1805 * @throws IllegalArgumentException if arrayClass is not an array type 1806 */ 1807 public static 1808 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 1809 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false); 1810 } 1811 1812 /** 1813 * Produces a method handle giving write access to elements of an array. 1814 * The type of the method handle will have a void return type. 1815 * Its last argument will be the array's element type. 1816 * The first and second arguments will be the array type and int. 1817 * @param arrayClass the class of an array 1818 * @return a method handle which can store values into the array type 1819 * @throws NullPointerException if the argument is null 1820 * @throws IllegalArgumentException if arrayClass is not an array type 1821 */ 1822 public static 1823 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 1824 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true); 1825 } 1826 1827 /// method handle invocation (reflective style) 1828 1829 /** 1830 * Produces a method handle which will invoke any method handle of the 1831 * given {@code type}, with a given number of trailing arguments replaced by 1832 * a single trailing {@code Object[]} array. 1833 * The resulting invoker will be a method handle with the following 1834 * arguments: 1835 * <ul> 1836 * <li>a single {@code MethodHandle} target 1837 * <li>zero or more leading values (counted by {@code leadingArgCount}) 1838 * <li>an {@code Object[]} array containing trailing arguments 1839 * </ul> 1840 * <p> 1841 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 1842 * the indicated {@code type}. 1843 * That is, if the target is exactly of the given {@code type}, it will behave 1844 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 1845 * is used to convert the target to the required {@code type}. 1846 * <p> 1847 * The type of the returned invoker will not be the given {@code type}, but rather 1848 * will have all parameters except the first {@code leadingArgCount} 1849 * replaced by a single array of type {@code Object[]}, which will be 1850 * the final parameter. 1851 * <p> 1852 * Before invoking its target, the invoker will spread the final array, apply 1853 * reference casts as necessary, and unbox and widen primitive arguments. 1854 * If, when the invoker is called, the supplied array argument does 1855 * not have the correct number of elements, the invoker will throw 1856 * an {@link IllegalArgumentException} instead of invoking the target. 1857 * <p> 1858 * This method is equivalent to the following code (though it may be more efficient): 1859 * <blockquote><pre>{@code 1860 MethodHandle invoker = MethodHandles.invoker(type); 1861 int spreadArgCount = type.parameterCount() - leadingArgCount; 1862 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 1863 return invoker; 1864 * }</pre></blockquote> 1865 * This method throws no reflective or security exceptions. 1866 * @param type the desired target type 1867 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 1868 * @return a method handle suitable for invoking any method handle of the given type 1869 * @throws NullPointerException if {@code type} is null 1870 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 1871 * the range from 0 to {@code type.parameterCount()} inclusive, 1872 * or if the resulting method handle's type would have 1873 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1874 */ 1875 static public 1876 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 1877 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 1878 throw new IllegalArgumentException("bad argument count "+leadingArgCount); 1879 return type.invokers().spreadInvoker(leadingArgCount); 1880 } 1881 1882 /** 1883 * Produces a special <em>invoker method handle</em> which can be used to 1884 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 1885 * The resulting invoker will have a type which is 1886 * exactly equal to the desired type, except that it will accept 1887 * an additional leading argument of type {@code MethodHandle}. 1888 * <p> 1889 * This method is equivalent to the following code (though it may be more efficient): 1890 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 1891 * 1892 * <p style="font-size:smaller;"> 1893 * <em>Discussion:</em> 1894 * Invoker method handles can be useful when working with variable method handles 1895 * of unknown types. 1896 * For example, to emulate an {@code invokeExact} call to a variable method 1897 * handle {@code M}, extract its type {@code T}, 1898 * look up the invoker method {@code X} for {@code T}, 1899 * and call the invoker method, as {@code X.invoke(T, A...)}. 1900 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 1901 * is unknown.) 1902 * If spreading, collecting, or other argument transformations are required, 1903 * they can be applied once to the invoker {@code X} and reused on many {@code M} 1904 * method handle values, as long as they are compatible with the type of {@code X}. 1905 * <p style="font-size:smaller;"> 1906 * <em>(Note: The invoker method is not available via the Core Reflection API. 1907 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 1908 * on the declared {@code invokeExact} or {@code invoke} method will raise an 1909 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 1910 * <p> 1911 * This method throws no reflective or security exceptions. 1912 * @param type the desired target type 1913 * @return a method handle suitable for invoking any method handle of the given type 1914 * @throws IllegalArgumentException if the resulting method handle's type would have 1915 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1916 */ 1917 static public 1918 MethodHandle exactInvoker(MethodType type) { 1919 return type.invokers().exactInvoker(); 1920 } 1921 1922 /** 1923 * Produces a special <em>invoker method handle</em> which can be used to 1924 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 1925 * The resulting invoker will have a type which is 1926 * exactly equal to the desired type, except that it will accept 1927 * an additional leading argument of type {@code MethodHandle}. 1928 * <p> 1929 * Before invoking its target, if the target differs from the expected type, 1930 * the invoker will apply reference casts as 1931 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 1932 * Similarly, the return value will be converted as necessary. 1933 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 1934 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 1935 * <p> 1936 * This method is equivalent to the following code (though it may be more efficient): 1937 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 1938 * <p style="font-size:smaller;"> 1939 * <em>Discussion:</em> 1940 * A {@linkplain MethodType#genericMethodType general method type} is one which 1941 * mentions only {@code Object} arguments and return values. 1942 * An invoker for such a type is capable of calling any method handle 1943 * of the same arity as the general type. 1944 * <p style="font-size:smaller;"> 1945 * <em>(Note: The invoker method is not available via the Core Reflection API. 1946 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 1947 * on the declared {@code invokeExact} or {@code invoke} method will raise an 1948 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 1949 * <p> 1950 * This method throws no reflective or security exceptions. 1951 * @param type the desired target type 1952 * @return a method handle suitable for invoking any method handle convertible to the given type 1953 * @throws IllegalArgumentException if the resulting method handle's type would have 1954 * <a href="MethodHandle.html#maxarity">too many parameters</a> 1955 */ 1956 static public 1957 MethodHandle invoker(MethodType type) { 1958 return type.invokers().generalInvoker(); 1959 } 1960 1961 static /*non-public*/ 1962 MethodHandle basicInvoker(MethodType type) { 1963 return type.form().basicInvoker(); 1964 } 1965 1966 /// method handle modification (creation from other method handles) 1967 1968 /** 1969 * Produces a method handle which adapts the type of the 1970 * given method handle to a new type by pairwise argument and return type conversion. 1971 * The original type and new type must have the same number of arguments. 1972 * The resulting method handle is guaranteed to report a type 1973 * which is equal to the desired new type. 1974 * <p> 1975 * If the original type and new type are equal, returns target. 1976 * <p> 1977 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 1978 * and some additional conversions are also applied if those conversions fail. 1979 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 1980 * if possible, before or instead of any conversions done by {@code asType}: 1981 * <ul> 1982 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 1983 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 1984 * (This treatment of interfaces follows the usage of the bytecode verifier.) 1985 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 1986 * the boolean is converted to a byte value, 1 for true, 0 for false. 1987 * (This treatment follows the usage of the bytecode verifier.) 1988 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 1989 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 1990 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 1991 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 1992 * then a Java casting conversion (JLS 5.5) is applied. 1993 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 1994 * widening and/or narrowing.) 1995 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 1996 * conversion will be applied at runtime, possibly followed 1997 * by a Java casting conversion (JLS 5.5) on the primitive value, 1998 * possibly followed by a conversion from byte to boolean by testing 1999 * the low-order bit. 2000 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2001 * and if the reference is null at runtime, a zero value is introduced. 2002 * </ul> 2003 * @param target the method handle to invoke after arguments are retyped 2004 * @param newType the expected type of the new method handle 2005 * @return a method handle which delegates to the target after performing 2006 * any necessary argument conversions, and arranges for any 2007 * necessary return value conversions 2008 * @throws NullPointerException if either argument is null 2009 * @throws WrongMethodTypeException if the conversion cannot be made 2010 * @see MethodHandle#asType 2011 */ 2012 public static 2013 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2014 if (!target.type().isCastableTo(newType)) { 2015 throw new WrongMethodTypeException("cannot explicitly cast "+target+" to "+newType); 2016 } 2017 return MethodHandleImpl.makePairwiseConvert(target, newType, 2); 2018 } 2019 2020 /** 2021 * Produces a method handle which adapts the calling sequence of the 2022 * given method handle to a new type, by reordering the arguments. 2023 * The resulting method handle is guaranteed to report a type 2024 * which is equal to the desired new type. 2025 * <p> 2026 * The given array controls the reordering. 2027 * Call {@code #I} the number of incoming parameters (the value 2028 * {@code newType.parameterCount()}, and call {@code #O} the number 2029 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2030 * Then the length of the reordering array must be {@code #O}, 2031 * and each element must be a non-negative number less than {@code #I}. 2032 * For every {@code N} less than {@code #O}, the {@code N}-th 2033 * outgoing argument will be taken from the {@code I}-th incoming 2034 * argument, where {@code I} is {@code reorder[N]}. 2035 * <p> 2036 * No argument or return value conversions are applied. 2037 * The type of each incoming argument, as determined by {@code newType}, 2038 * must be identical to the type of the corresponding outgoing parameter 2039 * or parameters in the target method handle. 2040 * The return type of {@code newType} must be identical to the return 2041 * type of the original target. 2042 * <p> 2043 * The reordering array need not specify an actual permutation. 2044 * An incoming argument will be duplicated if its index appears 2045 * more than once in the array, and an incoming argument will be dropped 2046 * if its index does not appear in the array. 2047 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2048 * incoming arguments which are not mentioned in the reordering array 2049 * are may be any type, as determined only by {@code newType}. 2050 * <blockquote><pre>{@code 2051 import static java.lang.invoke.MethodHandles.*; 2052 import static java.lang.invoke.MethodType.*; 2053 ... 2054 MethodType intfn1 = methodType(int.class, int.class); 2055 MethodType intfn2 = methodType(int.class, int.class, int.class); 2056 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2057 assert(sub.type().equals(intfn2)); 2058 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2059 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2060 assert((int)rsub.invokeExact(1, 100) == 99); 2061 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2062 assert(add.type().equals(intfn2)); 2063 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2064 assert(twice.type().equals(intfn1)); 2065 assert((int)twice.invokeExact(21) == 42); 2066 * }</pre></blockquote> 2067 * @param target the method handle to invoke after arguments are reordered 2068 * @param newType the expected type of the new method handle 2069 * @param reorder an index array which controls the reordering 2070 * @return a method handle which delegates to the target after it 2071 * drops unused arguments and moves and/or duplicates the other arguments 2072 * @throws NullPointerException if any argument is null 2073 * @throws IllegalArgumentException if the index array length is not equal to 2074 * the arity of the target, or if any index array element 2075 * not a valid index for a parameter of {@code newType}, 2076 * or if two corresponding parameter types in 2077 * {@code target.type()} and {@code newType} are not identical, 2078 */ 2079 public static 2080 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2081 reorder = reorder.clone(); 2082 checkReorder(reorder, newType, target.type()); 2083 return target.permuteArguments(newType, reorder); 2084 } 2085 2086 private static void checkReorder(int[] reorder, MethodType newType, MethodType oldType) { 2087 if (newType.returnType() != oldType.returnType()) 2088 throw newIllegalArgumentException("return types do not match", 2089 oldType, newType); 2090 if (reorder.length == oldType.parameterCount()) { 2091 int limit = newType.parameterCount(); 2092 boolean bad = false; 2093 for (int j = 0; j < reorder.length; j++) { 2094 int i = reorder[j]; 2095 if (i < 0 || i >= limit) { 2096 bad = true; break; 2097 } 2098 Class<?> src = newType.parameterType(i); 2099 Class<?> dst = oldType.parameterType(j); 2100 if (src != dst) 2101 throw newIllegalArgumentException("parameter types do not match after reorder", 2102 oldType, newType); 2103 } 2104 if (!bad) return; 2105 } 2106 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 2107 } 2108 2109 /** 2110 * Produces a method handle of the requested return type which returns the given 2111 * constant value every time it is invoked. 2112 * <p> 2113 * Before the method handle is returned, the passed-in value is converted to the requested type. 2114 * If the requested type is primitive, widening primitive conversions are attempted, 2115 * else reference conversions are attempted. 2116 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 2117 * @param type the return type of the desired method handle 2118 * @param value the value to return 2119 * @return a method handle of the given return type and no arguments, which always returns the given value 2120 * @throws NullPointerException if the {@code type} argument is null 2121 * @throws ClassCastException if the value cannot be converted to the required return type 2122 * @throws IllegalArgumentException if the given type is {@code void.class} 2123 */ 2124 public static 2125 MethodHandle constant(Class<?> type, Object value) { 2126 if (type.isPrimitive()) { 2127 if (type == void.class) 2128 throw newIllegalArgumentException("void type"); 2129 Wrapper w = Wrapper.forPrimitiveType(type); 2130 return insertArguments(identity(type), 0, w.convert(value, type)); 2131 } else { 2132 return identity(type).bindTo(type.cast(value)); 2133 } 2134 } 2135 2136 /** 2137 * Produces a method handle which returns its sole argument when invoked. 2138 * @param type the type of the sole parameter and return value of the desired method handle 2139 * @return a unary method handle which accepts and returns the given type 2140 * @throws NullPointerException if the argument is null 2141 * @throws IllegalArgumentException if the given type is {@code void.class} 2142 */ 2143 public static 2144 MethodHandle identity(Class<?> type) { 2145 if (type == void.class) 2146 throw newIllegalArgumentException("void type"); 2147 else if (type == Object.class) 2148 return ValueConversions.identity(); 2149 else if (type.isPrimitive()) 2150 return ValueConversions.identity(Wrapper.forPrimitiveType(type)); 2151 else 2152 return MethodHandleImpl.makeReferenceIdentity(type); 2153 } 2154 2155 /** 2156 * Provides a target method handle with one or more <em>bound arguments</em> 2157 * in advance of the method handle's invocation. 2158 * The formal parameters to the target corresponding to the bound 2159 * arguments are called <em>bound parameters</em>. 2160 * Returns a new method handle which saves away the bound arguments. 2161 * When it is invoked, it receives arguments for any non-bound parameters, 2162 * binds the saved arguments to their corresponding parameters, 2163 * and calls the original target. 2164 * <p> 2165 * The type of the new method handle will drop the types for the bound 2166 * parameters from the original target type, since the new method handle 2167 * will no longer require those arguments to be supplied by its callers. 2168 * <p> 2169 * Each given argument object must match the corresponding bound parameter type. 2170 * If a bound parameter type is a primitive, the argument object 2171 * must be a wrapper, and will be unboxed to produce the primitive value. 2172 * <p> 2173 * The {@code pos} argument selects which parameters are to be bound. 2174 * It may range between zero and <i>N-L</i> (inclusively), 2175 * where <i>N</i> is the arity of the target method handle 2176 * and <i>L</i> is the length of the values array. 2177 * @param target the method handle to invoke after the argument is inserted 2178 * @param pos where to insert the argument (zero for the first) 2179 * @param values the series of arguments to insert 2180 * @return a method handle which inserts an additional argument, 2181 * before calling the original method handle 2182 * @throws NullPointerException if the target or the {@code values} array is null 2183 * @see MethodHandle#bindTo 2184 */ 2185 public static 2186 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 2187 int insCount = values.length; 2188 MethodType oldType = target.type(); 2189 int outargs = oldType.parameterCount(); 2190 int inargs = outargs - insCount; 2191 if (inargs < 0) 2192 throw newIllegalArgumentException("too many values to insert"); 2193 if (pos < 0 || pos > inargs) 2194 throw newIllegalArgumentException("no argument type to append"); 2195 MethodHandle result = target; 2196 for (int i = 0; i < insCount; i++) { 2197 Object value = values[i]; 2198 Class<?> ptype = oldType.parameterType(pos+i); 2199 if (ptype.isPrimitive()) { 2200 BasicType btype = I_TYPE; 2201 Wrapper w = Wrapper.forPrimitiveType(ptype); 2202 switch (w) { 2203 case LONG: btype = J_TYPE; break; 2204 case FLOAT: btype = F_TYPE; break; 2205 case DOUBLE: btype = D_TYPE; break; 2206 } 2207 // perform unboxing and/or primitive conversion 2208 value = w.convert(value, ptype); 2209 result = result.bindArgument(pos, btype, value); 2210 continue; 2211 } 2212 value = ptype.cast(value); // throw CCE if needed 2213 if (pos == 0) { 2214 result = result.bindReceiver(value); 2215 } else { 2216 result = result.bindArgument(pos, L_TYPE, value); 2217 } 2218 } 2219 return result; 2220 } 2221 2222 /** 2223 * Produces a method handle which will discard some dummy arguments 2224 * before calling some other specified <i>target</i> method handle. 2225 * The type of the new method handle will be the same as the target's type, 2226 * except it will also include the dummy argument types, 2227 * at some given position. 2228 * <p> 2229 * The {@code pos} argument may range between zero and <i>N</i>, 2230 * where <i>N</i> is the arity of the target. 2231 * If {@code pos} is zero, the dummy arguments will precede 2232 * the target's real arguments; if {@code pos} is <i>N</i> 2233 * they will come after. 2234 * <p> 2235 * <b>Example:</b> 2236 * <blockquote><pre>{@code 2237 import static java.lang.invoke.MethodHandles.*; 2238 import static java.lang.invoke.MethodType.*; 2239 ... 2240 MethodHandle cat = lookup().findVirtual(String.class, 2241 "concat", methodType(String.class, String.class)); 2242 assertEquals("xy", (String) cat.invokeExact("x", "y")); 2243 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 2244 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 2245 assertEquals(bigType, d0.type()); 2246 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 2247 * }</pre></blockquote> 2248 * <p> 2249 * This method is also equivalent to the following code: 2250 * <blockquote><pre> 2251 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 2252 * </pre></blockquote> 2253 * @param target the method handle to invoke after the arguments are dropped 2254 * @param valueTypes the type(s) of the argument(s) to drop 2255 * @param pos position of first argument to drop (zero for the leftmost) 2256 * @return a method handle which drops arguments of the given types, 2257 * before calling the original method handle 2258 * @throws NullPointerException if the target is null, 2259 * or if the {@code valueTypes} list or any of its elements is null 2260 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 2261 * or if {@code pos} is negative or greater than the arity of the target, 2262 * or if the new method handle's type would have too many parameters 2263 */ 2264 public static 2265 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 2266 MethodType oldType = target.type(); // get NPE 2267 int dropped = valueTypes.size(); 2268 MethodType.checkSlotCount(dropped); 2269 if (dropped == 0) return target; 2270 int outargs = oldType.parameterCount(); 2271 int inargs = outargs + dropped; 2272 if (pos < 0 || pos >= inargs) 2273 throw newIllegalArgumentException("no argument type to remove"); 2274 ArrayList<Class<?>> ptypes = new ArrayList<>(oldType.parameterList()); 2275 ptypes.addAll(pos, valueTypes); 2276 if (ptypes.size() != inargs) throw newIllegalArgumentException("valueTypes"); 2277 MethodType newType = MethodType.methodType(oldType.returnType(), ptypes); 2278 return target.dropArguments(newType, pos, dropped); 2279 } 2280 2281 /** 2282 * Produces a method handle which will discard some dummy arguments 2283 * before calling some other specified <i>target</i> method handle. 2284 * The type of the new method handle will be the same as the target's type, 2285 * except it will also include the dummy argument types, 2286 * at some given position. 2287 * <p> 2288 * The {@code pos} argument may range between zero and <i>N</i>, 2289 * where <i>N</i> is the arity of the target. 2290 * If {@code pos} is zero, the dummy arguments will precede 2291 * the target's real arguments; if {@code pos} is <i>N</i> 2292 * they will come after. 2293 * <p> 2294 * <b>Example:</b> 2295 * <blockquote><pre>{@code 2296 import static java.lang.invoke.MethodHandles.*; 2297 import static java.lang.invoke.MethodType.*; 2298 ... 2299 MethodHandle cat = lookup().findVirtual(String.class, 2300 "concat", methodType(String.class, String.class)); 2301 assertEquals("xy", (String) cat.invokeExact("x", "y")); 2302 MethodHandle d0 = dropArguments(cat, 0, String.class); 2303 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 2304 MethodHandle d1 = dropArguments(cat, 1, String.class); 2305 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 2306 MethodHandle d2 = dropArguments(cat, 2, String.class); 2307 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 2308 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 2309 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 2310 * }</pre></blockquote> 2311 * <p> 2312 * This method is also equivalent to the following code: 2313 * <blockquote><pre> 2314 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 2315 * </pre></blockquote> 2316 * @param target the method handle to invoke after the arguments are dropped 2317 * @param valueTypes the type(s) of the argument(s) to drop 2318 * @param pos position of first argument to drop (zero for the leftmost) 2319 * @return a method handle which drops arguments of the given types, 2320 * before calling the original method handle 2321 * @throws NullPointerException if the target is null, 2322 * or if the {@code valueTypes} array or any of its elements is null 2323 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 2324 * or if {@code pos} is negative or greater than the arity of the target, 2325 * or if the new method handle's type would have 2326 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2327 */ 2328 public static 2329 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 2330 return dropArguments(target, pos, Arrays.asList(valueTypes)); 2331 } 2332 2333 /** 2334 * Adapts a target method handle by pre-processing 2335 * one or more of its arguments, each with its own unary filter function, 2336 * and then calling the target with each pre-processed argument 2337 * replaced by the result of its corresponding filter function. 2338 * <p> 2339 * The pre-processing is performed by one or more method handles, 2340 * specified in the elements of the {@code filters} array. 2341 * The first element of the filter array corresponds to the {@code pos} 2342 * argument of the target, and so on in sequence. 2343 * <p> 2344 * Null arguments in the array are treated as identity functions, 2345 * and the corresponding arguments left unchanged. 2346 * (If there are no non-null elements in the array, the original target is returned.) 2347 * Each filter is applied to the corresponding argument of the adapter. 2348 * <p> 2349 * If a filter {@code F} applies to the {@code N}th argument of 2350 * the target, then {@code F} must be a method handle which 2351 * takes exactly one argument. The type of {@code F}'s sole argument 2352 * replaces the corresponding argument type of the target 2353 * in the resulting adapted method handle. 2354 * The return type of {@code F} must be identical to the corresponding 2355 * parameter type of the target. 2356 * <p> 2357 * It is an error if there are elements of {@code filters} 2358 * (null or not) 2359 * which do not correspond to argument positions in the target. 2360 * <p><b>Example:</b> 2361 * <blockquote><pre>{@code 2362 import static java.lang.invoke.MethodHandles.*; 2363 import static java.lang.invoke.MethodType.*; 2364 ... 2365 MethodHandle cat = lookup().findVirtual(String.class, 2366 "concat", methodType(String.class, String.class)); 2367 MethodHandle upcase = lookup().findVirtual(String.class, 2368 "toUpperCase", methodType(String.class)); 2369 assertEquals("xy", (String) cat.invokeExact("x", "y")); 2370 MethodHandle f0 = filterArguments(cat, 0, upcase); 2371 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 2372 MethodHandle f1 = filterArguments(cat, 1, upcase); 2373 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 2374 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 2375 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 2376 * }</pre></blockquote> 2377 * <p> Here is pseudocode for the resulting adapter: 2378 * <blockquote><pre>{@code 2379 * V target(P... p, A[i]... a[i], B... b); 2380 * A[i] filter[i](V[i]); 2381 * T adapter(P... p, V[i]... v[i], B... b) { 2382 * return target(p..., f[i](v[i])..., b...); 2383 * } 2384 * }</pre></blockquote> 2385 * 2386 * @param target the method handle to invoke after arguments are filtered 2387 * @param pos the position of the first argument to filter 2388 * @param filters method handles to call initially on filtered arguments 2389 * @return method handle which incorporates the specified argument filtering logic 2390 * @throws NullPointerException if the target is null 2391 * or if the {@code filters} array is null 2392 * @throws IllegalArgumentException if a non-null element of {@code filters} 2393 * does not match a corresponding argument type of target as described above, 2394 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 2395 * or if the resulting method handle's type would have 2396 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2397 */ 2398 public static 2399 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 2400 MethodType targetType = target.type(); 2401 MethodHandle adapter = target; 2402 MethodType adapterType = null; 2403 assert((adapterType = targetType) != null); 2404 int maxPos = targetType.parameterCount(); 2405 if (pos + filters.length > maxPos) 2406 throw newIllegalArgumentException("too many filters"); 2407 int curPos = pos-1; // pre-incremented 2408 for (MethodHandle filter : filters) { 2409 curPos += 1; 2410 if (filter == null) continue; // ignore null elements of filters 2411 adapter = filterArgument(adapter, curPos, filter); 2412 assert((adapterType = adapterType.changeParameterType(curPos, filter.type().parameterType(0))) != null); 2413 } 2414 assert(adapterType.equals(adapter.type())); 2415 return adapter; 2416 } 2417 2418 /*non-public*/ static 2419 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 2420 MethodType targetType = target.type(); 2421 MethodType filterType = filter.type(); 2422 if (filterType.parameterCount() != 1 2423 || filterType.returnType() != targetType.parameterType(pos)) 2424 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 2425 return MethodHandleImpl.makeCollectArguments(target, filter, pos, false); 2426 } 2427 2428 /** 2429 * Adapts a target method handle by pre-processing 2430 * a sub-sequence of its arguments with a filter (another method handle). 2431 * The pre-processed arguments are replaced by the result (if any) of the 2432 * filter function. 2433 * The target is then called on the modified (usually shortened) argument list. 2434 * <p> 2435 * If the filter returns a value, the target must accept that value as 2436 * its argument in position {@code pos}, preceded and/or followed by 2437 * any arguments not passed to the filter. 2438 * If the filter returns void, the target must accept all arguments 2439 * not passed to the filter. 2440 * No arguments are reordered, and a result returned from the filter 2441 * replaces (in order) the whole subsequence of arguments originally 2442 * passed to the adapter. 2443 * <p> 2444 * The argument types (if any) of the filter 2445 * replace zero or one argument types of the target, at position {@code pos}, 2446 * in the resulting adapted method handle. 2447 * The return type of the filter (if any) must be identical to the 2448 * argument type of the target at position {@code pos}, and that target argument 2449 * is supplied by the return value of the filter. 2450 * <p> 2451 * In all cases, {@code pos} must be greater than or equal to zero, and 2452 * {@code pos} must also be less than or equal to the target's arity. 2453 * <p><b>Example:</b> 2454 * <blockquote><pre>{@code 2455 import static java.lang.invoke.MethodHandles.*; 2456 import static java.lang.invoke.MethodType.*; 2457 ... 2458 MethodHandle deepToString = publicLookup() 2459 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 2460 2461 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 2462 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 2463 2464 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 2465 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 2466 2467 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 2468 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 2469 assertEquals("[top, [up, down], strange]", 2470 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 2471 2472 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 2473 assertEquals("[top, [up, down], [strange]]", 2474 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 2475 2476 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 2477 assertEquals("[top, [[up, down, strange], charm], bottom]", 2478 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 2479 * }</pre></blockquote> 2480 * <p> Here is pseudocode for the resulting adapter: 2481 * <blockquote><pre>{@code 2482 * T target(A...,V,C...); 2483 * V filter(B...); 2484 * T adapter(A... a,B... b,C... c) { 2485 * V v = filter(b...); 2486 * return target(a...,v,c...); 2487 * } 2488 * // and if the filter has no arguments: 2489 * T target2(A...,V,C...); 2490 * V filter2(); 2491 * T adapter2(A... a,C... c) { 2492 * V v = filter2(); 2493 * return target2(a...,v,c...); 2494 * } 2495 * // and if the filter has a void return: 2496 * T target3(A...,C...); 2497 * void filter3(B...); 2498 * void adapter3(A... a,B... b,C... c) { 2499 * filter3(b...); 2500 * return target3(a...,c...); 2501 * } 2502 * }</pre></blockquote> 2503 * <p> 2504 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 2505 * one which first "folds" the affected arguments, and then drops them, in separate 2506 * steps as follows: 2507 * <blockquote><pre>{@code 2508 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 2509 * mh = MethodHandles.foldArguments(mh, coll); //step 1 2510 * }</pre></blockquote> 2511 * If the target method handle consumes no arguments besides than the result 2512 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 2513 * is equivalent to {@code filterReturnValue(coll, mh)}. 2514 * If the filter method handle {@code coll} consumes one argument and produces 2515 * a non-void result, then {@code collectArguments(mh, N, coll)} 2516 * is equivalent to {@code filterArguments(mh, N, coll)}. 2517 * Other equivalences are possible but would require argument permutation. 2518 * 2519 * @param target the method handle to invoke after filtering the subsequence of arguments 2520 * @param pos the position of the first adapter argument to pass to the filter, 2521 * and/or the target argument which receives the result of the filter 2522 * @param filter method handle to call on the subsequence of arguments 2523 * @return method handle which incorporates the specified argument subsequence filtering logic 2524 * @throws NullPointerException if either argument is null 2525 * @throws IllegalArgumentException if the return type of {@code filter} 2526 * is non-void and is not the same as the {@code pos} argument of the target, 2527 * or if {@code pos} is not between 0 and the target's arity, inclusive, 2528 * or if the resulting method handle's type would have 2529 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2530 * @see MethodHandles#foldArguments 2531 * @see MethodHandles#filterArguments 2532 * @see MethodHandles#filterReturnValue 2533 */ 2534 public static 2535 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 2536 MethodType targetType = target.type(); 2537 MethodType filterType = filter.type(); 2538 if (filterType.returnType() != void.class && 2539 filterType.returnType() != targetType.parameterType(pos)) 2540 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 2541 return MethodHandleImpl.makeCollectArguments(target, filter, pos, false); 2542 } 2543 2544 /** 2545 * Adapts a target method handle by post-processing 2546 * its return value (if any) with a filter (another method handle). 2547 * The result of the filter is returned from the adapter. 2548 * <p> 2549 * If the target returns a value, the filter must accept that value as 2550 * its only argument. 2551 * If the target returns void, the filter must accept no arguments. 2552 * <p> 2553 * The return type of the filter 2554 * replaces the return type of the target 2555 * in the resulting adapted method handle. 2556 * The argument type of the filter (if any) must be identical to the 2557 * return type of the target. 2558 * <p><b>Example:</b> 2559 * <blockquote><pre>{@code 2560 import static java.lang.invoke.MethodHandles.*; 2561 import static java.lang.invoke.MethodType.*; 2562 ... 2563 MethodHandle cat = lookup().findVirtual(String.class, 2564 "concat", methodType(String.class, String.class)); 2565 MethodHandle length = lookup().findVirtual(String.class, 2566 "length", methodType(int.class)); 2567 System.out.println((String) cat.invokeExact("x", "y")); // xy 2568 MethodHandle f0 = filterReturnValue(cat, length); 2569 System.out.println((int) f0.invokeExact("x", "y")); // 2 2570 * }</pre></blockquote> 2571 * <p> Here is pseudocode for the resulting adapter: 2572 * <blockquote><pre>{@code 2573 * V target(A...); 2574 * T filter(V); 2575 * T adapter(A... a) { 2576 * V v = target(a...); 2577 * return filter(v); 2578 * } 2579 * // and if the target has a void return: 2580 * void target2(A...); 2581 * T filter2(); 2582 * T adapter2(A... a) { 2583 * target2(a...); 2584 * return filter2(); 2585 * } 2586 * // and if the filter has a void return: 2587 * V target3(A...); 2588 * void filter3(V); 2589 * void adapter3(A... a) { 2590 * V v = target3(a...); 2591 * filter3(v); 2592 * } 2593 * }</pre></blockquote> 2594 * @param target the method handle to invoke before filtering the return value 2595 * @param filter method handle to call on the return value 2596 * @return method handle which incorporates the specified return value filtering logic 2597 * @throws NullPointerException if either argument is null 2598 * @throws IllegalArgumentException if the argument list of {@code filter} 2599 * does not match the return type of target as described above 2600 */ 2601 public static 2602 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 2603 MethodType targetType = target.type(); 2604 MethodType filterType = filter.type(); 2605 Class<?> rtype = targetType.returnType(); 2606 int filterValues = filterType.parameterCount(); 2607 if (filterValues == 0 2608 ? (rtype != void.class) 2609 : (rtype != filterType.parameterType(0))) 2610 throw newIllegalArgumentException("target and filter types do not match", target, filter); 2611 // result = fold( lambda(retval, arg...) { filter(retval) }, 2612 // lambda( arg...) { target(arg...) } ) 2613 return MethodHandleImpl.makeCollectArguments(filter, target, 0, false); 2614 } 2615 2616 /** 2617 * Adapts a target method handle by pre-processing 2618 * some of its arguments, and then calling the target with 2619 * the result of the pre-processing, inserted into the original 2620 * sequence of arguments. 2621 * <p> 2622 * The pre-processing is performed by {@code combiner}, a second method handle. 2623 * Of the arguments passed to the adapter, the first {@code N} arguments 2624 * are copied to the combiner, which is then called. 2625 * (Here, {@code N} is defined as the parameter count of the combiner.) 2626 * After this, control passes to the target, with any result 2627 * from the combiner inserted before the original {@code N} incoming 2628 * arguments. 2629 * <p> 2630 * If the combiner returns a value, the first parameter type of the target 2631 * must be identical with the return type of the combiner, and the next 2632 * {@code N} parameter types of the target must exactly match the parameters 2633 * of the combiner. 2634 * <p> 2635 * If the combiner has a void return, no result will be inserted, 2636 * and the first {@code N} parameter types of the target 2637 * must exactly match the parameters of the combiner. 2638 * <p> 2639 * The resulting adapter is the same type as the target, except that the 2640 * first parameter type is dropped, 2641 * if it corresponds to the result of the combiner. 2642 * <p> 2643 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 2644 * that either the combiner or the target does not wish to receive. 2645 * If some of the incoming arguments are destined only for the combiner, 2646 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 2647 * arguments will not need to be live on the stack on entry to the 2648 * target.) 2649 * <p><b>Example:</b> 2650 * <blockquote><pre>{@code 2651 import static java.lang.invoke.MethodHandles.*; 2652 import static java.lang.invoke.MethodType.*; 2653 ... 2654 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 2655 "println", methodType(void.class, String.class)) 2656 .bindTo(System.out); 2657 MethodHandle cat = lookup().findVirtual(String.class, 2658 "concat", methodType(String.class, String.class)); 2659 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 2660 MethodHandle catTrace = foldArguments(cat, trace); 2661 // also prints "boo": 2662 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 2663 * }</pre></blockquote> 2664 * <p> Here is pseudocode for the resulting adapter: 2665 * <blockquote><pre>{@code 2666 * // there are N arguments in A... 2667 * T target(V, A[N]..., B...); 2668 * V combiner(A...); 2669 * T adapter(A... a, B... b) { 2670 * V v = combiner(a...); 2671 * return target(v, a..., b...); 2672 * } 2673 * // and if the combiner has a void return: 2674 * T target2(A[N]..., B...); 2675 * void combiner2(A...); 2676 * T adapter2(A... a, B... b) { 2677 * combiner2(a...); 2678 * return target2(a..., b...); 2679 * } 2680 * }</pre></blockquote> 2681 * @param target the method handle to invoke after arguments are combined 2682 * @param combiner method handle to call initially on the incoming arguments 2683 * @return method handle which incorporates the specified argument folding logic 2684 * @throws NullPointerException if either argument is null 2685 * @throws IllegalArgumentException if {@code combiner}'s return type 2686 * is non-void and not the same as the first argument type of 2687 * the target, or if the initial {@code N} argument types 2688 * of the target 2689 * (skipping one matching the {@code combiner}'s return type) 2690 * are not identical with the argument types of {@code combiner} 2691 */ 2692 public static 2693 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 2694 int pos = 0; 2695 MethodType targetType = target.type(); 2696 MethodType combinerType = combiner.type(); 2697 int foldPos = pos; 2698 int foldArgs = combinerType.parameterCount(); 2699 int foldVals = combinerType.returnType() == void.class ? 0 : 1; 2700 int afterInsertPos = foldPos + foldVals; 2701 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 2702 if (ok && !(combinerType.parameterList() 2703 .equals(targetType.parameterList().subList(afterInsertPos, 2704 afterInsertPos + foldArgs)))) 2705 ok = false; 2706 if (ok && foldVals != 0 && !combinerType.returnType().equals(targetType.parameterType(0))) 2707 ok = false; 2708 if (!ok) 2709 throw misMatchedTypes("target and combiner types", targetType, combinerType); 2710 MethodType newType = targetType.dropParameterTypes(foldPos, afterInsertPos); 2711 return MethodHandleImpl.makeCollectArguments(target, combiner, foldPos, true); 2712 } 2713 2714 /** 2715 * Makes a method handle which adapts a target method handle, 2716 * by guarding it with a test, a boolean-valued method handle. 2717 * If the guard fails, a fallback handle is called instead. 2718 * All three method handles must have the same corresponding 2719 * argument and return types, except that the return type 2720 * of the test must be boolean, and the test is allowed 2721 * to have fewer arguments than the other two method handles. 2722 * <p> Here is pseudocode for the resulting adapter: 2723 * <blockquote><pre>{@code 2724 * boolean test(A...); 2725 * T target(A...,B...); 2726 * T fallback(A...,B...); 2727 * T adapter(A... a,B... b) { 2728 * if (test(a...)) 2729 * return target(a..., b...); 2730 * else 2731 * return fallback(a..., b...); 2732 * } 2733 * }</pre></blockquote> 2734 * Note that the test arguments ({@code a...} in the pseudocode) cannot 2735 * be modified by execution of the test, and so are passed unchanged 2736 * from the caller to the target or fallback as appropriate. 2737 * @param test method handle used for test, must return boolean 2738 * @param target method handle to call if test passes 2739 * @param fallback method handle to call if test fails 2740 * @return method handle which incorporates the specified if/then/else logic 2741 * @throws NullPointerException if any argument is null 2742 * @throws IllegalArgumentException if {@code test} does not return boolean, 2743 * or if all three method types do not match (with the return 2744 * type of {@code test} changed to match that of the target). 2745 */ 2746 public static 2747 MethodHandle guardWithTest(MethodHandle test, 2748 MethodHandle target, 2749 MethodHandle fallback) { 2750 MethodType gtype = test.type(); 2751 MethodType ttype = target.type(); 2752 MethodType ftype = fallback.type(); 2753 if (!ttype.equals(ftype)) 2754 throw misMatchedTypes("target and fallback types", ttype, ftype); 2755 if (gtype.returnType() != boolean.class) 2756 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 2757 List<Class<?>> targs = ttype.parameterList(); 2758 List<Class<?>> gargs = gtype.parameterList(); 2759 if (!targs.equals(gargs)) { 2760 int gpc = gargs.size(), tpc = targs.size(); 2761 if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs)) 2762 throw misMatchedTypes("target and test types", ttype, gtype); 2763 test = dropArguments(test, gpc, targs.subList(gpc, tpc)); 2764 gtype = test.type(); 2765 } 2766 return MethodHandleImpl.makeGuardWithTest(test, target, fallback); 2767 } 2768 2769 static RuntimeException misMatchedTypes(String what, MethodType t1, MethodType t2) { 2770 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 2771 } 2772 2773 /** 2774 * Makes a method handle which adapts a target method handle, 2775 * by running it inside an exception handler. 2776 * If the target returns normally, the adapter returns that value. 2777 * If an exception matching the specified type is thrown, the fallback 2778 * handle is called instead on the exception, plus the original arguments. 2779 * <p> 2780 * The target and handler must have the same corresponding 2781 * argument and return types, except that handler may omit trailing arguments 2782 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 2783 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 2784 * <p> Here is pseudocode for the resulting adapter: 2785 * <blockquote><pre>{@code 2786 * T target(A..., B...); 2787 * T handler(ExType, A...); 2788 * T adapter(A... a, B... b) { 2789 * try { 2790 * return target(a..., b...); 2791 * } catch (ExType ex) { 2792 * return handler(ex, a...); 2793 * } 2794 * } 2795 * }</pre></blockquote> 2796 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 2797 * be modified by execution of the target, and so are passed unchanged 2798 * from the caller to the handler, if the handler is invoked. 2799 * <p> 2800 * The target and handler must return the same type, even if the handler 2801 * always throws. (This might happen, for instance, because the handler 2802 * is simulating a {@code finally} clause). 2803 * To create such a throwing handler, compose the handler creation logic 2804 * with {@link #throwException throwException}, 2805 * in order to create a method handle of the correct return type. 2806 * @param target method handle to call 2807 * @param exType the type of exception which the handler will catch 2808 * @param handler method handle to call if a matching exception is thrown 2809 * @return method handle which incorporates the specified try/catch logic 2810 * @throws NullPointerException if any argument is null 2811 * @throws IllegalArgumentException if {@code handler} does not accept 2812 * the given exception type, or if the method handle types do 2813 * not match in their return types and their 2814 * corresponding parameters 2815 */ 2816 public static 2817 MethodHandle catchException(MethodHandle target, 2818 Class<? extends Throwable> exType, 2819 MethodHandle handler) { 2820 MethodType ttype = target.type(); 2821 MethodType htype = handler.type(); 2822 if (htype.parameterCount() < 1 || 2823 !htype.parameterType(0).isAssignableFrom(exType)) 2824 throw newIllegalArgumentException("handler does not accept exception type "+exType); 2825 if (htype.returnType() != ttype.returnType()) 2826 throw misMatchedTypes("target and handler return types", ttype, htype); 2827 List<Class<?>> targs = ttype.parameterList(); 2828 List<Class<?>> hargs = htype.parameterList(); 2829 hargs = hargs.subList(1, hargs.size()); // omit leading parameter from handler 2830 if (!targs.equals(hargs)) { 2831 int hpc = hargs.size(), tpc = targs.size(); 2832 if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs)) 2833 throw misMatchedTypes("target and handler types", ttype, htype); 2834 handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc)); 2835 htype = handler.type(); 2836 } 2837 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 2838 } 2839 2840 /** 2841 * Produces a method handle which will throw exceptions of the given {@code exType}. 2842 * The method handle will accept a single argument of {@code exType}, 2843 * and immediately throw it as an exception. 2844 * The method type will nominally specify a return of {@code returnType}. 2845 * The return type may be anything convenient: It doesn't matter to the 2846 * method handle's behavior, since it will never return normally. 2847 * @param returnType the return type of the desired method handle 2848 * @param exType the parameter type of the desired method handle 2849 * @return method handle which can throw the given exceptions 2850 * @throws NullPointerException if either argument is null 2851 */ 2852 public static 2853 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 2854 if (!Throwable.class.isAssignableFrom(exType)) 2855 throw new ClassCastException(exType.getName()); 2856 return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType)); 2857 } 2858 }