John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1 | /* |
Michael Haupt | d64d6d8 | 2016-01-14 13:53:13 +0100 | [diff] [blame] | 2 | * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 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 |
Kelly O'Hair | fe008ae | 2010-05-25 15:58:33 -0700 | [diff] [blame] | 7 | * published by the Free Software Foundation. Oracle designates this |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 8 | * particular file as subject to the "Classpath" exception as provided |
Kelly O'Hair | fe008ae | 2010-05-25 15:58:33 -0700 | [diff] [blame] | 9 | * by Oracle in the LICENSE file that accompanied this code. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 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 | * |
Kelly O'Hair | fe008ae | 2010-05-25 15:58:33 -0700 | [diff] [blame] | 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. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 24 | */ |
| 25 | |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 26 | package java.lang.invoke; |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 27 | |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 28 | import jdk.internal.org.objectweb.asm.ClassWriter; |
| 29 | import jdk.internal.org.objectweb.asm.Opcodes; |
| 30 | import jdk.internal.reflect.CallerSensitive; |
| 31 | import jdk.internal.reflect.Reflection; |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 32 | import sun.invoke.util.ValueConversions; |
| 33 | import sun.invoke.util.VerifyAccess; |
| 34 | import sun.invoke.util.Wrapper; |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 35 | import sun.reflect.misc.ReflectUtil; |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 36 | import sun.security.util.SecurityConstants; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 37 | |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 38 | import java.lang.invoke.LambdaForm.BasicType; |
| 39 | import java.lang.reflect.Constructor; |
| 40 | import java.lang.reflect.Field; |
| 41 | import java.lang.reflect.Member; |
| 42 | import java.lang.reflect.Method; |
| 43 | import java.lang.reflect.Modifier; |
| 44 | import java.lang.reflect.ReflectPermission; |
| 45 | import java.nio.ByteOrder; |
| 46 | import java.security.AccessController; |
| 47 | import java.security.PrivilegedAction; |
| 48 | import java.util.ArrayList; |
| 49 | import java.util.Arrays; |
| 50 | import java.util.BitSet; |
| 51 | import java.util.Iterator; |
| 52 | import java.util.List; |
| 53 | import java.util.Objects; |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 54 | import java.util.concurrent.ConcurrentHashMap; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 55 | import java.util.stream.Collectors; |
| 56 | import java.util.stream.Stream; |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 57 | |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 58 | import static java.lang.invoke.MethodHandleImpl.Intrinsic; |
| 59 | import static java.lang.invoke.MethodHandleNatives.Constants.*; |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 60 | import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 61 | import static java.lang.invoke.MethodType.methodType; |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 62 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 63 | /** |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 64 | * This class consists exclusively of static methods that operate on or return |
| 65 | * method handles. They fall into several categories: |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 66 | * <ul> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 67 | * <li>Lookup methods which help create method handles for methods and fields. |
| 68 | * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. |
| 69 | * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 70 | * </ul> |
Alexander Stepanov | 0547ad2 | 2014-05-12 14:12:33 +0400 | [diff] [blame] | 71 | * |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 72 | * @author John Rose, JSR 292 EG |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 73 | * @since 1.7 |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 74 | */ |
| 75 | public class MethodHandles { |
| 76 | |
| 77 | private MethodHandles() { } // do not instantiate |
| 78 | |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 79 | private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); |
Claes Redestad | 4e062cd | 2015-12-19 02:24:27 +0100 | [diff] [blame] | 80 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 81 | // See IMPL_LOOKUP below. |
| 82 | |
| 83 | //// Method handle creation from ordinary methods. |
| 84 | |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 85 | /** |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 86 | * Returns a {@link Lookup lookup object} with |
| 87 | * full capabilities to emulate all supported bytecode behaviors of the caller. |
| 88 | * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. |
| 89 | * Factory methods on the lookup object can create |
| 90 | * <a href="MethodHandleInfo.html#directmh">direct method handles</a> |
| 91 | * for any member that the caller has access to via bytecodes, |
| 92 | * including protected and private fields and methods. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 93 | * This lookup object is a <em>capability</em> which may be delegated to trusted agents. |
| 94 | * Do not store it in place where untrusted code can access it. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 95 | * <p> |
| 96 | * This method is caller sensitive, which means that it may return different |
| 97 | * values to different callers. |
| 98 | * <p> |
| 99 | * For any given caller class {@code C}, the lookup object returned by this call |
| 100 | * has equivalent capabilities to any lookup object |
| 101 | * supplied by the JVM to the bootstrap method of an |
| 102 | * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> |
| 103 | * executing in the same caller class {@code C}. |
| 104 | * @return a lookup object for the caller of this method, with private access |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 105 | */ |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 106 | @CallerSensitive |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 107 | public static Lookup lookup() { |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 108 | return new Lookup(Reflection.getCallerClass()); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 109 | } |
| 110 | |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 111 | /** |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 112 | * Returns a {@link Lookup lookup object} which is trusted minimally. |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 113 | * It can only be used to create method handles to public members in |
| 114 | * public classes in packages that are exported unconditionally. |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 115 | * <p> |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 116 | * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup |
| 117 | * object is in an unnamed module. |
Michael Haupt | bfb7e8c | 2016-03-13 20:26:29 +0100 | [diff] [blame] | 118 | * Consequently, the lookup context of this lookup object will be the bootstrap |
| 119 | * class loader, which means it cannot find user classes. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 120 | * |
| 121 | * <p style="font-size:smaller;"> |
| 122 | * <em>Discussion:</em> |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 123 | * The lookup class can be changed to any other class {@code C} using an expression of the form |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 124 | * {@link Lookup#in publicLookup().in(C.class)}. |
Michael Haupt | bfb7e8c | 2016-03-13 20:26:29 +0100 | [diff] [blame] | 125 | * but may change the lookup context by virtue of changing the class loader. |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 126 | * A public lookup object is always subject to |
| 127 | * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. |
| 128 | * Also, it cannot access |
| 129 | * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 130 | * @return a lookup object which is trusted minimally |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 131 | */ |
| 132 | public static Lookup publicLookup() { |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 133 | // During VM startup then only classes in the java.base module can be |
| 134 | // loaded and linked. This is because java.base exports aren't setup until |
| 135 | // the module system is initialized, hence types in the unnamed module |
| 136 | // (or any named module) can't link to java/lang/Object. |
| 137 | if (!jdk.internal.misc.VM.isModuleSystemInited()) { |
| 138 | return new Lookup(Object.class, Lookup.PUBLIC); |
| 139 | } else { |
| 140 | return LookupHelper.PUBLIC_LOOKUP; |
| 141 | } |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 142 | } |
| 143 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 144 | /** |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 145 | * Performs an unchecked "crack" of a |
| 146 | * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 147 | * The result is as if the user had obtained a lookup object capable enough |
| 148 | * to crack the target method handle, called |
| 149 | * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} |
| 150 | * on the target to obtain its symbolic reference, and then called |
| 151 | * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} |
| 152 | * to resolve the symbolic reference to a member. |
| 153 | * <p> |
| 154 | * If there is a security manager, its {@code checkPermission} method |
| 155 | * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. |
| 156 | * @param <T> the desired type of the result, either {@link Member} or a subtype |
| 157 | * @param target a direct method handle to crack into symbolic reference components |
| 158 | * @param expected a class object representing the desired result type {@code T} |
| 159 | * @return a reference to the method, constructor, or field object |
| 160 | * @exception SecurityException if the caller is not privileged to call {@code setAccessible} |
| 161 | * @exception NullPointerException if either argument is {@code null} |
| 162 | * @exception IllegalArgumentException if the target is not a direct method handle |
| 163 | * @exception ClassCastException if the member is not of the expected type |
| 164 | * @since 1.8 |
| 165 | */ |
| 166 | public static <T extends Member> T |
| 167 | reflectAs(Class<T> expected, MethodHandle target) { |
| 168 | SecurityManager smgr = System.getSecurityManager(); |
| 169 | if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION); |
| 170 | Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup |
| 171 | return lookup.revealDirect(target).reflectAs(expected, lookup); |
| 172 | } |
| 173 | // Copied from AccessibleObject, as used by Method.setAccessible, etc.: |
Martin Buchholz | a2f0fe3 | 2015-09-15 21:56:04 -0700 | [diff] [blame] | 174 | private static final java.security.Permission ACCESS_PERMISSION = |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 175 | new ReflectPermission("suppressAccessChecks"); |
| 176 | |
| 177 | /** |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 178 | * A <em>lookup object</em> is a factory for creating method handles, |
| 179 | * when the creation requires access checking. |
| 180 | * Method handles do not perform |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 181 | * access checks when they are called, but rather when they are created. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 182 | * Therefore, method handle access |
| 183 | * restrictions must be enforced when a method handle is created. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 184 | * The caller class against which those restrictions are enforced |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 185 | * is known as the {@linkplain #lookupClass lookup class}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 186 | * <p> |
| 187 | * A lookup class which needs to create method handles will call |
| 188 | * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. |
| 189 | * When the {@code Lookup} factory object is created, the identity of the lookup class is |
| 190 | * determined, and securely stored in the {@code Lookup} object. |
| 191 | * The lookup class (or its delegates) may then use factory methods |
| 192 | * on the {@code Lookup} object to create method handles for access-checked members. |
| 193 | * This includes all methods, constructors, and fields which are allowed to the lookup class, |
| 194 | * even private ones. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 195 | * |
| 196 | * <h1><a name="lookups"></a>Lookup Factory Methods</h1> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 197 | * The factory methods on a {@code Lookup} object correspond to all major |
| 198 | * use cases for methods, constructors, and fields. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 199 | * Each method handle created by a factory method is the functional |
| 200 | * equivalent of a particular <em>bytecode behavior</em>. |
| 201 | * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 202 | * Here is a summary of the correspondence between these factory methods and |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 203 | * the behavior of the resulting method handles: |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 204 | * <table border=1 cellpadding=5 summary="lookup method behaviors"> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 205 | * <tr> |
| 206 | * <th><a name="equiv"></a>lookup expression</th> |
| 207 | * <th>member</th> |
| 208 | * <th>bytecode behavior</th> |
| 209 | * </tr> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 210 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 211 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> |
| 212 | * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 213 | * </tr> |
| 214 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 215 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> |
| 216 | * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 217 | * </tr> |
| 218 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 219 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> |
| 220 | * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 221 | * </tr> |
| 222 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 223 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> |
| 224 | * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 225 | * </tr> |
| 226 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 227 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> |
| 228 | * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 229 | * </tr> |
| 230 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 231 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> |
| 232 | * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 233 | * </tr> |
| 234 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 235 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> |
| 236 | * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 237 | * </tr> |
| 238 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 239 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> |
| 240 | * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 241 | * </tr> |
| 242 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 243 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> |
| 244 | * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 245 | * </tr> |
| 246 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 247 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> |
| 248 | * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 249 | * </tr> |
| 250 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 251 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> |
| 252 | * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 253 | * </tr> |
| 254 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 255 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> |
| 256 | * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 257 | * </tr> |
| 258 | * <tr> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 259 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> |
| 260 | * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 261 | * </tr> |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 262 | * <tr> |
| 263 | * <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td> |
| 264 | * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> |
| 265 | * </tr> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 266 | * </table> |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 267 | * |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 268 | * Here, the type {@code C} is the class or interface being searched for a member, |
| 269 | * documented as a parameter named {@code refc} in the lookup methods. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 270 | * The method type {@code MT} is composed from the return type {@code T} |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 271 | * and the sequence of argument types {@code A*}. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 272 | * The constructor also has a sequence of argument types {@code A*} and |
| 273 | * is deemed to return the newly-created object of type {@code C}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 274 | * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. |
| 275 | * The formal parameter {@code this} stands for the self-reference of type {@code C}; |
| 276 | * if it is present, it is always the leading argument to the method handle invocation. |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 277 | * (In the case of some {@code protected} members, {@code this} may be |
| 278 | * restricted in type to the lookup class; see below.) |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 279 | * The name {@code arg} stands for all the other method handle arguments. |
| 280 | * In the code examples for the Core Reflection API, the name {@code thisOrNull} |
| 281 | * stands for a null reference if the accessed method or field is static, |
| 282 | * and {@code this} otherwise. |
| 283 | * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand |
| 284 | * for reflective objects corresponding to the given members. |
| 285 | * <p> |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 286 | * The bytecode behavior for a {@code findClass} operation is a load of a constant class, |
| 287 | * as if by {@code ldc CONSTANT_Class}. |
| 288 | * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. |
| 289 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 290 | * In cases where the given member is of variable arity (i.e., a method or constructor) |
| 291 | * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. |
| 292 | * In all other cases, the returned method handle will be of fixed arity. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 293 | * <p style="font-size:smaller;"> |
| 294 | * <em>Discussion:</em> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 295 | * The equivalence between looked-up method handles and underlying |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 296 | * class members and bytecode behaviors |
| 297 | * can break down in a few ways: |
| 298 | * <ul style="font-size:smaller;"> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 299 | * <li>If {@code C} is not symbolically accessible from the lookup class's loader, |
| 300 | * the lookup can still succeed, even when there is no equivalent |
| 301 | * Java expression or bytecoded constant. |
| 302 | * <li>Likewise, if {@code T} or {@code MT} |
| 303 | * is not symbolically accessible from the lookup class's loader, |
| 304 | * the lookup can still succeed. |
| 305 | * For example, lookups for {@code MethodHandle.invokeExact} and |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 306 | * {@code MethodHandle.invoke} will always succeed, regardless of requested type. |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 307 | * <li>If there is a security manager installed, it can forbid the lookup |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 308 | * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). |
| 309 | * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} |
| 310 | * constant is not subject to security manager checks. |
John R Rose | 77dc59f | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 311 | * <li>If the looked-up method has a |
| 312 | * <a href="MethodHandle.html#maxarity">very large arity</a>, |
| 313 | * the method handle creation may fail, due to the method handle |
| 314 | * type having too many parameters. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 315 | * </ul> |
| 316 | * |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 317 | * <h1><a name="access"></a>Access checking</h1> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 318 | * Access checks are applied in the factory methods of {@code Lookup}, |
| 319 | * when a method handle is created. |
| 320 | * This is a key difference from the Core Reflection API, since |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 321 | * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 322 | * performs access checking against every caller, on every call. |
| 323 | * <p> |
| 324 | * All access checks start from a {@code Lookup} object, which |
| 325 | * compares its recorded lookup class against all requests to |
| 326 | * create method handles. |
| 327 | * A single {@code Lookup} object can be used to create any number |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 328 | * of access-checked method handles, all checked against a single |
| 329 | * lookup class. |
| 330 | * <p> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 331 | * A {@code Lookup} object can be shared with other trusted code, |
| 332 | * such as a metaobject protocol. |
| 333 | * A shared {@code Lookup} object delegates the capability |
| 334 | * to create method handles on private members of the lookup class. |
| 335 | * Even if privileged code uses the {@code Lookup} object, |
| 336 | * the access checking is confined to the privileges of the |
| 337 | * original lookup class. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 338 | * <p> |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 339 | * A lookup can fail, because |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 340 | * the containing class is not accessible to the lookup class, or |
| 341 | * because the desired class member is missing, or because the |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 342 | * desired class member is not accessible to the lookup class, or |
| 343 | * because the lookup object is not trusted enough to access the member. |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 344 | * In any of these cases, a {@code ReflectiveOperationException} will be |
| 345 | * thrown from the attempted lookup. The exact class will be one of |
| 346 | * the following: |
| 347 | * <ul> |
| 348 | * <li>NoSuchMethodException — if a method is requested but does not exist |
| 349 | * <li>NoSuchFieldException — if a field is requested but does not exist |
| 350 | * <li>IllegalAccessException — if the member exists but an access check fails |
| 351 | * </ul> |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 352 | * <p> |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 353 | * In general, the conditions under which a method handle may be |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 354 | * looked up for a method {@code M} are no more restrictive than the conditions |
| 355 | * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 356 | * Where the JVM would raise exceptions like {@code NoSuchMethodError}, |
| 357 | * a method handle lookup will generally raise a corresponding |
| 358 | * checked exception, such as {@code NoSuchMethodException}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 359 | * And the effect of invoking the method handle resulting from the lookup |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 360 | * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> |
| 361 | * to executing the compiled, verified, and resolved call to {@code M}. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 362 | * The same point is true of fields and constructors. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 363 | * <p style="font-size:smaller;"> |
| 364 | * <em>Discussion:</em> |
| 365 | * Access checks only apply to named and reflected methods, |
| 366 | * constructors, and fields. |
| 367 | * Other method handle creation methods, such as |
| 368 | * {@link MethodHandle#asType MethodHandle.asType}, |
| 369 | * do not require any access checks, and are used |
| 370 | * independently of any {@code Lookup} object. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 371 | * <p> |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 372 | * If the desired member is {@code protected}, the usual JVM rules apply, |
| 373 | * including the requirement that the lookup class must be either be in the |
| 374 | * same package as the desired member, or must inherit that member. |
| 375 | * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) |
| 376 | * In addition, if the desired member is a non-static field or method |
| 377 | * in a different package, the resulting method handle may only be applied |
| 378 | * to objects of the lookup class or one of its subclasses. |
| 379 | * This requirement is enforced by narrowing the type of the leading |
| 380 | * {@code this} parameter from {@code C} |
| 381 | * (which will necessarily be a superclass of the lookup class) |
| 382 | * to the lookup class itself. |
| 383 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 384 | * The JVM imposes a similar requirement on {@code invokespecial} instruction, |
| 385 | * that the receiver argument must match both the resolved method <em>and</em> |
| 386 | * the current class. Again, this requirement is enforced by narrowing the |
| 387 | * type of the leading parameter to the resulting method handle. |
| 388 | * (See the Java Virtual Machine Specification, section 4.10.1.9.) |
| 389 | * <p> |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 390 | * The JVM represents constructors and static initializer blocks as internal methods |
| 391 | * with special names ({@code "<init>"} and {@code "<clinit>"}). |
| 392 | * The internal syntax of invocation instructions allows them to refer to such internal |
| 393 | * methods as if they were normal methods, but the JVM bytecode verifier rejects them. |
| 394 | * A lookup of such an internal method will produce a {@code NoSuchMethodException}. |
| 395 | * <p> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 396 | * In some cases, access between nested classes is obtained by the Java compiler by creating |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 397 | * an wrapper method to access a private method of another class |
| 398 | * in the same top-level declaration. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 399 | * For example, a nested class {@code C.D} |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 400 | * can access private members within other related classes such as |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 401 | * {@code C}, {@code C.D.E}, or {@code C.B}, |
| 402 | * but the Java compiler may need to generate wrapper methods in |
| 403 | * those related classes. In such cases, a {@code Lookup} object on |
| 404 | * {@code C.E} would be unable to those private members. |
| 405 | * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, |
| 406 | * which can transform a lookup on {@code C.E} into one on any of those other |
| 407 | * classes, without special elevation of privilege. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 408 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 409 | * The accesses permitted to a given lookup object may be limited, |
| 410 | * according to its set of {@link #lookupModes lookupModes}, |
| 411 | * to a subset of members normally accessible to the lookup class. |
| 412 | * For example, the {@link MethodHandles#publicLookup publicLookup} |
| 413 | * method produces a lookup object which is only allowed to access |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 414 | * public members in public classes of exported packages. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 415 | * The caller sensitive method {@link MethodHandles#lookup lookup} |
| 416 | * produces a lookup object with full capabilities relative to |
| 417 | * its caller class, to emulate all supported bytecode behaviors. |
| 418 | * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object |
| 419 | * with fewer access modes than the original lookup object. |
| 420 | * |
| 421 | * <p style="font-size:smaller;"> |
| 422 | * <a name="privacc"></a> |
| 423 | * <em>Discussion of private access:</em> |
| 424 | * We say that a lookup has <em>private access</em> |
| 425 | * if its {@linkplain #lookupModes lookup modes} |
| 426 | * include the possibility of accessing {@code private} members. |
| 427 | * As documented in the relevant methods elsewhere, |
| 428 | * only lookups with private access possess the following capabilities: |
| 429 | * <ul style="font-size:smaller;"> |
| 430 | * <li>access private fields, methods, and constructors of the lookup class |
| 431 | * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, |
| 432 | * such as {@code Class.forName} |
| 433 | * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions |
| 434 | * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> |
| 435 | * for classes accessible to the lookup class |
| 436 | * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes |
| 437 | * within the same package member |
| 438 | * </ul> |
| 439 | * <p style="font-size:smaller;"> |
| 440 | * Each of these permissions is a consequence of the fact that a lookup object |
| 441 | * with private access can be securely traced back to an originating class, |
| 442 | * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions |
| 443 | * can be reliably determined and emulated by method handles. |
| 444 | * |
| 445 | * <h1><a name="secmgr"></a>Security manager interactions</h1> |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 446 | * Although bytecode instructions can only refer to classes in |
| 447 | * a related class loader, this API can search for methods in any |
| 448 | * class, as long as a reference to its {@code Class} object is |
| 449 | * available. Such cross-loader references are also possible with the |
| 450 | * Core Reflection API, and are impossible to bytecode instructions |
| 451 | * such as {@code invokestatic} or {@code getfield}. |
| 452 | * There is a {@linkplain java.lang.SecurityManager security manager API} |
| 453 | * to allow applications to check such cross-loader references. |
| 454 | * These checks apply to both the {@code MethodHandles.Lookup} API |
| 455 | * and the Core Reflection API |
| 456 | * (as found on {@link java.lang.Class Class}). |
| 457 | * <p> |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 458 | * If a security manager is present, member and class lookups are subject to |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 459 | * additional checks. |
Mandy Chung | 5a360a7 | 2013-07-02 15:58:09 -0700 | [diff] [blame] | 460 | * From one to three calls are made to the security manager. |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 461 | * Any of these calls can refuse access by throwing a |
| 462 | * {@link java.lang.SecurityException SecurityException}. |
| 463 | * Define {@code smgr} as the security manager, |
Mandy Chung | 5a360a7 | 2013-07-02 15:58:09 -0700 | [diff] [blame] | 464 | * {@code lookc} as the lookup class of the current lookup object, |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 465 | * {@code refc} as the containing class in which the member |
| 466 | * is being sought, and {@code defc} as the class in which the |
| 467 | * member is actually defined. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 468 | * (If a class or other type is being accessed, |
| 469 | * the {@code refc} and {@code defc} values are the class itself.) |
Mandy Chung | 5a360a7 | 2013-07-02 15:58:09 -0700 | [diff] [blame] | 470 | * The value {@code lookc} is defined as <em>not present</em> |
| 471 | * if the current lookup object does not have |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 472 | * <a href="MethodHandles.Lookup.html#privacc">private access</a>. |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 473 | * The calls are made according to the following rules: |
| 474 | * <ul> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 475 | * <li><b>Step 1:</b> |
| 476 | * If {@code lookc} is not present, or if its class loader is not |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 477 | * the same as or an ancestor of the class loader of {@code refc}, |
| 478 | * then {@link SecurityManager#checkPackageAccess |
| 479 | * smgr.checkPackageAccess(refcPkg)} is called, |
| 480 | * where {@code refcPkg} is the package of {@code refc}. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 481 | * <li><b>Step 2a:</b> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 482 | * If the retrieved member is not public and |
Mandy Chung | 5a360a7 | 2013-07-02 15:58:09 -0700 | [diff] [blame] | 483 | * {@code lookc} is not present, then |
| 484 | * {@link SecurityManager#checkPermission smgr.checkPermission} |
| 485 | * with {@code RuntimePermission("accessDeclaredMembers")} is called. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 486 | * <li><b>Step 2b:</b> |
| 487 | * If the retrieved class has a {@code null} class loader, |
| 488 | * and {@code lookc} is not present, then |
| 489 | * {@link SecurityManager#checkPermission smgr.checkPermission} |
| 490 | * with {@code RuntimePermission("getClassLoader")} is called. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 491 | * <li><b>Step 3:</b> |
| 492 | * If the retrieved member is not public, |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 493 | * and if {@code lookc} is not present, |
Mandy Chung | 5a360a7 | 2013-07-02 15:58:09 -0700 | [diff] [blame] | 494 | * and if {@code defc} and {@code refc} are different, |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 495 | * then {@link SecurityManager#checkPackageAccess |
| 496 | * smgr.checkPackageAccess(defcPkg)} is called, |
| 497 | * where {@code defcPkg} is the package of {@code defc}. |
| 498 | * </ul> |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 499 | * Security checks are performed after other access checks have passed. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 500 | * Therefore, the above rules presuppose a member or class that is public, |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 501 | * or else that is being accessed from a lookup class that has |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 502 | * rights to access the member or class. |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 503 | * |
| 504 | * <h1><a name="callsens"></a>Caller sensitive methods</h1> |
| 505 | * A small number of Java methods have a special property called caller sensitivity. |
| 506 | * A <em>caller-sensitive</em> method can behave differently depending on the |
| 507 | * identity of its immediate caller. |
| 508 | * <p> |
| 509 | * If a method handle for a caller-sensitive method is requested, |
| 510 | * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, |
| 511 | * but they take account of the lookup class in a special way. |
| 512 | * The resulting method handle behaves as if it were called |
| 513 | * from an instruction contained in the lookup class, |
| 514 | * so that the caller-sensitive method detects the lookup class. |
| 515 | * (By contrast, the invoker of the method handle is disregarded.) |
| 516 | * Thus, in the case of caller-sensitive methods, |
| 517 | * different lookup classes may give rise to |
| 518 | * differently behaving method handles. |
| 519 | * <p> |
| 520 | * In cases where the lookup object is |
| 521 | * {@link MethodHandles#publicLookup() publicLookup()}, |
| 522 | * or some other lookup object without |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 523 | * <a href="MethodHandles.Lookup.html#privacc">private access</a>, |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 524 | * the lookup class is disregarded. |
| 525 | * In such cases, no caller-sensitive method handle can be created, |
| 526 | * access is forbidden, and the lookup fails with an |
| 527 | * {@code IllegalAccessException}. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 528 | * <p style="font-size:smaller;"> |
| 529 | * <em>Discussion:</em> |
| 530 | * For example, the caller-sensitive method |
| 531 | * {@link java.lang.Class#forName(String) Class.forName(x)} |
| 532 | * can return varying classes or throw varying exceptions, |
| 533 | * depending on the class loader of the class that calls it. |
| 534 | * A public lookup of {@code Class.forName} will fail, because |
| 535 | * there is no reasonable way to determine its bytecode behavior. |
| 536 | * <p style="font-size:smaller;"> |
| 537 | * If an application caches method handles for broad sharing, |
| 538 | * it should use {@code publicLookup()} to create them. |
| 539 | * If there is a lookup of {@code Class.forName}, it will fail, |
| 540 | * and the application must take appropriate action in that case. |
| 541 | * It may be that a later lookup, perhaps during the invocation of a |
| 542 | * bootstrap method, can incorporate the specific identity |
| 543 | * of the caller, making the method accessible. |
| 544 | * <p style="font-size:smaller;"> |
| 545 | * The function {@code MethodHandles.lookup} is caller sensitive |
| 546 | * so that there can be a secure foundation for lookups. |
| 547 | * Nearly all other methods in the JSR 292 API rely on lookup |
| 548 | * objects to check access requests. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 549 | */ |
| 550 | public static final |
| 551 | class Lookup { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 552 | /** The class on behalf of whom the lookup is being performed. */ |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 553 | private final Class<?> lookupClass; |
| 554 | |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 555 | /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 556 | private final int allowedModes; |
| 557 | |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 558 | /** A single-bit mask representing {@code public} access, |
| 559 | * which may contribute to the result of {@link #lookupModes lookupModes}. |
| 560 | * The value, {@code 0x01}, happens to be the same as the value of the |
| 561 | * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. |
| 562 | */ |
| 563 | public static final int PUBLIC = Modifier.PUBLIC; |
| 564 | |
| 565 | /** A single-bit mask representing {@code private} access, |
| 566 | * which may contribute to the result of {@link #lookupModes lookupModes}. |
| 567 | * The value, {@code 0x02}, happens to be the same as the value of the |
| 568 | * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. |
| 569 | */ |
| 570 | public static final int PRIVATE = Modifier.PRIVATE; |
| 571 | |
| 572 | /** A single-bit mask representing {@code protected} access, |
| 573 | * which may contribute to the result of {@link #lookupModes lookupModes}. |
| 574 | * The value, {@code 0x04}, happens to be the same as the value of the |
| 575 | * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. |
| 576 | */ |
| 577 | public static final int PROTECTED = Modifier.PROTECTED; |
| 578 | |
| 579 | /** A single-bit mask representing {@code package} access (default access), |
| 580 | * which may contribute to the result of {@link #lookupModes lookupModes}. |
| 581 | * The value is {@code 0x08}, which does not correspond meaningfully to |
| 582 | * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. |
| 583 | */ |
| 584 | public static final int PACKAGE = Modifier.STATIC; |
| 585 | |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 586 | /** A single-bit mask representing {@code module} access (default access), |
| 587 | * which may contribute to the result of {@link #lookupModes lookupModes}. |
| 588 | * The value is {@code 0x10}, which does not correspond meaningfully to |
| 589 | * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. |
| 590 | * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} |
| 591 | * with this lookup mode can access all public types in the module of the |
| 592 | * lookup class and public types in packages exported by other modules |
| 593 | * to the module of the lookup class. |
| 594 | * @since 9 |
| 595 | */ |
| 596 | public static final int MODULE = PACKAGE << 1; |
| 597 | |
| 598 | private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 599 | private static final int TRUSTED = -1; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 600 | |
| 601 | private static int fixmods(int mods) { |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 602 | mods &= (ALL_MODES - PACKAGE - MODULE); |
| 603 | return (mods != 0) ? mods : (PACKAGE | MODULE); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 604 | } |
| 605 | |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 606 | /** Tells which class is performing the lookup. It is this class against |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 607 | * which checks are performed for visibility and access permissions. |
| 608 | * <p> |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 609 | * The class implies a maximum level of access permission, |
| 610 | * but the permissions may be additionally limited by the bitmask |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 611 | * {@link #lookupModes lookupModes}, which controls whether non-public members |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 612 | * can be accessed. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 613 | * @return the lookup class, on behalf of which this lookup object finds members |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 614 | */ |
| 615 | public Class<?> lookupClass() { |
| 616 | return lookupClass; |
| 617 | } |
| 618 | |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 619 | // This is just for calling out to MethodHandleImpl. |
| 620 | private Class<?> lookupClassOrNull() { |
| 621 | return (allowedModes == TRUSTED) ? null : lookupClass; |
| 622 | } |
| 623 | |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 624 | /** Tells which access-protection classes of members this lookup object can produce. |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 625 | * The result is a bit-mask of the bits |
| 626 | * {@linkplain #PUBLIC PUBLIC (0x01)}, |
| 627 | * {@linkplain #PRIVATE PRIVATE (0x02)}, |
| 628 | * {@linkplain #PROTECTED PROTECTED (0x04)}, |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 629 | * {@linkplain #PACKAGE PACKAGE (0x08)}, |
| 630 | * and {@linkplain #MODULE MODULE (0x10)}. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 631 | * <p> |
| 632 | * A freshly-created lookup object |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 633 | * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 634 | * has all possible bits set, since the caller class can access all its own members, |
| 635 | * all public types in the caller's module, and all public types in packages exported |
| 636 | * by other modules to the caller's module. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 637 | * A lookup object on a new lookup class |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 638 | * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 639 | * may have some mode bits set to zero. |
| 640 | * The purpose of this is to restrict access via the new lookup object, |
| 641 | * so that it can access only names which can be reached by the original |
| 642 | * lookup object, and also by the new lookup class. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 643 | * @return the lookup modes, which limit the kinds of access performed by this lookup object |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 644 | */ |
John R Rose | 6fbfeff | 2010-09-08 18:40:23 -0700 | [diff] [blame] | 645 | public int lookupModes() { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 646 | return allowedModes & ALL_MODES; |
| 647 | } |
| 648 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 649 | /** Embody the current class (the lookupClass) as a lookup class |
| 650 | * for method handle creation. |
| 651 | * Must be called by from a method in this package, |
| 652 | * which in turn is called by a method not in this package. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 653 | */ |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 654 | Lookup(Class<?> lookupClass) { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 655 | this(lookupClass, ALL_MODES); |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 656 | // make sure we haven't accidentally picked up a privileged class: |
Mandy Chung | bd41c42 | 2013-07-22 19:41:07 -0700 | [diff] [blame] | 657 | checkUnprivilegedlookupClass(lookupClass, ALL_MODES); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 658 | } |
| 659 | |
| 660 | private Lookup(Class<?> lookupClass, int allowedModes) { |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 661 | this.lookupClass = lookupClass; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 662 | this.allowedModes = allowedModes; |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 663 | } |
| 664 | |
| 665 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 666 | * Creates a lookup on the specified new lookup class. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 667 | * The resulting object will report the specified |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 668 | * class as its own {@link #lookupClass lookupClass}. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 669 | * <p> |
| 670 | * However, the resulting {@code Lookup} object is guaranteed |
| 671 | * to have no more access capabilities than the original. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 672 | * In particular, access capabilities can be lost as follows:<ul> |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 673 | * <li>If the lookup class for this {@code Lookup} is not in a named module, |
| 674 | * and the new lookup class is in a named module {@code M}, then no members in |
| 675 | * {@code M}'s non-exported packages will be accessible. |
| 676 | * <li>If the lookup for this {@code Lookup} is in a named module, and the |
| 677 | * new lookup class is in a different module {@code M}, then no members, not even |
| 678 | * public members in {@code M}'s exported packages, will be accessible. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 679 | * <li>If the new lookup class differs from the old one, |
| 680 | * protected members will not be accessible by virtue of inheritance. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 681 | * (Protected members may continue to be accessible because of package sharing.) |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 682 | * <li>If the new lookup class is in a different package |
| 683 | * than the old one, protected and default (package) members will not be accessible. |
| 684 | * <li>If the new lookup class is not within the same package member |
| 685 | * as the old one, private members will not be accessible. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 686 | * <li>If the new lookup class is not accessible to the old lookup class, |
| 687 | * then no members, not even public members, will be accessible. |
| 688 | * (In all other cases, public members will continue to be accessible.) |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 689 | * </ul> |
Michael Haupt | bfb7e8c | 2016-03-13 20:26:29 +0100 | [diff] [blame] | 690 | * <p> |
| 691 | * The resulting lookup's capabilities for loading classes |
| 692 | * (used during {@link #findClass} invocations) |
| 693 | * are determined by the lookup class' loader, |
| 694 | * which may change due to this operation. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 695 | * |
| 696 | * @param requestedLookupClass the desired lookup class for the new lookup object |
| 697 | * @return a lookup object which reports the desired lookup class |
| 698 | * @throws NullPointerException if the argument is null |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 699 | */ |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 700 | public Lookup in(Class<?> requestedLookupClass) { |
Aleksey Shipilev | e0e6ce3 | 2015-02-20 18:32:10 +0300 | [diff] [blame] | 701 | Objects.requireNonNull(requestedLookupClass); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 702 | if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all |
| 703 | return new Lookup(requestedLookupClass, ALL_MODES); |
| 704 | if (requestedLookupClass == this.lookupClass) |
| 705 | return this; // keep same capabilities |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 706 | |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 707 | int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 708 | if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) { |
| 709 | // Allowed to teleport from an unnamed to a named module but resulting |
| 710 | // Lookup has no access to module private members |
| 711 | if (this.lookupClass.getModule().isNamed()) { |
| 712 | newModes = 0; |
| 713 | } else { |
| 714 | newModes &= ~MODULE; |
| 715 | } |
| 716 | } |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 717 | if ((newModes & PACKAGE) != 0 |
| 718 | && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { |
| 719 | newModes &= ~(PACKAGE|PRIVATE); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 720 | } |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 721 | // Allow nestmate lookups to be created without special privilege: |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 722 | if ((newModes & PRIVATE) != 0 |
| 723 | && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { |
| 724 | newModes &= ~PRIVATE; |
| 725 | } |
John R Rose | 6b14cf6 | 2012-05-18 20:31:28 -0700 | [diff] [blame] | 726 | if ((newModes & PUBLIC) != 0 |
| 727 | && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 728 | // The requested class it not accessible from the lookup class. |
| 729 | // No permissions. |
| 730 | newModes = 0; |
| 731 | } |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 732 | |
Mandy Chung | bd41c42 | 2013-07-22 19:41:07 -0700 | [diff] [blame] | 733 | checkUnprivilegedlookupClass(requestedLookupClass, newModes); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 734 | return new Lookup(requestedLookupClass, newModes); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 735 | } |
| 736 | |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 737 | // Make sure outer class is initialized first. |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 738 | static { IMPL_NAMES.getClass(); } |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 739 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 740 | /** Package-private version of lookup which is trusted. */ |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 741 | static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 742 | |
Mandy Chung | bd41c42 | 2013-07-22 19:41:07 -0700 | [diff] [blame] | 743 | private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { |
John R Rose | 708863f | 2009-05-12 13:54:22 -0700 | [diff] [blame] | 744 | String name = lookupClass.getName(); |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 745 | if (name.startsWith("java.lang.invoke.")) |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 746 | throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); |
Mandy Chung | bd41c42 | 2013-07-22 19:41:07 -0700 | [diff] [blame] | 747 | |
Paul Sandoz | 27f82be | 2016-04-26 18:42:51 -0700 | [diff] [blame] | 748 | // For caller-sensitive MethodHandles.lookup() disallow lookup from |
| 749 | // restricted packages. This a fragile and blunt approach. |
| 750 | // TODO replace with a more formal and less fragile mechanism |
| 751 | // that does not bluntly restrict classes under packages within |
| 752 | // java.base from looking up MethodHandles or VarHandles. |
Mandy Chung | bd41c42 | 2013-07-22 19:41:07 -0700 | [diff] [blame] | 753 | if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) { |
Paul Sandoz | 27f82be | 2016-04-26 18:42:51 -0700 | [diff] [blame] | 754 | if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) || |
Mandy Chung | bd41c42 | 2013-07-22 19:41:07 -0700 | [diff] [blame] | 755 | (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) { |
| 756 | throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); |
| 757 | } |
| 758 | } |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 759 | } |
| 760 | |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 761 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 762 | * Displays the name of the class from which lookups are to be made. |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 763 | * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) |
| 764 | * If there are restrictions on the access permitted to this lookup, |
| 765 | * this is indicated by adding a suffix to the class name, consisting |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 766 | * of a slash and a keyword. The keyword represents the strongest |
| 767 | * allowed access, and is chosen as follows: |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 768 | * <ul> |
| 769 | * <li>If no access is allowed, the suffix is "/noaccess". |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 770 | * <li>If only public access to types in exported packages is allowed, the suffix is "/public". |
| 771 | * <li>If only public and module access are allowed, the suffix is "/module". |
| 772 | * <li>If only public, module and package access are allowed, the suffix is "/package". |
| 773 | * <li>If only public, module, package, and private access are allowed, the suffix is "/private". |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 774 | * </ul> |
| 775 | * If none of the above cases apply, it is the case that full |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 776 | * access (public, module, package, private, and protected) is allowed. |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 777 | * In this case, no suffix is added. |
| 778 | * This is true only of an object obtained originally from |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 779 | * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. |
| 780 | * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 781 | * always have restricted access, and will display a suffix. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 782 | * <p> |
| 783 | * (It may seem strange that protected access should be |
| 784 | * stronger than private access. Viewed independently from |
| 785 | * package access, protected access is the first to be lost, |
| 786 | * because it requires a direct subclass relationship between |
| 787 | * caller and callee.) |
| 788 | * @see #in |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 789 | */ |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 790 | @Override |
| 791 | public String toString() { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 792 | String cname = lookupClass.getName(); |
| 793 | switch (allowedModes) { |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 794 | case 0: // no privileges |
| 795 | return cname + "/noaccess"; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 796 | case PUBLIC: |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 797 | return cname + "/public"; |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 798 | case PUBLIC|MODULE: |
| 799 | return cname + "/module"; |
| 800 | case PUBLIC|MODULE|PACKAGE: |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 801 | return cname + "/package"; |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 802 | case ALL_MODES & ~PROTECTED: |
| 803 | return cname + "/private"; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 804 | case ALL_MODES: |
| 805 | return cname; |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 806 | case TRUSTED: |
| 807 | return "/trusted"; // internal only; not exported |
| 808 | default: // Should not happen, but it's a bitfield... |
| 809 | cname = cname + "/" + Integer.toHexString(allowedModes); |
| 810 | assert(false) : cname; |
| 811 | return cname; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 812 | } |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 813 | } |
| 814 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 815 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 816 | * Produces a method handle for a static method. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 817 | * The type of the method handle will be that of the method. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 818 | * (Since static methods do not take receivers, there is no |
| 819 | * additional receiver argument inserted into the method handle type, |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 820 | * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 821 | * The method and all its argument types must be accessible to the lookup object. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 822 | * <p> |
| 823 | * The returned method handle will have |
| 824 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 825 | * the method's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 826 | * <p> |
| 827 | * If the returned method handle is invoked, the method's class will |
| 828 | * be initialized, if it has not already been initialized. |
| 829 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 830 | * <blockquote><pre>{@code |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 831 | import static java.lang.invoke.MethodHandles.*; |
| 832 | import static java.lang.invoke.MethodType.*; |
| 833 | ... |
| 834 | MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, |
| 835 | "asList", methodType(List.class, Object[].class)); |
| 836 | assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); |
| 837 | * }</pre></blockquote> |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 838 | * @param refc the class from which the method is accessed |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 839 | * @param name the name of the method |
| 840 | * @param type the type of the method |
| 841 | * @return the desired method handle |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 842 | * @throws NoSuchMethodException if the method does not exist |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 843 | * @throws IllegalAccessException if access checking fails, |
| 844 | * or if the method is not {@code static}, |
| 845 | * or if the method's variable arity modifier bit |
| 846 | * is set and {@code asVarargsCollector} fails |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 847 | * @exception SecurityException if a security manager is present and it |
| 848 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 849 | * @throws NullPointerException if any argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 850 | */ |
| 851 | public |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 852 | MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 853 | MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 854 | return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method)); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 855 | } |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 856 | |
| 857 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 858 | * Produces a method handle for a virtual method. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 859 | * The type of the method handle will be that of the method, |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 860 | * with the receiver type (usually {@code refc}) prepended. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 861 | * The method and all its argument types must be accessible to the lookup object. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 862 | * <p> |
| 863 | * When called, the handle will treat the first argument as a receiver |
| 864 | * and dispatch on the receiver's type to determine which method |
| 865 | * implementation to enter. |
| 866 | * (The dispatching action is identical with that performed by an |
| 867 | * {@code invokevirtual} or {@code invokeinterface} instruction.) |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 868 | * <p> |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 869 | * The first argument will be of type {@code refc} if the lookup |
| 870 | * class has full privileges to access the member. Otherwise |
| 871 | * the member must be {@code protected} and the first argument |
| 872 | * will be restricted in type to the lookup class. |
| 873 | * <p> |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 874 | * The returned method handle will have |
| 875 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 876 | * the method's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 877 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 878 | * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 879 | * instructions and method handles produced by {@code findVirtual}, |
| 880 | * if the class is {@code MethodHandle} and the name string is |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 881 | * {@code invokeExact} or {@code invoke}, the resulting |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 882 | * method handle is equivalent to one produced by |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 883 | * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 884 | * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 885 | * with the same {@code type} argument. |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 886 | * <p> |
| 887 | * If the class is {@code VarHandle} and the name string corresponds to |
| 888 | * the name of a signature-polymorphic access mode method, the resulting |
| 889 | * method handle is equivalent to one produced by |
| 890 | * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with |
| 891 | * the access mode corresponding to the name string and with the same |
| 892 | * {@code type} arguments. |
| 893 | * <p> |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 894 | * <b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 895 | * <blockquote><pre>{@code |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 896 | import static java.lang.invoke.MethodHandles.*; |
| 897 | import static java.lang.invoke.MethodType.*; |
| 898 | ... |
| 899 | MethodHandle MH_concat = publicLookup().findVirtual(String.class, |
| 900 | "concat", methodType(String.class, String.class)); |
| 901 | MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, |
| 902 | "hashCode", methodType(int.class)); |
| 903 | MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, |
| 904 | "hashCode", methodType(int.class)); |
| 905 | assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); |
| 906 | assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); |
| 907 | assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); |
| 908 | // interface method: |
| 909 | MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, |
| 910 | "subSequence", methodType(CharSequence.class, int.class, int.class)); |
| 911 | assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); |
| 912 | // constructor "internal method" must be accessed differently: |
| 913 | MethodType MT_newString = methodType(void.class); //()V for new String() |
| 914 | try { assertEquals("impossible", lookup() |
| 915 | .findVirtual(String.class, "<init>", MT_newString)); |
| 916 | } catch (NoSuchMethodException ex) { } // OK |
| 917 | MethodHandle MH_newString = publicLookup() |
| 918 | .findConstructor(String.class, MT_newString); |
| 919 | assertEquals("", (String) MH_newString.invokeExact()); |
| 920 | * }</pre></blockquote> |
| 921 | * |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 922 | * @param refc the class or interface from which the method is accessed |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 923 | * @param name the name of the method |
| 924 | * @param type the type of the method, with the receiver argument omitted |
| 925 | * @return the desired method handle |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 926 | * @throws NoSuchMethodException if the method does not exist |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 927 | * @throws IllegalAccessException if access checking fails, |
Shilpi Rastogi | 3e45966 | 2016-02-10 10:44:58 +0100 | [diff] [blame] | 928 | * or if the method is {@code static}, |
| 929 | * or if the method is {@code private} method of interface, |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 930 | * or if the method's variable arity modifier bit |
| 931 | * is set and {@code asVarargsCollector} fails |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 932 | * @exception SecurityException if a security manager is present and it |
| 933 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 934 | * @throws NullPointerException if any argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 935 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 936 | public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 937 | if (refc == MethodHandle.class) { |
| 938 | MethodHandle mh = findVirtualForMH(name, type); |
| 939 | if (mh != null) return mh; |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 940 | } else if (refc == VarHandle.class) { |
| 941 | MethodHandle mh = findVirtualForVH(name, type); |
| 942 | if (mh != null) return mh; |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 943 | } |
| 944 | byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); |
| 945 | MemberName method = resolveOrFail(refKind, refc, name, type); |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 946 | return getDirectMethod(refKind, refc, method, findBoundCallerClass(method)); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 947 | } |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 948 | private MethodHandle findVirtualForMH(String name, MethodType type) { |
| 949 | // these names require special lookups because of the implicit MethodType argument |
| 950 | if ("invoke".equals(name)) |
| 951 | return invoker(type); |
| 952 | if ("invokeExact".equals(name)) |
| 953 | return exactInvoker(type); |
John Rose | da56d3f | 2014-09-10 19:19:47 +0400 | [diff] [blame] | 954 | if ("invokeBasic".equals(name)) |
| 955 | return basicInvoker(type); |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 956 | assert(!MemberName.isMethodHandleInvokeName(name)); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 957 | return null; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 958 | } |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 959 | private MethodHandle findVirtualForVH(String name, MethodType type) { |
| 960 | try { |
Paul Sandoz | a7aff44 | 2016-04-13 15:05:48 +0200 | [diff] [blame] | 961 | return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 962 | } catch (IllegalArgumentException e) { |
| 963 | return null; |
| 964 | } |
| 965 | } |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 966 | |
| 967 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 968 | * Produces a method handle which creates an object and initializes it, using |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 969 | * the constructor of the specified type. |
| 970 | * The parameter types of the method handle will be those of the constructor, |
| 971 | * while the return type will be a reference to the constructor's class. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 972 | * The constructor and all its argument types must be accessible to the lookup object. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 973 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 974 | * The requested type must have a return type of {@code void}. |
| 975 | * (This is consistent with the JVM's treatment of constructor type descriptors.) |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 976 | * <p> |
| 977 | * The returned method handle will have |
| 978 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 979 | * the constructor's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 980 | * <p> |
| 981 | * If the returned method handle is invoked, the constructor's class will |
| 982 | * be initialized, if it has not already been initialized. |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 983 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 984 | * <blockquote><pre>{@code |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 985 | import static java.lang.invoke.MethodHandles.*; |
| 986 | import static java.lang.invoke.MethodType.*; |
| 987 | ... |
| 988 | MethodHandle MH_newArrayList = publicLookup().findConstructor( |
| 989 | ArrayList.class, methodType(void.class, Collection.class)); |
| 990 | Collection orig = Arrays.asList("x", "y"); |
| 991 | Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); |
| 992 | assert(orig != copy); |
| 993 | assertEquals(orig, copy); |
| 994 | // a variable-arity constructor: |
| 995 | MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( |
| 996 | ProcessBuilder.class, methodType(void.class, String[].class)); |
| 997 | ProcessBuilder pb = (ProcessBuilder) |
| 998 | MH_newProcessBuilder.invoke("x", "y", "z"); |
| 999 | assertEquals("[x, y, z]", pb.command().toString()); |
| 1000 | * }</pre></blockquote> |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1001 | * @param refc the class or interface from which the method is accessed |
| 1002 | * @param type the type of the method, with the receiver argument omitted, and a void return type |
| 1003 | * @return the desired method handle |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1004 | * @throws NoSuchMethodException if the constructor does not exist |
| 1005 | * @throws IllegalAccessException if access checking fails |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1006 | * or if the method's variable arity modifier bit |
| 1007 | * is set and {@code asVarargsCollector} fails |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1008 | * @exception SecurityException if a security manager is present and it |
| 1009 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1010 | * @throws NullPointerException if any argument is null |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1011 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1012 | public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { |
Michael Haupt | 0b77755 | 2016-04-27 20:18:49 +0200 | [diff] [blame] | 1013 | if (refc.isArray()) { |
| 1014 | throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); |
| 1015 | } |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1016 | String name = "<init>"; |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1017 | MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1018 | return getDirectConstructor(refc, ctor); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1019 | } |
| 1020 | |
| 1021 | /** |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1022 | * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static |
| 1023 | * initializer of the class is not run. |
Michael Haupt | bfb7e8c | 2016-03-13 20:26:29 +0100 | [diff] [blame] | 1024 | * <p> |
| 1025 | * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class |
| 1026 | * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to |
| 1027 | * load the requested class, and then determines whether the class is accessible to this lookup object. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1028 | * |
| 1029 | * @param targetName the fully qualified name of the class to be looked up. |
| 1030 | * @return the requested class. |
| 1031 | * @exception SecurityException if a security manager is present and it |
| 1032 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
| 1033 | * @throws LinkageError if the linkage fails |
Michael Haupt | bfb7e8c | 2016-03-13 20:26:29 +0100 | [diff] [blame] | 1034 | * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1035 | * @throws IllegalAccessException if the class is not accessible, using the allowed access |
| 1036 | * modes. |
| 1037 | * @exception SecurityException if a security manager is present and it |
| 1038 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
| 1039 | * @since 9 |
| 1040 | */ |
| 1041 | public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { |
| 1042 | Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); |
| 1043 | return accessClass(targetClass); |
| 1044 | } |
| 1045 | |
| 1046 | /** |
| 1047 | * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The |
| 1048 | * static initializer of the class is not run. |
Michael Haupt | bfb7e8c | 2016-03-13 20:26:29 +0100 | [diff] [blame] | 1049 | * <p> |
| 1050 | * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the |
| 1051 | * {@linkplain #lookupModes() lookup modes}. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1052 | * |
| 1053 | * @param targetClass the class to be access-checked |
| 1054 | * |
| 1055 | * @return the class that has been access-checked |
| 1056 | * |
| 1057 | * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access |
| 1058 | * modes. |
| 1059 | * @exception SecurityException if a security manager is present and it |
| 1060 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
| 1061 | * @since 9 |
| 1062 | */ |
| 1063 | public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { |
| 1064 | if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) { |
| 1065 | throw new MemberName(targetClass).makeAccessException("access violation", this); |
| 1066 | } |
| 1067 | checkSecurityManager(targetClass, null); |
| 1068 | return targetClass; |
| 1069 | } |
| 1070 | |
| 1071 | /** |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1072 | * Produces an early-bound method handle for a virtual method. |
| 1073 | * It will bypass checks for overriding methods on the receiver, |
| 1074 | * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} |
| 1075 | * instruction from within the explicitly specified {@code specialCaller}. |
John R Rose | 9d698bd | 2009-05-11 21:09:58 -0700 | [diff] [blame] | 1076 | * The type of the method handle will be that of the method, |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1077 | * with a suitably restricted receiver type prepended. |
| 1078 | * (The receiver type will be {@code specialCaller} or a subtype.) |
John R Rose | 9d698bd | 2009-05-11 21:09:58 -0700 | [diff] [blame] | 1079 | * The method and all its argument types must be accessible |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1080 | * to the lookup object. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1081 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1082 | * Before method resolution, |
| 1083 | * if the explicitly specified caller class is not identical with the |
| 1084 | * lookup class, or if this lookup object does not have |
| 1085 | * <a href="MethodHandles.Lookup.html#privacc">private access</a> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 1086 | * privileges, the access fails. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1087 | * <p> |
| 1088 | * The returned method handle will have |
| 1089 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 1090 | * the method's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1091 | * <p style="font-size:smaller;"> |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1092 | * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, |
| 1093 | * even though the {@code invokespecial} instruction can refer to them |
| 1094 | * in special circumstances. Use {@link #findConstructor findConstructor} |
| 1095 | * to access instance initialization methods in a safe manner.)</em> |
| 1096 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 1097 | * <blockquote><pre>{@code |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1098 | import static java.lang.invoke.MethodHandles.*; |
| 1099 | import static java.lang.invoke.MethodType.*; |
| 1100 | ... |
| 1101 | static class Listie extends ArrayList { |
| 1102 | public String toString() { return "[wee Listie]"; } |
| 1103 | static Lookup lookup() { return MethodHandles.lookup(); } |
| 1104 | } |
| 1105 | ... |
| 1106 | // no access to constructor via invokeSpecial: |
| 1107 | MethodHandle MH_newListie = Listie.lookup() |
| 1108 | .findConstructor(Listie.class, methodType(void.class)); |
| 1109 | Listie l = (Listie) MH_newListie.invokeExact(); |
| 1110 | try { assertEquals("impossible", Listie.lookup().findSpecial( |
| 1111 | Listie.class, "<init>", methodType(void.class), Listie.class)); |
| 1112 | } catch (NoSuchMethodException ex) { } // OK |
| 1113 | // access to super and self methods via invokeSpecial: |
| 1114 | MethodHandle MH_super = Listie.lookup().findSpecial( |
| 1115 | ArrayList.class, "toString" , methodType(String.class), Listie.class); |
| 1116 | MethodHandle MH_this = Listie.lookup().findSpecial( |
| 1117 | Listie.class, "toString" , methodType(String.class), Listie.class); |
| 1118 | MethodHandle MH_duper = Listie.lookup().findSpecial( |
| 1119 | Object.class, "toString" , methodType(String.class), Listie.class); |
| 1120 | assertEquals("[]", (String) MH_super.invokeExact(l)); |
| 1121 | assertEquals(""+l, (String) MH_this.invokeExact(l)); |
| 1122 | assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method |
| 1123 | try { assertEquals("inaccessible", Listie.lookup().findSpecial( |
| 1124 | String.class, "toString", methodType(String.class), Listie.class)); |
| 1125 | } catch (IllegalAccessException ex) { } // OK |
| 1126 | Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; |
| 1127 | assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method |
| 1128 | * }</pre></blockquote> |
| 1129 | * |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1130 | * @param refc the class or interface from which the method is accessed |
| 1131 | * @param name the name of the method (which must not be "<init>") |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1132 | * @param type the type of the method, with the receiver argument omitted |
| 1133 | * @param specialCaller the proposed calling class to perform the {@code invokespecial} |
| 1134 | * @return the desired method handle |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1135 | * @throws NoSuchMethodException if the method does not exist |
Shilpi Rastogi | e49c241 | 2016-02-08 17:37:46 +0100 | [diff] [blame] | 1136 | * @throws IllegalAccessException if access checking fails, |
| 1137 | * or if the method is {@code static}, |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1138 | * or if the method's variable arity modifier bit |
| 1139 | * is set and {@code asVarargsCollector} fails |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1140 | * @exception SecurityException if a security manager is present and it |
| 1141 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1142 | * @throws NullPointerException if any argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1143 | */ |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1144 | public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1145 | Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1146 | checkSpecialCaller(specialCaller, refc); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1147 | Lookup specialLookup = this.in(specialCaller); |
| 1148 | MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1149 | return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 1150 | } |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1151 | |
| 1152 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1153 | * Produces a method handle giving read access to a non-static field. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1154 | * The type of the method handle will have a return type of the field's |
| 1155 | * value type. |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1156 | * The method handle's single argument will be the instance containing |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1157 | * the field. |
| 1158 | * Access checking is performed immediately on behalf of the lookup class. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1159 | * @param refc the class or interface from which the method is accessed |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1160 | * @param name the field's name |
| 1161 | * @param type the field's type |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1162 | * @return a method handle which can load values from the field |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1163 | * @throws NoSuchFieldException if the field does not exist |
| 1164 | * @throws IllegalAccessException if access checking fails, or if the field is {@code static} |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1165 | * @exception SecurityException if a security manager is present and it |
| 1166 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1167 | * @throws NullPointerException if any argument is null |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1168 | * @see #findVarHandle(Class, String, Class) |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1169 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1170 | public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1171 | MemberName field = resolveOrFail(REF_getField, refc, name, type); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1172 | return getDirectField(REF_getField, refc, field); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 1173 | } |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1174 | |
| 1175 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1176 | * Produces a method handle giving write access to a non-static field. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1177 | * The type of the method handle will have a void return type. |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1178 | * The method handle will take two arguments, the instance containing |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1179 | * the field, and the value to be stored. |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1180 | * The second argument will be of the field's value type. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1181 | * Access checking is performed immediately on behalf of the lookup class. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1182 | * @param refc the class or interface from which the method is accessed |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1183 | * @param name the field's name |
| 1184 | * @param type the field's type |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1185 | * @return a method handle which can store values into the field |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1186 | * @throws NoSuchFieldException if the field does not exist |
| 1187 | * @throws IllegalAccessException if access checking fails, or if the field is {@code static} |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1188 | * @exception SecurityException if a security manager is present and it |
| 1189 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1190 | * @throws NullPointerException if any argument is null |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1191 | * @see #findVarHandle(Class, String, Class) |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1192 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1193 | public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1194 | MemberName field = resolveOrFail(REF_putField, refc, name, type); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1195 | return getDirectField(REF_putField, refc, field); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 1196 | } |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1197 | |
| 1198 | /** |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1199 | * Produces a VarHandle giving access to non-static fields of type |
| 1200 | * {@code T} declared by a receiver class of type {@code R}, supporting |
| 1201 | * shape {@code (R : T)}. |
| 1202 | * <p> |
| 1203 | * Access checking is performed immediately on behalf of the lookup |
| 1204 | * class. |
| 1205 | * <p> |
| 1206 | * Certain access modes of the returned VarHandle are unsupported under |
| 1207 | * the following conditions: |
| 1208 | * <ul> |
| 1209 | * <li>if the field is declared {@code final}, then the write, atomic |
| 1210 | * update, and numeric atomic update access modes are unsupported. |
| 1211 | * <li>if the field type is anything other than {@code int}, |
| 1212 | * {@code long} or a reference type, then atomic update access modes |
| 1213 | * are unsupported. (Future major platform releases of the JDK may |
| 1214 | * support additional types for certain currently unsupported access |
| 1215 | * modes.) |
| 1216 | * <li>if the field type is anything other than {@code int} or |
| 1217 | * {@code long}, then numeric atomic update access modes are |
| 1218 | * unsupported. (Future major platform releases of the JDK may |
| 1219 | * support additional numeric types for certain currently |
| 1220 | * unsupported access modes.) |
| 1221 | * </ul> |
| 1222 | * <p> |
| 1223 | * If the field is declared {@code volatile} then the returned VarHandle |
| 1224 | * will override access to the field (effectively ignore the |
| 1225 | * {@code volatile} declaration) in accordance to it's specified |
| 1226 | * access modes. |
| 1227 | * @param recv the receiver class, of type {@code R}, that declares the |
| 1228 | * non-static field |
| 1229 | * @param name the field's name |
| 1230 | * @param type the field's type, of type {@code T} |
| 1231 | * @return a VarHandle giving access to non-static fields. |
| 1232 | * @throws NoSuchFieldException if the field does not exist |
| 1233 | * @throws IllegalAccessException if access checking fails, or if the field is {@code static} |
| 1234 | * @exception SecurityException if a security manager is present and it |
| 1235 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
| 1236 | * @throws NullPointerException if any argument is null |
| 1237 | * @since 9 |
| 1238 | */ |
| 1239 | public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
| 1240 | MemberName getField = resolveOrFail(REF_getField, recv, name, type); |
| 1241 | MemberName putField = resolveOrFail(REF_putField, recv, name, type); |
| 1242 | return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); |
| 1243 | } |
| 1244 | |
| 1245 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1246 | * Produces a method handle giving read access to a static field. |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1247 | * The type of the method handle will have a return type of the field's |
| 1248 | * value type. |
| 1249 | * The method handle will take no arguments. |
| 1250 | * Access checking is performed immediately on behalf of the lookup class. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1251 | * <p> |
| 1252 | * If the returned method handle is invoked, the field's class will |
| 1253 | * be initialized, if it has not already been initialized. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1254 | * @param refc the class or interface from which the method is accessed |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1255 | * @param name the field's name |
| 1256 | * @param type the field's type |
| 1257 | * @return a method handle which can load values from the field |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1258 | * @throws NoSuchFieldException if the field does not exist |
| 1259 | * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1260 | * @exception SecurityException if a security manager is present and it |
| 1261 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1262 | * @throws NullPointerException if any argument is null |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1263 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1264 | public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1265 | MemberName field = resolveOrFail(REF_getStatic, refc, name, type); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1266 | return getDirectField(REF_getStatic, refc, field); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 1267 | } |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1268 | |
| 1269 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1270 | * Produces a method handle giving write access to a static field. |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1271 | * The type of the method handle will have a void return type. |
| 1272 | * The method handle will take a single |
| 1273 | * argument, of the field's value type, the value to be stored. |
| 1274 | * Access checking is performed immediately on behalf of the lookup class. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1275 | * <p> |
| 1276 | * If the returned method handle is invoked, the field's class will |
| 1277 | * be initialized, if it has not already been initialized. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1278 | * @param refc the class or interface from which the method is accessed |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1279 | * @param name the field's name |
| 1280 | * @param type the field's type |
| 1281 | * @return a method handle which can store values into the field |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1282 | * @throws NoSuchFieldException if the field does not exist |
| 1283 | * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1284 | * @exception SecurityException if a security manager is present and it |
| 1285 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1286 | * @throws NullPointerException if any argument is null |
John R Rose | 4df63ba | 2010-06-08 23:08:56 -0700 | [diff] [blame] | 1287 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1288 | public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1289 | MemberName field = resolveOrFail(REF_putStatic, refc, name, type); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1290 | return getDirectField(REF_putStatic, refc, field); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 1291 | } |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1292 | |
| 1293 | /** |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1294 | * Produces a VarHandle giving access to a static field of type |
| 1295 | * {@code T} declared by a given declaring class, supporting shape |
| 1296 | * {@code ((empty) : T)}. |
| 1297 | * <p> |
| 1298 | * Access checking is performed immediately on behalf of the lookup |
| 1299 | * class. |
| 1300 | * <p> |
| 1301 | * If the returned VarHandle is operated on, the declaring class will be |
| 1302 | * initialized, if it has not already been initialized. |
| 1303 | * <p> |
| 1304 | * Certain access modes of the returned VarHandle are unsupported under |
| 1305 | * the following conditions: |
| 1306 | * <ul> |
| 1307 | * <li>if the field is declared {@code final}, then the write, atomic |
| 1308 | * update, and numeric atomic update access modes are unsupported. |
| 1309 | * <li>if the field type is anything other than {@code int}, |
| 1310 | * {@code long} or a reference type, then atomic update access modes |
| 1311 | * are unsupported. (Future major platform releases of the JDK may |
| 1312 | * support additional types for certain currently unsupported access |
| 1313 | * modes.) |
| 1314 | * <li>if the field type is anything other than {@code int} or |
| 1315 | * {@code long}, then numeric atomic update access modes are |
| 1316 | * unsupported. (Future major platform releases of the JDK may |
| 1317 | * support additional numeric types for certain currently |
| 1318 | * unsupported access modes.) |
| 1319 | * </ul> |
| 1320 | * <p> |
| 1321 | * If the field is declared {@code volatile} then the returned VarHandle |
| 1322 | * will override access to the field (effectively ignore the |
| 1323 | * {@code volatile} declaration) in accordance to it's specified |
| 1324 | * access modes. |
| 1325 | * @param decl the class that declares the static field |
| 1326 | * @param name the field's name |
| 1327 | * @param type the field's type, of type {@code T} |
| 1328 | * @return a VarHandle giving access to a static field |
| 1329 | * @throws NoSuchFieldException if the field does not exist |
| 1330 | * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} |
| 1331 | * @exception SecurityException if a security manager is present and it |
| 1332 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
| 1333 | * @throws NullPointerException if any argument is null |
| 1334 | * @since 9 |
| 1335 | */ |
| 1336 | public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
| 1337 | MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); |
| 1338 | MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); |
| 1339 | return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); |
| 1340 | } |
| 1341 | |
| 1342 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1343 | * Produces an early-bound method handle for a non-static method. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1344 | * The receiver must have a supertype {@code defc} in which a method |
| 1345 | * of the given name and type is accessible to the lookup class. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1346 | * The method and all its argument types must be accessible to the lookup object. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 1347 | * The type of the method handle will be that of the method, |
| 1348 | * without any insertion of an additional receiver parameter. |
| 1349 | * The given receiver will be bound into the method handle, |
| 1350 | * so that every call to the method handle will invoke the |
| 1351 | * requested method on the given receiver. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1352 | * <p> |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1353 | * The returned method handle will have |
| 1354 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 1355 | * the method's variable arity modifier bit ({@code 0x0080}) is set |
| 1356 | * <em>and</em> the trailing array argument is not the only argument. |
| 1357 | * (If the trailing array argument is the only argument, |
| 1358 | * the given receiver value will be bound to it.) |
| 1359 | * <p> |
| 1360 | * This is equivalent to the following code: |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1361 | * <blockquote><pre>{@code |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1362 | import static java.lang.invoke.MethodHandles.*; |
| 1363 | import static java.lang.invoke.MethodType.*; |
| 1364 | ... |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1365 | MethodHandle mh0 = lookup().findVirtual(defc, name, type); |
| 1366 | MethodHandle mh1 = mh0.bindTo(receiver); |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 1367 | mh1 = mh1.withVarargs(mh0.isVarargsCollector()); |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1368 | return mh1; |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1369 | * }</pre></blockquote> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 1370 | * where {@code defc} is either {@code receiver.getClass()} or a super |
| 1371 | * type of that class, in which the requested method is accessible |
| 1372 | * to the lookup class. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1373 | * (Note that {@code bindTo} does not preserve variable arity.) |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1374 | * @param receiver the object from which the method is accessed |
| 1375 | * @param name the name of the method |
| 1376 | * @param type the type of the method, with the receiver argument omitted |
| 1377 | * @return the desired method handle |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1378 | * @throws NoSuchMethodException if the method does not exist |
| 1379 | * @throws IllegalAccessException if access checking fails |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1380 | * or if the method's variable arity modifier bit |
| 1381 | * is set and {@code asVarargsCollector} fails |
John R Rose | ba8c992 | 2011-02-15 00:16:53 -0800 | [diff] [blame] | 1382 | * @exception SecurityException if a security manager is present and it |
| 1383 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1384 | * @throws NullPointerException if any argument is null |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1385 | * @see MethodHandle#bindTo |
| 1386 | * @see #findVirtual |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1387 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1388 | public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1389 | Class<? extends Object> refc = receiver.getClass(); // may get NPE |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1390 | MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1391 | MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 1392 | return mh.bindArgumentL(0, receiver).setVarargs(method); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1393 | } |
| 1394 | |
| 1395 | /** |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1396 | * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> |
| 1397 | * to <i>m</i>, if the lookup class has permission. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1398 | * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. |
| 1399 | * If <i>m</i> is virtual, overriding is respected on every call. |
| 1400 | * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. |
| 1401 | * The type of the method handle will be that of the method, |
| 1402 | * with the receiver type prepended (but only if it is non-static). |
| 1403 | * If the method's {@code accessible} flag is not set, |
| 1404 | * access checking is performed immediately on behalf of the lookup class. |
| 1405 | * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1406 | * <p> |
| 1407 | * The returned method handle will have |
| 1408 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 1409 | * the method's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1410 | * <p> |
| 1411 | * If <i>m</i> is static, and |
| 1412 | * if the returned method handle is invoked, the method's class will |
| 1413 | * be initialized, if it has not already been initialized. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1414 | * @param m the reflected method |
| 1415 | * @return a method handle which can invoke the reflected method |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1416 | * @throws IllegalAccessException if access checking fails |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1417 | * or if the method's variable arity modifier bit |
| 1418 | * is set and {@code asVarargsCollector} fails |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1419 | * @throws NullPointerException if the argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1420 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1421 | public MethodHandle unreflect(Method m) throws IllegalAccessException { |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1422 | if (m.getDeclaringClass() == MethodHandle.class) { |
| 1423 | MethodHandle mh = unreflectForMH(m); |
| 1424 | if (mh != null) return mh; |
| 1425 | } |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1426 | if (m.getDeclaringClass() == VarHandle.class) { |
| 1427 | MethodHandle mh = unreflectForVH(m); |
| 1428 | if (mh != null) return mh; |
| 1429 | } |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1430 | MemberName method = new MemberName(m); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1431 | byte refKind = method.getReferenceKind(); |
| 1432 | if (refKind == REF_invokeSpecial) |
| 1433 | refKind = REF_invokeVirtual; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1434 | assert(method.isMethod()); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1435 | Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1436 | return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1437 | } |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1438 | private MethodHandle unreflectForMH(Method m) { |
| 1439 | // these names require special lookups because they throw UnsupportedOperationException |
| 1440 | if (MemberName.isMethodHandleInvokeName(m.getName())) |
| 1441 | return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); |
| 1442 | return null; |
| 1443 | } |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1444 | private MethodHandle unreflectForVH(Method m) { |
| 1445 | // these names require special lookups because they throw UnsupportedOperationException |
| 1446 | if (MemberName.isVarHandleMethodInvokeName(m.getName())) |
| 1447 | return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); |
| 1448 | return null; |
| 1449 | } |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1450 | |
| 1451 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1452 | * Produces a method handle for a reflected method. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1453 | * It will bypass checks for overriding methods on the receiver, |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1454 | * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} |
| 1455 | * instruction from within the explicitly specified {@code specialCaller}. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1456 | * The type of the method handle will be that of the method, |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1457 | * with a suitably restricted receiver type prepended. |
| 1458 | * (The receiver type will be {@code specialCaller} or a subtype.) |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1459 | * If the method's {@code accessible} flag is not set, |
| 1460 | * access checking is performed immediately on behalf of the lookup class, |
| 1461 | * as if {@code invokespecial} instruction were being linked. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1462 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1463 | * Before method resolution, |
| 1464 | * if the explicitly specified caller class is not identical with the |
| 1465 | * lookup class, or if this lookup object does not have |
| 1466 | * <a href="MethodHandles.Lookup.html#privacc">private access</a> |
| 1467 | * privileges, the access fails. |
| 1468 | * <p> |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1469 | * The returned method handle will have |
| 1470 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 1471 | * the method's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1472 | * @param m the reflected method |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1473 | * @param specialCaller the class nominally calling the method |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1474 | * @return a method handle which can invoke the reflected method |
Shilpi Rastogi | e49c241 | 2016-02-08 17:37:46 +0100 | [diff] [blame] | 1475 | * @throws IllegalAccessException if access checking fails, |
| 1476 | * or if the method is {@code static}, |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1477 | * or if the method's variable arity modifier bit |
| 1478 | * is set and {@code asVarargsCollector} fails |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1479 | * @throws NullPointerException if any argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1480 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1481 | public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1482 | checkSpecialCaller(specialCaller, null); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1483 | Lookup specialLookup = this.in(specialCaller); |
| 1484 | MemberName method = new MemberName(m, true); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1485 | assert(method.isMethod()); |
| 1486 | // ignore m.isAccessible: this is a new kind of access |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1487 | return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1488 | } |
| 1489 | |
| 1490 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1491 | * Produces a method handle for a reflected constructor. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 1492 | * The type of the method handle will be that of the constructor, |
| 1493 | * with the return type changed to the declaring class. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1494 | * The method handle will perform a {@code newInstance} operation, |
| 1495 | * creating a new instance of the constructor's class on the |
| 1496 | * arguments passed to the method handle. |
| 1497 | * <p> |
| 1498 | * If the constructor's {@code accessible} flag is not set, |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 1499 | * access checking is performed immediately on behalf of the lookup class. |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 1500 | * <p> |
| 1501 | * The returned method handle will have |
| 1502 | * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if |
| 1503 | * the constructor's variable arity modifier bit ({@code 0x0080}) is set. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1504 | * <p> |
| 1505 | * If the returned method handle is invoked, the constructor's class will |
| 1506 | * be initialized, if it has not already been initialized. |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1507 | * @param c the reflected constructor |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1508 | * @return a method handle which can invoke the reflected constructor |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1509 | * @throws IllegalAccessException if access checking fails |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1510 | * or if the method's variable arity modifier bit |
| 1511 | * is set and {@code asVarargsCollector} fails |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1512 | * @throws NullPointerException if the argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1513 | */ |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1514 | public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1515 | MemberName ctor = new MemberName(c); |
| 1516 | assert(ctor.isConstructor()); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1517 | Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1518 | return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1519 | } |
| 1520 | |
| 1521 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1522 | * Produces a method handle giving read access to a reflected field. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1523 | * The type of the method handle will have a return type of the field's |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 1524 | * value type. |
| 1525 | * If the field is static, the method handle will take no arguments. |
| 1526 | * Otherwise, its single argument will be the instance containing |
| 1527 | * the field. |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 1528 | * If the field's {@code accessible} flag is not set, |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1529 | * access checking is performed immediately on behalf of the lookup class. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1530 | * <p> |
| 1531 | * If the field is static, and |
| 1532 | * if the returned method handle is invoked, the field's class will |
| 1533 | * be initialized, if it has not already been initialized. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1534 | * @param f the reflected field |
| 1535 | * @return a method handle which can load values from the reflected field |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1536 | * @throws IllegalAccessException if access checking fails |
| 1537 | * @throws NullPointerException if the argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1538 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1539 | public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1540 | return unreflectField(f, false); |
| 1541 | } |
| 1542 | private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { |
| 1543 | MemberName field = new MemberName(f, isSetter); |
| 1544 | assert(isSetter |
| 1545 | ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) |
| 1546 | : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); |
| 1547 | Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1548 | return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1549 | } |
| 1550 | |
| 1551 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 1552 | * Produces a method handle giving write access to a reflected field. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1553 | * The type of the method handle will have a void return type. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 1554 | * If the field is static, the method handle will take a single |
| 1555 | * argument, of the field's value type, the value to be stored. |
| 1556 | * Otherwise, the two arguments will be the instance containing |
| 1557 | * the field, and the value to be stored. |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 1558 | * If the field's {@code accessible} flag is not set, |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1559 | * access checking is performed immediately on behalf of the lookup class. |
John R Rose | 4ea5f81 | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1560 | * <p> |
| 1561 | * If the field is static, and |
| 1562 | * if the returned method handle is invoked, the field's class will |
| 1563 | * be initialized, if it has not already been initialized. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1564 | * @param f the reflected field |
| 1565 | * @return a method handle which can store values into the reflected field |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1566 | * @throws IllegalAccessException if access checking fails |
| 1567 | * @throws NullPointerException if the argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1568 | */ |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1569 | public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1570 | return unreflectField(f, true); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1571 | } |
| 1572 | |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1573 | /** |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1574 | * Produces a VarHandle that accesses fields of type {@code T} declared |
| 1575 | * by a class of type {@code R}, as described by the given reflected |
| 1576 | * field. |
| 1577 | * If the field is non-static the VarHandle supports a shape of |
| 1578 | * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}. |
| 1579 | * <p> |
| 1580 | * Access checking is performed immediately on behalf of the lookup |
| 1581 | * class, regardless of the value of the field's {@code accessible} |
| 1582 | * flag. |
| 1583 | * <p> |
| 1584 | * If the field is static, and if the returned VarHandle is operated |
| 1585 | * on, the field's declaring class will be initialized, if it has not |
| 1586 | * already been initialized. |
| 1587 | * <p> |
| 1588 | * Certain access modes of the returned VarHandle are unsupported under |
| 1589 | * the following conditions: |
| 1590 | * <ul> |
| 1591 | * <li>if the field is declared {@code final}, then the write, atomic |
| 1592 | * update, and numeric atomic update access modes are unsupported. |
| 1593 | * <li>if the field type is anything other than {@code int}, |
| 1594 | * {@code long} or a reference type, then atomic update access modes |
| 1595 | * are unsupported. (Future major platform releases of the JDK may |
| 1596 | * support additional types for certain currently unsupported access |
| 1597 | * modes.) |
| 1598 | * <li>if the field type is anything other than {@code int} or |
| 1599 | * {@code long}, then numeric atomic update access modes are |
| 1600 | * unsupported. (Future major platform releases of the JDK may |
| 1601 | * support additional numeric types for certain currently |
| 1602 | * unsupported access modes.) |
| 1603 | * </ul> |
| 1604 | * <p> |
| 1605 | * If the field is declared {@code volatile} then the returned VarHandle |
| 1606 | * will override access to the field (effectively ignore the |
| 1607 | * {@code volatile} declaration) in accordance to it's specified |
| 1608 | * access modes. |
| 1609 | * @param f the reflected field, with a field of type {@code T}, and |
| 1610 | * a declaring class of type {@code R} |
| 1611 | * @return a VarHandle giving access to non-static fields or a static |
| 1612 | * field |
| 1613 | * @throws IllegalAccessException if access checking fails |
| 1614 | * @throws NullPointerException if the argument is null |
| 1615 | * @since 9 |
| 1616 | */ |
| 1617 | public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { |
| 1618 | MemberName getField = new MemberName(f, false); |
| 1619 | MemberName putField = new MemberName(f, true); |
| 1620 | return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), |
| 1621 | f.getDeclaringClass(), getField, putField); |
| 1622 | } |
| 1623 | |
| 1624 | /** |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1625 | * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> |
| 1626 | * created by this lookup object or a similar one. |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1627 | * Security and access checks are performed to ensure that this lookup object |
| 1628 | * is capable of reproducing the target method handle. |
| 1629 | * This means that the cracking may fail if target is a direct method handle |
| 1630 | * but was created by an unrelated lookup object. |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1631 | * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> |
| 1632 | * and was created by a lookup object for a different class. |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1633 | * @param target a direct method handle to crack into symbolic reference components |
| 1634 | * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object |
| 1635 | * @exception SecurityException if a security manager is present and it |
| 1636 | * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> |
| 1637 | * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails |
| 1638 | * @exception NullPointerException if the target is {@code null} |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1639 | * @see MethodHandleInfo |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1640 | * @since 1.8 |
| 1641 | */ |
| 1642 | public MethodHandleInfo revealDirect(MethodHandle target) { |
| 1643 | MemberName member = target.internalMemberName(); |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 1644 | if (member == null || (!member.isResolved() && |
| 1645 | !member.isMethodHandleInvoke() && |
| 1646 | !member.isVarHandleMethodInvoke())) |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1647 | throw newIllegalArgumentException("not a direct method handle"); |
| 1648 | Class<?> defc = member.getDeclaringClass(); |
| 1649 | byte refKind = member.getReferenceKind(); |
| 1650 | assert(MethodHandleNatives.refKindIsValid(refKind)); |
| 1651 | if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) |
| 1652 | // Devirtualized method invocation is usually formally virtual. |
| 1653 | // To avoid creating extra MemberName objects for this common case, |
| 1654 | // we encode this extra degree of freedom using MH.isInvokeSpecial. |
| 1655 | refKind = REF_invokeVirtual; |
| 1656 | if (refKind == REF_invokeVirtual && defc.isInterface()) |
| 1657 | // Symbolic reference is through interface but resolves to Object method (toString, etc.) |
| 1658 | refKind = REF_invokeInterface; |
| 1659 | // Check SM permissions and member access before cracking. |
| 1660 | try { |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1661 | checkAccess(refKind, defc, member); |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1662 | checkSecurityManager(defc, member); |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1663 | } catch (IllegalAccessException ex) { |
| 1664 | throw new IllegalArgumentException(ex); |
| 1665 | } |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1666 | if (allowedModes != TRUSTED && member.isCallerSensitive()) { |
| 1667 | Class<?> callerClass = target.internalCallerClass(); |
| 1668 | if (!hasPrivateAccess() || callerClass != lookupClass()) |
| 1669 | throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); |
| 1670 | } |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1671 | // Produce the handle to the results. |
| 1672 | return new InfoFromMemberName(this, member, refKind); |
| 1673 | } |
| 1674 | |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1675 | /// Helper methods, all package-private. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1676 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1677 | MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1678 | checkSymbolicClass(refc); // do this before attempting to resolve |
Aleksey Shipilev | e0e6ce3 | 2015-02-20 18:32:10 +0300 | [diff] [blame] | 1679 | Objects.requireNonNull(name); |
| 1680 | Objects.requireNonNull(type); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1681 | return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1682 | NoSuchFieldException.class); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1683 | } |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 1684 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1685 | MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1686 | checkSymbolicClass(refc); // do this before attempting to resolve |
Aleksey Shipilev | e0e6ce3 | 2015-02-20 18:32:10 +0300 | [diff] [blame] | 1687 | Objects.requireNonNull(name); |
| 1688 | Objects.requireNonNull(type); |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1689 | checkMethodName(refKind, name); // NPE check on name |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1690 | return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1691 | NoSuchMethodException.class); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1692 | } |
| 1693 | |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 1694 | MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { |
| 1695 | checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve |
Aleksey Shipilev | e0e6ce3 | 2015-02-20 18:32:10 +0300 | [diff] [blame] | 1696 | Objects.requireNonNull(member.getName()); |
| 1697 | Objects.requireNonNull(member.getType()); |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 1698 | return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), |
| 1699 | ReflectiveOperationException.class); |
| 1700 | } |
| 1701 | |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1702 | void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { |
Aleksey Shipilev | e0e6ce3 | 2015-02-20 18:32:10 +0300 | [diff] [blame] | 1703 | Objects.requireNonNull(refc); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1704 | Class<?> caller = lookupClassOrNull(); |
John R Rose | 6b14cf6 | 2012-05-18 20:31:28 -0700 | [diff] [blame] | 1705 | if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 1706 | throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1707 | } |
| 1708 | |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 1709 | /** Check name for an illegal leading "<" character. */ |
John R Rose | 154969a | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1710 | void checkMethodName(byte refKind, String name) throws NoSuchMethodException { |
| 1711 | if (name.startsWith("<") && refKind != REF_newInvokeSpecial) |
| 1712 | throw new NoSuchMethodException("illegal method name: "+name); |
| 1713 | } |
| 1714 | |
| 1715 | |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1716 | /** |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1717 | * Find my trustable caller class if m is a caller sensitive method. |
| 1718 | * If this lookup object has private access, then the caller class is the lookupClass. |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1719 | * Otherwise, if m is caller-sensitive, throw IllegalAccessException. |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1720 | */ |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1721 | Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1722 | Class<?> callerClass = null; |
| 1723 | if (MethodHandleNatives.isCallerSensitive(m)) { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1724 | // Only lookups with private access are allowed to resolve caller-sensitive methods |
| 1725 | if (hasPrivateAccess()) { |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1726 | callerClass = lookupClass; |
| 1727 | } else { |
| 1728 | throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); |
| 1729 | } |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1730 | } |
| 1731 | return callerClass; |
| 1732 | } |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 1733 | |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1734 | private boolean hasPrivateAccess() { |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1735 | return (allowedModes & PRIVATE) != 0; |
| 1736 | } |
| 1737 | |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 1738 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1739 | * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1740 | * Determines a trustable caller class to compare with refc, the symbolic reference class. |
| 1741 | * If this lookup object has private access, then the caller class is the lookupClass. |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1742 | */ |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1743 | void checkSecurityManager(Class<?> refc, MemberName m) { |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1744 | SecurityManager smgr = System.getSecurityManager(); |
| 1745 | if (smgr == null) return; |
| 1746 | if (allowedModes == TRUSTED) return; |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 1747 | |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1748 | // Step 1: |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1749 | boolean fullPowerLookup = hasPrivateAccess(); |
| 1750 | if (!fullPowerLookup || |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1751 | !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { |
| 1752 | ReflectUtil.checkPackageAccess(refc); |
| 1753 | } |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 1754 | |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1755 | if (m == null) { // findClass or accessClass |
| 1756 | // Step 2b: |
| 1757 | if (!fullPowerLookup) { |
| 1758 | smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); |
| 1759 | } |
| 1760 | return; |
| 1761 | } |
| 1762 | |
| 1763 | // Step 2a: |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1764 | if (m.isPublic()) return; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1765 | if (!fullPowerLookup) { |
| 1766 | smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); |
Mandy Chung | 176ed8d | 2013-04-16 21:39:52 -0700 | [diff] [blame] | 1767 | } |
| 1768 | |
Mandy Chung | 5a360a7 | 2013-07-02 15:58:09 -0700 | [diff] [blame] | 1769 | // Step 3: |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1770 | Class<?> defc = m.getDeclaringClass(); |
| 1771 | if (!fullPowerLookup && defc != refc) { |
Christian Thalinger | 94bc732 | 2013-05-08 12:09:35 -0700 | [diff] [blame] | 1772 | ReflectUtil.checkPackageAccess(defc); |
| 1773 | } |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 1774 | } |
| 1775 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1776 | void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { |
| 1777 | boolean wantStatic = (refKind == REF_invokeStatic); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1778 | String message; |
| 1779 | if (m.isConstructor()) |
| 1780 | message = "expected a method, not a constructor"; |
| 1781 | else if (!m.isMethod()) |
| 1782 | message = "expected a method"; |
| 1783 | else if (wantStatic != m.isStatic()) |
| 1784 | message = wantStatic ? "expected a static method" : "expected a non-static method"; |
| 1785 | else |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1786 | { checkAccess(refKind, refc, m); return; } |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 1787 | throw m.makeAccessException(message, this); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1788 | } |
| 1789 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1790 | void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { |
| 1791 | boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); |
| 1792 | String message; |
| 1793 | if (wantStatic != m.isStatic()) |
| 1794 | message = wantStatic ? "expected a static field" : "expected a non-static field"; |
| 1795 | else |
| 1796 | { checkAccess(refKind, refc, m); return; } |
| 1797 | throw m.makeAccessException(message, this); |
| 1798 | } |
| 1799 | |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1800 | /** Check public/protected/private bits on the symbolic reference class and its member. */ |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1801 | void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { |
| 1802 | assert(m.referenceKindIsConsistentWith(refKind) && |
| 1803 | MethodHandleNatives.refKindIsValid(refKind) && |
| 1804 | (MethodHandleNatives.refKindIsField(refKind) == m.isField())); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1805 | int allowedModes = this.allowedModes; |
| 1806 | if (allowedModes == TRUSTED) return; |
| 1807 | int mods = m.getModifiers(); |
John R Rose | 622186e | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 1808 | if (Modifier.isProtected(mods) && |
| 1809 | refKind == REF_invokeVirtual && |
| 1810 | m.getDeclaringClass() == Object.class && |
| 1811 | m.getName().equals("clone") && |
| 1812 | refc.isArray()) { |
| 1813 | // The JVM does this hack also. |
| 1814 | // (See ClassVerifier::verify_invoke_instructions |
| 1815 | // and LinkResolver::check_method_accessability.) |
| 1816 | // Because the JVM does not allow separate methods on array types, |
| 1817 | // there is no separate method for int[].clone. |
| 1818 | // All arrays simply inherit Object.clone. |
| 1819 | // But for access checking logic, we make Object.clone |
| 1820 | // (normally protected) appear to be public. |
| 1821 | // Later on, when the DirectMethodHandle is created, |
| 1822 | // its leading argument will be restricted to the |
| 1823 | // requested array type. |
| 1824 | // N.B. The return type is not adjusted, because |
| 1825 | // that is *not* the bytecode behavior. |
| 1826 | mods ^= Modifier.PROTECTED | Modifier.PUBLIC; |
| 1827 | } |
Christian Thalinger | 33ccc26 | 2014-07-14 13:57:44 +0400 | [diff] [blame] | 1828 | if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { |
| 1829 | // cannot "new" a protected ctor in a different package |
| 1830 | mods ^= Modifier.PROTECTED; |
| 1831 | } |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1832 | if (Modifier.isFinal(mods) && |
| 1833 | MethodHandleNatives.refKindIsSetter(refKind)) |
| 1834 | throw m.makeAccessException("unexpected set of a final field", this); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1835 | int requestedModes = fixmods(mods); // adjust 0 => PACKAGE |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1836 | if ((requestedModes & allowedModes) != 0) { |
| 1837 | if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), |
| 1838 | mods, lookupClass(), allowedModes)) |
| 1839 | return; |
| 1840 | } else { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1841 | // Protected members can also be checked as if they were package-private. |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1842 | if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 |
| 1843 | && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) |
| 1844 | return; |
| 1845 | } |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 1846 | throw m.makeAccessException(accessFailedMessage(refc, m), this); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1847 | } |
| 1848 | |
| 1849 | String accessFailedMessage(Class<?> refc, MemberName m) { |
| 1850 | Class<?> defc = m.getDeclaringClass(); |
| 1851 | int mods = m.getModifiers(); |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1852 | // check the class first: |
| 1853 | boolean classOK = (Modifier.isPublic(defc.getModifiers()) && |
| 1854 | (defc == refc || |
| 1855 | Modifier.isPublic(refc.getModifiers()))); |
| 1856 | if (!classOK && (allowedModes & PACKAGE) != 0) { |
John R Rose | 6b14cf6 | 2012-05-18 20:31:28 -0700 | [diff] [blame] | 1857 | classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1858 | (defc == refc || |
John R Rose | 6b14cf6 | 2012-05-18 20:31:28 -0700 | [diff] [blame] | 1859 | VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); |
John R Rose | f485ab5 | 2011-02-11 01:26:32 -0800 | [diff] [blame] | 1860 | } |
| 1861 | if (!classOK) |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1862 | return "class is not public"; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1863 | if (Modifier.isPublic(mods)) |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 1864 | return "access to public member failed"; // (how?, module not readable?) |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1865 | if (Modifier.isPrivate(mods)) |
| 1866 | return "member is private"; |
| 1867 | if (Modifier.isProtected(mods)) |
| 1868 | return "member is protected"; |
| 1869 | return "member is private to package"; |
| 1870 | } |
| 1871 | |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 1872 | private static final boolean ALLOW_NESTMATE_ACCESS = false; |
| 1873 | |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1874 | private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1875 | int allowedModes = this.allowedModes; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1876 | if (allowedModes == TRUSTED) return; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1877 | if (!hasPrivateAccess() |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 1878 | || (specialCaller != lookupClass() |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 1879 | // ensure non-abstract methods in superinterfaces can be special-invoked |
| 1880 | && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)) |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 1881 | && !(ALLOW_NESTMATE_ACCESS && |
| 1882 | VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 1883 | throw new MemberName(specialCaller). |
| 1884 | makeAccessException("no private access for invokespecial", this); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1885 | } |
| 1886 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1887 | private boolean restrictProtectedReceiver(MemberName method) { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1888 | // The accessing class only has the right to use a protected member |
| 1889 | // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. |
| 1890 | if (!method.isProtected() || method.isStatic() |
| 1891 | || allowedModes == TRUSTED |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 1892 | || method.getDeclaringClass() == lookupClass() |
John R Rose | 8bb387d | 2011-05-17 19:48:19 -0700 | [diff] [blame] | 1893 | || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 1894 | || (ALLOW_NESTMATE_ACCESS && |
| 1895 | VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1896 | return false; |
| 1897 | return true; |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1898 | } |
John Rose | 71bae4a | 2014-09-10 19:19:49 +0400 | [diff] [blame] | 1899 | private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1900 | assert(!method.isStatic()); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1901 | // receiver type of mh is too wide; narrow to caller |
| 1902 | if (!method.getDeclaringClass().isAssignableFrom(caller)) { |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 1903 | throw method.makeAccessException("caller class must be a subclass below the method", caller); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1904 | } |
| 1905 | MethodType rawType = mh.type(); |
| 1906 | if (rawType.parameterType(0) == caller) return mh; |
| 1907 | MethodType narrowType = rawType.changeParameterType(0, caller); |
John Rose | 71bae4a | 2014-09-10 19:19:49 +0400 | [diff] [blame] | 1908 | assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness |
| 1909 | assert(mh.viewAsTypeChecks(narrowType, true)); |
| 1910 | return mh.copyWith(narrowType, mh.form); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 1911 | } |
| 1912 | |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1913 | /** Check access and get the requested method. */ |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1914 | private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1915 | final boolean doRestrict = true; |
| 1916 | final boolean checkSecurity = true; |
| 1917 | return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1918 | } |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1919 | /** Check access and get the requested method, eliding receiver narrowing rules. */ |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1920 | private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1921 | final boolean doRestrict = false; |
| 1922 | final boolean checkSecurity = true; |
| 1923 | return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1924 | } |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1925 | /** Check access and get the requested method, eliding security manager checks. */ |
| 1926 | private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { |
| 1927 | final boolean doRestrict = true; |
| 1928 | final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants |
| 1929 | return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); |
| 1930 | } |
| 1931 | /** Common code for all methods; do not call directly except from immediately above. */ |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1932 | private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1933 | boolean checkSecurity, |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1934 | boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1935 | checkMethod(refKind, refc, method); |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1936 | // Optionally check with the security manager; this isn't needed for unreflect* calls. |
| 1937 | if (checkSecurity) |
| 1938 | checkSecurityManager(refc, method); |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1939 | assert(!method.isMethodHandleInvoke()); |
Vladimir Ivanov | fbc6f85 | 2013-03-01 04:45:12 +0400 | [diff] [blame] | 1940 | |
Vladimir Ivanov | fbc6f85 | 2013-03-01 04:45:12 +0400 | [diff] [blame] | 1941 | if (refKind == REF_invokeSpecial && |
| 1942 | refc != lookupClass() && |
John Rose | 59440ee | 2013-09-03 21:42:56 -0700 | [diff] [blame] | 1943 | !refc.isInterface() && |
Vladimir Ivanov | b2e8017 | 2014-06-09 15:40:40 +0400 | [diff] [blame] | 1944 | refc != lookupClass().getSuperclass() && |
Vladimir Ivanov | fbc6f85 | 2013-03-01 04:45:12 +0400 | [diff] [blame] | 1945 | refc.isAssignableFrom(lookupClass())) { |
| 1946 | assert(!method.getName().equals("<init>")); // not this code path |
| 1947 | // Per JVMS 6.5, desc. of invokespecial instruction: |
| 1948 | // If the method is in a superclass of the LC, |
| 1949 | // and if our original search was above LC.super, |
Vladimir Ivanov | b2e8017 | 2014-06-09 15:40:40 +0400 | [diff] [blame] | 1950 | // repeat the search (symbolic lookup) from LC.super |
| 1951 | // and continue with the direct superclass of that class, |
| 1952 | // and so forth, until a match is found or no further superclasses exist. |
Vladimir Ivanov | fbc6f85 | 2013-03-01 04:45:12 +0400 | [diff] [blame] | 1953 | // FIXME: MemberName.resolve should handle this instead. |
Vladimir Ivanov | b2e8017 | 2014-06-09 15:40:40 +0400 | [diff] [blame] | 1954 | Class<?> refcAsSuper = lookupClass(); |
| 1955 | MemberName m2; |
| 1956 | do { |
| 1957 | refcAsSuper = refcAsSuper.getSuperclass(); |
| 1958 | m2 = new MemberName(refcAsSuper, |
| 1959 | method.getName(), |
| 1960 | method.getMethodType(), |
| 1961 | REF_invokeSpecial); |
| 1962 | m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); |
| 1963 | } while (m2 == null && // no method is found yet |
| 1964 | refc != refcAsSuper); // search up to refc |
Vladimir Ivanov | fbc6f85 | 2013-03-01 04:45:12 +0400 | [diff] [blame] | 1965 | if (m2 == null) throw new InternalError(method.toString()); |
| 1966 | method = m2; |
| 1967 | refc = refcAsSuper; |
| 1968 | // redo basic checks |
| 1969 | checkMethod(refKind, refc, method); |
| 1970 | } |
| 1971 | |
John Rose | 71bae4a | 2014-09-10 19:19:49 +0400 | [diff] [blame] | 1972 | DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); |
| 1973 | MethodHandle mh = dmh; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1974 | // Optionally narrow the receiver argument to refc using restrictReceiver. |
| 1975 | if (doRestrict && |
| 1976 | (refKind == REF_invokeSpecial || |
| 1977 | (MethodHandleNatives.refKindHasReceiver(refKind) && |
John Rose | 71bae4a | 2014-09-10 19:19:49 +0400 | [diff] [blame] | 1978 | restrictProtectedReceiver(method)))) { |
| 1979 | mh = restrictReceiver(method, dmh, lookupClass()); |
| 1980 | } |
| 1981 | mh = maybeBindCaller(method, mh, callerClass); |
| 1982 | mh = mh.setVarargs(method); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1983 | return mh; |
| 1984 | } |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1985 | private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, |
| 1986 | Class<?> callerClass) |
| 1987 | throws IllegalAccessException { |
John R Rose | 0a735e7 | 2012-09-20 14:02:55 -0700 | [diff] [blame] | 1988 | if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) |
| 1989 | return mh; |
| 1990 | Class<?> hostClass = lookupClass; |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1991 | if (!hasPrivateAccess()) // caller must have private access |
Vladimir Ivanov | 98e5a4b | 2013-02-22 03:00:48 -0800 | [diff] [blame] | 1992 | hostClass = callerClass; // callerClass came from a security manager style stack walk |
John R Rose | 0a735e7 | 2012-09-20 14:02:55 -0700 | [diff] [blame] | 1993 | MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); |
| 1994 | // Note: caller will apply varargs after this step happens. |
| 1995 | return cbmh; |
| 1996 | } |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1997 | /** Check access and get the requested field. */ |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 1998 | private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 1999 | final boolean checkSecurity = true; |
| 2000 | return getDirectFieldCommon(refKind, refc, field, checkSecurity); |
| 2001 | } |
| 2002 | /** Check access and get the requested field, eliding security manager checks. */ |
| 2003 | private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { |
| 2004 | final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants |
| 2005 | return getDirectFieldCommon(refKind, refc, field, checkSecurity); |
| 2006 | } |
| 2007 | /** Common code for all fields; do not call directly except from immediately above. */ |
| 2008 | private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, |
| 2009 | boolean checkSecurity) throws IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2010 | checkField(refKind, refc, field); |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2011 | // Optionally check with the security manager; this isn't needed for unreflect* calls. |
| 2012 | if (checkSecurity) |
| 2013 | checkSecurityManager(refc, field); |
John Rose | 71bae4a | 2014-09-10 19:19:49 +0400 | [diff] [blame] | 2014 | DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2015 | boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && |
| 2016 | restrictProtectedReceiver(field)); |
| 2017 | if (doRestrict) |
John Rose | 71bae4a | 2014-09-10 19:19:49 +0400 | [diff] [blame] | 2018 | return restrictReceiver(field, dmh, lookupClass()); |
| 2019 | return dmh; |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2020 | } |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2021 | private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, |
| 2022 | Class<?> refc, MemberName getField, MemberName putField) |
| 2023 | throws IllegalAccessException { |
| 2024 | final boolean checkSecurity = true; |
| 2025 | return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); |
| 2026 | } |
| 2027 | private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, |
| 2028 | Class<?> refc, MemberName getField, MemberName putField) |
| 2029 | throws IllegalAccessException { |
| 2030 | final boolean checkSecurity = false; |
| 2031 | return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); |
| 2032 | } |
| 2033 | private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, |
| 2034 | Class<?> refc, MemberName getField, MemberName putField, |
| 2035 | boolean checkSecurity) throws IllegalAccessException { |
| 2036 | assert getField.isStatic() == putField.isStatic(); |
| 2037 | assert getField.isGetter() && putField.isSetter(); |
| 2038 | assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); |
| 2039 | assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); |
| 2040 | |
| 2041 | checkField(getRefKind, refc, getField); |
| 2042 | if (checkSecurity) |
| 2043 | checkSecurityManager(refc, getField); |
| 2044 | |
| 2045 | if (!putField.isFinal()) { |
| 2046 | // A VarHandle does not support updates to final fields, any |
| 2047 | // such VarHandle to a final field will be read-only and |
| 2048 | // therefore the following write-based accessibility checks are |
| 2049 | // only required for non-final fields |
| 2050 | checkField(putRefKind, refc, putField); |
| 2051 | if (checkSecurity) |
| 2052 | checkSecurityManager(refc, putField); |
| 2053 | } |
| 2054 | |
| 2055 | boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && |
| 2056 | restrictProtectedReceiver(getField)); |
| 2057 | if (doRestrict) { |
| 2058 | assert !getField.isStatic(); |
| 2059 | // receiver type of VarHandle is too wide; narrow to caller |
| 2060 | if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { |
| 2061 | throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); |
| 2062 | } |
| 2063 | refc = lookupClass(); |
| 2064 | } |
| 2065 | return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); |
| 2066 | } |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2067 | /** Check access and get the requested constructor. */ |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2068 | private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2069 | final boolean checkSecurity = true; |
| 2070 | return getDirectConstructorCommon(refc, ctor, checkSecurity); |
| 2071 | } |
| 2072 | /** Check access and get the requested constructor, eliding security manager checks. */ |
| 2073 | private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { |
| 2074 | final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants |
| 2075 | return getDirectConstructorCommon(refc, ctor, checkSecurity); |
| 2076 | } |
| 2077 | /** Common code for all constructors; do not call directly except from immediately above. */ |
| 2078 | private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, |
| 2079 | boolean checkSecurity) throws IllegalAccessException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2080 | assert(ctor.isConstructor()); |
| 2081 | checkAccess(REF_newInvokeSpecial, refc, ctor); |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2082 | // Optionally check with the security manager; this isn't needed for unreflect* calls. |
| 2083 | if (checkSecurity) |
| 2084 | checkSecurityManager(refc, ctor); |
John R Rose | 0a735e7 | 2012-09-20 14:02:55 -0700 | [diff] [blame] | 2085 | assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2086 | return DirectMethodHandle.make(ctor).setVarargs(ctor); |
John R Rose | 0d30a78 | 2010-04-30 23:48:23 -0700 | [diff] [blame] | 2087 | } |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 2088 | |
| 2089 | /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: |
| 2090 | */ |
| 2091 | /*non-public*/ |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2092 | MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 2093 | if (!(type instanceof Class || type instanceof MethodType)) |
| 2094 | throw new InternalError("unresolved MemberName"); |
| 2095 | MemberName member = new MemberName(refKind, defc, name, type); |
| 2096 | MethodHandle mh = LOOKASIDE_TABLE.get(member); |
| 2097 | if (mh != null) { |
| 2098 | checkSymbolicClass(defc); |
| 2099 | return mh; |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2100 | } |
Christian Thalinger | 1ac0200 | 2013-10-24 10:52:15 -0700 | [diff] [blame] | 2101 | // Treat MethodHandle.invoke and invokeExact specially. |
| 2102 | if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { |
| 2103 | mh = findVirtualForMH(member.getName(), member.getMethodType()); |
| 2104 | if (mh != null) { |
| 2105 | return mh; |
| 2106 | } |
| 2107 | } |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 2108 | MemberName resolved = resolveOrFail(refKind, member); |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2109 | mh = getDirectMethodForConstant(refKind, defc, resolved); |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 2110 | if (mh instanceof DirectMethodHandle |
| 2111 | && canBeCached(refKind, defc, resolved)) { |
| 2112 | MemberName key = mh.internalMemberName(); |
| 2113 | if (key != null) { |
| 2114 | key = key.asNormalOriginal(); |
| 2115 | } |
| 2116 | if (member.equals(key)) { // better safe than sorry |
| 2117 | LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); |
| 2118 | } |
| 2119 | } |
| 2120 | return mh; |
| 2121 | } |
| 2122 | private |
| 2123 | boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { |
| 2124 | if (refKind == REF_invokeSpecial) { |
| 2125 | return false; |
| 2126 | } |
| 2127 | if (!Modifier.isPublic(defc.getModifiers()) || |
| 2128 | !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || |
| 2129 | !member.isPublic() || |
| 2130 | member.isCallerSensitive()) { |
| 2131 | return false; |
| 2132 | } |
| 2133 | ClassLoader loader = defc.getClassLoader(); |
Chris Hegarty | aa0ef2e | 2016-01-06 10:01:44 +0000 | [diff] [blame] | 2134 | if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 2135 | ClassLoader sysl = ClassLoader.getSystemClassLoader(); |
| 2136 | boolean found = false; |
| 2137 | while (sysl != null) { |
| 2138 | if (loader == sysl) { found = true; break; } |
| 2139 | sysl = sysl.getParent(); |
| 2140 | } |
| 2141 | if (!found) { |
| 2142 | return false; |
| 2143 | } |
| 2144 | } |
| 2145 | try { |
| 2146 | MemberName resolved2 = publicLookup().resolveOrFail(refKind, |
| 2147 | new MemberName(refKind, defc, member.getName(), member.getType())); |
| 2148 | checkSecurityManager(defc, resolved2); |
| 2149 | } catch (ReflectiveOperationException | SecurityException ex) { |
| 2150 | return false; |
| 2151 | } |
| 2152 | return true; |
| 2153 | } |
| 2154 | private |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2155 | MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) |
| 2156 | throws ReflectiveOperationException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2157 | if (MethodHandleNatives.refKindIsField(refKind)) { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2158 | return getDirectFieldNoSecurityManager(refKind, defc, member); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2159 | } else if (MethodHandleNatives.refKindIsMethod(refKind)) { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2160 | return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2161 | } else if (refKind == REF_newInvokeSpecial) { |
John R Rose | c5b5f0d | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2162 | return getDirectConstructorNoSecurityManager(defc, member); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 2163 | } |
| 2164 | // oops |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 2165 | throw newIllegalArgumentException("bad MethodHandle constant #"+member); |
John R Rose | f327953 | 2011-06-01 23:56:47 -0700 | [diff] [blame] | 2166 | } |
John R Rose | 62ee211 | 2013-10-05 05:30:38 -0700 | [diff] [blame] | 2167 | |
| 2168 | static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2169 | } |
| 2170 | |
| 2171 | /** |
Alan Bateman | db4d383 | 2016-03-17 19:04:16 +0000 | [diff] [blame] | 2172 | * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class |
| 2173 | * in an <em>unnamed module</em>. |
| 2174 | * |
| 2175 | * @see Lookup#publicLookup |
| 2176 | */ |
| 2177 | private static class LookupHelper { |
| 2178 | private static final String UNNAMED = "Unnamed"; |
| 2179 | private static final String OBJECT = "java/lang/Object"; |
| 2180 | |
| 2181 | private static Class<?> createClass() { |
| 2182 | try { |
| 2183 | ClassWriter cw = new ClassWriter(0); |
| 2184 | cw.visit(Opcodes.V1_8, |
| 2185 | Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, |
| 2186 | UNNAMED, |
| 2187 | null, |
| 2188 | OBJECT, |
| 2189 | null); |
| 2190 | cw.visitSource(UNNAMED, null); |
| 2191 | cw.visitEnd(); |
| 2192 | byte[] bytes = cw.toByteArray(); |
| 2193 | ClassLoader loader = new ClassLoader(null) { |
| 2194 | @Override |
| 2195 | protected Class<?> findClass(String cn) throws ClassNotFoundException { |
| 2196 | if (cn.equals(UNNAMED)) |
| 2197 | return super.defineClass(UNNAMED, bytes, 0, bytes.length); |
| 2198 | throw new ClassNotFoundException(cn); |
| 2199 | } |
| 2200 | }; |
| 2201 | return loader.loadClass(UNNAMED); |
| 2202 | } catch (Exception e) { |
| 2203 | throw new InternalError(e); |
| 2204 | } |
| 2205 | } |
| 2206 | |
| 2207 | private static final Class<?> PUBLIC_LOOKUP_CLASS; |
| 2208 | static { |
| 2209 | PrivilegedAction<Class<?>> pa = new PrivilegedAction<Class<?>>() { |
| 2210 | public Class<?> run() { |
| 2211 | return createClass(); |
| 2212 | } |
| 2213 | }; |
| 2214 | PUBLIC_LOOKUP_CLASS = AccessController.doPrivileged(pa); |
| 2215 | } |
| 2216 | |
| 2217 | /** |
| 2218 | * Lookup that is trusted minimally. It can only be used to create |
| 2219 | * method handles to publicly accessible members in exported packages. |
| 2220 | * |
| 2221 | * @see MethodHandles#publicLookup |
| 2222 | */ |
| 2223 | static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC); |
| 2224 | } |
| 2225 | |
| 2226 | /** |
Michael Haupt | 0b77755 | 2016-04-27 20:18:49 +0200 | [diff] [blame] | 2227 | * Produces a method handle constructing arrays of a desired type. |
| 2228 | * The return type of the method handle will be the array type. |
| 2229 | * The type of its sole argument will be {@code int}, which specifies the size of the array. |
| 2230 | * @param arrayClass an array type |
| 2231 | * @return a method handle which can create arrays of the given type |
| 2232 | * @throws NullPointerException if the argument is {@code null} |
| 2233 | * @throws IllegalArgumentException if {@code arrayClass} is not an array type |
| 2234 | * @see java.lang.reflect.Array#newInstance(Class, int) |
| 2235 | * @since 9 |
| 2236 | */ |
| 2237 | public static |
| 2238 | MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { |
| 2239 | if (!arrayClass.isArray()) { |
| 2240 | throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); |
| 2241 | } |
| 2242 | MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). |
| 2243 | bindTo(arrayClass.getComponentType()); |
| 2244 | return ani.asType(ani.type().changeReturnType(arrayClass)); |
| 2245 | } |
| 2246 | |
| 2247 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2248 | * Produces a method handle giving read access to elements of an array. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2249 | * The type of the method handle will have a return type of the array's |
| 2250 | * element type. Its first argument will be the array type, |
| 2251 | * and the second will be {@code int}. |
| 2252 | * @param arrayClass an array type |
| 2253 | * @return a method handle which can load values from the given array type |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2254 | * @throws NullPointerException if the argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2255 | * @throws IllegalArgumentException if arrayClass is not an array type |
| 2256 | */ |
| 2257 | public static |
| 2258 | MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2259 | return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2260 | } |
| 2261 | |
| 2262 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2263 | * Produces a method handle giving write access to elements of an array. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2264 | * The type of the method handle will have a void return type. |
| 2265 | * Its last argument will be the array's element type. |
| 2266 | * The first and second arguments will be the array type and int. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 2267 | * @param arrayClass the class of an array |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2268 | * @return a method handle which can store values into the array type |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2269 | * @throws NullPointerException if the argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2270 | * @throws IllegalArgumentException if arrayClass is not an array type |
| 2271 | */ |
| 2272 | public static |
| 2273 | MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2274 | return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2275 | } |
| 2276 | |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2277 | /** |
| 2278 | * |
| 2279 | * Produces a VarHandle giving access to elements of an array type |
| 2280 | * {@code T[]}, supporting shape {@code (T[], int : T)}. |
| 2281 | * <p> |
| 2282 | * Certain access modes of the returned VarHandle are unsupported under |
| 2283 | * the following conditions: |
| 2284 | * <ul> |
| 2285 | * <li>if the component type is anything other than {@code int}, |
| 2286 | * {@code long} or a reference type, then atomic update access modes |
| 2287 | * are unsupported. (Future major platform releases of the JDK may |
| 2288 | * support additional types for certain currently unsupported access |
| 2289 | * modes.) |
| 2290 | * <li>if the component type is anything other than {@code int} or |
| 2291 | * {@code long}, then numeric atomic update access modes are |
| 2292 | * unsupported. (Future major platform releases of the JDK may |
| 2293 | * support additional numeric types for certain currently |
| 2294 | * unsupported access modes.) |
| 2295 | * </ul> |
| 2296 | * @param arrayClass the class of an array, of type {@code T[]} |
| 2297 | * @return a VarHandle giving access to elements of an array |
| 2298 | * @throws NullPointerException if the arrayClass is null |
| 2299 | * @throws IllegalArgumentException if arrayClass is not an array type |
| 2300 | * @since 9 |
| 2301 | */ |
| 2302 | public static |
| 2303 | VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { |
| 2304 | return VarHandles.makeArrayElementHandle(arrayClass); |
| 2305 | } |
| 2306 | |
| 2307 | /** |
| 2308 | * Produces a VarHandle giving access to elements of a {@code byte[]} array |
| 2309 | * viewed as if it were a different primitive array type, such as |
| 2310 | * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is |
| 2311 | * {@code (byte[], int : T)}, where the {@code int} coordinate type |
| 2312 | * corresponds to an argument that is an index in a {@code byte[]} array, |
| 2313 | * and {@code T} is the component type of the given view array class. The |
| 2314 | * returned VarHandle accesses bytes at an index in a {@code byte[]} array, |
| 2315 | * composing bytes to or from a value of {@code T} according to the given |
| 2316 | * endianness. |
| 2317 | * <p> |
| 2318 | * The supported component types (variables types) are {@code short}, |
| 2319 | * {@code char}, {@code int}, {@code long}, {@code float} and |
| 2320 | * {@code double}. |
| 2321 | * <p> |
| 2322 | * Access of bytes at a given index will result in an |
| 2323 | * {@code IndexOutOfBoundsException} if the index is less than {@code 0} |
| 2324 | * or greater than the {@code byte[]} array length minus the size (in bytes) |
| 2325 | * of {@code T}. |
| 2326 | * <p> |
| 2327 | * Access of bytes at an index may be aligned or misaligned for {@code T}, |
| 2328 | * with respect to the underlying memory address, {@code A} say, associated |
| 2329 | * with the array and index. |
| 2330 | * If access is misaligned then access for anything other than the |
| 2331 | * {@code get} and {@code set} access modes will result in an |
| 2332 | * {@code IllegalStateException}. In such cases atomic access is only |
| 2333 | * guaranteed with respect to the largest power of two that divides the GCD |
| 2334 | * of {@code A} and the size (in bytes) of {@code T}. |
| 2335 | * If access is aligned then following access modes are supported and are |
| 2336 | * guaranteed to support atomic access: |
| 2337 | * <ul> |
| 2338 | * <li>read write access modes for all {@code T}; |
| 2339 | * <li>atomic update access modes for {@code int}, {@code long}, |
| 2340 | * {@code float} or {@code double}. |
| 2341 | * (Future major platform releases of the JDK may support additional |
| 2342 | * types for certain currently unsupported access modes.) |
| 2343 | * <li>numeric atomic update access modes for {@code int} and {@code long}. |
| 2344 | * (Future major platform releases of the JDK may support additional |
| 2345 | * numeric types for certain currently unsupported access modes.) |
| 2346 | * </ul> |
| 2347 | * <p> |
| 2348 | * Misaligned access, and therefore atomicity guarantees, may be determined |
| 2349 | * for {@code byte[]} arrays without operating on a specific array. Given |
| 2350 | * an {@code index}, {@code T} and it's corresponding boxed type, |
| 2351 | * {@code T_BOX}, misalignment may be determined as follows: |
| 2352 | * <pre>{@code |
| 2353 | * int sizeOfT = T_BOX.BYTES; // size in bytes of T |
| 2354 | * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). |
| 2355 | * alignmentOffset(0, sizeOfT); |
| 2356 | * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; |
| 2357 | * boolean isMisaligned = misalignedAtIndex != 0; |
| 2358 | * }</pre> |
| 2359 | * |
| 2360 | * @implNote |
| 2361 | * The variable types {@code float} and {@code double} are supported as if |
| 2362 | * by transformation to and access with the variable types {@code int} and |
| 2363 | * {@code long} respectively. For example, the transformation of a |
| 2364 | * {@code double} value to a long value is performed as if using |
| 2365 | * {@link Double#doubleToRawLongBits(double)}, and the reverse |
| 2366 | * transformation is performed as if using |
| 2367 | * {@link Double#longBitsToDouble(long)}. |
| 2368 | * |
| 2369 | * @param viewArrayClass the view array class, with a component type of |
| 2370 | * type {@code T} |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 2371 | * @param byteOrder the endianness of the view array elements, as |
| 2372 | * stored in the underlying {@code byte} array |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2373 | * @return a VarHandle giving access to elements of a {@code byte[]} array |
| 2374 | * viewed as if elements corresponding to the components type of the view |
| 2375 | * array class |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 2376 | * @throws NullPointerException if viewArrayClass or byteOrder is null |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2377 | * @throws IllegalArgumentException if viewArrayClass is not an array type |
| 2378 | * @throws UnsupportedOperationException if the component type of |
| 2379 | * viewArrayClass is not supported as a variable type |
| 2380 | * @since 9 |
| 2381 | */ |
| 2382 | public static |
| 2383 | VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 2384 | ByteOrder byteOrder) throws IllegalArgumentException { |
| 2385 | Objects.requireNonNull(byteOrder); |
| 2386 | return VarHandles.byteArrayViewHandle(viewArrayClass, |
| 2387 | byteOrder == ByteOrder.BIG_ENDIAN); |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2388 | } |
| 2389 | |
| 2390 | /** |
| 2391 | * Produces a VarHandle giving access to elements of a {@code ByteBuffer} |
| 2392 | * viewed as if it were an array of elements of a different primitive |
| 2393 | * component type to that of {@code byte}, such as {@code int[]} or |
| 2394 | * {@code long[]}. The shape of the resulting VarHandle is |
| 2395 | * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type |
| 2396 | * corresponds to an argument that is an index in a {@code ByteBuffer}, and |
| 2397 | * {@code T} is the component type of the given view array class. The |
| 2398 | * returned VarHandle accesses bytes at an index in a {@code ByteBuffer}, |
| 2399 | * composing bytes to or from a value of {@code T} according to the given |
| 2400 | * endianness. |
| 2401 | * <p> |
| 2402 | * The supported component types (variables types) are {@code short}, |
| 2403 | * {@code char}, {@code int}, {@code long}, {@code float} and |
| 2404 | * {@code double}. |
| 2405 | * <p> |
| 2406 | * Access will result in a {@code ReadOnlyBufferException} for anything |
| 2407 | * other than the read access modes if the {@code ByteBuffer} is read-only. |
| 2408 | * <p> |
| 2409 | * Access of bytes at a given index will result in an |
| 2410 | * {@code IndexOutOfBoundsException} if the index is less than {@code 0} |
| 2411 | * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of |
| 2412 | * {@code T}. |
| 2413 | * <p> |
| 2414 | * Access of bytes at an index may be aligned or misaligned for {@code T}, |
| 2415 | * with respect to the underlying memory address, {@code A} say, associated |
| 2416 | * with the {@code ByteBuffer} and index. |
| 2417 | * If access is misaligned then access for anything other than the |
| 2418 | * {@code get} and {@code set} access modes will result in an |
| 2419 | * {@code IllegalStateException}. In such cases atomic access is only |
| 2420 | * guaranteed with respect to the largest power of two that divides the GCD |
| 2421 | * of {@code A} and the size (in bytes) of {@code T}. |
| 2422 | * If access is aligned then following access modes are supported and are |
| 2423 | * guaranteed to support atomic access: |
| 2424 | * <ul> |
| 2425 | * <li>read write access modes for all {@code T}; |
| 2426 | * <li>atomic update access modes for {@code int}, {@code long}, |
| 2427 | * {@code float} or {@code double}. |
| 2428 | * (Future major platform releases of the JDK may support additional |
| 2429 | * types for certain currently unsupported access modes.) |
| 2430 | * <li>numeric atomic update access modes for {@code int} and {@code long}. |
| 2431 | * (Future major platform releases of the JDK may support additional |
| 2432 | * numeric types for certain currently unsupported access modes.) |
| 2433 | * </ul> |
| 2434 | * <p> |
| 2435 | * Misaligned access, and therefore atomicity guarantees, may be determined |
| 2436 | * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an |
| 2437 | * {@code index}, {@code T} and it's corresponding boxed type, |
| 2438 | * {@code T_BOX}, as follows: |
| 2439 | * <pre>{@code |
| 2440 | * int sizeOfT = T_BOX.BYTES; // size in bytes of T |
| 2441 | * ByteBuffer bb = ... |
| 2442 | * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); |
| 2443 | * boolean isMisaligned = misalignedAtIndex != 0; |
| 2444 | * }</pre> |
| 2445 | * |
| 2446 | * @implNote |
| 2447 | * The variable types {@code float} and {@code double} are supported as if |
| 2448 | * by transformation to and access with the variable types {@code int} and |
| 2449 | * {@code long} respectively. For example, the transformation of a |
| 2450 | * {@code double} value to a long value is performed as if using |
| 2451 | * {@link Double#doubleToRawLongBits(double)}, and the reverse |
| 2452 | * transformation is performed as if using |
| 2453 | * {@link Double#longBitsToDouble(long)}. |
| 2454 | * |
| 2455 | * @param viewArrayClass the view array class, with a component type of |
| 2456 | * type {@code T} |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 2457 | * @param byteOrder the endianness of the view array elements, as |
| 2458 | * stored in the underlying {@code ByteBuffer} (Note this overrides the |
| 2459 | * endianness of a {@code ByteBuffer}) |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2460 | * @return a VarHandle giving access to elements of a {@code ByteBuffer} |
| 2461 | * viewed as if elements corresponding to the components type of the view |
| 2462 | * array class |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 2463 | * @throws NullPointerException if viewArrayClass or byteOrder is null |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2464 | * @throws IllegalArgumentException if viewArrayClass is not an array type |
| 2465 | * @throws UnsupportedOperationException if the component type of |
| 2466 | * viewArrayClass is not supported as a variable type |
| 2467 | * @since 9 |
| 2468 | */ |
| 2469 | public static |
| 2470 | VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, |
Paul Sandoz | 1af2806 | 2016-04-26 18:30:00 -0700 | [diff] [blame] | 2471 | ByteOrder byteOrder) throws IllegalArgumentException { |
| 2472 | Objects.requireNonNull(byteOrder); |
| 2473 | return VarHandles.makeByteBufferViewHandle(viewArrayClass, |
| 2474 | byteOrder == ByteOrder.BIG_ENDIAN); |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2475 | } |
| 2476 | |
| 2477 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2478 | /// method handle invocation (reflective style) |
| 2479 | |
| 2480 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2481 | * Produces a method handle which will invoke any method handle of the |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2482 | * given {@code type}, with a given number of trailing arguments replaced by |
| 2483 | * a single trailing {@code Object[]} array. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2484 | * The resulting invoker will be a method handle with the following |
| 2485 | * arguments: |
| 2486 | * <ul> |
| 2487 | * <li>a single {@code MethodHandle} target |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2488 | * <li>zero or more leading values (counted by {@code leadingArgCount}) |
| 2489 | * <li>an {@code Object[]} array containing trailing arguments |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2490 | * </ul> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2491 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2492 | * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2493 | * the indicated {@code type}. |
| 2494 | * That is, if the target is exactly of the given {@code type}, it will behave |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2495 | * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2496 | * is used to convert the target to the required {@code type}. |
| 2497 | * <p> |
| 2498 | * The type of the returned invoker will not be the given {@code type}, but rather |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2499 | * will have all parameters except the first {@code leadingArgCount} |
| 2500 | * replaced by a single array of type {@code Object[]}, which will be |
| 2501 | * the final parameter. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2502 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2503 | * Before invoking its target, the invoker will spread the final array, apply |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2504 | * reference casts as necessary, and unbox and widen primitive arguments. |
John R Rose | e4df9dc | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2505 | * If, when the invoker is called, the supplied array argument does |
| 2506 | * not have the correct number of elements, the invoker will throw |
| 2507 | * an {@link IllegalArgumentException} instead of invoking the target. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2508 | * <p> |
| 2509 | * This method is equivalent to the following code (though it may be more efficient): |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 2510 | * <blockquote><pre>{@code |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2511 | MethodHandle invoker = MethodHandles.invoker(type); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2512 | int spreadArgCount = type.parameterCount() - leadingArgCount; |
John R Rose | eedbeda | 2011-02-11 01:26:24 -0800 | [diff] [blame] | 2513 | invoker = invoker.asSpreader(Object[].class, spreadArgCount); |
| 2514 | return invoker; |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 2515 | * }</pre></blockquote> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2516 | * This method throws no reflective or security exceptions. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2517 | * @param type the desired target type |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2518 | * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2519 | * @return a method handle suitable for invoking any method handle of the given type |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2520 | * @throws NullPointerException if {@code type} is null |
| 2521 | * @throws IllegalArgumentException if {@code leadingArgCount} is not in |
John R Rose | 77dc59f | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2522 | * the range from 0 to {@code type.parameterCount()} inclusive, |
| 2523 | * or if the resulting method handle's type would have |
| 2524 | * <a href="MethodHandle.html#maxarity">too many parameters</a> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2525 | */ |
Martin Buchholz | a2f0fe3 | 2015-09-15 21:56:04 -0700 | [diff] [blame] | 2526 | public static |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2527 | MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { |
| 2528 | if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) |
John Rose | da56d3f | 2014-09-10 19:19:47 +0400 | [diff] [blame] | 2529 | throw newIllegalArgumentException("bad argument count", leadingArgCount); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 2530 | type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2531 | return type.invokers().spreadInvoker(leadingArgCount); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2532 | } |
| 2533 | |
| 2534 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2535 | * Produces a special <em>invoker method handle</em> which can be used to |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2536 | * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2537 | * The resulting invoker will have a type which is |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2538 | * exactly equal to the desired type, except that it will accept |
| 2539 | * an additional leading argument of type {@code MethodHandle}. |
| 2540 | * <p> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2541 | * This method is equivalent to the following code (though it may be more efficient): |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 2542 | * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2543 | * |
| 2544 | * <p style="font-size:smaller;"> |
| 2545 | * <em>Discussion:</em> |
| 2546 | * Invoker method handles can be useful when working with variable method handles |
| 2547 | * of unknown types. |
| 2548 | * For example, to emulate an {@code invokeExact} call to a variable method |
| 2549 | * handle {@code M}, extract its type {@code T}, |
| 2550 | * look up the invoker method {@code X} for {@code T}, |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2551 | * and call the invoker method, as {@code X.invoke(T, A...)}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2552 | * (It would not work to call {@code X.invokeExact}, since the type {@code T} |
| 2553 | * is unknown.) |
| 2554 | * If spreading, collecting, or other argument transformations are required, |
| 2555 | * they can be applied once to the invoker {@code X} and reused on many {@code M} |
| 2556 | * method handle values, as long as they are compatible with the type of {@code X}. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 2557 | * <p style="font-size:smaller;"> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2558 | * <em>(Note: The invoker method is not available via the Core Reflection API. |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2559 | * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2560 | * on the declared {@code invokeExact} or {@code invoke} method will raise an |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2561 | * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> |
| 2562 | * <p> |
| 2563 | * This method throws no reflective or security exceptions. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2564 | * @param type the desired target type |
| 2565 | * @return a method handle suitable for invoking any method handle of the given type |
John R Rose | 77dc59f | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2566 | * @throws IllegalArgumentException if the resulting method handle's type would have |
| 2567 | * <a href="MethodHandle.html#maxarity">too many parameters</a> |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2568 | */ |
Martin Buchholz | a2f0fe3 | 2015-09-15 21:56:04 -0700 | [diff] [blame] | 2569 | public static |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2570 | MethodHandle exactInvoker(MethodType type) { |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 2571 | return type.invokers().exactInvoker(); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2572 | } |
| 2573 | |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2574 | /** |
| 2575 | * Produces a special <em>invoker method handle</em> which can be used to |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2576 | * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2577 | * The resulting invoker will have a type which is |
| 2578 | * exactly equal to the desired type, except that it will accept |
| 2579 | * an additional leading argument of type {@code MethodHandle}. |
| 2580 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2581 | * Before invoking its target, if the target differs from the expected type, |
| 2582 | * the invoker will apply reference casts as |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2583 | * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. |
| 2584 | * Similarly, the return value will be converted as necessary. |
| 2585 | * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, |
| 2586 | * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2587 | * <p> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 2588 | * This method is equivalent to the following code (though it may be more efficient): |
| 2589 | * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} |
| 2590 | * <p style="font-size:smaller;"> |
| 2591 | * <em>Discussion:</em> |
| 2592 | * A {@linkplain MethodType#genericMethodType general method type} is one which |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2593 | * mentions only {@code Object} arguments and return values. |
| 2594 | * An invoker for such a type is capable of calling any method handle |
| 2595 | * of the same arity as the general type. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 2596 | * <p style="font-size:smaller;"> |
| 2597 | * <em>(Note: The invoker method is not available via the Core Reflection API. |
| 2598 | * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} |
| 2599 | * on the declared {@code invokeExact} or {@code invoke} method will raise an |
| 2600 | * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2601 | * <p> |
| 2602 | * This method throws no reflective or security exceptions. |
| 2603 | * @param type the desired target type |
| 2604 | * @return a method handle suitable for invoking any method handle convertible to the given type |
John R Rose | 77dc59f | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 2605 | * @throws IllegalArgumentException if the resulting method handle's type would have |
| 2606 | * <a href="MethodHandle.html#maxarity">too many parameters</a> |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2607 | */ |
Martin Buchholz | a2f0fe3 | 2015-09-15 21:56:04 -0700 | [diff] [blame] | 2608 | public static |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2609 | MethodHandle invoker(MethodType type) { |
John Rose | 6a177f4 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 2610 | return type.invokers().genericInvoker(); |
John R Rose | eb96325 | 2011-05-12 19:27:33 -0700 | [diff] [blame] | 2611 | } |
| 2612 | |
Paul Sandoz | 9fb30a3 | 2016-03-24 11:21:21 +0100 | [diff] [blame] | 2613 | /** |
| 2614 | * Produces a special <em>invoker method handle</em> which can be used to |
| 2615 | * invoke a signature-polymorphic access mode method on any VarHandle whose |
| 2616 | * associated access mode type is compatible with the given type. |
| 2617 | * The resulting invoker will have a type which is exactly equal to the |
| 2618 | * desired given type, except that it will accept an additional leading |
| 2619 | * argument of type {@code VarHandle}. |
| 2620 | * |
| 2621 | * @param accessMode the VarHandle access mode |
| 2622 | * @param type the desired target type |
| 2623 | * @return a method handle suitable for invoking an access mode method of |
| 2624 | * any VarHandle whose access mode type is of the given type. |
| 2625 | * @since 9 |
| 2626 | */ |
| 2627 | static public |
| 2628 | MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { |
| 2629 | return type.invokers().varHandleMethodExactInvoker(accessMode); |
| 2630 | } |
| 2631 | |
| 2632 | /** |
| 2633 | * Produces a special <em>invoker method handle</em> which can be used to |
| 2634 | * invoke a signature-polymorphic access mode method on any VarHandle whose |
| 2635 | * associated access mode type is compatible with the given type. |
| 2636 | * The resulting invoker will have a type which is exactly equal to the |
| 2637 | * desired given type, except that it will accept an additional leading |
| 2638 | * argument of type {@code VarHandle}. |
| 2639 | * <p> |
| 2640 | * Before invoking its target, if the access mode type differs from the |
| 2641 | * desired given type, the invoker will apply reference casts as necessary |
| 2642 | * and box, unbox, or widen primitive values, as if by |
| 2643 | * {@link MethodHandle#asType asType}. Similarly, the return value will be |
| 2644 | * converted as necessary. |
| 2645 | * <p> |
| 2646 | * This method is equivalent to the following code (though it may be more |
| 2647 | * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} |
| 2648 | * |
| 2649 | * @param accessMode the VarHandle access mode |
| 2650 | * @param type the desired target type |
| 2651 | * @return a method handle suitable for invoking an access mode method of |
| 2652 | * any VarHandle whose access mode type is convertible to the given |
| 2653 | * type. |
| 2654 | * @since 9 |
| 2655 | */ |
| 2656 | static public |
| 2657 | MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { |
| 2658 | return type.invokers().varHandleMethodInvoker(accessMode); |
| 2659 | } |
| 2660 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2661 | static /*non-public*/ |
| 2662 | MethodHandle basicInvoker(MethodType type) { |
John Rose | da56d3f | 2014-09-10 19:19:47 +0400 | [diff] [blame] | 2663 | return type.invokers().basicInvoker(); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2664 | } |
| 2665 | |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2666 | /// method handle modification (creation from other method handles) |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2667 | |
| 2668 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2669 | * Produces a method handle which adapts the type of the |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2670 | * given method handle to a new type by pairwise argument and return type conversion. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2671 | * The original type and new type must have the same number of arguments. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2672 | * The resulting method handle is guaranteed to report a type |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 2673 | * which is equal to the desired new type. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2674 | * <p> |
| 2675 | * If the original type and new type are equal, returns target. |
| 2676 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2677 | * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2678 | * and some additional conversions are also applied if those conversions fail. |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2679 | * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied |
| 2680 | * if possible, before or instead of any conversions done by {@code asType}: |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2681 | * <ul> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2682 | * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, |
| 2683 | * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2684 | * (This treatment of interfaces follows the usage of the bytecode verifier.) |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2685 | * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, |
| 2686 | * the boolean is converted to a byte value, 1 for true, 0 for false. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2687 | * (This treatment follows the usage of the bytecode verifier.) |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2688 | * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, |
| 2689 | * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), |
| 2690 | * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. |
| 2691 | * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, |
| 2692 | * then a Java casting conversion (JLS 5.5) is applied. |
| 2693 | * (Specifically, <em>T0</em> will convert to <em>T1</em> by |
| 2694 | * widening and/or narrowing.) |
| 2695 | * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing |
| 2696 | * conversion will be applied at runtime, possibly followed |
| 2697 | * by a Java casting conversion (JLS 5.5) on the primitive value, |
| 2698 | * possibly followed by a conversion from byte to boolean by testing |
| 2699 | * the low-order bit. |
| 2700 | * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, |
| 2701 | * and if the reference is null at runtime, a zero value is introduced. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2702 | * </ul> |
| 2703 | * @param target the method handle to invoke after arguments are retyped |
| 2704 | * @param newType the expected type of the new method handle |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2705 | * @return a method handle which delegates to the target after performing |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2706 | * any necessary argument conversions, and arranges for any |
| 2707 | * necessary return value conversions |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2708 | * @throws NullPointerException if either argument is null |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2709 | * @throws WrongMethodTypeException if the conversion cannot be made |
| 2710 | * @see MethodHandle#asType |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2711 | */ |
| 2712 | public static |
| 2713 | MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { |
Vladimir Ivanov | e490ad1 | 2014-09-16 18:05:01 +0400 | [diff] [blame] | 2714 | explicitCastArgumentsChecks(target, newType); |
John Rose | 563b1c7 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 2715 | // use the asTypeCache when possible: |
Vladimir Ivanov | e490ad1 | 2014-09-16 18:05:01 +0400 | [diff] [blame] | 2716 | MethodType oldType = target.type(); |
John Rose | 563b1c7 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 2717 | if (oldType == newType) return target; |
| 2718 | if (oldType.explicitCastEquivalentToAsType(newType)) { |
Vladimir Ivanov | e0eba41 | 2014-12-09 09:22:07 -0800 | [diff] [blame] | 2719 | return target.asFixedArity().asType(newType); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 2720 | } |
John Rose | f365de5 | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 2721 | return MethodHandleImpl.makePairwiseConvert(target, newType, false); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2722 | } |
| 2723 | |
Vladimir Ivanov | e490ad1 | 2014-09-16 18:05:01 +0400 | [diff] [blame] | 2724 | private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { |
| 2725 | if (target.type().parameterCount() != newType.parameterCount()) { |
| 2726 | throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); |
| 2727 | } |
| 2728 | } |
| 2729 | |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2730 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2731 | * Produces a method handle which adapts the calling sequence of the |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2732 | * given method handle to a new type, by reordering the arguments. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2733 | * The resulting method handle is guaranteed to report a type |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2734 | * which is equal to the desired new type. |
| 2735 | * <p> |
| 2736 | * The given array controls the reordering. |
| 2737 | * Call {@code #I} the number of incoming parameters (the value |
| 2738 | * {@code newType.parameterCount()}, and call {@code #O} the number |
| 2739 | * of outgoing parameters (the value {@code target.type().parameterCount()}). |
| 2740 | * Then the length of the reordering array must be {@code #O}, |
| 2741 | * and each element must be a non-negative number less than {@code #I}. |
| 2742 | * For every {@code N} less than {@code #O}, the {@code N}-th |
| 2743 | * outgoing argument will be taken from the {@code I}-th incoming |
| 2744 | * argument, where {@code I} is {@code reorder[N]}. |
| 2745 | * <p> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2746 | * No argument or return value conversions are applied. |
| 2747 | * The type of each incoming argument, as determined by {@code newType}, |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2748 | * must be identical to the type of the corresponding outgoing parameter |
| 2749 | * or parameters in the target method handle. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2750 | * The return type of {@code newType} must be identical to the return |
| 2751 | * type of the original target. |
| 2752 | * <p> |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2753 | * The reordering array need not specify an actual permutation. |
| 2754 | * An incoming argument will be duplicated if its index appears |
| 2755 | * more than once in the array, and an incoming argument will be dropped |
| 2756 | * if its index does not appear in the array. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2757 | * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, |
| 2758 | * incoming arguments which are not mentioned in the reordering array |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 2759 | * may be of any type, as determined only by {@code newType}. |
Alan Bateman | 451a003 | 2013-06-10 12:58:32 +0100 | [diff] [blame] | 2760 | * <blockquote><pre>{@code |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2761 | import static java.lang.invoke.MethodHandles.*; |
| 2762 | import static java.lang.invoke.MethodType.*; |
| 2763 | ... |
| 2764 | MethodType intfn1 = methodType(int.class, int.class); |
| 2765 | MethodType intfn2 = methodType(int.class, int.class, int.class); |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 2766 | MethodHandle sub = ... (int x, int y) -> (x-y) ...; |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2767 | assert(sub.type().equals(intfn2)); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2768 | MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); |
| 2769 | MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2770 | assert((int)rsub.invokeExact(1, 100) == 99); |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 2771 | MethodHandle add = ... (int x, int y) -> (x+y) ...; |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2772 | assert(add.type().equals(intfn2)); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2773 | MethodHandle twice = permuteArguments(add, intfn1, 0, 0); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2774 | assert(twice.type().equals(intfn1)); |
| 2775 | assert((int)twice.invokeExact(21) == 42); |
Alan Bateman | 451a003 | 2013-06-10 12:58:32 +0100 | [diff] [blame] | 2776 | * }</pre></blockquote> |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 2777 | * <p> |
| 2778 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 2779 | * variable-arity method handle}, even if the original target method handle was. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2780 | * @param target the method handle to invoke after arguments are reordered |
| 2781 | * @param newType the expected type of the new method handle |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2782 | * @param reorder an index array which controls the reordering |
| 2783 | * @return a method handle which delegates to the target after it |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2784 | * drops unused arguments and moves and/or duplicates the other arguments |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2785 | * @throws NullPointerException if any argument is null |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2786 | * @throws IllegalArgumentException if the index array length is not equal to |
| 2787 | * the arity of the target, or if any index array element |
| 2788 | * not a valid index for a parameter of {@code newType}, |
| 2789 | * or if two corresponding parameter types in |
| 2790 | * {@code target.type()} and {@code newType} are not identical, |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2791 | */ |
| 2792 | public static |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2793 | MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2794 | reorder = reorder.clone(); // get a private copy |
| 2795 | MethodType oldType = target.type(); |
| 2796 | permuteArgumentChecks(reorder, newType, oldType); |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 2797 | // first detect dropped arguments and handle them separately |
| 2798 | int[] originalReorder = reorder; |
| 2799 | BoundMethodHandle result = target.rebind(); |
| 2800 | LambdaForm form = result.form; |
| 2801 | int newArity = newType.parameterCount(); |
| 2802 | // Normalize the reordering into a real permutation, |
| 2803 | // by removing duplicates and adding dropped elements. |
| 2804 | // This somewhat improves lambda form caching, as well |
| 2805 | // as simplifying the transform by breaking it up into steps. |
| 2806 | for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { |
| 2807 | if (ddIdx > 0) { |
| 2808 | // We found a duplicated entry at reorder[ddIdx]. |
| 2809 | // Example: (x,y,z)->asList(x,y,z) |
| 2810 | // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) |
| 2811 | // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) |
| 2812 | // The starred element corresponds to the argument |
| 2813 | // deleted by the dupArgumentForm transform. |
| 2814 | int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; |
| 2815 | boolean killFirst = false; |
| 2816 | for (int val; (val = reorder[--dstPos]) != dupVal; ) { |
| 2817 | // Set killFirst if the dup is larger than an intervening position. |
| 2818 | // This will remove at least one inversion from the permutation. |
| 2819 | if (dupVal > val) killFirst = true; |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2820 | } |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 2821 | if (!killFirst) { |
| 2822 | srcPos = dstPos; |
| 2823 | dstPos = ddIdx; |
| 2824 | } |
| 2825 | form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); |
| 2826 | assert (reorder[srcPos] == reorder[dstPos]); |
| 2827 | oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); |
| 2828 | // contract the reordering by removing the element at dstPos |
| 2829 | int tailPos = dstPos + 1; |
| 2830 | System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); |
| 2831 | reorder = Arrays.copyOf(reorder, reorder.length - 1); |
| 2832 | } else { |
| 2833 | int dropVal = ~ddIdx, insPos = 0; |
| 2834 | while (insPos < reorder.length && reorder[insPos] < dropVal) { |
| 2835 | // Find first element of reorder larger than dropVal. |
| 2836 | // This is where we will insert the dropVal. |
| 2837 | insPos += 1; |
| 2838 | } |
| 2839 | Class<?> ptype = newType.parameterType(dropVal); |
| 2840 | form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); |
| 2841 | oldType = oldType.insertParameterTypes(insPos, ptype); |
| 2842 | // expand the reordering by inserting an element at insPos |
| 2843 | int tailPos = insPos + 1; |
| 2844 | reorder = Arrays.copyOf(reorder, reorder.length + 1); |
| 2845 | System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); |
| 2846 | reorder[insPos] = dropVal; |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2847 | } |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 2848 | assert (permuteArgumentChecks(reorder, newType, oldType)); |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 2849 | } |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 2850 | assert (reorder.length == newArity); // a perfect permutation |
| 2851 | // Note: This may cache too many distinct LFs. Consider backing off to varargs code. |
| 2852 | form = form.editor().permuteArgumentsForm(1, reorder); |
| 2853 | if (newType == result.type() && form == result.internalForm()) |
| 2854 | return result; |
| 2855 | return result.copyWith(newType, form); |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 2856 | } |
| 2857 | |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2858 | /** |
| 2859 | * Return an indication of any duplicate or omission in reorder. |
| 2860 | * If the reorder contains a duplicate entry, return the index of the second occurrence. |
| 2861 | * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. |
| 2862 | * Otherwise, return zero. |
| 2863 | * If an element not in [0..newArity-1] is encountered, return reorder.length. |
| 2864 | */ |
| 2865 | private static int findFirstDupOrDrop(int[] reorder, int newArity) { |
| 2866 | final int BIT_LIMIT = 63; // max number of bits in bit mask |
| 2867 | if (newArity < BIT_LIMIT) { |
| 2868 | long mask = 0; |
| 2869 | for (int i = 0; i < reorder.length; i++) { |
| 2870 | int arg = reorder[i]; |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2871 | if (arg >= newArity) { |
| 2872 | return reorder.length; |
| 2873 | } |
| 2874 | long bit = 1L << arg; |
| 2875 | if ((mask & bit) != 0) { |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2876 | return i; // >0 indicates a dup |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2877 | } |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2878 | mask |= bit; |
| 2879 | } |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2880 | if (mask == (1L << newArity) - 1) { |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2881 | assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); |
| 2882 | return 0; |
| 2883 | } |
| 2884 | // find first zero |
| 2885 | long zeroBit = Long.lowestOneBit(~mask); |
| 2886 | int zeroPos = Long.numberOfTrailingZeros(zeroBit); |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2887 | assert(zeroPos <= newArity); |
| 2888 | if (zeroPos == newArity) { |
| 2889 | return 0; |
| 2890 | } |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2891 | return ~zeroPos; |
| 2892 | } else { |
| 2893 | // same algorithm, different bit set |
| 2894 | BitSet mask = new BitSet(newArity); |
| 2895 | for (int i = 0; i < reorder.length; i++) { |
| 2896 | int arg = reorder[i]; |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2897 | if (arg >= newArity) { |
| 2898 | return reorder.length; |
| 2899 | } |
| 2900 | if (mask.get(arg)) { |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2901 | return i; // >0 indicates a dup |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2902 | } |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2903 | mask.set(arg); |
| 2904 | } |
| 2905 | int zeroPos = mask.nextClearBit(0); |
Vladimir Ivanov | 475c0a7 | 2014-09-16 18:05:03 +0400 | [diff] [blame] | 2906 | assert(zeroPos <= newArity); |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 2907 | if (zeroPos == newArity) { |
| 2908 | return 0; |
| 2909 | } |
| 2910 | return ~zeroPos; |
| 2911 | } |
| 2912 | } |
| 2913 | |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 2914 | private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 2915 | if (newType.returnType() != oldType.returnType()) |
| 2916 | throw newIllegalArgumentException("return types do not match", |
| 2917 | oldType, newType); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2918 | if (reorder.length == oldType.parameterCount()) { |
| 2919 | int limit = newType.parameterCount(); |
| 2920 | boolean bad = false; |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 2921 | for (int j = 0; j < reorder.length; j++) { |
| 2922 | int i = reorder[j]; |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2923 | if (i < 0 || i >= limit) { |
| 2924 | bad = true; break; |
| 2925 | } |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 2926 | Class<?> src = newType.parameterType(i); |
| 2927 | Class<?> dst = oldType.parameterType(j); |
| 2928 | if (src != dst) |
| 2929 | throw newIllegalArgumentException("parameter types do not match after reorder", |
| 2930 | oldType, newType); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2931 | } |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 2932 | if (!bad) return true; |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2933 | } |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 2934 | throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 2935 | } |
| 2936 | |
| 2937 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2938 | * Produces a method handle of the requested return type which returns the given |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2939 | * constant value every time it is invoked. |
| 2940 | * <p> |
| 2941 | * Before the method handle is returned, the passed-in value is converted to the requested type. |
| 2942 | * If the requested type is primitive, widening primitive conversions are attempted, |
| 2943 | * else reference conversions are attempted. |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 2944 | * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2945 | * @param type the return type of the desired method handle |
| 2946 | * @param value the value to return |
| 2947 | * @return a method handle of the given return type and no arguments, which always returns the given value |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2948 | * @throws NullPointerException if the {@code type} argument is null |
| 2949 | * @throws ClassCastException if the value cannot be converted to the required return type |
| 2950 | * @throws IllegalArgumentException if the given type is {@code void.class} |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2951 | */ |
| 2952 | public static |
| 2953 | MethodHandle constant(Class<?> type, Object value) { |
| 2954 | if (type.isPrimitive()) { |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2955 | if (type == void.class) |
| 2956 | throw newIllegalArgumentException("void type"); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2957 | Wrapper w = Wrapper.forPrimitiveType(type); |
John Rose | 70c6eae | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 2958 | value = w.convert(value, type); |
| 2959 | if (w.zero().equals(value)) |
| 2960 | return zero(w, type); |
| 2961 | return insertArguments(identity(type), 0, value); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2962 | } else { |
John Rose | 70c6eae | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 2963 | if (value == null) |
| 2964 | return zero(Wrapper.OBJECT, type); |
| 2965 | return identity(type).bindTo(value); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2966 | } |
| 2967 | } |
| 2968 | |
| 2969 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2970 | * Produces a method handle which returns its sole argument when invoked. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 2971 | * @param type the type of the sole parameter and return value of the desired method handle |
| 2972 | * @return a unary method handle which accepts and returns the given type |
| 2973 | * @throws NullPointerException if the argument is null |
| 2974 | * @throws IllegalArgumentException if the given type is {@code void.class} |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2975 | */ |
| 2976 | public static |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 2977 | MethodHandle identity(Class<?> type) { |
John Rose | 9c80853 | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 2978 | Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); |
| 2979 | int pos = btw.ordinal(); |
| 2980 | MethodHandle ident = IDENTITY_MHS[pos]; |
| 2981 | if (ident == null) { |
| 2982 | ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); |
| 2983 | } |
| 2984 | if (ident.type().returnType() == type) |
| 2985 | return ident; |
| 2986 | // something like identity(Foo.class); do not bother to intern these |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 2987 | assert (btw == Wrapper.OBJECT); |
John Rose | 9c80853 | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 2988 | return makeIdentity(type); |
| 2989 | } |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 2990 | |
| 2991 | /** |
| 2992 | * Produces a constant method handle of the requested return type which |
| 2993 | * returns the default value for that type every time it is invoked. |
| 2994 | * The resulting constant method handle will have no side effects. |
| 2995 | * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. |
| 2996 | * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, |
| 2997 | * since {@code explicitCastArguments} converts {@code null} to default values. |
| 2998 | * @param type the expected return type of the desired method handle |
| 2999 | * @return a constant method handle that takes no arguments |
| 3000 | * and returns the default value of the given type (or void, if the type is void) |
| 3001 | * @throws NullPointerException if the argument is null |
| 3002 | * @see MethodHandles#constant |
| 3003 | * @see MethodHandles#empty |
| 3004 | * @since 9 |
| 3005 | */ |
| 3006 | public static MethodHandle zero(Class<?> type) { |
| 3007 | Objects.requireNonNull(type); |
| 3008 | return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); |
| 3009 | } |
| 3010 | |
| 3011 | private static MethodHandle identityOrVoid(Class<?> type) { |
| 3012 | return type == void.class ? zero(type) : identity(type); |
| 3013 | } |
| 3014 | |
| 3015 | /** |
| 3016 | * Produces a method handle of the requested type which ignores any arguments, does nothing, |
| 3017 | * and returns a suitable default depending on the return type. |
| 3018 | * That is, it returns a zero primitive value, a {@code null}, or {@code void}. |
| 3019 | * <p>The returned method handle is equivalent to |
| 3020 | * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. |
| 3021 | * <p> |
| 3022 | * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as |
| 3023 | * {@code guardWithTest(pred, target, empty(target.type())}. |
| 3024 | * @param type the type of the desired method handle |
| 3025 | * @return a constant method handle of the given type, which returns a default value of the given return type |
| 3026 | * @throws NullPointerException if the argument is null |
| 3027 | * @see MethodHandles#zero |
| 3028 | * @see MethodHandles#constant |
| 3029 | * @since 9 |
| 3030 | */ |
| 3031 | public static MethodHandle empty(MethodType type) { |
| 3032 | Objects.requireNonNull(type); |
| 3033 | return dropArguments(zero(type.returnType()), 0, type.parameterList()); |
| 3034 | } |
| 3035 | |
John Rose | 9c80853 | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 3036 | private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length]; |
| 3037 | private static MethodHandle makeIdentity(Class<?> ptype) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 3038 | MethodType mtype = methodType(ptype, ptype); |
John Rose | 9c80853 | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 3039 | LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); |
| 3040 | return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); |
| 3041 | } |
John Rose | 70c6eae | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 3042 | |
| 3043 | private static MethodHandle zero(Wrapper btw, Class<?> rtype) { |
| 3044 | int pos = btw.ordinal(); |
| 3045 | MethodHandle zero = ZERO_MHS[pos]; |
| 3046 | if (zero == null) { |
| 3047 | zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); |
| 3048 | } |
| 3049 | if (zero.type().returnType() == rtype) |
| 3050 | return zero; |
| 3051 | assert(btw == Wrapper.OBJECT); |
| 3052 | return makeZero(rtype); |
| 3053 | } |
| 3054 | private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length]; |
| 3055 | private static MethodHandle makeZero(Class<?> rtype) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 3056 | MethodType mtype = methodType(rtype); |
John Rose | 70c6eae | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 3057 | LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); |
| 3058 | return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); |
| 3059 | } |
| 3060 | |
Martin Buchholz | a2f0fe3 | 2015-09-15 21:56:04 -0700 | [diff] [blame] | 3061 | private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { |
John Rose | 9c80853 | 2014-09-10 19:19:50 +0400 | [diff] [blame] | 3062 | // Simulate a CAS, to avoid racy duplication of results. |
| 3063 | MethodHandle prev = cache[pos]; |
| 3064 | if (prev != null) return prev; |
| 3065 | return cache[pos] = value; |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3066 | } |
| 3067 | |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3068 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3069 | * Provides a target method handle with one or more <em>bound arguments</em> |
| 3070 | * in advance of the method handle's invocation. |
| 3071 | * The formal parameters to the target corresponding to the bound |
| 3072 | * arguments are called <em>bound parameters</em>. |
| 3073 | * Returns a new method handle which saves away the bound arguments. |
| 3074 | * When it is invoked, it receives arguments for any non-bound parameters, |
| 3075 | * binds the saved arguments to their corresponding parameters, |
| 3076 | * and calls the original target. |
| 3077 | * <p> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3078 | * The type of the new method handle will drop the types for the bound |
| 3079 | * parameters from the original target type, since the new method handle |
| 3080 | * will no longer require those arguments to be supplied by its callers. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3081 | * <p> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3082 | * Each given argument object must match the corresponding bound parameter type. |
| 3083 | * If a bound parameter type is a primitive, the argument object |
| 3084 | * must be a wrapper, and will be unboxed to produce the primitive value. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3085 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3086 | * The {@code pos} argument selects which parameters are to be bound. |
| 3087 | * It may range between zero and <i>N-L</i> (inclusively), |
| 3088 | * where <i>N</i> is the arity of the target method handle |
| 3089 | * and <i>L</i> is the length of the values array. |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 3090 | * <p> |
| 3091 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 3092 | * variable-arity method handle}, even if the original target method handle was. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3093 | * @param target the method handle to invoke after the argument is inserted |
| 3094 | * @param pos where to insert the argument (zero for the first) |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3095 | * @param values the series of arguments to insert |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3096 | * @return a method handle which inserts an additional argument, |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3097 | * before calling the original method handle |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3098 | * @throws NullPointerException if the target or the {@code values} array is null |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3099 | * @see MethodHandle#bindTo |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3100 | */ |
| 3101 | public static |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3102 | MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { |
| 3103 | int insCount = values.length; |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 3104 | Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); |
| 3105 | if (insCount == 0) return target; |
| 3106 | BoundMethodHandle result = target.rebind(); |
| 3107 | for (int i = 0; i < insCount; i++) { |
| 3108 | Object value = values[i]; |
| 3109 | Class<?> ptype = ptypes[pos+i]; |
| 3110 | if (ptype.isPrimitive()) { |
| 3111 | result = insertArgumentPrimitive(result, pos, ptype, value); |
| 3112 | } else { |
| 3113 | value = ptype.cast(value); // throw CCE if needed |
| 3114 | result = result.bindArgumentL(pos, value); |
| 3115 | } |
| 3116 | } |
| 3117 | return result; |
| 3118 | } |
| 3119 | |
| 3120 | private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, |
| 3121 | Class<?> ptype, Object value) { |
| 3122 | Wrapper w = Wrapper.forPrimitiveType(ptype); |
| 3123 | // perform unboxing and/or primitive conversion |
| 3124 | value = w.convert(value, ptype); |
| 3125 | switch (w) { |
| 3126 | case INT: return result.bindArgumentI(pos, (int)value); |
| 3127 | case LONG: return result.bindArgumentJ(pos, (long)value); |
| 3128 | case FLOAT: return result.bindArgumentF(pos, (float)value); |
| 3129 | case DOUBLE: return result.bindArgumentD(pos, (double)value); |
| 3130 | default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); |
| 3131 | } |
| 3132 | } |
| 3133 | |
| 3134 | private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3135 | MethodType oldType = target.type(); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3136 | int outargs = oldType.parameterCount(); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3137 | int inargs = outargs - insCount; |
| 3138 | if (inargs < 0) |
| 3139 | throw newIllegalArgumentException("too many values to insert"); |
| 3140 | if (pos < 0 || pos > inargs) |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3141 | throw newIllegalArgumentException("no argument type to append"); |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 3142 | return oldType.ptypes(); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3143 | } |
| 3144 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3145 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3146 | * Produces a method handle which will discard some dummy arguments |
| 3147 | * before calling some other specified <i>target</i> method handle. |
| 3148 | * The type of the new method handle will be the same as the target's type, |
| 3149 | * except it will also include the dummy argument types, |
| 3150 | * at some given position. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3151 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3152 | * The {@code pos} argument may range between zero and <i>N</i>, |
| 3153 | * where <i>N</i> is the arity of the target. |
| 3154 | * If {@code pos} is zero, the dummy arguments will precede |
| 3155 | * the target's real arguments; if {@code pos} is <i>N</i> |
| 3156 | * they will come after. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3157 | * <p> |
| 3158 | * <b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3159 | * <blockquote><pre>{@code |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3160 | import static java.lang.invoke.MethodHandles.*; |
| 3161 | import static java.lang.invoke.MethodType.*; |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3162 | ... |
| 3163 | MethodHandle cat = lookup().findVirtual(String.class, |
| 3164 | "concat", methodType(String.class, String.class)); |
| 3165 | assertEquals("xy", (String) cat.invokeExact("x", "y")); |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3166 | MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); |
| 3167 | MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); |
| 3168 | assertEquals(bigType, d0.type()); |
| 3169 | assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3170 | * }</pre></blockquote> |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3171 | * <p> |
| 3172 | * This method is also equivalent to the following code: |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3173 | * <blockquote><pre> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3174 | * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3175 | * </pre></blockquote> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3176 | * @param target the method handle to invoke after the arguments are dropped |
| 3177 | * @param valueTypes the type(s) of the argument(s) to drop |
| 3178 | * @param pos position of first argument to drop (zero for the leftmost) |
| 3179 | * @return a method handle which drops arguments of the given types, |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3180 | * before calling the original method handle |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3181 | * @throws NullPointerException if the target is null, |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3182 | * or if the {@code valueTypes} list or any of its elements is null |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3183 | * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, |
| 3184 | * or if {@code pos} is negative or greater than the arity of the target, |
| 3185 | * or if the new method handle's type would have too many parameters |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3186 | */ |
| 3187 | public static |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3188 | MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3189 | MethodType oldType = target.type(); // get NPE |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 3190 | int dropped = dropArgumentChecks(oldType, pos, valueTypes); |
Vladimir Ivanov | e490ad1 | 2014-09-16 18:05:01 +0400 | [diff] [blame] | 3191 | MethodType newType = oldType.insertParameterTypes(pos, valueTypes); |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 3192 | if (dropped == 0) return target; |
| 3193 | BoundMethodHandle result = target.rebind(); |
| 3194 | LambdaForm lform = result.form; |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 3195 | int insertFormArg = 1 + pos; |
| 3196 | for (Class<?> ptype : valueTypes) { |
| 3197 | lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3198 | } |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 3199 | result = result.copyWith(newType, lform); |
| 3200 | return result; |
| 3201 | } |
| 3202 | |
| 3203 | private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 3204 | int dropped = valueTypes.size(); |
| 3205 | MethodType.checkSlotCount(dropped); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3206 | int outargs = oldType.parameterCount(); |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 3207 | int inargs = outargs + dropped; |
John Rose | 2f4b5e8 | 2014-09-10 19:19:48 +0400 | [diff] [blame] | 3208 | if (pos < 0 || pos > outargs) |
| 3209 | throw newIllegalArgumentException("no argument type to remove" |
| 3210 | + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) |
| 3211 | ); |
| 3212 | return dropped; |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3213 | } |
| 3214 | |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3215 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3216 | * Produces a method handle which will discard some dummy arguments |
| 3217 | * before calling some other specified <i>target</i> method handle. |
| 3218 | * The type of the new method handle will be the same as the target's type, |
| 3219 | * except it will also include the dummy argument types, |
| 3220 | * at some given position. |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3221 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3222 | * The {@code pos} argument may range between zero and <i>N</i>, |
| 3223 | * where <i>N</i> is the arity of the target. |
| 3224 | * If {@code pos} is zero, the dummy arguments will precede |
| 3225 | * the target's real arguments; if {@code pos} is <i>N</i> |
| 3226 | * they will come after. |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 3227 | * @apiNote |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3228 | * <blockquote><pre>{@code |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3229 | import static java.lang.invoke.MethodHandles.*; |
| 3230 | import static java.lang.invoke.MethodType.*; |
| 3231 | ... |
| 3232 | MethodHandle cat = lookup().findVirtual(String.class, |
| 3233 | "concat", methodType(String.class, String.class)); |
| 3234 | assertEquals("xy", (String) cat.invokeExact("x", "y")); |
| 3235 | MethodHandle d0 = dropArguments(cat, 0, String.class); |
| 3236 | assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); |
| 3237 | MethodHandle d1 = dropArguments(cat, 1, String.class); |
| 3238 | assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); |
| 3239 | MethodHandle d2 = dropArguments(cat, 2, String.class); |
| 3240 | assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); |
| 3241 | MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); |
| 3242 | assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3243 | * }</pre></blockquote> |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3244 | * <p> |
| 3245 | * This method is also equivalent to the following code: |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3246 | * <blockquote><pre> |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3247 | * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3248 | * </pre></blockquote> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3249 | * @param target the method handle to invoke after the arguments are dropped |
| 3250 | * @param valueTypes the type(s) of the argument(s) to drop |
| 3251 | * @param pos position of first argument to drop (zero for the leftmost) |
| 3252 | * @return a method handle which drops arguments of the given types, |
| 3253 | * before calling the original method handle |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3254 | * @throws NullPointerException if the target is null, |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3255 | * or if the {@code valueTypes} array or any of its elements is null |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3256 | * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, |
| 3257 | * or if {@code pos} is negative or greater than the arity of the target, |
John R Rose | 77dc59f | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3258 | * or if the new method handle's type would have |
| 3259 | * <a href="MethodHandle.html#maxarity">too many parameters</a> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3260 | */ |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3261 | public static |
| 3262 | MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { |
| 3263 | return dropArguments(target, pos, Arrays.asList(valueTypes)); |
| 3264 | } |
| 3265 | |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 3266 | // private version which allows caller some freedom with error handling |
| 3267 | private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, |
| 3268 | boolean nullOnFailure) { |
| 3269 | List<Class<?>> oldTypes = target.type().parameterList(); |
| 3270 | int match = oldTypes.size(); |
| 3271 | if (skip != 0) { |
| 3272 | if (skip < 0 || skip > match) { |
| 3273 | throw newIllegalArgumentException("illegal skip", skip, target); |
| 3274 | } |
| 3275 | oldTypes = oldTypes.subList(skip, match); |
| 3276 | match -= skip; |
| 3277 | } |
| 3278 | List<Class<?>> addTypes = newTypes; |
| 3279 | int add = addTypes.size(); |
| 3280 | if (pos != 0) { |
| 3281 | if (pos < 0 || pos > add) { |
| 3282 | throw newIllegalArgumentException("illegal pos", pos, newTypes); |
| 3283 | } |
| 3284 | addTypes = addTypes.subList(pos, add); |
| 3285 | add -= pos; assert(addTypes.size() == add); |
| 3286 | } |
| 3287 | // Do not add types which already match the existing arguments. |
| 3288 | if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { |
| 3289 | if (nullOnFailure) { |
| 3290 | return null; |
| 3291 | } |
| 3292 | throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); |
| 3293 | } |
| 3294 | addTypes = addTypes.subList(match, add); |
| 3295 | add -= match; assert(addTypes.size() == add); |
| 3296 | // newTypes: ( P*[pos], M*[match], A*[add] ) |
| 3297 | // target: ( S*[skip], M*[match] ) |
| 3298 | MethodHandle adapter = target; |
| 3299 | if (add > 0) { |
| 3300 | adapter = dropArguments(adapter, skip+ match, addTypes); |
| 3301 | } |
| 3302 | // adapter: (S*[skip], M*[match], A*[add] ) |
| 3303 | if (pos > 0) { |
| 3304 | adapter = dropArguments(adapter, skip, newTypes.subList(0, pos)); |
| 3305 | } |
| 3306 | // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) |
| 3307 | return adapter; |
| 3308 | } |
| 3309 | |
| 3310 | /** |
| 3311 | * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments. |
| 3312 | * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored. |
| 3313 | * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list, |
| 3314 | * at the given position. |
| 3315 | * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding |
| 3316 | * positions of the target method handle's parameters, as if by {@link #dropArguments}. |
| 3317 | * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip}, |
| 3318 | * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the |
| 3319 | * target list.) |
| 3320 | * The target's return type will be unchanged. |
| 3321 | * @apiNote |
| 3322 | * Two method handles whose argument lists are "effectively identical" (i.e., identical |
| 3323 | * in a common prefix) may be mutually converted to a common type |
| 3324 | * by two calls to {@code dropArgumentsToMatch}, as follows: |
| 3325 | * <blockquote><pre>{@code |
| 3326 | import static java.lang.invoke.MethodHandles.*; |
| 3327 | import static java.lang.invoke.MethodType.*; |
| 3328 | ... |
| 3329 | ... |
| 3330 | MethodHandle h0 = constant(boolean.class, true); |
| 3331 | MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); |
| 3332 | MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); |
| 3333 | MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); |
| 3334 | if (h1.type().parameterCount() < h2.type().parameterCount()) |
| 3335 | h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 |
| 3336 | else |
| 3337 | h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 |
| 3338 | MethodHandle h3 = guardWithTest(h0, h1, h2); |
| 3339 | assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); |
| 3340 | * }</pre></blockquote> |
| 3341 | * @param target the method handle to adapt |
| 3342 | * @param skip number of targets parameters to disregard (they will be unchanged) |
| 3343 | * @param newTypes the desired argument list of the method handle |
| 3344 | * @param pos place in {@code newTypes} where the non-skipped target parameters must occur |
| 3345 | * @return a possibly adapted method handle |
| 3346 | * @throws NullPointerException if either argument is null |
| 3347 | * @throws IllegalArgumentException |
| 3348 | * if either index is out of range in its corresponding list, or |
| 3349 | * if the non-skipped target parameter types match the new types at {@code pos} |
| 3350 | * @since 9 |
| 3351 | */ |
| 3352 | public static |
| 3353 | MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { |
| 3354 | Objects.requireNonNull(target); |
| 3355 | Objects.requireNonNull(newTypes); |
| 3356 | return dropArgumentsToMatch(target, skip, newTypes, pos, false); |
| 3357 | } |
| 3358 | |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3359 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3360 | * Adapts a target method handle by pre-processing |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3361 | * one or more of its arguments, each with its own unary filter function, |
| 3362 | * and then calling the target with each pre-processed argument |
| 3363 | * replaced by the result of its corresponding filter function. |
| 3364 | * <p> |
| 3365 | * The pre-processing is performed by one or more method handles, |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3366 | * specified in the elements of the {@code filters} array. |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3367 | * The first element of the filter array corresponds to the {@code pos} |
| 3368 | * argument of the target, and so on in sequence. |
| 3369 | * <p> |
| 3370 | * Null arguments in the array are treated as identity functions, |
| 3371 | * and the corresponding arguments left unchanged. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3372 | * (If there are no non-null elements in the array, the original target is returned.) |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3373 | * Each filter is applied to the corresponding argument of the adapter. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3374 | * <p> |
| 3375 | * If a filter {@code F} applies to the {@code N}th argument of |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3376 | * the target, then {@code F} must be a method handle which |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3377 | * takes exactly one argument. The type of {@code F}'s sole argument |
| 3378 | * replaces the corresponding argument type of the target |
| 3379 | * in the resulting adapted method handle. |
| 3380 | * The return type of {@code F} must be identical to the corresponding |
| 3381 | * parameter type of the target. |
| 3382 | * <p> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3383 | * It is an error if there are elements of {@code filters} |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3384 | * (null or not) |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3385 | * which do not correspond to argument positions in the target. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3386 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3387 | * <blockquote><pre>{@code |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3388 | import static java.lang.invoke.MethodHandles.*; |
| 3389 | import static java.lang.invoke.MethodType.*; |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3390 | ... |
| 3391 | MethodHandle cat = lookup().findVirtual(String.class, |
| 3392 | "concat", methodType(String.class, String.class)); |
| 3393 | MethodHandle upcase = lookup().findVirtual(String.class, |
| 3394 | "toUpperCase", methodType(String.class)); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3395 | assertEquals("xy", (String) cat.invokeExact("x", "y")); |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3396 | MethodHandle f0 = filterArguments(cat, 0, upcase); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3397 | assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3398 | MethodHandle f1 = filterArguments(cat, 1, upcase); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3399 | assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3400 | MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3401 | assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3402 | * }</pre></blockquote> |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3403 | * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} |
| 3404 | * denotes the return type of both the {@code target} and resulting adapter. |
| 3405 | * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values |
| 3406 | * of the parameters and arguments that precede and follow the filter position |
| 3407 | * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and |
| 3408 | * values of the filtered parameters and arguments; they also represent the |
| 3409 | * return types of the {@code filter[i]} handles. The latter accept arguments |
| 3410 | * {@code v[i]} of type {@code V[i]}, which also appear in the signature of |
| 3411 | * the resulting adapter. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3412 | * <blockquote><pre>{@code |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3413 | * T target(P... p, A[i]... a[i], B... b); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3414 | * A[i] filter[i](V[i]); |
| 3415 | * T adapter(P... p, V[i]... v[i], B... b) { |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3416 | * return target(p..., filter[i](v[i])..., b...); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3417 | * } |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3418 | * }</pre></blockquote> |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 3419 | * <p> |
| 3420 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 3421 | * variable-arity method handle}, even if the original target method handle was. |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3422 | * |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3423 | * @param target the method handle to invoke after arguments are filtered |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3424 | * @param pos the position of the first argument to filter |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3425 | * @param filters method handles to call initially on filtered arguments |
| 3426 | * @return method handle which incorporates the specified argument filtering logic |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3427 | * @throws NullPointerException if the target is null |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3428 | * or if the {@code filters} array is null |
| 3429 | * @throws IllegalArgumentException if a non-null element of {@code filters} |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3430 | * does not match a corresponding argument type of target as described above, |
John R Rose | 77dc59f | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3431 | * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, |
| 3432 | * or if the resulting method handle's type would have |
| 3433 | * <a href="MethodHandle.html#maxarity">too many parameters</a> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3434 | */ |
| 3435 | public static |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3436 | MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3437 | filterArgumentsCheckArity(target, pos, filters); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3438 | MethodHandle adapter = target; |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3439 | int curPos = pos-1; // pre-incremented |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3440 | for (MethodHandle filter : filters) { |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3441 | curPos += 1; |
| 3442 | if (filter == null) continue; // ignore null elements of filters |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 3443 | adapter = filterArgument(adapter, curPos, filter); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3444 | } |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3445 | return adapter; |
| 3446 | } |
| 3447 | |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 3448 | /*non-public*/ static |
| 3449 | MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3450 | filterArgumentChecks(target, pos, filter); |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 3451 | MethodType targetType = target.type(); |
| 3452 | MethodType filterType = filter.type(); |
| 3453 | BoundMethodHandle result = target.rebind(); |
| 3454 | Class<?> newParamType = filterType.parameterType(0); |
| 3455 | LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); |
| 3456 | MethodType newType = targetType.changeParameterType(pos, newParamType); |
| 3457 | result = result.copyWithExtendL(newType, lform, filter); |
| 3458 | return result; |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3459 | } |
| 3460 | |
| 3461 | private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { |
| 3462 | MethodType targetType = target.type(); |
| 3463 | int maxPos = targetType.parameterCount(); |
| 3464 | if (pos + filters.length > maxPos) |
| 3465 | throw newIllegalArgumentException("too many filters"); |
| 3466 | } |
| 3467 | |
| 3468 | private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 3469 | MethodType targetType = target.type(); |
| 3470 | MethodType filterType = filter.type(); |
| 3471 | if (filterType.parameterCount() != 1 |
| 3472 | || filterType.returnType() != targetType.parameterType(pos)) |
| 3473 | throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 3474 | } |
| 3475 | |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3476 | /** |
| 3477 | * Adapts a target method handle by pre-processing |
| 3478 | * a sub-sequence of its arguments with a filter (another method handle). |
| 3479 | * The pre-processed arguments are replaced by the result (if any) of the |
| 3480 | * filter function. |
| 3481 | * The target is then called on the modified (usually shortened) argument list. |
| 3482 | * <p> |
| 3483 | * If the filter returns a value, the target must accept that value as |
| 3484 | * its argument in position {@code pos}, preceded and/or followed by |
| 3485 | * any arguments not passed to the filter. |
| 3486 | * If the filter returns void, the target must accept all arguments |
| 3487 | * not passed to the filter. |
| 3488 | * No arguments are reordered, and a result returned from the filter |
| 3489 | * replaces (in order) the whole subsequence of arguments originally |
| 3490 | * passed to the adapter. |
| 3491 | * <p> |
| 3492 | * The argument types (if any) of the filter |
| 3493 | * replace zero or one argument types of the target, at position {@code pos}, |
| 3494 | * in the resulting adapted method handle. |
| 3495 | * The return type of the filter (if any) must be identical to the |
| 3496 | * argument type of the target at position {@code pos}, and that target argument |
| 3497 | * is supplied by the return value of the filter. |
| 3498 | * <p> |
| 3499 | * In all cases, {@code pos} must be greater than or equal to zero, and |
| 3500 | * {@code pos} must also be less than or equal to the target's arity. |
| 3501 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3502 | * <blockquote><pre>{@code |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3503 | import static java.lang.invoke.MethodHandles.*; |
| 3504 | import static java.lang.invoke.MethodType.*; |
| 3505 | ... |
| 3506 | MethodHandle deepToString = publicLookup() |
| 3507 | .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); |
| 3508 | |
| 3509 | MethodHandle ts1 = deepToString.asCollector(String[].class, 1); |
| 3510 | assertEquals("[strange]", (String) ts1.invokeExact("strange")); |
| 3511 | |
| 3512 | MethodHandle ts2 = deepToString.asCollector(String[].class, 2); |
| 3513 | assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); |
| 3514 | |
| 3515 | MethodHandle ts3 = deepToString.asCollector(String[].class, 3); |
| 3516 | MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); |
| 3517 | assertEquals("[top, [up, down], strange]", |
| 3518 | (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); |
| 3519 | |
| 3520 | MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); |
| 3521 | assertEquals("[top, [up, down], [strange]]", |
| 3522 | (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); |
| 3523 | |
| 3524 | MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); |
| 3525 | assertEquals("[top, [[up, down, strange], charm], bottom]", |
| 3526 | (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3527 | * }</pre></blockquote> |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3528 | * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} |
| 3529 | * represents the return type of the {@code target} and resulting adapter. |
| 3530 | * {@code V}/{@code v} stand for the return type and value of the |
| 3531 | * {@code filter}, which are also found in the signature and arguments of |
| 3532 | * the {@code target}, respectively, unless {@code V} is {@code void}. |
| 3533 | * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types |
| 3534 | * and values preceding and following the collection position, {@code pos}, |
| 3535 | * in the {@code target}'s signature. They also turn up in the resulting |
| 3536 | * adapter's signature and arguments, where they surround |
| 3537 | * {@code B}/{@code b}, which represent the parameter types and arguments |
| 3538 | * to the {@code filter} (if any). |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3539 | * <blockquote><pre>{@code |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3540 | * T target(A...,V,C...); |
| 3541 | * V filter(B...); |
| 3542 | * T adapter(A... a,B... b,C... c) { |
| 3543 | * V v = filter(b...); |
| 3544 | * return target(a...,v,c...); |
| 3545 | * } |
| 3546 | * // and if the filter has no arguments: |
| 3547 | * T target2(A...,V,C...); |
| 3548 | * V filter2(); |
| 3549 | * T adapter2(A... a,C... c) { |
| 3550 | * V v = filter2(); |
| 3551 | * return target2(a...,v,c...); |
| 3552 | * } |
| 3553 | * // and if the filter has a void return: |
| 3554 | * T target3(A...,C...); |
| 3555 | * void filter3(B...); |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3556 | * T adapter3(A... a,B... b,C... c) { |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3557 | * filter3(b...); |
| 3558 | * return target3(a...,c...); |
| 3559 | * } |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3560 | * }</pre></blockquote> |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3561 | * <p> |
| 3562 | * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to |
| 3563 | * one which first "folds" the affected arguments, and then drops them, in separate |
| 3564 | * steps as follows: |
| 3565 | * <blockquote><pre>{@code |
| 3566 | * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 |
| 3567 | * mh = MethodHandles.foldArguments(mh, coll); //step 1 |
| 3568 | * }</pre></blockquote> |
| 3569 | * If the target method handle consumes no arguments besides than the result |
| 3570 | * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} |
| 3571 | * is equivalent to {@code filterReturnValue(coll, mh)}. |
| 3572 | * If the filter method handle {@code coll} consumes one argument and produces |
| 3573 | * a non-void result, then {@code collectArguments(mh, N, coll)} |
| 3574 | * is equivalent to {@code filterArguments(mh, N, coll)}. |
| 3575 | * Other equivalences are possible but would require argument permutation. |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 3576 | * <p> |
| 3577 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 3578 | * variable-arity method handle}, even if the original target method handle was. |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3579 | * |
| 3580 | * @param target the method handle to invoke after filtering the subsequence of arguments |
| 3581 | * @param pos the position of the first adapter argument to pass to the filter, |
| 3582 | * and/or the target argument which receives the result of the filter |
| 3583 | * @param filter method handle to call on the subsequence of arguments |
| 3584 | * @return method handle which incorporates the specified argument subsequence filtering logic |
| 3585 | * @throws NullPointerException if either argument is null |
| 3586 | * @throws IllegalArgumentException if the return type of {@code filter} |
| 3587 | * is non-void and is not the same as the {@code pos} argument of the target, |
| 3588 | * or if {@code pos} is not between 0 and the target's arity, inclusive, |
| 3589 | * or if the resulting method handle's type would have |
| 3590 | * <a href="MethodHandle.html#maxarity">too many parameters</a> |
| 3591 | * @see MethodHandles#foldArguments |
| 3592 | * @see MethodHandles#filterArguments |
| 3593 | * @see MethodHandles#filterReturnValue |
| 3594 | */ |
| 3595 | public static |
| 3596 | MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3597 | MethodType newType = collectArgumentsChecks(target, pos, filter); |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 3598 | MethodType collectorType = filter.type(); |
| 3599 | BoundMethodHandle result = target.rebind(); |
| 3600 | LambdaForm lform; |
| 3601 | if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { |
| 3602 | lform = result.editor().collectArgumentArrayForm(1 + pos, filter); |
| 3603 | if (lform != null) { |
| 3604 | return result.copyWith(newType, lform); |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3605 | } |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3606 | } |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 3607 | lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); |
| 3608 | return result.copyWithExtendL(newType, lform, filter); |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3609 | } |
| 3610 | |
| 3611 | private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { |
John R Rose | 9d9d787 | 2012-08-17 13:42:25 -0700 | [diff] [blame] | 3612 | MethodType targetType = target.type(); |
John R Rose | 32e77ea | 2013-10-05 05:30:39 -0700 | [diff] [blame] | 3613 | MethodType filterType = filter.type(); |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3614 | Class<?> rtype = filterType.returnType(); |
| 3615 | List<Class<?>> filterArgs = filterType.parameterList(); |
| 3616 | if (rtype == void.class) { |
| 3617 | return targetType.insertParameterTypes(pos, filterArgs); |
| 3618 | } |
| 3619 | if (rtype != targetType.parameterType(pos)) { |
John R Rose | 9d9d787 | 2012-08-17 13:42:25 -0700 | [diff] [blame] | 3620 | throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); |
John Rose | dbbce78 | 2014-09-10 19:19:52 +0400 | [diff] [blame] | 3621 | } |
| 3622 | return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); |
John R Rose | 9d9d787 | 2012-08-17 13:42:25 -0700 | [diff] [blame] | 3623 | } |
| 3624 | |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3625 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3626 | * Adapts a target method handle by post-processing |
| 3627 | * its return value (if any) with a filter (another method handle). |
| 3628 | * The result of the filter is returned from the adapter. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3629 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3630 | * If the target returns a value, the filter must accept that value as |
| 3631 | * its only argument. |
| 3632 | * If the target returns void, the filter must accept no arguments. |
| 3633 | * <p> |
| 3634 | * The return type of the filter |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3635 | * replaces the return type of the target |
| 3636 | * in the resulting adapted method handle. |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3637 | * The argument type of the filter (if any) must be identical to the |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3638 | * return type of the target. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3639 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3640 | * <blockquote><pre>{@code |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3641 | import static java.lang.invoke.MethodHandles.*; |
| 3642 | import static java.lang.invoke.MethodType.*; |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3643 | ... |
| 3644 | MethodHandle cat = lookup().findVirtual(String.class, |
| 3645 | "concat", methodType(String.class, String.class)); |
| 3646 | MethodHandle length = lookup().findVirtual(String.class, |
| 3647 | "length", methodType(int.class)); |
| 3648 | System.out.println((String) cat.invokeExact("x", "y")); // xy |
| 3649 | MethodHandle f0 = filterReturnValue(cat, length); |
| 3650 | System.out.println((int) f0.invokeExact("x", "y")); // 2 |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3651 | * }</pre></blockquote> |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3652 | * <p>Here is pseudocode for the resulting adapter. In the code, |
| 3653 | * {@code T}/{@code t} represent the result type and value of the |
| 3654 | * {@code target}; {@code V}, the result type of the {@code filter}; and |
| 3655 | * {@code A}/{@code a}, the types and values of the parameters and arguments |
| 3656 | * of the {@code target} as well as the resulting adapter. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3657 | * <blockquote><pre>{@code |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3658 | * T target(A...); |
| 3659 | * V filter(T); |
| 3660 | * V adapter(A... a) { |
| 3661 | * T t = target(a...); |
| 3662 | * return filter(t); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3663 | * } |
| 3664 | * // and if the target has a void return: |
| 3665 | * void target2(A...); |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3666 | * V filter2(); |
| 3667 | * V adapter2(A... a) { |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3668 | * target2(a...); |
| 3669 | * return filter2(); |
| 3670 | * } |
| 3671 | * // and if the filter has a void return: |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3672 | * T target3(A...); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3673 | * void filter3(V); |
| 3674 | * void adapter3(A... a) { |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3675 | * T t = target3(a...); |
| 3676 | * filter3(t); |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3677 | * } |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3678 | * }</pre></blockquote> |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 3679 | * <p> |
| 3680 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 3681 | * variable-arity method handle}, even if the original target method handle was. |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3682 | * @param target the method handle to invoke before filtering the return value |
| 3683 | * @param filter method handle to call on the return value |
| 3684 | * @return method handle which incorporates the specified return value filtering logic |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3685 | * @throws NullPointerException if either argument is null |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3686 | * @throws IllegalArgumentException if the argument list of {@code filter} |
| 3687 | * does not match the return type of target as described above |
John R Rose | 2a322bb | 2010-10-30 21:02:30 -0700 | [diff] [blame] | 3688 | */ |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3689 | public static |
John R Rose | 2a322bb | 2010-10-30 21:02:30 -0700 | [diff] [blame] | 3690 | MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { |
| 3691 | MethodType targetType = target.type(); |
| 3692 | MethodType filterType = filter.type(); |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3693 | filterReturnValueChecks(targetType, filterType); |
Vladimir Ivanov | b1ad801 | 2014-11-24 07:16:38 -0800 | [diff] [blame] | 3694 | BoundMethodHandle result = target.rebind(); |
| 3695 | BasicType rtype = BasicType.basicType(filterType.returnType()); |
| 3696 | LambdaForm lform = result.editor().filterReturnForm(rtype, false); |
| 3697 | MethodType newType = targetType.changeReturnType(filterType.returnType()); |
| 3698 | result = result.copyWithExtendL(newType, lform, filter); |
| 3699 | return result; |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3700 | } |
| 3701 | |
| 3702 | private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 3703 | Class<?> rtype = targetType.returnType(); |
| 3704 | int filterValues = filterType.parameterCount(); |
| 3705 | if (filterValues == 0 |
| 3706 | ? (rtype != void.class) |
| 3707 | : (rtype != filterType.parameterType(0))) |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3708 | throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); |
John R Rose | 2a322bb | 2010-10-30 21:02:30 -0700 | [diff] [blame] | 3709 | } |
| 3710 | |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3711 | /** |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3712 | * Adapts a target method handle by pre-processing |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3713 | * some of its arguments, and then calling the target with |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3714 | * the result of the pre-processing, inserted into the original |
| 3715 | * sequence of arguments. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3716 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3717 | * The pre-processing is performed by {@code combiner}, a second method handle. |
| 3718 | * Of the arguments passed to the adapter, the first {@code N} arguments |
| 3719 | * are copied to the combiner, which is then called. |
| 3720 | * (Here, {@code N} is defined as the parameter count of the combiner.) |
| 3721 | * After this, control passes to the target, with any result |
| 3722 | * from the combiner inserted before the original {@code N} incoming |
| 3723 | * arguments. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3724 | * <p> |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3725 | * If the combiner returns a value, the first parameter type of the target |
| 3726 | * must be identical with the return type of the combiner, and the next |
| 3727 | * {@code N} parameter types of the target must exactly match the parameters |
| 3728 | * of the combiner. |
| 3729 | * <p> |
| 3730 | * If the combiner has a void return, no result will be inserted, |
| 3731 | * and the first {@code N} parameter types of the target |
| 3732 | * must exactly match the parameters of the combiner. |
| 3733 | * <p> |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3734 | * The resulting adapter is the same type as the target, except that the |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3735 | * first parameter type is dropped, |
| 3736 | * if it corresponds to the result of the combiner. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3737 | * <p> |
John R Rose | 4f508ab | 2010-10-30 21:08:23 -0700 | [diff] [blame] | 3738 | * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3739 | * that either the combiner or the target does not wish to receive. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3740 | * If some of the incoming arguments are destined only for the combiner, |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3741 | * consider using {@link MethodHandle#asCollector asCollector} instead, since those |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3742 | * arguments will not need to be live on the stack on entry to the |
| 3743 | * target.) |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3744 | * <p><b>Example:</b> |
Roger Riggs | 056189c | 2013-10-17 13:43:46 -0400 | [diff] [blame] | 3745 | * <blockquote><pre>{@code |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3746 | import static java.lang.invoke.MethodHandles.*; |
| 3747 | import static java.lang.invoke.MethodType.*; |
| 3748 | ... |
| 3749 | MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, |
| 3750 | "println", methodType(void.class, String.class)) |
| 3751 | .bindTo(System.out); |
| 3752 | MethodHandle cat = lookup().findVirtual(String.class, |
| 3753 | "concat", methodType(String.class, String.class)); |
| 3754 | assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); |
| 3755 | MethodHandle catTrace = foldArguments(cat, trace); |
| 3756 | // also prints "boo": |
| 3757 | assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3758 | * }</pre></blockquote> |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3759 | * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} |
| 3760 | * represents the result type of the {@code target} and resulting adapter. |
| 3761 | * {@code V}/{@code v} represent the type and value of the parameter and argument |
| 3762 | * of {@code target} that precedes the folding position; {@code V} also is |
| 3763 | * the result type of the {@code combiner}. {@code A}/{@code a} denote the |
| 3764 | * types and values of the {@code N} parameters and arguments at the folding |
| 3765 | * position. {@code B}/{@code b} represent the types and values of the |
| 3766 | * {@code target} parameters and arguments that follow the folded parameters |
| 3767 | * and arguments. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3768 | * <blockquote><pre>{@code |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3769 | * // there are N arguments in A... |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3770 | * T target(V, A[N]..., B...); |
| 3771 | * V combiner(A...); |
| 3772 | * T adapter(A... a, B... b) { |
| 3773 | * V v = combiner(a...); |
| 3774 | * return target(v, a..., b...); |
| 3775 | * } |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3776 | * // and if the combiner has a void return: |
| 3777 | * T target2(A[N]..., B...); |
| 3778 | * void combiner2(A...); |
| 3779 | * T adapter2(A... a, B... b) { |
| 3780 | * combiner2(a...); |
| 3781 | * return target2(a..., b...); |
| 3782 | * } |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3783 | * }</pre></blockquote> |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 3784 | * <p> |
| 3785 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 3786 | * variable-arity method handle}, even if the original target method handle was. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3787 | * @param target the method handle to invoke after arguments are combined |
| 3788 | * @param combiner method handle to call initially on the incoming arguments |
| 3789 | * @return method handle which incorporates the specified argument folding logic |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3790 | * @throws NullPointerException if either argument is null |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3791 | * @throws IllegalArgumentException if {@code combiner}'s return type |
| 3792 | * is non-void and not the same as the first argument type of |
| 3793 | * the target, or if the initial {@code N} argument types |
| 3794 | * of the target |
| 3795 | * (skipping one matching the {@code combiner}'s return type) |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3796 | * are not identical with the argument types of {@code combiner} |
| 3797 | */ |
| 3798 | public static |
| 3799 | MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 3800 | return foldArguments(target, 0, combiner); |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3801 | } |
| 3802 | |
| 3803 | private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { |
| 3804 | int foldArgs = combinerType.parameterCount(); |
| 3805 | Class<?> rtype = combinerType.returnType(); |
| 3806 | int foldVals = rtype == void.class ? 0 : 1; |
John R Rose | 9a58e30 | 2011-05-12 19:27:49 -0700 | [diff] [blame] | 3807 | int afterInsertPos = foldPos + foldVals; |
| 3808 | boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); |
| 3809 | if (ok && !(combinerType.parameterList() |
| 3810 | .equals(targetType.parameterList().subList(afterInsertPos, |
| 3811 | afterInsertPos + foldArgs)))) |
John R Rose | 2a322bb | 2010-10-30 21:02:30 -0700 | [diff] [blame] | 3812 | ok = false; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 3813 | if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) |
John R Rose | 2a322bb | 2010-10-30 21:02:30 -0700 | [diff] [blame] | 3814 | ok = false; |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3815 | if (!ok) |
| 3816 | throw misMatchedTypes("target and combiner types", targetType, combinerType); |
John Rose | 6750474 | 2014-09-10 19:19:51 +0400 | [diff] [blame] | 3817 | return rtype; |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3818 | } |
| 3819 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3820 | /** |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3821 | * Makes a method handle which adapts a target method handle, |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3822 | * by guarding it with a test, a boolean-valued method handle. |
| 3823 | * If the guard fails, a fallback handle is called instead. |
| 3824 | * All three method handles must have the same corresponding |
| 3825 | * argument and return types, except that the return type |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3826 | * of the test must be boolean, and the test is allowed |
| 3827 | * to have fewer arguments than the other two method handles. |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3828 | * <p> |
| 3829 | * Here is pseudocode for the resulting adapter. In the code, {@code T} |
| 3830 | * represents the uniform result type of the three involved handles; |
| 3831 | * {@code A}/{@code a}, the types and values of the {@code target} |
| 3832 | * parameters and arguments that are consumed by the {@code test}; and |
| 3833 | * {@code B}/{@code b}, those types and values of the {@code target} |
| 3834 | * parameters and arguments that are not consumed by the {@code test}. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3835 | * <blockquote><pre>{@code |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3836 | * boolean test(A...); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3837 | * T target(A...,B...); |
| 3838 | * T fallback(A...,B...); |
| 3839 | * T adapter(A... a,B... b) { |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3840 | * if (test(a...)) |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3841 | * return target(a..., b...); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3842 | * else |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3843 | * return fallback(a..., b...); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3844 | * } |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3845 | * }</pre></blockquote> |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3846 | * Note that the test arguments ({@code a...} in the pseudocode) cannot |
| 3847 | * be modified by execution of the test, and so are passed unchanged |
| 3848 | * from the caller to the target or fallback as appropriate. |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3849 | * @param test method handle used for test, must return boolean |
| 3850 | * @param target method handle to call if test passes |
| 3851 | * @param fallback method handle to call if test fails |
| 3852 | * @return method handle which incorporates the specified if/then/else logic |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3853 | * @throws NullPointerException if any argument is null |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3854 | * @throws IllegalArgumentException if {@code test} does not return boolean, |
| 3855 | * or if all three method types do not match (with the return |
John R Rose | 025d0ae | 2011-05-26 17:37:36 -0700 | [diff] [blame] | 3856 | * type of {@code test} changed to match that of the target). |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3857 | */ |
| 3858 | public static |
| 3859 | MethodHandle guardWithTest(MethodHandle test, |
| 3860 | MethodHandle target, |
| 3861 | MethodHandle fallback) { |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3862 | MethodType gtype = test.type(); |
| 3863 | MethodType ttype = target.type(); |
| 3864 | MethodType ftype = fallback.type(); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3865 | if (!ttype.equals(ftype)) |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3866 | throw misMatchedTypes("target and fallback types", ttype, ftype); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3867 | if (gtype.returnType() != boolean.class) |
| 3868 | throw newIllegalArgumentException("guard type is not a predicate "+gtype); |
| 3869 | List<Class<?>> targs = ttype.parameterList(); |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 3870 | test = dropArgumentsToMatch(test, 0, targs, 0, true); |
| 3871 | if (test == null) { |
| 3872 | throw misMatchedTypes("target and test types", ttype, gtype); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3873 | } |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 3874 | return MethodHandleImpl.makeGuardWithTest(test, target, fallback); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3875 | } |
| 3876 | |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 3877 | static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3878 | return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 3879 | } |
| 3880 | |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3881 | /** |
John R Rose | 3718824 | 2011-03-23 23:02:31 -0700 | [diff] [blame] | 3882 | * Makes a method handle which adapts a target method handle, |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3883 | * by running it inside an exception handler. |
| 3884 | * If the target returns normally, the adapter returns that value. |
| 3885 | * If an exception matching the specified type is thrown, the fallback |
| 3886 | * handle is called instead on the exception, plus the original arguments. |
| 3887 | * <p> |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3888 | * The target and handler must have the same corresponding |
| 3889 | * argument and return types, except that handler may omit trailing arguments |
| 3890 | * (similarly to the predicate in {@link #guardWithTest guardWithTest}). |
| 3891 | * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 3892 | * <p> |
| 3893 | * Here is pseudocode for the resulting adapter. In the code, {@code T} |
| 3894 | * represents the return type of the {@code target} and {@code handler}, |
| 3895 | * and correspondingly that of the resulting adapter; {@code A}/{@code a}, |
| 3896 | * the types and values of arguments to the resulting handle consumed by |
| 3897 | * {@code handler}; and {@code B}/{@code b}, those of arguments to the |
| 3898 | * resulting handle discarded by {@code handler}. |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3899 | * <blockquote><pre>{@code |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3900 | * T target(A..., B...); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3901 | * T handler(ExType, A...); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3902 | * T adapter(A... a, B... b) { |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3903 | * try { |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3904 | * return target(a..., b...); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3905 | * } catch (ExType ex) { |
| 3906 | * return handler(ex, a...); |
| 3907 | * } |
| 3908 | * } |
John R Rose | be5df96 | 2013-10-05 05:30:40 -0700 | [diff] [blame] | 3909 | * }</pre></blockquote> |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3910 | * Note that the saved arguments ({@code a...} in the pseudocode) cannot |
| 3911 | * be modified by execution of the target, and so are passed unchanged |
| 3912 | * from the caller to the handler, if the handler is invoked. |
| 3913 | * <p> |
| 3914 | * The target and handler must return the same type, even if the handler |
| 3915 | * always throws. (This might happen, for instance, because the handler |
| 3916 | * is simulating a {@code finally} clause). |
| 3917 | * To create such a throwing handler, compose the handler creation logic |
| 3918 | * with {@link #throwException throwException}, |
| 3919 | * in order to create a method handle of the correct return type. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3920 | * @param target method handle to call |
| 3921 | * @param exType the type of exception which the handler will catch |
| 3922 | * @param handler method handle to call if a matching exception is thrown |
| 3923 | * @return method handle which incorporates the specified try/catch logic |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3924 | * @throws NullPointerException if any argument is null |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3925 | * @throws IllegalArgumentException if {@code handler} does not accept |
| 3926 | * the given exception type, or if the method handle types do |
| 3927 | * not match in their return types and their |
| 3928 | * corresponding parameters |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 3929 | * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3930 | */ |
| 3931 | public static |
| 3932 | MethodHandle catchException(MethodHandle target, |
| 3933 | Class<? extends Throwable> exType, |
| 3934 | MethodHandle handler) { |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3935 | MethodType ttype = target.type(); |
| 3936 | MethodType htype = handler.type(); |
Michael Haupt | d64d6d8 | 2016-01-14 13:53:13 +0100 | [diff] [blame] | 3937 | if (!Throwable.class.isAssignableFrom(exType)) |
| 3938 | throw new ClassCastException(exType.getName()); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3939 | if (htype.parameterCount() < 1 || |
| 3940 | !htype.parameterType(0).isAssignableFrom(exType)) |
| 3941 | throw newIllegalArgumentException("handler does not accept exception type "+exType); |
| 3942 | if (htype.returnType() != ttype.returnType()) |
| 3943 | throw misMatchedTypes("target and handler return types", ttype, htype); |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 3944 | handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); |
| 3945 | if (handler == null) { |
| 3946 | throw misMatchedTypes("target and handler types", ttype, htype); |
John R Rose | 34cd7bc | 2010-12-16 15:59:27 -0800 | [diff] [blame] | 3947 | } |
John R Rose | e7ebd47 | 2011-03-18 00:03:24 -0700 | [diff] [blame] | 3948 | return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3949 | } |
| 3950 | |
| 3951 | /** |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3952 | * Produces a method handle which will throw exceptions of the given {@code exType}. |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3953 | * The method handle will accept a single argument of {@code exType}, |
| 3954 | * and immediately throw it as an exception. |
| 3955 | * The method type will nominally specify a return of {@code returnType}. |
| 3956 | * The return type may be anything convenient: It doesn't matter to the |
| 3957 | * method handle's behavior, since it will never return normally. |
Joe Darcy | 0e32f67 | 2013-06-27 19:02:02 -0700 | [diff] [blame] | 3958 | * @param returnType the return type of the desired method handle |
| 3959 | * @param exType the parameter type of the desired method handle |
John R Rose | 54e473f | 2011-02-11 01:26:28 -0800 | [diff] [blame] | 3960 | * @return method handle which can throw the given exceptions |
| 3961 | * @throws NullPointerException if either argument is null |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3962 | */ |
| 3963 | public static |
| 3964 | MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { |
Christian Thalinger | 360d512 | 2012-07-24 10:47:44 -0700 | [diff] [blame] | 3965 | if (!Throwable.class.isAssignableFrom(exType)) |
| 3966 | throw new ClassCastException(exType.getName()); |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 3967 | return MethodHandleImpl.throwException(methodType(returnType, exType)); |
John R Rose | 020e550 | 2010-01-07 16:16:45 -0800 | [diff] [blame] | 3968 | } |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 3969 | |
| 3970 | /** |
| 3971 | * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each |
| 3972 | * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and |
| 3973 | * delivers the loop's result, which is the return value of the resulting handle. |
| 3974 | * <p> |
| 3975 | * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop |
| 3976 | * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration |
| 3977 | * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in |
| 3978 | * terms of method handles, each clause will determine four actions:<ul> |
| 3979 | * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local. |
| 3980 | * <li>When a clause executes, an update step for the iteration variable. |
| 3981 | * <li>When a clause executes, a predicate execution to test for loop exit. |
| 3982 | * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value. |
| 3983 | * </ul> |
| 3984 | * <p> |
| 3985 | * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in |
| 3986 | * this case. See below for a detailed description. |
| 3987 | * <p> |
| 3988 | * Each clause function, with the exception of clause initializers, is able to observe the entire loop state, |
| 3989 | * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop |
| 3990 | * parameters. Most clause functions will not need all of this information, but they will be formally connected as |
| 3991 | * if by {@link #dropArguments}. |
| 3992 | * <p> |
| 3993 | * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the |
| 3994 | * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" |
| 3995 | * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met |
| 3996 | * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means |
| 3997 | * that they must be identical, or else one list must be a proper prefix of the other. |
| 3998 | * <p> |
| 3999 | * <em>Step 0: Determine clause structure.</em><ol type="a"> |
| 4000 | * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element. |
| 4001 | * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. |
| 4002 | * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length |
| 4003 | * four. Padding takes place by appending elements to the array. |
| 4004 | * <li>Clauses with all {@code null}s are disregarded. |
| 4005 | * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". |
| 4006 | * </ol> |
| 4007 | * <p> |
| 4008 | * <em>Step 1A: Determine iteration variables.</em><ol type="a"> |
| 4009 | * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type. |
| 4010 | * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else |
| 4011 | * use the common return type (they must be identical). |
| 4012 | * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. |
| 4013 | * <li>This list of types is called the "common prefix". |
| 4014 | * </ol> |
| 4015 | * <p> |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4016 | * <em>Step 1B: Determine loop parameters.</em><ul> |
| 4017 | * <li><b>If at least one init function is given,</b><ol type="a"> |
| 4018 | * <li>Examine init function parameter lists. |
| 4019 | * <li>Omitted init functions are deemed to have {@code null} parameter lists. |
| 4020 | * <li>All init function parameter lists must be effectively identical. |
| 4021 | * <li>The longest parameter list (which is necessarily unique) is called the "common suffix". |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4022 | * </ol> |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4023 | * <li><b>If no init function is given,</b><ol type="a"> |
| 4024 | * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix". |
| 4025 | * <li>The longest of these suffixes is taken as the "common suffix". |
| 4026 | * </ol></ul> |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4027 | * <p> |
| 4028 | * <em>Step 1C: Determine loop return type.</em><ol type="a"> |
| 4029 | * <li>Examine fini function return types, disregarding omitted fini functions. |
| 4030 | * <li>If there are no fini functions, use {@code void} as the loop return type. |
| 4031 | * <li>Otherwise, use the common return type of the fini functions; they must all be identical. |
| 4032 | * </ol> |
| 4033 | * <p> |
| 4034 | * <em>Step 1D: Check other types.</em><ol type="a"> |
| 4035 | * <li>There must be at least one non-omitted pred function. |
| 4036 | * <li>Every non-omitted pred function must have a {@code boolean} return type. |
| 4037 | * </ol> |
| 4038 | * <p> |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4039 | * <em>Step 2: Determine parameter lists.</em><ol type="a"> |
| 4040 | * <li>The parameter list for the resulting loop handle will be the "common suffix". |
| 4041 | * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter |
| 4042 | * lists are already effectively identical to the common suffix.) |
| 4043 | * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix |
| 4044 | * followed by the common suffix, called the "common parameter sequence". |
| 4045 | * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter |
| 4046 | * sequence. |
| 4047 | * </ol> |
| 4048 | * <p> |
| 4049 | * <em>Step 3: Fill in omitted functions.</em><ol type="a"> |
| 4050 | * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate |
| 4051 | * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a |
| 4052 | * function which does nothing and returns {@code void}; it can be obtained from another constant function by |
| 4053 | * {@linkplain MethodHandle#asType type conversion}.) |
| 4054 | * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration |
| 4055 | * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} |
| 4056 | * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) |
| 4057 | * <li>If a pred function is omitted, the corresponding fini function must also be omitted. |
| 4058 | * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far |
| 4059 | * as this clause is concerned.) |
| 4060 | * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the |
| 4061 | * loop return type. |
| 4062 | * </ol> |
| 4063 | * <p> |
| 4064 | * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> |
| 4065 | * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some |
| 4066 | * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by |
| 4067 | * {@linkplain #dropArguments dropping arguments}. |
| 4068 | * <li>At this point, every non-init function parameter list is effectively identical to the common parameter |
| 4069 | * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end |
| 4070 | * of the list by {@linkplain #dropArguments dropping arguments}. |
| 4071 | * </ol> |
| 4072 | * <p> |
| 4073 | * <em>Final observations.</em><ol type="a"> |
| 4074 | * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. |
| 4075 | * <li>All init functions have a common parameter type list, which the final loop handle will also have. |
| 4076 | * <li>All fini functions have a common return type, which the final loop handle will also have. |
| 4077 | * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of |
| 4078 | * (non-{@code void}) iteration variables followed by loop parameters. |
| 4079 | * <li>Each pair of init and step functions agrees in their return types. |
| 4080 | * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the |
| 4081 | * common prefix. |
| 4082 | * </ol> |
| 4083 | * <p> |
| 4084 | * <em>Loop execution.</em><ol type="a"> |
| 4085 | * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to |
| 4086 | * every clause function. These locals are loop invariant. |
| 4087 | * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values |
| 4088 | * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity |
| 4089 | * functions, as noted above). |
| 4090 | * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of |
| 4091 | * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order). |
| 4092 | * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function |
| 4093 | * returns {@code false}. |
| 4094 | * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The |
| 4095 | * updated value is immediately visible to all subsequent function calls. |
| 4096 | * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value |
| 4097 | * is returned from the loop as a whole. |
| 4098 | * </ol> |
| 4099 | * <p> |
| 4100 | * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values |
| 4101 | * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the |
| 4102 | * result types of finalizers as well as of the resulting loop. |
| 4103 | * <blockquote><pre>{@code |
| 4104 | * V... init...(A...); |
| 4105 | * boolean pred...(V..., A...); |
| 4106 | * V... step...(V..., A...); |
| 4107 | * R fini...(V..., A...); |
| 4108 | * R loop(A... a) { |
| 4109 | * V... v... = init...(a...); |
| 4110 | * for (;;) { |
| 4111 | * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { |
| 4112 | * v = s(v..., a...); |
| 4113 | * if (!p(v..., a...)) { |
| 4114 | * return f(v..., a...); |
| 4115 | * } |
| 4116 | * } |
| 4117 | * } |
| 4118 | * } |
| 4119 | * }</pre></blockquote> |
| 4120 | * <p> |
| 4121 | * @apiNote Example: |
| 4122 | * <blockquote><pre>{@code |
| 4123 | * // iterative implementation of the factorial function as a loop handle |
| 4124 | * static int one(int k) { return 1; } |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4125 | * static int inc(int i, int acc, int k) { return i + 1; } |
| 4126 | * static int mult(int i, int acc, int k) { return i * acc; } |
| 4127 | * static boolean pred(int i, int acc, int k) { return i < k; } |
| 4128 | * static int fin(int i, int acc, int k) { return acc; } |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4129 | * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods |
| 4130 | * // null initializer for counter, should initialize to 0 |
| 4131 | * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; |
| 4132 | * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; |
| 4133 | * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); |
| 4134 | * assertEquals(120, loop.invoke(5)); |
| 4135 | * }</pre></blockquote> |
| 4136 | * |
| 4137 | * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. |
| 4138 | * |
| 4139 | * @return a method handle embodying the looping behavior as defined by the arguments. |
| 4140 | * |
| 4141 | * @throws IllegalArgumentException in case any of the constraints described above is violated. |
| 4142 | * |
| 4143 | * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) |
| 4144 | * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) |
| 4145 | * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) |
| 4146 | * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) |
| 4147 | * @since 9 |
| 4148 | */ |
| 4149 | public static MethodHandle loop(MethodHandle[]... clauses) { |
| 4150 | // Step 0: determine clause structure. |
| 4151 | checkLoop0(clauses); |
| 4152 | |
| 4153 | List<MethodHandle> init = new ArrayList<>(); |
| 4154 | List<MethodHandle> step = new ArrayList<>(); |
| 4155 | List<MethodHandle> pred = new ArrayList<>(); |
| 4156 | List<MethodHandle> fini = new ArrayList<>(); |
| 4157 | |
| 4158 | Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { |
| 4159 | init.add(clause[0]); // all clauses have at least length 1 |
| 4160 | step.add(clause.length <= 1 ? null : clause[1]); |
| 4161 | pred.add(clause.length <= 2 ? null : clause[2]); |
| 4162 | fini.add(clause.length <= 3 ? null : clause[3]); |
| 4163 | }); |
| 4164 | |
| 4165 | assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; |
| 4166 | final int nclauses = init.size(); |
| 4167 | |
| 4168 | // Step 1A: determine iteration variables. |
| 4169 | final List<Class<?>> iterationVariableTypes = new ArrayList<>(); |
| 4170 | for (int i = 0; i < nclauses; ++i) { |
| 4171 | MethodHandle in = init.get(i); |
| 4172 | MethodHandle st = step.get(i); |
| 4173 | if (in == null && st == null) { |
| 4174 | iterationVariableTypes.add(void.class); |
| 4175 | } else if (in != null && st != null) { |
| 4176 | checkLoop1a(i, in, st); |
| 4177 | iterationVariableTypes.add(in.type().returnType()); |
| 4178 | } else { |
| 4179 | iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); |
| 4180 | } |
| 4181 | } |
| 4182 | final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). |
| 4183 | collect(Collectors.toList()); |
| 4184 | |
| 4185 | // Step 1B: determine loop parameters. |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4186 | final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4187 | checkLoop1b(init, commonSuffix); |
| 4188 | |
| 4189 | // Step 1C: determine loop return type. |
| 4190 | // Step 1D: check other types. |
| 4191 | final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type). |
| 4192 | map(MethodType::returnType).findFirst().orElse(void.class); |
| 4193 | checkLoop1cd(pred, fini, loopReturnType); |
| 4194 | |
| 4195 | // Step 2: determine parameter lists. |
| 4196 | final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); |
| 4197 | commonParameterSequence.addAll(commonSuffix); |
| 4198 | checkLoop2(step, pred, fini, commonParameterSequence); |
| 4199 | |
| 4200 | // Step 3: fill in omitted functions. |
| 4201 | for (int i = 0; i < nclauses; ++i) { |
| 4202 | Class<?> t = iterationVariableTypes.get(i); |
| 4203 | if (init.get(i) == null) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4204 | init.set(i, empty(methodType(t, commonSuffix))); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4205 | } |
| 4206 | if (step.get(i) == null) { |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 4207 | step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4208 | } |
| 4209 | if (pred.get(i) == null) { |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 4210 | pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence)); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4211 | } |
| 4212 | if (fini.get(i) == null) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4213 | fini.set(i, empty(methodType(t, commonParameterSequence))); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4214 | } |
| 4215 | } |
| 4216 | |
| 4217 | // Step 4: fill in missing parameter types. |
| 4218 | List<MethodHandle> finit = fillParameterTypes(init, commonSuffix); |
| 4219 | List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence); |
| 4220 | List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence); |
| 4221 | List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence); |
| 4222 | |
| 4223 | assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). |
| 4224 | allMatch(pl -> pl.equals(commonSuffix)); |
| 4225 | assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). |
| 4226 | allMatch(pl -> pl.equals(commonParameterSequence)); |
| 4227 | |
| 4228 | return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini); |
| 4229 | } |
| 4230 | |
| 4231 | private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { |
| 4232 | return hs.stream().map(h -> { |
| 4233 | int pc = h.type().parameterCount(); |
| 4234 | int tpsize = targetParams.size(); |
| 4235 | return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h; |
| 4236 | }).collect(Collectors.toList()); |
| 4237 | } |
| 4238 | |
| 4239 | /** |
| 4240 | * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for |
| 4241 | * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. |
| 4242 | * <p> |
| 4243 | * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. |
| 4244 | * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle |
| 4245 | * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code |
| 4246 | * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) |
| 4247 | * generic loop combinator}. |
| 4248 | * <p> |
| 4249 | * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of |
| 4250 | * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument |
| 4251 | * passed to the loop. |
| 4252 | * <blockquote><pre>{@code |
| 4253 | * V init(A); |
| 4254 | * boolean pred(V, A); |
| 4255 | * V body(V, A); |
| 4256 | * V whileLoop(A a) { |
| 4257 | * V v = init(a); |
| 4258 | * while (pred(v, a)) { |
| 4259 | * v = body(v, a); |
| 4260 | * } |
| 4261 | * return v; |
| 4262 | * } |
| 4263 | * }</pre></blockquote> |
| 4264 | * <p> |
| 4265 | * @apiNote Example: |
| 4266 | * <blockquote><pre>{@code |
| 4267 | * // implement the zip function for lists as a loop handle |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4268 | * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } |
| 4269 | * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } |
| 4270 | * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4271 | * zip.add(a.next()); |
| 4272 | * zip.add(b.next()); |
| 4273 | * return zip; |
| 4274 | * } |
| 4275 | * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods |
Michael Haupt | fc2641e | 2016-03-02 14:15:15 +0100 | [diff] [blame] | 4276 | * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4277 | * List<String> a = Arrays.asList("a", "b", "c", "d"); |
| 4278 | * List<String> b = Arrays.asList("e", "f", "g", "h"); |
| 4279 | * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); |
| 4280 | * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); |
| 4281 | * }</pre></blockquote> |
| 4282 | * |
| 4283 | * <p> |
| 4284 | * @implSpec The implementation of this method is equivalent to: |
| 4285 | * <blockquote><pre>{@code |
| 4286 | * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { |
| 4287 | * MethodHandle[] |
| 4288 | * checkExit = {null, null, pred, identity(init.type().returnType())}, |
| 4289 | * varBody = {init, body}; |
| 4290 | * return loop(checkExit, varBody); |
| 4291 | * } |
| 4292 | * }</pre></blockquote> |
| 4293 | * |
| 4294 | * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's |
| 4295 | * result type. Passing {@code null} or a {@code void} init function will make the loop's result type |
| 4296 | * {@code void}. |
| 4297 | * @param pred condition for the loop, which may not be {@code null}. |
| 4298 | * @param body body of the loop, which may not be {@code null}. |
| 4299 | * |
| 4300 | * @return the value of the loop variable as the loop terminates. |
| 4301 | * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure |
| 4302 | * |
| 4303 | * @see MethodHandles#loop(MethodHandle[][]) |
| 4304 | * @since 9 |
| 4305 | */ |
| 4306 | public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4307 | MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : |
| 4308 | identity(init.type().returnType()); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4309 | MethodHandle[] checkExit = {null, null, pred, fin}; |
| 4310 | MethodHandle[] varBody = {init, body}; |
| 4311 | return loop(checkExit, varBody); |
| 4312 | } |
| 4313 | |
| 4314 | /** |
| 4315 | * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper |
| 4316 | * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. |
| 4317 | * <p> |
| 4318 | * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. |
| 4319 | * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle |
| 4320 | * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code |
| 4321 | * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) |
| 4322 | * generic loop combinator}. |
| 4323 | * <p> |
| 4324 | * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of |
| 4325 | * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument |
| 4326 | * passed to the loop. |
| 4327 | * <blockquote><pre>{@code |
| 4328 | * V init(A); |
| 4329 | * boolean pred(V, A); |
| 4330 | * V body(V, A); |
| 4331 | * V doWhileLoop(A a) { |
| 4332 | * V v = init(a); |
| 4333 | * do { |
| 4334 | * v = body(v, a); |
| 4335 | * } while (pred(v, a)); |
| 4336 | * return v; |
| 4337 | * } |
| 4338 | * }</pre></blockquote> |
| 4339 | * <p> |
| 4340 | * @apiNote Example: |
| 4341 | * <blockquote><pre>{@code |
| 4342 | * // int i = 0; while (i < limit) { ++i; } return i; => limit |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4343 | * static int zero(int limit) { return 0; } |
| 4344 | * static int step(int i, int limit) { return i + 1; } |
| 4345 | * static boolean pred(int i, int limit) { return i < limit; } |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4346 | * // assume MH_zero, MH_step, and MH_pred are handles to the above methods |
| 4347 | * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); |
| 4348 | * assertEquals(23, loop.invoke(23)); |
| 4349 | * }</pre></blockquote> |
| 4350 | * |
| 4351 | * <p> |
| 4352 | * @implSpec The implementation of this method is equivalent to: |
| 4353 | * <blockquote><pre>{@code |
| 4354 | * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { |
| 4355 | * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) }; |
| 4356 | * return loop(clause); |
| 4357 | * } |
| 4358 | * }</pre></blockquote> |
| 4359 | * |
| 4360 | * |
| 4361 | * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's |
| 4362 | * result type. Passing {@code null} or a {@code void} init function will make the loop's result type |
| 4363 | * {@code void}. |
| 4364 | * @param pred condition for the loop, which may not be {@code null}. |
| 4365 | * @param body body of the loop, which may not be {@code null}. |
| 4366 | * |
| 4367 | * @return the value of the loop variable as the loop terminates. |
| 4368 | * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure |
| 4369 | * |
| 4370 | * @see MethodHandles#loop(MethodHandle[][]) |
| 4371 | * @since 9 |
| 4372 | */ |
| 4373 | public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4374 | MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : |
| 4375 | identity(init.type().returnType()); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4376 | MethodHandle[] clause = {init, body, pred, fin}; |
| 4377 | return loop(clause); |
| 4378 | } |
| 4379 | |
| 4380 | /** |
| 4381 | * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the |
| 4382 | * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must |
| 4383 | * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional |
| 4384 | * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop |
| 4385 | * combinator}. |
| 4386 | * <p> |
| 4387 | * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code |
| 4388 | * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code |
| 4389 | * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter, |
| 4390 | * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described |
| 4391 | * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. |
| 4392 | * <p> |
| 4393 | * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of |
| 4394 | * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument |
| 4395 | * passed to the loop. |
| 4396 | * <blockquote><pre>{@code |
| 4397 | * int iterations(A); |
| 4398 | * V init(A); |
| 4399 | * V body(int, V, A); |
| 4400 | * V countedLoop(A a) { |
| 4401 | * int end = iterations(a); |
| 4402 | * V v = init(a); |
| 4403 | * for (int i = 0; i < end; ++i) { |
| 4404 | * v = body(i, v, a); |
| 4405 | * } |
| 4406 | * return v; |
| 4407 | * } |
| 4408 | * }</pre></blockquote> |
| 4409 | * <p> |
| 4410 | * @apiNote Example: |
| 4411 | * <blockquote><pre>{@code |
| 4412 | * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; |
| 4413 | * // => a variation on a well known theme |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4414 | * static String start(String arg) { return arg; } |
| 4415 | * static String step(int counter, String v, String arg) { return "na " + v; } |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4416 | * // assume MH_start and MH_step are handles to the two methods above |
Michael Haupt | 03e64ce | 2015-12-03 15:36:20 +0100 | [diff] [blame] | 4417 | * MethodHandle fit13 = MethodHandles.constant(int.class, 13); |
| 4418 | * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4419 | * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); |
| 4420 | * }</pre></blockquote> |
| 4421 | * |
| 4422 | * <p> |
| 4423 | * @implSpec The implementation of this method is equivalent to: |
| 4424 | * <blockquote><pre>{@code |
| 4425 | * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { |
| 4426 | * return countedLoop(null, iterations, init, body); // null => constant zero |
| 4427 | * } |
| 4428 | * }</pre></blockquote> |
| 4429 | * |
| 4430 | * @param iterations a handle to return the number of iterations this loop should run. |
| 4431 | * @param init initializer for additional loop state. This determines the loop's result type. |
| 4432 | * Passing {@code null} or a {@code void} init function will make the loop's result type |
| 4433 | * {@code void}. |
| 4434 | * @param body the body of the loop, which must not be {@code null}. |
| 4435 | * It must accept an initial {@code int} parameter (for the counter), and then any |
| 4436 | * additional loop-local variable plus loop parameters. |
| 4437 | * |
| 4438 | * @return a method handle representing the loop. |
| 4439 | * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure |
| 4440 | * |
| 4441 | * @since 9 |
| 4442 | */ |
| 4443 | public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { |
| 4444 | return countedLoop(null, iterations, init, body); |
| 4445 | } |
| 4446 | |
| 4447 | /** |
| 4448 | * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be |
| 4449 | * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the |
| 4450 | * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code |
| 4451 | * body} function in each iteration; it has to accept an initial {@code int} parameter |
| 4452 | * for that. The result of the loop execution is the final value of the additional local state |
| 4453 | * obtained by running {@code init}. |
| 4454 | * This is a |
| 4455 | * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. |
| 4456 | * <p> |
| 4457 | * The constraints for the {@code init} and {@code body} handles are the same as for {@link |
| 4458 | * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles |
| 4459 | * must return an {@code int} and accept the same parameters as {@code init}. |
| 4460 | * <p> |
| 4461 | * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of |
| 4462 | * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument |
| 4463 | * passed to the loop. |
| 4464 | * <blockquote><pre>{@code |
| 4465 | * int start(A); |
| 4466 | * int end(A); |
| 4467 | * V init(A); |
| 4468 | * V body(int, V, A); |
| 4469 | * V countedLoop(A a) { |
| 4470 | * int s = start(a); |
| 4471 | * int e = end(a); |
| 4472 | * V v = init(a); |
| 4473 | * for (int i = s; i < e; ++i) { |
| 4474 | * v = body(i, v, a); |
| 4475 | * } |
| 4476 | * return v; |
| 4477 | * } |
| 4478 | * }</pre></blockquote> |
| 4479 | * |
| 4480 | * <p> |
| 4481 | * @implSpec The implementation of this method is equivalent to: |
| 4482 | * <blockquote><pre>{@code |
| 4483 | * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { |
| 4484 | * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); |
Michael Haupt | c304110 | 2016-04-13 09:20:22 +0200 | [diff] [blame] | 4485 | * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int, |
| 4486 | * // assume MH_decrement is a handle to x-1 of type int |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4487 | * MethodHandle[] |
| 4488 | * indexVar = {start, MH_increment}, // i = start; i = i+1 |
| 4489 | * loopLimit = {end, null, MH_lessThan, returnVar }, // i<end |
Michael Haupt | c304110 | 2016-04-13 09:20:22 +0200 | [diff] [blame] | 4490 | * bodyClause = {init, |
| 4491 | * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v) |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4492 | * return loop(indexVar, loopLimit, bodyClause); |
| 4493 | * } |
| 4494 | * }</pre></blockquote> |
| 4495 | * |
| 4496 | * @param start a handle to return the start value of the loop counter. |
| 4497 | * If it is {@code null}, a constant zero is assumed. |
| 4498 | * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}). |
| 4499 | * @param init initializer for additional loop state. This determines the loop's result type. |
| 4500 | * Passing {@code null} or a {@code void} init function will make the loop's result type |
| 4501 | * {@code void}. |
| 4502 | * @param body the body of the loop, which must not be {@code null}. |
| 4503 | * It must accept an initial {@code int} parameter (for the counter), and then any |
| 4504 | * additional loop-local variable plus loop parameters. |
| 4505 | * |
| 4506 | * @return a method handle representing the loop. |
| 4507 | * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure |
| 4508 | * |
| 4509 | * @since 9 |
| 4510 | */ |
| 4511 | public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { |
Michael Haupt | cafabca | 2016-04-22 15:05:54 +0200 | [diff] [blame] | 4512 | Class<?> resultType; |
| 4513 | MethodHandle actualInit; |
| 4514 | if (init == null) { |
| 4515 | resultType = body == null ? void.class : body.type().returnType(); |
| 4516 | actualInit = empty(methodType(resultType)); |
| 4517 | } else { |
| 4518 | resultType = init.type().returnType(); |
| 4519 | actualInit = init; |
| 4520 | } |
| 4521 | MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType); |
| 4522 | MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body; |
Michael Haupt | e53e280 | 2016-04-22 15:05:26 +0200 | [diff] [blame] | 4523 | MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class); |
Michael Haupt | cafabca | 2016-04-22 15:05:54 +0200 | [diff] [blame] | 4524 | MethodHandle actualEnd = end == null ? constant(int.class, 0) : end; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4525 | MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)}; |
Michael Haupt | cafabca | 2016-04-22 15:05:54 +0200 | [diff] [blame] | 4526 | MethodHandle[] loopLimit = {actualEnd, null, |
| 4527 | MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar}; |
| 4528 | MethodHandle[] bodyClause = {actualInit, |
| 4529 | filterArgument(dropArguments(actualBody, 1, int.class), 0, |
Michael Haupt | c304110 | 2016-04-13 09:20:22 +0200 | [diff] [blame] | 4530 | MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))}; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4531 | return loop(indexVar, loopLimit, bodyClause); |
| 4532 | } |
| 4533 | |
| 4534 | /** |
| 4535 | * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}. |
| 4536 | * The iterator will be produced by the evaluation of the {@code iterator} handle. |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4537 | * This handle must have {@link java.util.Iterator} as its return type. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4538 | * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead, |
| 4539 | * and will be applied to a leading argument of the loop handle. |
| 4540 | * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter. |
| 4541 | * The result of the loop execution is the final value of the additional local state |
| 4542 | * obtained by running {@code init}. |
| 4543 | * <p> |
| 4544 | * This is a convenience wrapper for the |
| 4545 | * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body} |
| 4546 | * handle follow directly from those described for the latter. |
| 4547 | * <p> |
| 4548 | * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of |
| 4549 | * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the |
| 4550 | * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop. |
| 4551 | * <blockquote><pre>{@code |
| 4552 | * Iterator<T> iterator(A); // defaults to Iterable::iterator |
| 4553 | * V init(A); |
| 4554 | * V body(T,V,A); |
| 4555 | * V iteratedLoop(A a) { |
| 4556 | * Iterator<T> it = iterator(a); |
| 4557 | * V v = init(a); |
| 4558 | * for (T t : it) { |
| 4559 | * v = body(t, v, a); |
| 4560 | * } |
| 4561 | * return v; |
| 4562 | * } |
| 4563 | * }</pre></blockquote> |
| 4564 | * <p> |
| 4565 | * The type {@code T} may be either a primitive or reference. |
| 4566 | * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type |
| 4567 | * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} |
| 4568 | * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method. |
| 4569 | * Therefore, if an iterator of the wrong type appears as the loop is executed, |
| 4570 | * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}. |
| 4571 | * <p> |
| 4572 | * @apiNote Example: |
| 4573 | * <blockquote><pre>{@code |
| 4574 | * // reverse a list |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4575 | * static List<String> reverseStep(String e, List<String> r, List<String> l) { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4576 | * r.add(0, e); |
| 4577 | * return r; |
| 4578 | * } |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4579 | * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); } |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4580 | * // assume MH_reverseStep, MH_newArrayList are handles to the above methods |
| 4581 | * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); |
| 4582 | * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); |
| 4583 | * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); |
| 4584 | * assertEquals(reversedList, (List<String>) loop.invoke(list)); |
| 4585 | * }</pre></blockquote> |
| 4586 | * <p> |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4587 | * @implSpec The implementation of this method is equivalent to (excluding error handling): |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4588 | * <blockquote><pre>{@code |
| 4589 | * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { |
| 4590 | * // assume MH_next and MH_hasNext are handles to methods of Iterator |
| 4591 | * Class<?> itype = iterator.type().returnType(); |
| 4592 | * Class<?> ttype = body.type().parameterType(0); |
| 4593 | * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype); |
| 4594 | * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); |
| 4595 | * MethodHandle[] |
| 4596 | * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext) |
| 4597 | * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a); |
| 4598 | * return loop(iterVar, bodyClause); |
| 4599 | * } |
| 4600 | * }</pre></blockquote> |
| 4601 | * |
| 4602 | * @param iterator a handle to return the iterator to start the loop. |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4603 | * The handle must have {@link java.util.Iterator} as its return type. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4604 | * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first |
| 4605 | * incoming value. |
| 4606 | * @param init initializer for additional loop state. This determines the loop's result type. |
| 4607 | * Passing {@code null} or a {@code void} init function will make the loop's result type |
| 4608 | * {@code void}. |
| 4609 | * @param body the body of the loop, which must not be {@code null}. |
| 4610 | * It must accept an initial {@code T} parameter (for the iterated values), and then any |
| 4611 | * additional loop-local variable plus loop parameters. |
| 4612 | * |
| 4613 | * @return a method handle embodying the iteration loop functionality. |
| 4614 | * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure |
| 4615 | * |
| 4616 | * @since 9 |
| 4617 | */ |
| 4618 | public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4619 | checkIteratedLoop(iterator, body); |
Michael Haupt | 5b392c0 | 2016-04-22 13:36:22 +0200 | [diff] [blame] | 4620 | Class<?> resultType = init == null ? |
| 4621 | body == null ? void.class : body.type().returnType() : |
| 4622 | init.type().returnType(); |
| 4623 | boolean voidResult = resultType == void.class; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4624 | |
Michael Haupt | 5b392c0 | 2016-04-22 13:36:22 +0200 | [diff] [blame] | 4625 | MethodHandle initIterator; |
| 4626 | if (iterator == null) { |
| 4627 | MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); |
| 4628 | initIterator = initit.asType(initit.type().changeParameterType(0, |
| 4629 | body.type().parameterType(voidResult ? 1 : 2))); |
| 4630 | } else { |
| 4631 | initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class)); |
| 4632 | } |
| 4633 | |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4634 | Class<?> ttype = body.type().parameterType(0); |
| 4635 | |
| 4636 | MethodHandle returnVar = |
Michael Haupt | 5b392c0 | 2016-04-22 13:36:22 +0200 | [diff] [blame] | 4637 | dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4638 | MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); |
| 4639 | MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype)); |
| 4640 | |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4641 | MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), |
| 4642 | returnVar}; |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4643 | MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)}; |
| 4644 | |
| 4645 | return loop(iterVar, bodyClause); |
| 4646 | } |
| 4647 | |
| 4648 | /** |
| 4649 | * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. |
| 4650 | * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception |
| 4651 | * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The |
| 4652 | * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The |
| 4653 | * value returned from the {@code cleanup} handle's execution will be the result of the execution of the |
| 4654 | * {@code try-finally} handle. |
| 4655 | * <p> |
| 4656 | * The {@code cleanup} handle will be passed one or two additional leading arguments. |
| 4657 | * The first is the exception thrown during the |
| 4658 | * execution of the {@code target} handle, or {@code null} if no exception was thrown. |
| 4659 | * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, |
| 4660 | * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. |
| 4661 | * The second argument is not present if the {@code target} handle has a {@code void} return type. |
| 4662 | * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists |
| 4663 | * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) |
| 4664 | * <p> |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 4665 | * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except |
| 4666 | * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or |
| 4667 | * two extra leading parameters:<ul> |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4668 | * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and |
| 4669 | * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry |
| 4670 | * the result from the execution of the {@code target} handle. |
| 4671 | * This parameter is not present if the {@code target} returns {@code void}. |
| 4672 | * </ul> |
| 4673 | * <p> |
| 4674 | * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of |
| 4675 | * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting |
| 4676 | * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by |
| 4677 | * the cleanup. |
| 4678 | * <blockquote><pre>{@code |
| 4679 | * V target(A..., B...); |
| 4680 | * V cleanup(Throwable, V, A...); |
| 4681 | * V adapter(A... a, B... b) { |
| 4682 | * V result = (zero value for V); |
| 4683 | * Throwable throwable = null; |
| 4684 | * try { |
| 4685 | * result = target(a..., b...); |
| 4686 | * } catch (Throwable t) { |
| 4687 | * throwable = t; |
| 4688 | * throw t; |
| 4689 | * } finally { |
| 4690 | * result = cleanup(throwable, result, a...); |
| 4691 | * } |
| 4692 | * return result; |
| 4693 | * } |
| 4694 | * }</pre></blockquote> |
| 4695 | * <p> |
| 4696 | * Note that the saved arguments ({@code a...} in the pseudocode) cannot |
| 4697 | * be modified by execution of the target, and so are passed unchanged |
| 4698 | * from the caller to the cleanup, if it is invoked. |
| 4699 | * <p> |
| 4700 | * The target and cleanup must return the same type, even if the cleanup |
| 4701 | * always throws. |
| 4702 | * To create such a throwing cleanup, compose the cleanup logic |
| 4703 | * with {@link #throwException throwException}, |
| 4704 | * in order to create a method handle of the correct return type. |
| 4705 | * <p> |
| 4706 | * Note that {@code tryFinally} never converts exceptions into normal returns. |
| 4707 | * In rare cases where exceptions must be converted in that way, first wrap |
| 4708 | * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} |
| 4709 | * to capture an outgoing exception, and then wrap with {@code tryFinally}. |
| 4710 | * |
| 4711 | * @param target the handle whose execution is to be wrapped in a {@code try} block. |
| 4712 | * @param cleanup the handle that is invoked in the finally block. |
| 4713 | * |
| 4714 | * @return a method handle embodying the {@code try-finally} block composed of the two arguments. |
| 4715 | * @throws NullPointerException if any argument is null |
| 4716 | * @throws IllegalArgumentException if {@code cleanup} does not accept |
| 4717 | * the required leading arguments, or if the method handle types do |
| 4718 | * not match in their return types and their |
| 4719 | * corresponding trailing parameters |
| 4720 | * |
| 4721 | * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) |
| 4722 | * @since 9 |
| 4723 | */ |
| 4724 | public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { |
| 4725 | List<Class<?>> targetParamTypes = target.type().parameterList(); |
| 4726 | List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); |
| 4727 | Class<?> rtype = target.type().returnType(); |
| 4728 | |
| 4729 | checkTryFinally(target, cleanup); |
| 4730 | |
| 4731 | // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 4732 | // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the |
| 4733 | // target parameter list. |
| 4734 | cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4735 | MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount()); |
Shilpi Rastogi | 284ec15 | 2016-04-13 15:48:14 +0200 | [diff] [blame] | 4736 | MethodHandle aCleanup = cleanup.asSpreader(Object[].class, targetParamTypes.size()); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4737 | |
| 4738 | return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes); |
| 4739 | } |
| 4740 | |
| 4741 | /** |
| 4742 | * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then |
| 4743 | * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just |
| 4744 | * before the folded arguments. |
| 4745 | * <p> |
| 4746 | * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the |
| 4747 | * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a |
| 4748 | * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position |
| 4749 | * 0. |
| 4750 | * <p> |
| 4751 | * @apiNote Example: |
| 4752 | * <blockquote><pre>{@code |
| 4753 | import static java.lang.invoke.MethodHandles.*; |
| 4754 | import static java.lang.invoke.MethodType.*; |
| 4755 | ... |
| 4756 | MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, |
| 4757 | "println", methodType(void.class, String.class)) |
| 4758 | .bindTo(System.out); |
| 4759 | MethodHandle cat = lookup().findVirtual(String.class, |
| 4760 | "concat", methodType(String.class, String.class)); |
| 4761 | assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); |
| 4762 | MethodHandle catTrace = foldArguments(cat, 1, trace); |
| 4763 | // also prints "jum": |
| 4764 | assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); |
| 4765 | * }</pre></blockquote> |
Michael Haupt | 19a07cb | 2016-02-23 09:49:04 +0100 | [diff] [blame] | 4766 | * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} |
| 4767 | * represents the result type of the {@code target} and resulting adapter. |
| 4768 | * {@code V}/{@code v} represent the type and value of the parameter and argument |
| 4769 | * of {@code target} that precedes the folding position; {@code V} also is |
| 4770 | * the result type of the {@code combiner}. {@code A}/{@code a} denote the |
| 4771 | * types and values of the {@code N} parameters and arguments at the folding |
| 4772 | * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types |
| 4773 | * and values of the {@code target} parameters and arguments that precede and |
| 4774 | * follow the folded parameters and arguments starting at {@code pos}, |
| 4775 | * respectively. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4776 | * <blockquote><pre>{@code |
| 4777 | * // there are N arguments in A... |
| 4778 | * T target(Z..., V, A[N]..., B...); |
| 4779 | * V combiner(A...); |
| 4780 | * T adapter(Z... z, A... a, B... b) { |
| 4781 | * V v = combiner(a...); |
| 4782 | * return target(z..., v, a..., b...); |
| 4783 | * } |
| 4784 | * // and if the combiner has a void return: |
| 4785 | * T target2(Z..., A[N]..., B...); |
| 4786 | * void combiner2(A...); |
| 4787 | * T adapter2(Z... z, A... a, B... b) { |
| 4788 | * combiner2(a...); |
| 4789 | * return target2(z..., a..., b...); |
| 4790 | * } |
| 4791 | * }</pre></blockquote> |
Michael Haupt | 5baf4fc | 2016-02-23 07:17:54 +0100 | [diff] [blame] | 4792 | * <p> |
| 4793 | * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector |
| 4794 | * variable-arity method handle}, even if the original target method handle was. |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4795 | * |
| 4796 | * @param target the method handle to invoke after arguments are combined |
| 4797 | * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code |
| 4798 | * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. |
| 4799 | * @param combiner method handle to call initially on the incoming arguments |
| 4800 | * @return method handle which incorporates the specified argument folding logic |
| 4801 | * @throws NullPointerException if either argument is null |
| 4802 | * @throws IllegalArgumentException if {@code combiner}'s return type |
| 4803 | * is non-void and not the same as the argument type at position {@code pos} of |
| 4804 | * the target signature, or if the {@code N} argument types at position {@code pos} |
| 4805 | * of the target signature |
| 4806 | * (skipping one matching the {@code combiner}'s return type) |
| 4807 | * are not identical with the argument types of {@code combiner} |
| 4808 | * |
| 4809 | * @see #foldArguments(MethodHandle, MethodHandle) |
| 4810 | * @since 9 |
| 4811 | */ |
| 4812 | public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { |
| 4813 | MethodType targetType = target.type(); |
| 4814 | MethodType combinerType = combiner.type(); |
| 4815 | Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); |
| 4816 | BoundMethodHandle result = target.rebind(); |
| 4817 | boolean dropResult = rtype == void.class; |
| 4818 | LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); |
| 4819 | MethodType newType = targetType; |
| 4820 | if (!dropResult) { |
| 4821 | newType = newType.dropParameterTypes(pos, pos + 1); |
| 4822 | } |
| 4823 | result = result.copyWithExtendL(newType, lform, combiner); |
| 4824 | return result; |
| 4825 | } |
| 4826 | |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4827 | |
| 4828 | private static void checkLoop0(MethodHandle[][] clauses) { |
| 4829 | if (clauses == null || clauses.length == 0) { |
| 4830 | throw newIllegalArgumentException("null or no clauses passed"); |
| 4831 | } |
| 4832 | if (Stream.of(clauses).anyMatch(Objects::isNull)) { |
| 4833 | throw newIllegalArgumentException("null clauses are not allowed"); |
| 4834 | } |
| 4835 | if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { |
| 4836 | throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); |
| 4837 | } |
| 4838 | } |
| 4839 | |
| 4840 | private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) { |
| 4841 | if (in.type().returnType() != st.type().returnType()) { |
| 4842 | throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), |
| 4843 | st.type().returnType()); |
| 4844 | } |
| 4845 | } |
| 4846 | |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4847 | private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { |
| 4848 | final List<Class<?>> empty = List.of(); |
| 4849 | final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList()); |
| 4850 | if (nonNullInits.isEmpty()) { |
| 4851 | final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull). |
| 4852 | // take only those that can contribute to a common suffix because they are longer than the prefix |
| 4853 | map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList). |
| 4854 | reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); |
| 4855 | return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size()); |
| 4856 | } else { |
| 4857 | return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList). |
| 4858 | reduce((p, q) -> p.size() >= q.size() ? p : q).get(); |
| 4859 | } |
| 4860 | } |
| 4861 | |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4862 | private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { |
| 4863 | if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList). |
| 4864 | anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) { |
| 4865 | throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + |
| 4866 | " (common suffix: " + commonSuffix + ")"); |
| 4867 | } |
| 4868 | } |
| 4869 | |
| 4870 | private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { |
| 4871 | if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). |
| 4872 | anyMatch(t -> t != loopReturnType)) { |
| 4873 | throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + |
| 4874 | loopReturnType + ")"); |
| 4875 | } |
| 4876 | |
| 4877 | if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { |
| 4878 | throw newIllegalArgumentException("no predicate found", pred); |
| 4879 | } |
| 4880 | if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). |
| 4881 | anyMatch(t -> t != boolean.class)) { |
| 4882 | throw newIllegalArgumentException("predicates must have boolean return type", pred); |
| 4883 | } |
| 4884 | } |
| 4885 | |
| 4886 | private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4887 | final int cpSize = commonParameterSequence.size(); |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4888 | if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). |
Michael Haupt | 1619ac1 | 2016-03-02 20:16:11 +0100 | [diff] [blame] | 4889 | map(MethodType::parameterList). |
| 4890 | anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4891 | throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + |
| 4892 | "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); |
| 4893 | } |
| 4894 | } |
| 4895 | |
Michael Haupt | 402c448 | 2016-04-19 14:39:35 +0200 | [diff] [blame] | 4896 | private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) { |
| 4897 | if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) { |
| 4898 | throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); |
| 4899 | } |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4900 | if (null == body) { |
| 4901 | throw newIllegalArgumentException("iterated loop body must not be null"); |
| 4902 | } |
| 4903 | } |
| 4904 | |
| 4905 | private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) { |
| 4906 | Class<?> rtype = target.type().returnType(); |
| 4907 | if (rtype != cleanup.type().returnType()) { |
| 4908 | throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); |
| 4909 | } |
| 4910 | List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); |
| 4911 | if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) { |
| 4912 | throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); |
| 4913 | } |
| 4914 | if (rtype != void.class && cleanupParamTypes.get(1) != rtype) { |
| 4915 | throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); |
| 4916 | } |
| 4917 | // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the |
| 4918 | // target parameter list. |
| 4919 | int cleanupArgIndex = rtype == void.class ? 1 : 2; |
Michael Haupt | 2d20eec | 2016-02-29 14:16:20 +0100 | [diff] [blame] | 4920 | List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()); |
| 4921 | List<Class<?>> targetParamTypes = target.type().parameterList(); |
| 4922 | if (targetParamTypes.size() < cleanupArgSuffix.size() || |
| 4923 | !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) { |
Michael Haupt | 5b2c88e | 2015-11-20 15:34:12 +0100 | [diff] [blame] | 4924 | throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", |
| 4925 | cleanup.type(), target.type()); |
| 4926 | } |
| 4927 | } |
| 4928 | |
John R Rose | fb6164c | 2009-05-05 22:40:09 -0700 | [diff] [blame] | 4929 | } |