blob: b77f74e3d261923634648d4aea8f253af03bbb78 [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
alanb0d058232012-11-02 15:50:11 +00002 * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
jrose55220c32009-10-21 23:19:48 -07003 * 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
ohair2283b9d2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
jrose55220c32009-10-21 23:19:48 -07008 * particular file as subject to the "Classpath" exception as provided
ohair2283b9d2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
jrose55220c32009-10-21 23:19:48 -070010 *
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 *
ohair2283b9d2010-05-25 15:58:33 -070021 * 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.
jrose55220c32009-10-21 23:19:48 -070024 */
25
26/* @test
jroseada69fa2011-03-23 23:02:31 -070027 * @summary unit tests for java.lang.invoke.MethodHandles
twisti10d37ec2012-07-24 10:47:44 -070028 * @compile MethodHandlesTest.java remote/RemoteExample.java
jiangli52f57082012-11-05 12:51:14 -050029 * @run junit/othervm/timeout=2500 -XX:+IgnoreUnrecognizedVMOptions -XX:-VerifyDependencies -esa test.java.lang.invoke.MethodHandlesTest
jrose55220c32009-10-21 23:19:48 -070030 */
31
jroseada69fa2011-03-23 23:02:31 -070032package test.java.lang.invoke;
jrose55220c32009-10-21 23:19:48 -070033
twisti10d37ec2012-07-24 10:47:44 -070034import test.java.lang.invoke.remote.RemoteExample;
jroseada69fa2011-03-23 23:02:31 -070035import java.lang.invoke.*;
36import java.lang.invoke.MethodHandles.Lookup;
jrose55220c32009-10-21 23:19:48 -070037import java.lang.reflect.*;
38import java.util.*;
39import org.junit.*;
40import static org.junit.Assert.*;
jrose55220c32009-10-21 23:19:48 -070041
42
43/**
44 *
45 * @author jrose
46 */
47public class MethodHandlesTest {
jroseb4be0262011-07-16 15:44:33 -070048 static final Class<?> THIS_CLASS = MethodHandlesTest.class;
jrose55220c32009-10-21 23:19:48 -070049 // How much output?
jrose2cc9c832010-04-30 23:48:23 -070050 static int verbosity = 0;
jrosecf98d422010-06-08 23:08:56 -070051 static {
jroseb4be0262011-07-16 15:44:33 -070052 String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".verbosity");
53 if (vstr == null)
54 vstr = System.getProperty(THIS_CLASS.getName()+".verbosity");
jrosecf98d422010-06-08 23:08:56 -070055 if (vstr != null) verbosity = Integer.parseInt(vstr);
56 }
jrose55220c32009-10-21 23:19:48 -070057
58 // Set this true during development if you want to fast-forward to
59 // a particular new, non-working test. Tests which are known to
60 // work (or have recently worked) test this flag and return on true.
twisti10d37ec2012-07-24 10:47:44 -070061 static final boolean CAN_SKIP_WORKING;
62 static {
63 String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".CAN_SKIP_WORKING");
64 if (vstr == null)
65 vstr = System.getProperty(THIS_CLASS.getName()+".CAN_SKIP_WORKING");
66 CAN_SKIP_WORKING = Boolean.parseBoolean(vstr);
67 }
jrose55220c32009-10-21 23:19:48 -070068
jroseb4be0262011-07-16 15:44:33 -070069 // Set 'true' to do about 15x fewer tests, especially those redundant with RicochetTest.
70 // This might be useful with -Xcomp stress tests that compile all method handles.
71 static boolean CAN_TEST_LIGHTLY = Boolean.getBoolean(THIS_CLASS.getName()+".CAN_TEST_LIGHTLY");
jrose55220c32009-10-21 23:19:48 -070072
jrose55220c32009-10-21 23:19:48 -070073 @Test
74 public void testFirst() throws Throwable {
75 verbosity += 9; try {
76 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070077 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070078 }
79
80 static final int MAX_ARG_INCREASE = 3;
81
82 public MethodHandlesTest() {
83 }
84
jrose55220c32009-10-21 23:19:48 -070085 String testName;
jrosecf98d422010-06-08 23:08:56 -070086 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -070087 int posTests, negTests;
88 @After
89 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -070090 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -070091 System.out.println();
92 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
93 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -070094 allPosTests += posTests;
95 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -070096 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -070097 }
98 }
99 void countTest(boolean positive) {
100 if (positive) ++posTests;
101 else ++negTests;
102 }
103 void countTest() { countTest(true); }
104 void startTest(String name) {
105 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700106 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700107 System.out.println(name);
108 posTests = negTests = 0;
109 testName = name;
110 }
111
112 @BeforeClass
113 public static void setUpClass() throws Exception {
114 calledLog.clear();
115 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700116 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700117 }
118
119 @AfterClass
120 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700121 int posTests = allPosTests, negTests = allNegTests;
jroseb4be0262011-07-16 15:44:33 -0700122 if (verbosity >= 0 && (posTests | negTests) != 0) {
jrosecf98d422010-06-08 23:08:56 -0700123 System.out.println();
124 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
125 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
126 }
jrose55220c32009-10-21 23:19:48 -0700127 }
128
jrose49494522012-01-18 17:34:29 -0800129 static List<Object> calledLog = new ArrayList<>();
jrose55220c32009-10-21 23:19:48 -0700130 static Object logEntry(String name, Object... args) {
131 return Arrays.asList(name, Arrays.asList(args));
132 }
twisti10d37ec2012-07-24 10:47:44 -0700133 public static Object called(String name, Object... args) {
jrose55220c32009-10-21 23:19:48 -0700134 Object entry = logEntry(name, args);
135 calledLog.add(entry);
136 return entry;
137 }
138 static void assertCalled(String name, Object... args) {
139 Object expected = logEntry(name, args);
140 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700141 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700142 System.out.println("assertCalled "+name+":");
jroseb5cd3912013-10-05 05:30:38 -0700143 System.out.println("expected: "+deepToString(expected));
jrose55220c32009-10-21 23:19:48 -0700144 System.out.println("actual: "+actual);
145 System.out.println("ex. types: "+getClasses(expected));
146 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700147 assertEquals("previous method call", expected, actual);
148 }
149 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700150 if (verbosity >= 3)
jroseb5cd3912013-10-05 05:30:38 -0700151 System.out.println("calling MH="+target+" to "+name+deepToString(args));
152 }
153 static String deepToString(Object x) {
154 if (x == null) return "null";
155 if (x instanceof Collection)
156 x = ((Collection)x).toArray();
157 if (x instanceof Object[]) {
158 Object[] ax = (Object[]) x;
159 ax = Arrays.copyOf(ax, ax.length, Object[].class);
160 for (int i = 0; i < ax.length; i++)
161 ax[i] = deepToString(ax[i]);
162 x = Arrays.deepToString(ax);
163 }
164 if (x.getClass().isArray())
165 try {
166 x = Arrays.class.getMethod("toString", x.getClass()).invoke(null, x);
167 } catch (ReflectiveOperationException ex) { throw new Error(ex); }
168 assert(!(x instanceof Object[]));
169 return x.toString();
jrose55220c32009-10-21 23:19:48 -0700170 }
171
172 static Object castToWrapper(Object value, Class<?> dst) {
173 Object wrap = null;
174 if (value instanceof Number)
175 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
176 if (value instanceof Character)
177 wrap = castToWrapperOrNull((char)(Character)value, dst);
178 if (wrap != null) return wrap;
179 return dst.cast(value);
180 }
181
jrose49494522012-01-18 17:34:29 -0800182 @SuppressWarnings("cast") // primitive cast to (long) is part of the pattern
jrose55220c32009-10-21 23:19:48 -0700183 static Object castToWrapperOrNull(long value, Class<?> dst) {
184 if (dst == int.class || dst == Integer.class)
185 return (int)(value);
186 if (dst == long.class || dst == Long.class)
187 return (long)(value);
188 if (dst == char.class || dst == Character.class)
189 return (char)(value);
190 if (dst == short.class || dst == Short.class)
191 return (short)(value);
192 if (dst == float.class || dst == Float.class)
193 return (float)(value);
194 if (dst == double.class || dst == Double.class)
195 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800196 if (dst == byte.class || dst == Byte.class)
197 return (byte)(value);
198 if (dst == boolean.class || dst == boolean.class)
199 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700200 return null;
201 }
202
jrose2cc9c832010-04-30 23:48:23 -0700203 static final int ONE_MILLION = (1000*1000), // first int value
204 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
205 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
206 static long nextArgVal;
207 static long nextArg(boolean moreBits) {
208 long val = nextArgVal++;
209 long sign = -(val & 1); // alternate signs
210 val >>= 1;
211 if (moreBits)
212 // Guarantee some bits in the high word.
213 // In any case keep the decimal representation simple-looking,
214 // with lots of zeroes, so as not to make the printed decimal
215 // strings unnecessarily noisy.
216 val += (val % ONE_MILLION) * TEN_BILLION;
217 return val ^ sign;
218 }
219 static int nextArg() {
220 // Produce a 32-bit result something like ONE_MILLION+(smallint).
221 // Example: 1_000_042.
222 return (int) nextArg(false);
223 }
224 static long nextArg(Class<?> kind) {
225 if (kind == long.class || kind == Long.class ||
226 kind == double.class || kind == Double.class)
227 // produce a 64-bit result something like
228 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
229 // Example: 10_000_420_001_000_042.
230 return nextArg(true);
231 return (long) nextArg();
232 }
233
jrose55220c32009-10-21 23:19:48 -0700234 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700235 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700236 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700237 return wrap;
238 }
jroseada69fa2011-03-23 23:02:31 -0700239// import sun.invoke.util.Wrapper;
jrose55220c32009-10-21 23:19:48 -0700240// Wrapper wrap = Wrapper.forBasicType(dst);
241// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
242// wrap = Wrapper.forWrapperType(dst);
243// if (wrap != Wrapper.OBJECT)
244// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700245 if (param.isInterface()) {
246 for (Class<?> c : param.getClasses()) {
247 if (param.isAssignableFrom(c) && !c.isInterface())
248 { param = c; break; }
249 }
250 }
jroseb5cd3912013-10-05 05:30:38 -0700251 if (param.isArray()) {
252 Class<?> ctype = param.getComponentType();
253 Object arg = Array.newInstance(ctype, 2);
254 Array.set(arg, 0, randomArg(ctype));
255 return arg;
256 }
jrose485df122012-07-12 00:11:35 -0700257 if (param.isInterface() && param.isAssignableFrom(List.class))
258 return Arrays.asList("#"+nextArg());
jrose55220c32009-10-21 23:19:48 -0700259 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700260 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700261 else
262 try {
263 return param.newInstance();
jrose49494522012-01-18 17:34:29 -0800264 } catch (InstantiationException | IllegalAccessException ex) {
jrose55220c32009-10-21 23:19:48 -0700265 }
266 return null; // random class not Object, String, Integer, etc.
267 }
268 static Object[] randomArgs(Class<?>... params) {
269 Object[] args = new Object[params.length];
270 for (int i = 0; i < args.length; i++)
271 args[i] = randomArg(params[i]);
272 return args;
273 }
274 static Object[] randomArgs(int nargs, Class<?> param) {
275 Object[] args = new Object[nargs];
276 for (int i = 0; i < args.length; i++)
277 args[i] = randomArg(param);
278 return args;
279 }
280
jrose49494522012-01-18 17:34:29 -0800281 @SafeVarargs @SuppressWarnings("varargs")
jrose55220c32009-10-21 23:19:48 -0700282 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
283 return Arrays.copyOf(a, a.length, atype);
284 }
jrose49494522012-01-18 17:34:29 -0800285 @SafeVarargs @SuppressWarnings("varargs")
jrose55220c32009-10-21 23:19:48 -0700286 static <T> T[] cat(T[] a, T... b) {
287 int alen = a.length, blen = b.length;
288 if (blen == 0) return a;
289 T[] c = Arrays.copyOf(a, alen + blen);
290 System.arraycopy(b, 0, c, alen, blen);
291 return c;
292 }
293 static Integer[] boxAll(int... vx) {
294 Integer[] res = new Integer[vx.length];
295 for (int i = 0; i < res.length; i++) {
296 res[i] = vx[i];
297 }
298 return res;
299 }
300 static Object getClasses(Object x) {
301 if (x == null) return x;
302 if (x instanceof String) return x; // keep the name
303 if (x instanceof List) {
304 // recursively report classes of the list elements
305 Object[] xa = ((List)x).toArray();
306 for (int i = 0; i < xa.length; i++)
307 xa[i] = getClasses(xa[i]);
308 return Arrays.asList(xa);
309 }
310 return x.getClass().getSimpleName();
311 }
312
jroseadc650a2011-02-11 01:26:28 -0800313 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
314 static MethodHandle varargsList(int arity) {
315 return ValueConversions.varargsList(arity);
316 }
317 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
318 static MethodHandle varargsArray(int arity) {
319 return ValueConversions.varargsArray(arity);
320 }
jrose320b7692011-05-12 19:27:49 -0700321 static MethodHandle varargsArray(Class<?> arrayType, int arity) {
322 return ValueConversions.varargsArray(arrayType, arity);
323 }
jroseadc650a2011-02-11 01:26:28 -0800324 /** Variation of varargsList, but with the given rtype. */
325 static MethodHandle varargsList(int arity, Class<?> rtype) {
326 MethodHandle list = varargsList(arity);
327 MethodType listType = list.type().changeReturnType(rtype);
328 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
329 // OK
330 } else if (rtype.isAssignableFrom(String.class)) {
331 if (LIST_TO_STRING == null)
332 try {
333 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
334 MethodType.methodType(String.class, List.class));
jrose49494522012-01-18 17:34:29 -0800335 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseadc650a2011-02-11 01:26:28 -0800336 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
337 } else if (rtype.isPrimitive()) {
338 if (LIST_TO_INT == null)
339 try {
340 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
341 MethodType.methodType(int.class, List.class));
jrose49494522012-01-18 17:34:29 -0800342 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseadc650a2011-02-11 01:26:28 -0800343 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
344 list = MethodHandles.explicitCastArguments(list, listType);
345 } else {
346 throw new RuntimeException("varargsList: "+rtype);
347 }
348 return list.asType(listType);
349 }
350 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
jrose49494522012-01-18 17:34:29 -0800351 private static String listToString(List<?> x) { return x.toString(); }
352 private static int listToInt(List<?> x) { return x.toString().hashCode(); }
jroseadc650a2011-02-11 01:26:28 -0800353
jrose55220c32009-10-21 23:19:48 -0700354 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
355 return changeArgTypes(target, 0, 999, argType);
356 }
357 static MethodHandle changeArgTypes(MethodHandle target,
358 int beg, int end, Class<?> argType) {
359 MethodType targetType = target.type();
360 end = Math.min(end, targetType.parameterCount());
jrose49494522012-01-18 17:34:29 -0800361 ArrayList<Class<?>> argTypes = new ArrayList<>(targetType.parameterList());
jrose55220c32009-10-21 23:19:48 -0700362 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800363 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose9b82ad62011-05-26 17:37:36 -0700364 return target.asType(ttype2);
jrose55220c32009-10-21 23:19:48 -0700365 }
jroseb4be0262011-07-16 15:44:33 -0700366 static MethodHandle addTrailingArgs(MethodHandle target, int nargs, Class<?> argClass) {
367 int targetLen = target.type().parameterCount();
368 int extra = (nargs - targetLen);
369 if (extra <= 0) return target;
370 List<Class<?>> fakeArgs = Collections.<Class<?>>nCopies(extra, argClass);
371 return MethodHandles.dropArguments(target, targetLen, fakeArgs);
372 }
jrose55220c32009-10-21 23:19:48 -0700373
374 // This lookup is good for all members in and under MethodHandlesTest.
375 static final Lookup PRIVATE = MethodHandles.lookup();
376 // This lookup is good for package-private members but not private ones.
377 static final Lookup PACKAGE = PackageSibling.lookup();
twisti10d37ec2012-07-24 10:47:44 -0700378 // This lookup is good for public members and protected members of PubExample
379 static final Lookup SUBCLASS = RemoteExample.lookup();
jrose55220c32009-10-21 23:19:48 -0700380 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800381 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700382
383 // Subject methods...
384 static class Example implements IntExample {
385 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700386 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700387 protected Example(String name) { this.name = name; }
jrose49494522012-01-18 17:34:29 -0800388 @SuppressWarnings("LeakingThisInConstructor")
jrose55220c32009-10-21 23:19:48 -0700389 protected Example(int x) { this(); called("protected <init>", this, x); }
jrose942f3d32013-10-05 05:30:39 -0700390 //Example(Void x) { does not exist; lookup elicts NoSuchMethodException }
jrose55220c32009-10-21 23:19:48 -0700391 @Override public String toString() { return name; }
392
393 public void v0() { called("v0", this); }
twisti10d37ec2012-07-24 10:47:44 -0700394 protected void pro_v0() { called("pro_v0", this); }
jrose55220c32009-10-21 23:19:48 -0700395 void pkg_v0() { called("pkg_v0", this); }
396 private void pri_v0() { called("pri_v0", this); }
397 public static void s0() { called("s0"); }
twisti10d37ec2012-07-24 10:47:44 -0700398 protected static void pro_s0() { called("pro_s0"); }
jrose55220c32009-10-21 23:19:48 -0700399 static void pkg_s0() { called("pkg_s0"); }
400 private static void pri_s0() { called("pri_s0"); }
401
402 public Object v1(Object x) { return called("v1", this, x); }
403 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
404 public Object v2(Object x, int y) { return called("v2", this, x, y); }
405 public Object v2(int x, Object y) { return called("v2", this, x, y); }
406 public Object v2(int x, int y) { return called("v2", this, x, y); }
407 public static Object s1(Object x) { return called("s1", x); }
408 public static Object s2(int x) { return called("s2", x); }
409 public static Object s3(long x) { return called("s3", x); }
410 public static Object s4(int x, int y) { return called("s4", x, y); }
411 public static Object s5(long x, int y) { return called("s5", x, y); }
412 public static Object s6(int x, long y) { return called("s6", x, y); }
413 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700414
jroseb4be0262011-07-16 15:44:33 -0700415 // for testing findConstructor:
416 public Example(String x, int y) { this.name = x+y; called("Example.<init>", x, y); }
417 public Example(int x, String y) { this.name = x+y; called("Example.<init>", x, y); }
twisti10d37ec2012-07-24 10:47:44 -0700418 public Example(int x, int y) { this.name = x+""+y; called("Example.<init>", x, y); }
419 public Example(int x, long y) { this.name = x+""+y; called("Example.<init>", x, y); }
420 public Example(int x, float y) { this.name = x+""+y; called("Example.<init>", x, y); }
421 public Example(int x, double y) { this.name = x+""+y; called("Example.<init>", x, y); }
422 public Example(int x, int y, int z) { this.name = x+""+y+""+z; called("Example.<init>", x, y, z); }
423 public Example(int x, int y, int z, int a) { this.name = x+""+y+""+z+""+a; called("Example.<init>", x, y, z, a); }
jroseb4be0262011-07-16 15:44:33 -0700424
jrose2cc9c832010-04-30 23:48:23 -0700425 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700426 }
jrose2cc9c832010-04-30 23:48:23 -0700427 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700428 public static class PubExample extends Example {
twisti10d37ec2012-07-24 10:47:44 -0700429 public PubExample() { this("PubExample"); }
430 protected PubExample(String prefix) { super(prefix+"#"+nextArg()); }
431 protected void pro_v0() { called("Pub/pro_v0", this); }
432 protected static void pro_s0() { called("Pub/pro_s0"); }
jrose55220c32009-10-21 23:19:48 -0700433 }
434 static class SubExample extends Example {
435 @Override public void v0() { called("Sub/v0", this); }
436 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
jrose49494522012-01-18 17:34:29 -0800437 @SuppressWarnings("LeakingThisInConstructor")
jrose55220c32009-10-21 23:19:48 -0700438 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700439 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700440 }
441 public static interface IntExample {
442 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700443 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700444 public void v0() { called("Int/v0", this); }
445 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700446 public Impl() { name = "Impl#"+nextArg(); }
447 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700448 }
449 }
jrose485df122012-07-12 00:11:35 -0700450 static interface SubIntExample extends IntExample { }
jrose55220c32009-10-21 23:19:48 -0700451
452 static final Object[][][] ACCESS_CASES = {
twisti10d37ec2012-07-24 10:47:44 -0700453 { { false, PUBLIC }, { false, SUBCLASS }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
454 { { false, PUBLIC }, { false, SUBCLASS }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
455 { { false, PUBLIC }, { false, SUBCLASS }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
456 { { false, PUBLIC }, { true, SUBCLASS }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: subclass OK
457 { { true, PUBLIC }, { true, SUBCLASS }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[4]: all true
jrose55220c32009-10-21 23:19:48 -0700458 };
459
jrose2cc9c832010-04-30 23:48:23 -0700460 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
461 Object[][] cases;
462 if (name.contains("pri_") || isSpecial) {
463 cases = ACCESS_CASES[1]; // PRIVATE only
464 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
465 cases = ACCESS_CASES[2]; // not PUBLIC
twisti10d37ec2012-07-24 10:47:44 -0700466 } else if (name.contains("pro_")) {
467 cases = ACCESS_CASES[3]; // PUBLIC class, protected member
jrose10f3b682010-01-07 16:16:45 -0800468 } else {
twisti10d37ec2012-07-24 10:47:44 -0700469 assertTrue(name.indexOf('_') < 0 || name.contains("fin_"));
jrose10f3b682010-01-07 16:16:45 -0800470 boolean pubc = Modifier.isPublic(defc.getModifiers());
471 if (pubc)
twisti10d37ec2012-07-24 10:47:44 -0700472 cases = ACCESS_CASES[4]; // all access levels
jrose2cc9c832010-04-30 23:48:23 -0700473 else
474 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800475 }
jrose2cc9c832010-04-30 23:48:23 -0700476 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
477 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
478 return cases;
479 }
480 static Object[][] accessCases(Class<?> defc, String name) {
481 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700482 }
483
twisti10d37ec2012-07-24 10:47:44 -0700484 static Lookup maybeMoveIn(Lookup lookup, Class<?> defc) {
485 if (lookup == PUBLIC || lookup == SUBCLASS || lookup == PACKAGE)
486 // external views stay external
487 return lookup;
488 return lookup.in(defc);
489 }
490
jrose942f3d32013-10-05 05:30:39 -0700491 /** Is findVirtual (etc.) of "<init>" supposed to elicit a NoSuchMethodException? */
492 final static boolean INIT_REF_CAUSES_NSME = true;
493
jrose55220c32009-10-21 23:19:48 -0700494 @Test
495 public void testFindStatic() throws Throwable {
496 if (CAN_SKIP_WORKING) return;
497 startTest("findStatic");
498 testFindStatic(PubExample.class, void.class, "s0");
499 testFindStatic(Example.class, void.class, "s0");
500 testFindStatic(Example.class, void.class, "pkg_s0");
501 testFindStatic(Example.class, void.class, "pri_s0");
twisti10d37ec2012-07-24 10:47:44 -0700502 testFindStatic(Example.class, void.class, "pro_s0");
503 testFindStatic(PubExample.class, void.class, "Pub/pro_s0");
jrose55220c32009-10-21 23:19:48 -0700504
505 testFindStatic(Example.class, Object.class, "s1", Object.class);
506 testFindStatic(Example.class, Object.class, "s2", int.class);
507 testFindStatic(Example.class, Object.class, "s3", long.class);
508 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
509 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
510 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
511 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
512
513 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
jrose942f3d32013-10-05 05:30:39 -0700514 testFindStatic(false, PRIVATE, Example.class, void.class, "<init>", int.class);
515 testFindStatic(false, PRIVATE, Example.class, void.class, "<init>", Void.class);
twisti10d37ec2012-07-24 10:47:44 -0700516 testFindStatic(false, PRIVATE, Example.class, void.class, "v0");
jrose55220c32009-10-21 23:19:48 -0700517 }
518
519 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
520 for (Object[] ac : accessCases(defc, name)) {
521 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
522 }
523 }
524 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
525 testFindStatic(true, lookup, defc, ret, name, params);
526 }
527 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
528 countTest(positive);
twisti10d37ec2012-07-24 10:47:44 -0700529 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800530 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700531 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700532 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700533 try {
jrose2cc9c832010-04-30 23:48:23 -0700534 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
twisti10d37ec2012-07-24 10:47:44 -0700535 target = maybeMoveIn(lookup, defc).findStatic(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800536 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700537 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -0700538 assertExceptionClass(
539 (name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
540 ? NoSuchMethodException.class
541 : IllegalAccessException.class,
542 noAccess);
twisti10d37ec2012-07-24 10:47:44 -0700543 if (verbosity >= 5) ex.printStackTrace(System.out);
jrose55220c32009-10-21 23:19:48 -0700544 }
jrose2cc9c832010-04-30 23:48:23 -0700545 if (verbosity >= 3)
546 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700547 +(noAccess == null ? "" : " !! "+noAccess));
548 if (positive && noAccess != null) throw noAccess;
549 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
550 if (!positive) return; // negative test failed as expected
551 assertEquals(type, target.type());
twisti10d37ec2012-07-24 10:47:44 -0700552 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700553 Object[] args = randomArgs(params);
554 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700555 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700556 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700557 if (verbosity >= 1)
558 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700559 }
560
jrose942f3d32013-10-05 05:30:39 -0700561 static void assertExceptionClass(Class<? extends Throwable> expected,
562 Throwable actual) {
563 if (expected.isInstance(actual)) return;
564 actual.printStackTrace();
565 assertEquals(expected, actual.getClass());
566 }
567
jrose73016262011-05-17 19:48:19 -0700568 static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
569
jrose900bafd2010-10-30 21:08:23 -0700570 // rough check of name string
jrose73016262011-05-17 19:48:19 -0700571 static void assertNameStringContains(MethodHandle x, String s) {
572 if (!DEBUG_METHOD_HANDLE_NAMES) {
573 // ignore s
574 assertEquals("MethodHandle"+x.type(), x.toString());
575 return;
576 }
jrose900bafd2010-10-30 21:08:23 -0700577 if (x.toString().contains(s)) return;
578 assertEquals(s, x);
579 }
580
jrose55220c32009-10-21 23:19:48 -0700581 @Test
582 public void testFindVirtual() throws Throwable {
583 if (CAN_SKIP_WORKING) return;
584 startTest("findVirtual");
585 testFindVirtual(Example.class, void.class, "v0");
586 testFindVirtual(Example.class, void.class, "pkg_v0");
587 testFindVirtual(Example.class, void.class, "pri_v0");
588 testFindVirtual(Example.class, Object.class, "v1", Object.class);
589 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
590 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
591 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
592 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
twisti10d37ec2012-07-24 10:47:44 -0700593 testFindVirtual(Example.class, void.class, "pro_v0");
594 testFindVirtual(PubExample.class, void.class, "Pub/pro_v0");
595
jrose55220c32009-10-21 23:19:48 -0700596 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
jrose942f3d32013-10-05 05:30:39 -0700597 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "<init>", int.class);
598 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "<init>", Void.class);
twisti10d37ec2012-07-24 10:47:44 -0700599 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "s0");
600
jrose55220c32009-10-21 23:19:48 -0700601 // test dispatch
602 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
603 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
604 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
605 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
606 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
607 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
608 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
609 }
610
jroseb5cd3912013-10-05 05:30:38 -0700611 @Test
612 public void testFindVirtualClone() throws Throwable {
613 // test some ad hoc system methods
614 testFindVirtual(false, PUBLIC, Object.class, Object.class, "clone");
615 testFindVirtual(true, PUBLIC, Object[].class, Object.class, "clone");
616 testFindVirtual(true, PUBLIC, int[].class, Object.class, "clone");
617 for (Class<?> cls : new Class<?>[]{ boolean[].class, long[].class, float[].class, char[].class })
618 testFindVirtual(true, PUBLIC, cls, Object.class, "clone");
619 }
620
jrose55220c32009-10-21 23:19:48 -0700621 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
622 Class<?> rcvc = defc;
623 testFindVirtual(rcvc, defc, ret, name, params);
624 }
625 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
626 for (Object[] ac : accessCases(defc, name)) {
627 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
628 }
629 }
630 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
631 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
632 }
jroseb5cd3912013-10-05 05:30:38 -0700633 void testFindVirtual(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
634 testFindVirtual(positive, lookup, defc, defc, ret, name, params);
635 }
jrose55220c32009-10-21 23:19:48 -0700636 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
637 countTest(positive);
638 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800639 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700640 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700641 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700642 try {
jrose2cc9c832010-04-30 23:48:23 -0700643 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
twisti10d37ec2012-07-24 10:47:44 -0700644 target = maybeMoveIn(lookup, defc).findVirtual(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800645 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700646 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -0700647 assertExceptionClass(
648 (name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
649 ? NoSuchMethodException.class
650 : IllegalAccessException.class,
651 noAccess);
twisti10d37ec2012-07-24 10:47:44 -0700652 if (verbosity >= 5) ex.printStackTrace(System.out);
jrose55220c32009-10-21 23:19:48 -0700653 }
jrose2cc9c832010-04-30 23:48:23 -0700654 if (verbosity >= 3)
655 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700656 +(noAccess == null ? "" : " !! "+noAccess));
657 if (positive && noAccess != null) throw noAccess;
658 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
659 if (!positive) return; // negative test failed as expected
twisti10d37ec2012-07-24 10:47:44 -0700660 Class<?> selfc = defc;
661 // predict receiver type narrowing:
662 if (lookup == SUBCLASS &&
663 name.contains("pro_") &&
664 selfc.isAssignableFrom(lookup.lookupClass())) {
665 selfc = lookup.lookupClass();
666 if (name.startsWith("Pub/")) name = "Rem/"+name.substring(4);
667 }
668 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)selfc), params);
jrose10f3b682010-01-07 16:16:45 -0800669 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700670 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700671 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700672 Object[] argsWithSelf = randomArgs(paramsWithSelf);
twisti10d37ec2012-07-24 10:47:44 -0700673 if (selfc.isAssignableFrom(rcvc) && rcvc != selfc) argsWithSelf[0] = randomArg(rcvc);
jrose55220c32009-10-21 23:19:48 -0700674 printCalled(target, name, argsWithSelf);
jroseb5cd3912013-10-05 05:30:38 -0700675 Object res = target.invokeWithArguments(argsWithSelf);
676 if (Example.class.isAssignableFrom(defc) || IntExample.class.isAssignableFrom(defc)) {
677 assertCalled(name, argsWithSelf);
678 } else if (name.equals("clone")) {
679 // Ad hoc method call outside Example. For Object[].clone.
680 printCalled(target, name, argsWithSelf);
681 assertEquals(MethodType.methodType(Object.class, rcvc), target.type());
682 Object orig = argsWithSelf[0];
683 assertEquals(orig.getClass(), res.getClass());
684 if (res instanceof Object[])
685 assertArrayEquals((Object[])res, (Object[])argsWithSelf[0]);
686 assert(Arrays.deepEquals(new Object[]{res}, new Object[]{argsWithSelf[0]}));
687 } else {
688 assert(false) : Arrays.asList(positive, lookup, rcvc, defc, ret, name, deepToString(params));
689 }
jrose2cc9c832010-04-30 23:48:23 -0700690 if (verbosity >= 1)
691 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700692 }
693
694 @Test
695 public void testFindSpecial() throws Throwable {
696 if (CAN_SKIP_WORKING) return;
697 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700698 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
699 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
twisti10d37ec2012-07-24 10:47:44 -0700700 testFindSpecial(RemoteExample.class, PubExample.class, void.class, "Pub/pro_v0");
jrose2cc9c832010-04-30 23:48:23 -0700701 // Do some negative testing:
702 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
703 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
jrose942f3d32013-10-05 05:30:39 -0700704 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "bogus");
jrose2cc9c832010-04-30 23:48:23 -0700705 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
jrose942f3d32013-10-05 05:30:39 -0700706 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", Void.class);
jrose2cc9c832010-04-30 23:48:23 -0700707 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
jrose2cc9c832010-04-30 23:48:23 -0700708 }
jrose55220c32009-10-21 23:19:48 -0700709 }
710
jrose2cc9c832010-04-30 23:48:23 -0700711 void testFindSpecial(Class<?> specialCaller,
712 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -0700713 if (specialCaller == RemoteExample.class) {
714 testFindSpecial(false, EXAMPLE, specialCaller, defc, ret, name, params);
715 testFindSpecial(false, PRIVATE, specialCaller, defc, ret, name, params);
716 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
717 testFindSpecial(true, SUBCLASS, specialCaller, defc, ret, name, params);
718 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
719 return;
720 }
721 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
722 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
723 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
724 testFindSpecial(false, SUBCLASS, specialCaller, defc, ret, name, params);
725 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700726 }
jrose2cc9c832010-04-30 23:48:23 -0700727 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
728 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700729 countTest(positive);
twisti10d37ec2012-07-24 10:47:44 -0700730 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800731 MethodType type = MethodType.methodType(ret, params);
jrose942f3d32013-10-05 05:30:39 -0700732 Lookup specialLookup = maybeMoveIn(lookup, specialCaller);
733 boolean specialAccessOK = (specialLookup.lookupClass() == specialCaller &&
734 (specialLookup.lookupModes() & Lookup.PRIVATE) != 0);
jrose55220c32009-10-21 23:19:48 -0700735 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700736 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700737 try {
jrose2cc9c832010-04-30 23:48:23 -0700738 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose942f3d32013-10-05 05:30:39 -0700739 if (verbosity >= 5) System.out.println(" lookup => "+specialLookup);
740 target = specialLookup.findSpecial(defc, methodName, type, specialCaller);
jrosef15905c2011-02-11 01:26:32 -0800741 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700742 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -0700743 assertExceptionClass(
744 (!specialAccessOK) // this check should happen first
745 ? IllegalAccessException.class
746 : (name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
747 ? NoSuchMethodException.class
748 : IllegalAccessException.class,
749 noAccess);
twisti10d37ec2012-07-24 10:47:44 -0700750 if (verbosity >= 5) ex.printStackTrace(System.out);
jrose55220c32009-10-21 23:19:48 -0700751 }
jrose2cc9c832010-04-30 23:48:23 -0700752 if (verbosity >= 3)
753 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
754 +(target == null ? "" : target.type())
755 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700756 if (positive && noAccess != null) throw noAccess;
757 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
758 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700759 assertEquals(specialCaller, target.type().parameterType(0));
760 assertEquals(type, target.type().dropParameterTypes(0,1));
761 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800762 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
twisti10d37ec2012-07-24 10:47:44 -0700763 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700764 Object[] args = randomArgs(paramsWithSelf);
765 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700766 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700767 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700768 }
769
770 @Test
jroseb4be0262011-07-16 15:44:33 -0700771 public void testFindConstructor() throws Throwable {
772 if (CAN_SKIP_WORKING) return;
773 startTest("findConstructor");
774 testFindConstructor(true, EXAMPLE, Example.class);
775 testFindConstructor(true, EXAMPLE, Example.class, int.class);
twisti10d37ec2012-07-24 10:47:44 -0700776 testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class);
777 testFindConstructor(true, EXAMPLE, Example.class, int.class, long.class);
778 testFindConstructor(true, EXAMPLE, Example.class, int.class, float.class);
779 testFindConstructor(true, EXAMPLE, Example.class, int.class, double.class);
jroseb4be0262011-07-16 15:44:33 -0700780 testFindConstructor(true, EXAMPLE, Example.class, String.class);
twisti10d37ec2012-07-24 10:47:44 -0700781 testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class, int.class);
782 testFindConstructor(true, EXAMPLE, Example.class, int.class, int.class, int.class, int.class);
jroseb4be0262011-07-16 15:44:33 -0700783 }
784 void testFindConstructor(boolean positive, Lookup lookup,
785 Class<?> defc, Class<?>... params) throws Throwable {
786 countTest(positive);
787 MethodType type = MethodType.methodType(void.class, params);
788 MethodHandle target = null;
789 Exception noAccess = null;
790 try {
791 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" <init>"+type);
792 target = lookup.findConstructor(defc, type);
793 } catch (ReflectiveOperationException ex) {
794 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -0700795 assertTrue(noAccess.getClass().getName(), noAccess instanceof IllegalAccessException);
jroseb4be0262011-07-16 15:44:33 -0700796 }
797 if (verbosity >= 3)
798 System.out.println("findConstructor "+defc.getName()+".<init>/"+type+" => "+target
799 +(target == null ? "" : target.type())
800 +(noAccess == null ? "" : " !! "+noAccess));
801 if (positive && noAccess != null) throw noAccess;
802 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
803 if (!positive) return; // negative test failed as expected
804 assertEquals(type.changeReturnType(defc), target.type());
805 Object[] args = randomArgs(params);
806 printCalled(target, defc.getSimpleName(), args);
807 Object obj = target.invokeWithArguments(args);
808 if (!(defc == Example.class && params.length < 2))
809 assertCalled(defc.getSimpleName()+".<init>", args);
810 assertTrue("instance of "+defc.getName(), defc.isInstance(obj));
811 }
812
813 @Test
jrose55220c32009-10-21 23:19:48 -0700814 public void testBind() throws Throwable {
815 if (CAN_SKIP_WORKING) return;
816 startTest("bind");
817 testBind(Example.class, void.class, "v0");
818 testBind(Example.class, void.class, "pkg_v0");
819 testBind(Example.class, void.class, "pri_v0");
820 testBind(Example.class, Object.class, "v1", Object.class);
821 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
822 testBind(Example.class, Object.class, "v2", Object.class, int.class);
823 testBind(Example.class, Object.class, "v2", int.class, Object.class);
824 testBind(Example.class, Object.class, "v2", int.class, int.class);
825 testBind(false, PRIVATE, Example.class, void.class, "bogus");
jrose942f3d32013-10-05 05:30:39 -0700826 testBind(false, PRIVATE, Example.class, void.class, "<init>", int.class);
827 testBind(false, PRIVATE, Example.class, void.class, "<init>", Void.class);
jrose55220c32009-10-21 23:19:48 -0700828 testBind(SubExample.class, void.class, "Sub/v0");
829 testBind(SubExample.class, void.class, "Sub/pkg_v0");
830 testBind(IntExample.Impl.class, void.class, "Int/v0");
831 }
832
833 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
834 for (Object[] ac : accessCases(defc, name)) {
835 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
836 }
837 }
838
839 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
840 countTest(positive);
841 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800842 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700843 Object receiver = randomArg(defc);
844 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700845 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700846 try {
jrose2cc9c832010-04-30 23:48:23 -0700847 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
twisti10d37ec2012-07-24 10:47:44 -0700848 target = maybeMoveIn(lookup, defc).bind(receiver, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800849 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700850 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -0700851 assertExceptionClass(
852 (name.contains("bogus") || INIT_REF_CAUSES_NSME && name.contains("<init>"))
853 ? NoSuchMethodException.class
854 : IllegalAccessException.class,
855 noAccess);
twisti10d37ec2012-07-24 10:47:44 -0700856 if (verbosity >= 5) ex.printStackTrace(System.out);
jrose55220c32009-10-21 23:19:48 -0700857 }
jrose2cc9c832010-04-30 23:48:23 -0700858 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700859 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
860 +(noAccess == null ? "" : " !! "+noAccess));
861 if (positive && noAccess != null) throw noAccess;
862 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
863 if (!positive) return; // negative test failed as expected
864 assertEquals(type, target.type());
865 Object[] args = randomArgs(params);
866 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700867 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700868 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
869 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700870 if (verbosity >= 1)
871 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700872 }
873
874 @Test
875 public void testUnreflect() throws Throwable {
876 if (CAN_SKIP_WORKING) return;
877 startTest("unreflect");
878 testUnreflect(Example.class, true, void.class, "s0");
twisti10d37ec2012-07-24 10:47:44 -0700879 testUnreflect(Example.class, true, void.class, "pro_s0");
jrose55220c32009-10-21 23:19:48 -0700880 testUnreflect(Example.class, true, void.class, "pkg_s0");
881 testUnreflect(Example.class, true, void.class, "pri_s0");
882
883 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
884 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700885 testUnreflect(Example.class, true, Object.class, "s3", long.class);
886 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
887 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
888 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700889
890 testUnreflect(Example.class, false, void.class, "v0");
891 testUnreflect(Example.class, false, void.class, "pkg_v0");
892 testUnreflect(Example.class, false, void.class, "pri_v0");
893 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
894 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
895 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
896 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
897 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
twisti10d37ec2012-07-24 10:47:44 -0700898
899 // Test a public final member in another package:
900 testUnreflect(RemoteExample.class, false, void.class, "Rem/fin_v0");
jrose55220c32009-10-21 23:19:48 -0700901 }
902
903 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
904 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700905 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700906 }
907 }
jrose2cc9c832010-04-30 23:48:23 -0700908 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
909 for (Object[] ac : accessCases(defc, name)) {
910 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
911 }
912 }
913 void testUnreflectMaybeSpecial(Class<?> specialCaller,
914 boolean positive, Lookup lookup,
915 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700916 countTest(positive);
twisti10d37ec2012-07-24 10:47:44 -0700917 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800918 MethodType type = MethodType.methodType(ret, params);
jrose942f3d32013-10-05 05:30:39 -0700919 Lookup specialLookup = (specialCaller != null ? maybeMoveIn(lookup, specialCaller) : null);
920 boolean specialAccessOK = (specialCaller != null &&
921 specialLookup.lookupClass() == specialCaller &&
922 (specialLookup.lookupModes() & Lookup.PRIVATE) != 0);
twisti10d37ec2012-07-24 10:47:44 -0700923 Method rmethod = defc.getDeclaredMethod(methodName, params);
jrose55220c32009-10-21 23:19:48 -0700924 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700925 Exception noAccess = null;
jrose2cc9c832010-04-30 23:48:23 -0700926 boolean isStatic = (rcvc == null);
927 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700928 try {
jrose2cc9c832010-04-30 23:48:23 -0700929 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
930 if (isSpecial)
jrose942f3d32013-10-05 05:30:39 -0700931 target = specialLookup.unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700932 else
twisti10d37ec2012-07-24 10:47:44 -0700933 target = maybeMoveIn(lookup, defc).unreflect(rmethod);
jrosef15905c2011-02-11 01:26:32 -0800934 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700935 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -0700936 assertExceptionClass(
937 IllegalAccessException.class, // NSME is impossible, since it was already reflected
938 noAccess);
twisti10d37ec2012-07-24 10:47:44 -0700939 if (verbosity >= 5) ex.printStackTrace(System.out);
jrose55220c32009-10-21 23:19:48 -0700940 }
jrose2cc9c832010-04-30 23:48:23 -0700941 if (verbosity >= 3)
942 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
943 +(!isSpecial ? "" : " specialCaller="+specialCaller)
944 +( isStatic ? "" : " receiver="+rcvc)
945 +" => "+target
946 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700947 if (positive && noAccess != null) throw noAccess;
948 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
949 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700950 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700951 Class<?>[] paramsMaybeWithSelf = params;
952 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700953 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700954 }
jrose10f3b682010-01-07 16:16:45 -0800955 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700956 if (isStatic) {
957 assertEquals(typeMaybeWithSelf, target.type());
958 } else {
jrose2cc9c832010-04-30 23:48:23 -0700959 if (isSpecial)
960 assertEquals(specialCaller, target.type().parameterType(0));
961 else
962 assertEquals(defc, target.type().parameterType(0));
963 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
964 }
jrose55220c32009-10-21 23:19:48 -0700965 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
966 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700967 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700968 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700969 if (verbosity >= 1)
970 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700971 }
972
jrose2cc9c832010-04-30 23:48:23 -0700973 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
974 for (Object[] ac : accessCases(defc, name, true)) {
975 Class<?> specialCaller = rcvc;
976 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
977 }
978 }
979
980 @Test
jrose55220c32009-10-21 23:19:48 -0700981 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700982 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700983 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700984 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
985 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
986 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
987 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
988 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
989 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
990 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700991 }
992
jrose10f3b682010-01-07 16:16:45 -0800993 public static class HasFields {
994 boolean fZ = false;
995 byte fB = (byte)'B';
996 short fS = (short)'S';
997 char fC = 'C';
998 int fI = 'I';
999 long fJ = 'J';
1000 float fF = 'F';
1001 double fD = 'D';
1002 static boolean sZ = true;
1003 static byte sB = 1+(byte)'B';
1004 static short sS = 1+(short)'S';
1005 static char sC = 1+'C';
1006 static int sI = 1+'I';
1007 static long sJ = 1+'J';
1008 static float sF = 1+'F';
1009 static double sD = 1+'D';
1010
1011 Object fL = 'L';
1012 String fR = "R";
1013 static Object sL = 'M';
1014 static String sR = "S";
1015
1016 static final Object[][] CASES;
1017 static {
jrose49494522012-01-18 17:34:29 -08001018 ArrayList<Object[]> cases = new ArrayList<>();
jrose10f3b682010-01-07 16:16:45 -08001019 Object types[][] = {
1020 {'L',Object.class}, {'R',String.class},
1021 {'I',int.class}, {'J',long.class},
1022 {'F',float.class}, {'D',double.class},
1023 {'Z',boolean.class}, {'B',byte.class},
1024 {'S',short.class}, {'C',char.class},
1025 };
1026 HasFields fields = new HasFields();
1027 for (Object[] t : types) {
1028 for (int kind = 0; kind <= 1; kind++) {
1029 boolean isStatic = (kind != 0);
1030 char btc = (Character)t[0];
1031 String name = (isStatic ? "s" : "f") + btc;
1032 Class<?> type = (Class<?>) t[1];
1033 Object value;
1034 Field field;
jrose320b7692011-05-12 19:27:49 -07001035 try {
jrose10f3b682010-01-07 16:16:45 -08001036 field = HasFields.class.getDeclaredField(name);
jrose49494522012-01-18 17:34:29 -08001037 } catch (NoSuchFieldException | SecurityException ex) {
jrose10f3b682010-01-07 16:16:45 -08001038 throw new InternalError("no field HasFields."+name);
1039 }
1040 try {
1041 value = field.get(fields);
jrose49494522012-01-18 17:34:29 -08001042 } catch (IllegalArgumentException | IllegalAccessException ex) {
jrose10f3b682010-01-07 16:16:45 -08001043 throw new InternalError("cannot fetch field HasFields."+name);
1044 }
1045 if (type == float.class) {
1046 float v = 'F';
1047 if (isStatic) v++;
jrosef15905c2011-02-11 01:26:32 -08001048 assertTrue(value.equals(v));
jrose10f3b682010-01-07 16:16:45 -08001049 }
jrosef15905c2011-02-11 01:26:32 -08001050 assertTrue(name.equals(field.getName()));
1051 assertTrue(type.equals(field.getType()));
1052 assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
jrose10f3b682010-01-07 16:16:45 -08001053 cases.add(new Object[]{ field, value });
1054 }
1055 }
jrosef15905c2011-02-11 01:26:32 -08001056 cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
1057 cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
jrose10f3b682010-01-07 16:16:45 -08001058 CASES = cases.toArray(new Object[0][]);
1059 }
1060 }
1061
twisti10d37ec2012-07-24 10:47:44 -07001062 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10, TEST_BOUND = 0x20, TEST_NPE = 0x40;
jrosecf98d422010-06-08 23:08:56 -07001063 static boolean testModeMatches(int testMode, boolean isStatic) {
1064 switch (testMode) {
jrosef15905c2011-02-11 01:26:32 -08001065 case TEST_FIND_STATIC: return isStatic;
jrosecf98d422010-06-08 23:08:56 -07001066 case TEST_FIND_FIELD: return !isStatic;
jrosef15905c2011-02-11 01:26:32 -08001067 case TEST_UNREFLECT: return true; // unreflect matches both
jrosecf98d422010-06-08 23:08:56 -07001068 }
jrosef15905c2011-02-11 01:26:32 -08001069 throw new InternalError("testMode="+testMode);
jrosecf98d422010-06-08 23:08:56 -07001070 }
1071
jrose10f3b682010-01-07 16:16:45 -08001072 @Test
jrose55220c32009-10-21 23:19:48 -07001073 public void testUnreflectGetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001074 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -07001075 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -07001076 testGetter(TEST_UNREFLECT);
1077 }
1078 @Test
1079 public void testFindGetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001080 if (CAN_SKIP_WORKING) return;
jrosecf98d422010-06-08 23:08:56 -07001081 startTest("findGetter");
1082 testGetter(TEST_FIND_FIELD);
twisti10d37ec2012-07-24 10:47:44 -07001083 testGetter(TEST_FIND_FIELD | TEST_BOUND);
jrosecf98d422010-06-08 23:08:56 -07001084 }
1085 @Test
1086 public void testFindStaticGetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001087 if (CAN_SKIP_WORKING) return;
jrosecf98d422010-06-08 23:08:56 -07001088 startTest("findStaticGetter");
jrosef15905c2011-02-11 01:26:32 -08001089 testGetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001090 }
1091 public void testGetter(int testMode) throws Throwable {
1092 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -08001093 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001094 boolean positive = (c[1] != Error.class);
1095 testGetter(positive, lookup, c[0], c[1], testMode);
jrose485df122012-07-12 00:11:35 -07001096 if (positive)
1097 testGetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
jrosef15905c2011-02-11 01:26:32 -08001098 }
1099 testGetter(true, lookup,
1100 new Object[]{ true, System.class, "out", java.io.PrintStream.class },
1101 System.out, testMode);
1102 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1103 testGetter(false, lookup,
1104 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1105 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001106 }
1107 }
jrosef15905c2011-02-11 01:26:32 -08001108 public void testGetter(boolean positive, MethodHandles.Lookup lookup,
1109 Object fieldRef, Object value, int testMode) throws Throwable {
1110 testAccessor(positive, lookup, fieldRef, value, testMode);
1111 }
1112
jrose485df122012-07-12 00:11:35 -07001113 public void testAccessor(boolean positive0, MethodHandles.Lookup lookup,
jrosef15905c2011-02-11 01:26:32 -08001114 Object fieldRef, Object value, int testMode0) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07001115 if (verbosity >= 4)
jrose485df122012-07-12 00:11:35 -07001116 System.out.println("testAccessor"+Arrays.deepToString(new Object[]{positive0, lookup, fieldRef, value, testMode0}));
jrosef15905c2011-02-11 01:26:32 -08001117 boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
twisti10d37ec2012-07-24 10:47:44 -07001118 boolean doBound = ((testMode0 & TEST_BOUND) != 0);
jrose485df122012-07-12 00:11:35 -07001119 boolean testNPE = ((testMode0 & TEST_NPE) != 0);
twisti10d37ec2012-07-24 10:47:44 -07001120 int testMode = testMode0 & ~(TEST_SETTER | TEST_BOUND | TEST_NPE);
jrose485df122012-07-12 00:11:35 -07001121 boolean positive = positive0 && !testNPE;
jrosef15905c2011-02-11 01:26:32 -08001122 boolean isStatic;
1123 Class<?> fclass;
1124 String fname;
1125 Class<?> ftype;
1126 Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
1127 if (f != null) {
1128 isStatic = Modifier.isStatic(f.getModifiers());
1129 fclass = f.getDeclaringClass();
1130 fname = f.getName();
1131 ftype = f.getType();
1132 } else {
1133 Object[] scnt = (Object[]) fieldRef;
1134 isStatic = (Boolean) scnt[0];
1135 fclass = (Class<?>) scnt[1];
1136 fname = (String) scnt[2];
1137 ftype = (Class<?>) scnt[3];
1138 try {
1139 f = fclass.getDeclaredField(fname);
1140 } catch (ReflectiveOperationException ex) {
1141 f = null;
1142 }
1143 }
jrosecf98d422010-06-08 23:08:56 -07001144 if (!testModeMatches(testMode, isStatic)) return;
jrosef15905c2011-02-11 01:26:32 -08001145 if (f == null && testMode == TEST_UNREFLECT) return;
jrose485df122012-07-12 00:11:35 -07001146 if (testNPE && isStatic) return;
jrosef15905c2011-02-11 01:26:32 -08001147 countTest(positive);
1148 MethodType expType;
1149 if (isGetter)
1150 expType = MethodType.methodType(ftype, HasFields.class);
1151 else
1152 expType = MethodType.methodType(void.class, HasFields.class, ftype);
jrose10f3b682010-01-07 16:16:45 -08001153 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosef15905c2011-02-11 01:26:32 -08001154 Exception noAccess = null;
1155 MethodHandle mh;
1156 try {
twisti10d37ec2012-07-24 10:47:44 -07001157 switch (testMode0 & ~(TEST_BOUND | TEST_NPE)) {
jrosef15905c2011-02-11 01:26:32 -08001158 case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
1159 case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
1160 case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
1161 case TEST_SETTER|
1162 TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
1163 case TEST_SETTER|
1164 TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
1165 case TEST_SETTER|
1166 TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
1167 default:
1168 throw new InternalError("testMode="+testMode);
1169 }
1170 } catch (ReflectiveOperationException ex) {
1171 mh = null;
1172 noAccess = ex;
jrose942f3d32013-10-05 05:30:39 -07001173 assertExceptionClass(
1174 (fname.contains("bogus"))
1175 ? NoSuchFieldException.class
1176 : IllegalAccessException.class,
1177 noAccess);
twisti10d37ec2012-07-24 10:47:44 -07001178 if (verbosity >= 5) ex.printStackTrace(System.out);
jrosef15905c2011-02-11 01:26:32 -08001179 }
1180 if (verbosity >= 3)
1181 System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
1182 +" => "+mh
1183 +(noAccess == null ? "" : " !! "+noAccess));
jrose485df122012-07-12 00:11:35 -07001184 if (positive && !testNPE && noAccess != null) throw new RuntimeException(noAccess);
1185 assertEquals(positive0 ? "positive test" : "negative test erroneously passed", positive0, mh != null);
1186 if (!positive && !testNPE) return; // negative access test failed as expected
jrosef15905c2011-02-11 01:26:32 -08001187 assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
1188
1189
jrose10f3b682010-01-07 16:16:45 -08001190 assertSame(mh.type(), expType);
twisti10d37ec2012-07-24 10:47:44 -07001191 //assertNameStringContains(mh, fname); // This does not hold anymore with LFs
jrose10f3b682010-01-07 16:16:45 -08001192 HasFields fields = new HasFields();
jrose485df122012-07-12 00:11:35 -07001193 HasFields fieldsForMH = fields;
1194 if (testNPE) fieldsForMH = null; // perturb MH argument to elicit expected error
twisti10d37ec2012-07-24 10:47:44 -07001195 if (doBound)
1196 mh = mh.bindTo(fieldsForMH);
jrose10f3b682010-01-07 16:16:45 -08001197 Object sawValue;
jrosef15905c2011-02-11 01:26:32 -08001198 Class<?> vtype = ftype;
1199 if (ftype != int.class) vtype = Object.class;
1200 if (isGetter) {
jrose9b82ad62011-05-26 17:37:36 -07001201 mh = mh.asType(mh.type().generic()
1202 .changeReturnType(vtype));
jrosef15905c2011-02-11 01:26:32 -08001203 } else {
1204 int last = mh.type().parameterCount() - 1;
jrose9b82ad62011-05-26 17:37:36 -07001205 mh = mh.asType(mh.type().generic()
1206 .changeReturnType(void.class)
1207 .changeParameterType(last, vtype));
jrose10f3b682010-01-07 16:16:45 -08001208 }
jrosef15905c2011-02-11 01:26:32 -08001209 if (f != null && f.getDeclaringClass() == HasFields.class) {
1210 assertEquals(f.get(fields), value); // clean to start with
1211 }
jrose485df122012-07-12 00:11:35 -07001212 Throwable caughtEx = null;
jrosef15905c2011-02-11 01:26:32 -08001213 if (isGetter) {
1214 Object expValue = value;
1215 for (int i = 0; i <= 1; i++) {
twisti10d37ec2012-07-24 10:47:44 -07001216 sawValue = null; // make DA rules happy under try/catch
1217 try {
1218 if (isStatic || doBound) {
1219 if (ftype == int.class)
1220 sawValue = (int) mh.invokeExact(); // do these exactly
1221 else
1222 sawValue = mh.invokeExact();
1223 } else {
jrose485df122012-07-12 00:11:35 -07001224 if (ftype == int.class)
1225 sawValue = (int) mh.invokeExact((Object) fieldsForMH);
1226 else
1227 sawValue = mh.invokeExact((Object) fieldsForMH);
twisti10d37ec2012-07-24 10:47:44 -07001228 }
1229 } catch (RuntimeException ex) {
1230 if (ex instanceof NullPointerException && testNPE) {
1231 caughtEx = ex;
1232 break;
jrose485df122012-07-12 00:11:35 -07001233 }
jrosef15905c2011-02-11 01:26:32 -08001234 }
1235 assertEquals(sawValue, expValue);
1236 if (f != null && f.getDeclaringClass() == HasFields.class
1237 && !Modifier.isFinal(f.getModifiers())) {
1238 Object random = randomArg(ftype);
1239 f.set(fields, random);
1240 expValue = random;
1241 } else {
1242 break;
1243 }
1244 }
1245 } else {
1246 for (int i = 0; i <= 1; i++) {
1247 Object putValue = randomArg(ftype);
twisti10d37ec2012-07-24 10:47:44 -07001248 try {
1249 if (isStatic || doBound) {
1250 if (ftype == int.class)
1251 mh.invokeExact((int)putValue); // do these exactly
1252 else
1253 mh.invokeExact(putValue);
1254 } else {
jrose485df122012-07-12 00:11:35 -07001255 if (ftype == int.class)
1256 mh.invokeExact((Object) fieldsForMH, (int)putValue);
1257 else
1258 mh.invokeExact((Object) fieldsForMH, putValue);
twisti10d37ec2012-07-24 10:47:44 -07001259 }
1260 } catch (RuntimeException ex) {
1261 if (ex instanceof NullPointerException && testNPE) {
1262 caughtEx = ex;
1263 break;
jrose485df122012-07-12 00:11:35 -07001264 }
jrosef15905c2011-02-11 01:26:32 -08001265 }
1266 if (f != null && f.getDeclaringClass() == HasFields.class) {
1267 assertEquals(f.get(fields), putValue);
1268 }
1269 }
1270 }
1271 if (f != null && f.getDeclaringClass() == HasFields.class) {
1272 f.set(fields, value); // put it back
1273 }
jrose485df122012-07-12 00:11:35 -07001274 if (testNPE) {
1275 if (caughtEx == null || !(caughtEx instanceof NullPointerException))
1276 throw new RuntimeException("failed to catch NPE exception"+(caughtEx == null ? " (caughtEx=null)" : ""), caughtEx);
1277 caughtEx = null; // nullify expected exception
1278 }
1279 if (caughtEx != null) {
1280 throw new RuntimeException("unexpected exception", caughtEx);
1281 }
jrose55220c32009-10-21 23:19:48 -07001282 }
1283
jrose10f3b682010-01-07 16:16:45 -08001284
1285 @Test
jrose55220c32009-10-21 23:19:48 -07001286 public void testUnreflectSetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001287 if (CAN_SKIP_WORKING) return;
jrosecf98d422010-06-08 23:08:56 -07001288 startTest("unreflectSetter");
1289 testSetter(TEST_UNREFLECT);
1290 }
1291 @Test
1292 public void testFindSetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001293 if (CAN_SKIP_WORKING) return;
jrosecf98d422010-06-08 23:08:56 -07001294 startTest("findSetter");
1295 testSetter(TEST_FIND_FIELD);
twisti10d37ec2012-07-24 10:47:44 -07001296 testSetter(TEST_FIND_FIELD | TEST_BOUND);
jrosecf98d422010-06-08 23:08:56 -07001297 }
1298 @Test
1299 public void testFindStaticSetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001300 if (CAN_SKIP_WORKING) return;
jrosecf98d422010-06-08 23:08:56 -07001301 startTest("findStaticSetter");
jrosef15905c2011-02-11 01:26:32 -08001302 testSetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001303 }
1304 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001305 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
1306 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -08001307 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001308 boolean positive = (c[1] != Error.class);
1309 testSetter(positive, lookup, c[0], c[1], testMode);
jrose485df122012-07-12 00:11:35 -07001310 if (positive)
1311 testSetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
jrosef15905c2011-02-11 01:26:32 -08001312 }
1313 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1314 testSetter(false, lookup,
1315 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1316 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001317 }
1318 }
jrosef15905c2011-02-11 01:26:32 -08001319 public void testSetter(boolean positive, MethodHandles.Lookup lookup,
1320 Object fieldRef, Object value, int testMode) throws Throwable {
1321 testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
jrose55220c32009-10-21 23:19:48 -07001322 }
1323
jrose10f3b682010-01-07 16:16:45 -08001324 @Test
jrose55220c32009-10-21 23:19:48 -07001325 public void testArrayElementGetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001326 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -07001327 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001328 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001329 }
1330
jrose10f3b682010-01-07 16:16:45 -08001331 @Test
jrose55220c32009-10-21 23:19:48 -07001332 public void testArrayElementSetter() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001333 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -07001334 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001335 testArrayElementGetterSetter(true);
1336 }
1337
jrose485df122012-07-12 00:11:35 -07001338 private static final int TEST_ARRAY_NONE = 0, TEST_ARRAY_NPE = 1, TEST_ARRAY_OOB = 2, TEST_ARRAY_ASE = 3;
1339
jrose2cc9c832010-04-30 23:48:23 -07001340 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
jrose485df122012-07-12 00:11:35 -07001341 testArrayElementGetterSetter(testSetter, TEST_ARRAY_NONE);
jrose10f3b682010-01-07 16:16:45 -08001342 }
1343
jrose485df122012-07-12 00:11:35 -07001344 @Test
1345 public void testArrayElementErrors() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001346 if (CAN_SKIP_WORKING) return;
jrose485df122012-07-12 00:11:35 -07001347 startTest("arrayElementErrors");
1348 testArrayElementGetterSetter(false, TEST_ARRAY_NPE);
1349 testArrayElementGetterSetter(true, TEST_ARRAY_NPE);
1350 testArrayElementGetterSetter(false, TEST_ARRAY_OOB);
1351 testArrayElementGetterSetter(true, TEST_ARRAY_OOB);
1352 testArrayElementGetterSetter(new Object[10], true, TEST_ARRAY_ASE);
1353 testArrayElementGetterSetter(new Example[10], true, TEST_ARRAY_ASE);
1354 testArrayElementGetterSetter(new IntExample[10], true, TEST_ARRAY_ASE);
1355 }
1356
1357 public void testArrayElementGetterSetter(boolean testSetter, int negTest) throws Throwable {
1358 testArrayElementGetterSetter(new String[10], testSetter, negTest);
1359 testArrayElementGetterSetter(new Iterable<?>[10], testSetter, negTest);
1360 testArrayElementGetterSetter(new Example[10], testSetter, negTest);
1361 testArrayElementGetterSetter(new IntExample[10], testSetter, negTest);
1362 testArrayElementGetterSetter(new Object[10], testSetter, negTest);
1363 testArrayElementGetterSetter(new boolean[10], testSetter, negTest);
1364 testArrayElementGetterSetter(new byte[10], testSetter, negTest);
1365 testArrayElementGetterSetter(new char[10], testSetter, negTest);
1366 testArrayElementGetterSetter(new short[10], testSetter, negTest);
1367 testArrayElementGetterSetter(new int[10], testSetter, negTest);
1368 testArrayElementGetterSetter(new float[10], testSetter, negTest);
1369 testArrayElementGetterSetter(new long[10], testSetter, negTest);
1370 testArrayElementGetterSetter(new double[10], testSetter, negTest);
1371 }
1372
1373 public void testArrayElementGetterSetter(Object array, boolean testSetter, int negTest) throws Throwable {
1374 boolean positive = (negTest == TEST_ARRAY_NONE);
1375 int length = java.lang.reflect.Array.getLength(array);
jrose10f3b682010-01-07 16:16:45 -08001376 Class<?> arrayType = array.getClass();
1377 Class<?> elemType = arrayType.getComponentType();
jrose485df122012-07-12 00:11:35 -07001378 Object arrayToMH = array;
1379 // this stanza allows negative tests to make argument perturbations:
1380 switch (negTest) {
1381 case TEST_ARRAY_NPE:
1382 arrayToMH = null;
1383 break;
1384 case TEST_ARRAY_OOB:
1385 assert(length > 0);
1386 arrayToMH = java.lang.reflect.Array.newInstance(elemType, 0);
1387 break;
1388 case TEST_ARRAY_ASE:
1389 assert(testSetter && !elemType.isPrimitive());
1390 if (elemType == Object.class)
1391 arrayToMH = new StringBuffer[length]; // very random subclass of Object!
1392 else if (elemType == Example.class)
1393 arrayToMH = new SubExample[length];
1394 else if (elemType == IntExample.class)
1395 arrayToMH = new SubIntExample[length];
1396 else
1397 return; // can't make an ArrayStoreException test
1398 assert(arrayType.isInstance(arrayToMH))
1399 : Arrays.asList(arrayType, arrayToMH.getClass(), testSetter, negTest);
1400 break;
1401 }
1402 countTest(positive);
1403 if (verbosity > 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+length+"]"+(positive ? "" : " negative test #"+negTest+" using "+Arrays.deepToString(new Object[]{arrayToMH})));
jrose10f3b682010-01-07 16:16:45 -08001404 MethodType expType = !testSetter
1405 ? MethodType.methodType(elemType, arrayType, int.class)
1406 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1407 MethodHandle mh = !testSetter
1408 ? MethodHandles.arrayElementGetter(arrayType)
1409 : MethodHandles.arrayElementSetter(arrayType);
1410 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001411 if (elemType != int.class && elemType != boolean.class) {
jrose485df122012-07-12 00:11:35 -07001412 MethodType gtype = mh.type().generic().changeParameterType(1, int.class);
jrose320b7692011-05-12 19:27:49 -07001413 if (testSetter) gtype = gtype.changeReturnType(void.class);
jrose9b82ad62011-05-26 17:37:36 -07001414 mh = mh.asType(gtype);
jrose2cc9c832010-04-30 23:48:23 -07001415 }
jrose10f3b682010-01-07 16:16:45 -08001416 Object sawValue, expValue;
1417 List<Object> model = array2list(array);
jrose485df122012-07-12 00:11:35 -07001418 Throwable caughtEx = null;
jrose10f3b682010-01-07 16:16:45 -08001419 for (int i = 0; i < length; i++) {
1420 // update array element
1421 Object random = randomArg(elemType);
1422 model.set(i, random);
1423 if (testSetter) {
jrose485df122012-07-12 00:11:35 -07001424 try {
1425 if (elemType == int.class)
1426 mh.invokeExact((int[]) arrayToMH, i, (int)random);
1427 else if (elemType == boolean.class)
1428 mh.invokeExact((boolean[]) arrayToMH, i, (boolean)random);
1429 else
1430 mh.invokeExact(arrayToMH, i, random);
1431 } catch (RuntimeException ex) {
1432 caughtEx = ex;
1433 break;
1434 }
jrose10f3b682010-01-07 16:16:45 -08001435 assertEquals(model, array2list(array));
1436 } else {
1437 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001438 }
1439 if (verbosity >= 5) {
1440 List<Object> array2list = array2list(array);
1441 System.out.println("a["+i+"]="+random+" => "+array2list);
1442 if (!array2list.equals(model))
1443 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001444 }
1445 // observe array element
1446 sawValue = Array.get(array, i);
1447 if (!testSetter) {
1448 expValue = sawValue;
jrose485df122012-07-12 00:11:35 -07001449 try {
1450 if (elemType == int.class)
1451 sawValue = (int) mh.invokeExact((int[]) arrayToMH, i);
1452 else if (elemType == boolean.class)
1453 sawValue = (boolean) mh.invokeExact((boolean[]) arrayToMH, i);
1454 else
1455 sawValue = mh.invokeExact(arrayToMH, i);
1456 } catch (RuntimeException ex) {
1457 caughtEx = ex;
1458 break;
1459 }
jrose10f3b682010-01-07 16:16:45 -08001460 assertEquals(sawValue, expValue);
1461 assertEquals(model, array2list(array));
1462 }
1463 }
jrose485df122012-07-12 00:11:35 -07001464 if (!positive) {
1465 if (caughtEx == null)
1466 throw new RuntimeException("failed to catch exception for negTest="+negTest);
1467 // test the kind of exception
1468 Class<?> reqType = null;
1469 switch (negTest) {
1470 case TEST_ARRAY_ASE: reqType = ArrayStoreException.class; break;
1471 case TEST_ARRAY_OOB: reqType = ArrayIndexOutOfBoundsException.class; break;
1472 case TEST_ARRAY_NPE: reqType = NullPointerException.class; break;
1473 default: assert(false);
1474 }
1475 if (reqType.isInstance(caughtEx)) {
1476 caughtEx = null; // nullify expected exception
1477 }
1478 }
1479 if (caughtEx != null) {
1480 throw new RuntimeException("unexpected exception", caughtEx);
1481 }
jrose10f3b682010-01-07 16:16:45 -08001482 }
1483
1484 List<Object> array2list(Object array) {
1485 int length = Array.getLength(array);
jrose49494522012-01-18 17:34:29 -08001486 ArrayList<Object> model = new ArrayList<>(length);
jrose10f3b682010-01-07 16:16:45 -08001487 for (int i = 0; i < length; i++)
1488 model.add(Array.get(array, i));
1489 return model;
jrose55220c32009-10-21 23:19:48 -07001490 }
1491
1492 static class Callee {
1493 static Object id() { return called("id"); }
1494 static Object id(Object x) { return called("id", x); }
1495 static Object id(Object x, Object y) { return called("id", x, y); }
1496 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1497 static Object id(Object... vx) { return called("id", vx); }
1498 static MethodHandle ofType(int n) {
1499 return ofType(Object.class, n);
1500 }
1501 static MethodHandle ofType(Class<?> rtype, int n) {
1502 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001503 return ofType(MethodType.methodType(rtype, Object[].class));
1504 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001505 }
1506 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001507 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001508 }
1509 static MethodHandle ofType(MethodType type) {
1510 Class<?> rtype = type.returnType();
1511 String pfx = "";
1512 if (rtype != Object.class)
1513 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1514 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001515 try {
1516 return PRIVATE.findStatic(Callee.class, name, type);
jrose49494522012-01-18 17:34:29 -08001517 } catch (NoSuchMethodException | IllegalAccessException ex) {
jrosea1ebbe62010-09-08 18:40:23 -07001518 throw new RuntimeException(ex);
1519 }
jrose55220c32009-10-21 23:19:48 -07001520 }
1521 }
1522
1523 @Test
1524 public void testConvertArguments() throws Throwable {
1525 if (CAN_SKIP_WORKING) return;
1526 startTest("convertArguments");
1527 testConvert(Callee.ofType(1), null, "id", int.class);
1528 testConvert(Callee.ofType(1), null, "id", String.class);
1529 testConvert(Callee.ofType(1), null, "id", Integer.class);
1530 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001531 testConvert(Callee.ofType(1), null, "id", char.class);
1532 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001533 }
1534
1535 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -07001536 testConvert(true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001537 }
1538
jrose9b82ad62011-05-26 17:37:36 -07001539 void testConvert(boolean positive,
jrose900bafd2010-10-30 21:08:23 -07001540 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001541 countTest(positive);
1542 MethodType idType = id.type();
1543 if (rtype == null) rtype = idType.returnType();
1544 for (int i = 0; i < params.length; i++) {
1545 if (params[i] == null) params[i] = idType.parameterType(i);
1546 }
1547 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001548 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001549 Object[] args = randomArgs(newType.parameterArray());
1550 Object[] convArgs = args.clone();
1551 for (int i = 0; i < args.length; i++) {
1552 Class<?> src = newType.parameterType(i);
1553 Class<?> dst = idType.parameterType(i);
1554 if (src != dst)
1555 convArgs[i] = castToWrapper(convArgs[i], dst);
1556 }
jrose900bafd2010-10-30 21:08:23 -07001557 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001558 {
1559 Class<?> dst = newType.returnType();
1560 Class<?> src = idType.returnType();
1561 if (src != dst)
1562 convResult = castToWrapper(convResult, dst);
1563 }
1564 MethodHandle target = null;
1565 RuntimeException error = null;
1566 try {
jrose9b82ad62011-05-26 17:37:36 -07001567 target = id.asType(newType);
jrose4f019ca2012-08-17 13:42:25 -07001568 } catch (WrongMethodTypeException ex) {
jrose55220c32009-10-21 23:19:48 -07001569 error = ex;
1570 }
jrose2cc9c832010-04-30 23:48:23 -07001571 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001572 System.out.println("convert "+id+ " to "+newType+" => "+target
1573 +(error == null ? "" : " !! "+error));
1574 if (positive && error != null) throw error;
1575 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1576 if (!positive) return; // negative test failed as expected
1577 assertEquals(newType, target.type());
1578 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001579 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001580 assertCalled(name, convArgs);
1581 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001582 if (verbosity >= 1)
1583 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001584 }
1585
1586 @Test
jrosef108fc02011-02-11 01:26:24 -08001587 public void testVarargsCollector() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07001588 if (CAN_SKIP_WORKING) return;
1589 startTest("varargsCollector");
jrosef108fc02011-02-11 01:26:24 -08001590 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1591 MethodType.methodType(Object.class, String.class, Object[].class));
1592 vac0 = vac0.bindTo("vac");
1593 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -07001594 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1595 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
jrose49494522012-01-18 17:34:29 -08001596 for (Class<?> at : new Class<?>[] { Object.class, String.class, Integer.class }) {
jrose9b82ad62011-05-26 17:37:36 -07001597 testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1598 testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
jrosef108fc02011-02-11 01:26:24 -08001599 }
1600 }
1601
twisti10d37ec2012-07-24 10:47:44 -07001602 @Test // SLOW
jrose10f3b682010-01-07 16:16:45 -08001603 public void testPermuteArguments() throws Throwable {
1604 if (CAN_SKIP_WORKING) return;
1605 startTest("permuteArguments");
jroseb4be0262011-07-16 15:44:33 -07001606 testPermuteArguments(4, Integer.class, 2, long.class, 6);
1607 if (CAN_TEST_LIGHTLY) return;
jrose10f3b682010-01-07 16:16:45 -08001608 testPermuteArguments(4, Integer.class, 2, String.class, 0);
jrose9b82ad62011-05-26 17:37:36 -07001609 testPermuteArguments(6, Integer.class, 0, null, 30);
jrose10f3b682010-01-07 16:16:45 -08001610 }
1611 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001612 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001613 System.out.println("permuteArguments "+max+"*"+type1.getName()
1614 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1615 +(dilution > 0 ? " with dilution "+dilution : ""));
1616 int t2pos = t2c == 0 ? 0 : 1;
1617 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1618 Class<?>[] types = new Class<?>[inargs];
1619 Arrays.fill(types, type1);
1620 if (t2c != 0) {
1621 // Fill in a middle range with type2:
1622 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1623 }
1624 Object[] args = randomArgs(types);
1625 int numcases = 1;
1626 for (int outargs = 0; outargs <= max; outargs++) {
1627 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
jrose10f3b682010-01-07 16:16:45 -08001628 int casStep = dilution + 1;
1629 // Avoid some common factors:
1630 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1631 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1632 casStep++;
jrose320b7692011-05-12 19:27:49 -07001633 testPermuteArguments(args, types, outargs, numcases, casStep);
jrose10f3b682010-01-07 16:16:45 -08001634 numcases *= inargs;
jroseb4be0262011-07-16 15:44:33 -07001635 if (CAN_TEST_LIGHTLY && outargs < max-2) continue;
jrose10f3b682010-01-07 16:16:45 -08001636 if (dilution > 10 && outargs >= 4) {
jroseb4be0262011-07-16 15:44:33 -07001637 if (CAN_TEST_LIGHTLY) continue;
jrose320b7692011-05-12 19:27:49 -07001638 int[] reorder = new int[outargs];
jrose10f3b682010-01-07 16:16:45 -08001639 // Do some special patterns, which we probably missed.
1640 // Replication of a single argument or argument pair.
1641 for (int i = 0; i < inargs; i++) {
1642 Arrays.fill(reorder, i);
1643 testPermuteArguments(args, types, reorder);
1644 for (int d = 1; d <= 2; d++) {
1645 if (i + d >= inargs) continue;
1646 for (int j = 1; j < outargs; j += 2)
1647 reorder[j] += 1;
1648 testPermuteArguments(args, types, reorder);
1649 testPermuteArguments(args, types, reverse(reorder));
1650 }
1651 }
1652 // Repetition of a sequence of 3 or more arguments.
1653 for (int i = 1; i < inargs; i++) {
1654 for (int len = 3; len <= inargs; len++) {
1655 for (int j = 0; j < outargs; j++)
1656 reorder[j] = (i + (j % len)) % inargs;
1657 testPermuteArguments(args, types, reorder);
1658 testPermuteArguments(args, types, reverse(reorder));
1659 }
1660 }
1661 }
1662 }
1663 }
1664 }
1665
jrose320b7692011-05-12 19:27:49 -07001666 public void testPermuteArguments(Object[] args, Class<?>[] types,
1667 int outargs, int numcases, int casStep) throws Throwable {
1668 int inargs = args.length;
1669 int[] reorder = new int[outargs];
1670 for (int cas = 0; cas < numcases; cas += casStep) {
1671 for (int i = 0, c = cas; i < outargs; i++) {
1672 reorder[i] = c % inargs;
1673 c /= inargs;
1674 }
jroseb4be0262011-07-16 15:44:33 -07001675 if (CAN_TEST_LIGHTLY && outargs >= 3 && (reorder[0] == reorder[1] || reorder[1] == reorder[2])) continue;
jrose320b7692011-05-12 19:27:49 -07001676 testPermuteArguments(args, types, reorder);
1677 }
1678 }
1679
jrose10f3b682010-01-07 16:16:45 -08001680 static int[] reverse(int[] reorder) {
1681 reorder = reorder.clone();
1682 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1683 int j = reorder.length - 1 - i;
1684 int tem = reorder[i];
1685 reorder[i] = reorder[j];
1686 reorder[j] = tem;
1687 }
1688 return reorder;
1689 }
1690
1691 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1692 countTest();
1693 if (args == null && types == null) {
1694 int max = 0;
1695 for (int j : reorder) {
1696 if (max < j) max = j;
1697 }
1698 args = randomArgs(max+1, Integer.class);
1699 }
1700 if (args == null) {
1701 args = randomArgs(types);
1702 }
1703 if (types == null) {
1704 types = new Class<?>[args.length];
1705 for (int i = 0; i < args.length; i++)
1706 types[i] = args[i].getClass();
1707 }
1708 int inargs = args.length, outargs = reorder.length;
jrosef15905c2011-02-11 01:26:32 -08001709 assertTrue(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001710 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001711 System.out.println("permuteArguments "+Arrays.toString(reorder));
1712 Object[] permArgs = new Object[outargs];
1713 Class<?>[] permTypes = new Class<?>[outargs];
1714 for (int i = 0; i < outargs; i++) {
1715 permArgs[i] = args[reorder[i]];
1716 permTypes[i] = types[reorder[i]];
1717 }
jrose2cc9c832010-04-30 23:48:23 -07001718 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001719 System.out.println("in args: "+Arrays.asList(args));
1720 System.out.println("out args: "+Arrays.asList(permArgs));
1721 System.out.println("in types: "+Arrays.asList(types));
1722 System.out.println("out types: "+Arrays.asList(permTypes));
1723 }
1724 MethodType inType = MethodType.methodType(Object.class, types);
1725 MethodType outType = MethodType.methodType(Object.class, permTypes);
jrose9b82ad62011-05-26 17:37:36 -07001726 MethodHandle target = varargsList(outargs).asType(outType);
jrose10f3b682010-01-07 16:16:45 -08001727 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose9b82ad62011-05-26 17:37:36 -07001728 if (verbosity >= 5) System.out.println("newTarget = "+newTarget);
jrose900bafd2010-10-30 21:08:23 -07001729 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001730 Object expected = Arrays.asList(permArgs);
jrose320b7692011-05-12 19:27:49 -07001731 if (!expected.equals(result)) {
1732 System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
1733 System.out.println("in args: "+Arrays.asList(args));
1734 System.out.println("out args: "+expected);
1735 System.out.println("bad args: "+result);
1736 }
jrose10f3b682010-01-07 16:16:45 -08001737 assertEquals(expected, result);
1738 }
1739
1740
twisti10d37ec2012-07-24 10:47:44 -07001741 @Test // SLOW
jrose10f3b682010-01-07 16:16:45 -08001742 public void testSpreadArguments() throws Throwable {
1743 if (CAN_SKIP_WORKING) return;
1744 startTest("spreadArguments");
jrose49494522012-01-18 17:34:29 -08001745 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001746 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001747 System.out.println("spreadArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001748 for (int nargs = 0; nargs < 50; nargs++) {
twisti10d37ec2012-07-24 10:47:44 -07001749 if (CAN_TEST_LIGHTLY && nargs > 11) break;
jroseb4be0262011-07-16 15:44:33 -07001750 for (int pos = 0; pos <= nargs; pos++) {
1751 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1752 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1753 continue;
1754 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001755 }
1756 }
1757 }
1758 }
1759 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1760 countTest();
jrose320b7692011-05-12 19:27:49 -07001761 Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
1762 MethodHandle target2 = varargsArray(arrayType, nargs);
1763 MethodHandle target = target2.asType(target2.type().generic());
jrose2cc9c832010-04-30 23:48:23 -07001764 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001765 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1766 Object[] args = randomArgs(target2.type().parameterArray());
1767 // make sure the target does what we think it does:
jrose320b7692011-05-12 19:27:49 -07001768 if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
jrose49494522012-01-18 17:34:29 -08001769 Object[] check = (Object[]) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001770 assertArrayEquals(args, check);
1771 switch (nargs) {
1772 case 0:
jrose320b7692011-05-12 19:27:49 -07001773 check = (Object[]) (Object) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001774 assertArrayEquals(args, check);
1775 break;
1776 case 1:
jrose320b7692011-05-12 19:27:49 -07001777 check = (Object[]) (Object) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001778 assertArrayEquals(args, check);
1779 break;
1780 case 2:
jrose320b7692011-05-12 19:27:49 -07001781 check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001782 assertArrayEquals(args, check);
1783 break;
1784 }
1785 }
jrose49494522012-01-18 17:34:29 -08001786 List<Class<?>> newParams = new ArrayList<>(target2.type().parameterList());
jrose10f3b682010-01-07 16:16:45 -08001787 { // modify newParams in place
1788 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
jrose320b7692011-05-12 19:27:49 -07001789 spreadParams.clear(); spreadParams.add(arrayType);
jrose10f3b682010-01-07 16:16:45 -08001790 }
jrose320b7692011-05-12 19:27:49 -07001791 MethodType newType = MethodType.methodType(arrayType, newParams);
1792 MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
1793 assert(result.type() == newType) : Arrays.asList(result, newType);
1794 result = result.asType(newType.generic());
1795 Object returnValue;
jrose10f3b682010-01-07 16:16:45 -08001796 if (pos == 0) {
jrose320b7692011-05-12 19:27:49 -07001797 Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1798 returnValue = result.invokeExact(args2);
jrose10f3b682010-01-07 16:16:45 -08001799 } else {
1800 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
jrose320b7692011-05-12 19:27:49 -07001801 args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1802 returnValue = result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001803 }
jrose320b7692011-05-12 19:27:49 -07001804 String argstr = Arrays.toString(args);
1805 if (!argType.isPrimitive()) {
1806 Object[] rv = (Object[]) returnValue;
1807 String rvs = Arrays.toString(rv);
1808 if (!Arrays.equals(args, rv)) {
1809 System.out.println("method: "+result);
1810 System.out.println("expected: "+argstr);
1811 System.out.println("returned: "+rvs);
1812 assertArrayEquals(args, rv);
1813 }
1814 } else if (argType == int.class) {
1815 String rvs = Arrays.toString((int[]) returnValue);
1816 if (!argstr.equals(rvs)) {
1817 System.out.println("method: "+result);
1818 System.out.println("expected: "+argstr);
1819 System.out.println("returned: "+rvs);
1820 assertEquals(argstr, rvs);
1821 }
1822 } else if (argType == long.class) {
1823 String rvs = Arrays.toString((long[]) returnValue);
1824 if (!argstr.equals(rvs)) {
1825 System.out.println("method: "+result);
1826 System.out.println("expected: "+argstr);
1827 System.out.println("returned: "+rvs);
1828 assertEquals(argstr, rvs);
1829 }
1830 } else {
1831 // cannot test...
1832 }
jrose10f3b682010-01-07 16:16:45 -08001833 }
1834
twisti10d37ec2012-07-24 10:47:44 -07001835 @Test // SLOW
jrose10f3b682010-01-07 16:16:45 -08001836 public void testCollectArguments() throws Throwable {
1837 if (CAN_SKIP_WORKING) return;
1838 startTest("collectArguments");
jrose49494522012-01-18 17:34:29 -08001839 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001840 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001841 System.out.println("collectArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001842 for (int nargs = 0; nargs < 50; nargs++) {
twisti10d37ec2012-07-24 10:47:44 -07001843 if (CAN_TEST_LIGHTLY && nargs > 11) break;
jroseb4be0262011-07-16 15:44:33 -07001844 for (int pos = 0; pos <= nargs; pos++) {
1845 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1846 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1847 continue;
jrose10f3b682010-01-07 16:16:45 -08001848 testCollectArguments(argType, pos, nargs);
1849 }
1850 }
1851 }
1852 }
1853 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1854 countTest();
1855 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001856 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001857 fake = changeArgTypes(fake, argType);
1858 MethodType newType = fake.type();
1859 Object[] args = randomArgs(newType.parameterArray());
1860 // here is what should happen:
1861 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1862 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1863 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001864 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001865 target = changeArgTypes(target, 0, pos, argType);
1866 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001867 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001868 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001869 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001870 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001871// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1872// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1873// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1874 assertArrayEquals(collectedArgs, returnValue);
1875 }
1876
twisti10d37ec2012-07-24 10:47:44 -07001877 @Test // SLOW
jrose55220c32009-10-21 23:19:48 -07001878 public void testInsertArguments() throws Throwable {
1879 if (CAN_SKIP_WORKING) return;
1880 startTest("insertArguments");
jroseb4be0262011-07-16 15:44:33 -07001881 for (int nargs = 0; nargs < 50; nargs++) {
twisti10d37ec2012-07-24 10:47:44 -07001882 if (CAN_TEST_LIGHTLY && nargs > 11) break;
jroseb4be0262011-07-16 15:44:33 -07001883 for (int ins = 0; ins <= nargs; ins++) {
1884 if (nargs > 10 && ins > 4 && ins < nargs-4 && ins % 10 != 3)
1885 continue;
jrose55220c32009-10-21 23:19:48 -07001886 for (int pos = 0; pos <= nargs; pos++) {
jroseb4be0262011-07-16 15:44:33 -07001887 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1888 continue;
1889 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
jrose55220c32009-10-21 23:19:48 -07001890 testInsertArguments(nargs, pos, ins);
1891 }
1892 }
1893 }
1894 }
1895
1896 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001897 countTest();
jroseadc650a2011-02-11 01:26:28 -08001898 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001899 Object[] args = randomArgs(target.type().parameterArray());
1900 List<Object> resList = Arrays.asList(args);
jrose49494522012-01-18 17:34:29 -08001901 List<Object> argsToPass = new ArrayList<>(resList);
jrose55220c32009-10-21 23:19:48 -07001902 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001903 if (verbosity >= 3)
twisti10d37ec2012-07-24 10:47:44 -07001904 System.out.println("insert: "+argsToInsert+" @"+pos+" into "+target);
jrose49494522012-01-18 17:34:29 -08001905 @SuppressWarnings("cast") // cast to spread Object... is helpful
jrose10f3b682010-01-07 16:16:45 -08001906 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
jrose49494522012-01-18 17:34:29 -08001907 (Object[]/*...*/) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001908 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001909 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001910 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001911 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001912 System.out.println("result: "+res2List);
1913 //if (!resList.equals(res2List))
1914 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1915 assertEquals(resList, res2List);
1916 }
1917
jrose10f3b682010-01-07 16:16:45 -08001918 @Test
jroseadc650a2011-02-11 01:26:28 -08001919 public void testFilterReturnValue() throws Throwable {
1920 if (CAN_SKIP_WORKING) return;
1921 startTest("filterReturnValue");
1922 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1923 assertTrue(List.class.isAssignableFrom(classOfVCList));
1924 for (int nargs = 0; nargs <= 3; nargs++) {
jrose49494522012-01-18 17:34:29 -08001925 for (Class<?> rtype : new Class<?>[] { Object.class,
jroseadc650a2011-02-11 01:26:28 -08001926 List.class,
1927 int.class,
jroseb4be0262011-07-16 15:44:33 -07001928 byte.class,
1929 long.class,
jroseadc650a2011-02-11 01:26:28 -08001930 CharSequence.class,
1931 String.class }) {
1932 testFilterReturnValue(nargs, rtype);
1933 }
1934 }
1935 }
1936
1937 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1938 countTest();
1939 MethodHandle target = varargsList(nargs, rtype);
1940 MethodHandle filter;
1941 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1942 filter = varargsList(1); // add another layer of list-ness
1943 else
1944 filter = MethodHandles.identity(rtype);
1945 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1946 Object[] argsToPass = randomArgs(nargs, Object.class);
1947 if (verbosity >= 3)
1948 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1949 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1950 if (verbosity >= 4)
1951 System.out.println("filtered target: "+target2);
1952 // Simulate expected effect of filter on return value:
1953 Object unfiltered = target.invokeWithArguments(argsToPass);
1954 Object expected = filter.invokeWithArguments(unfiltered);
1955 if (verbosity >= 4)
1956 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1957 if (verbosity >= 4)
1958 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1959 Object result = target2.invokeWithArguments(argsToPass);
1960 if (verbosity >= 3)
1961 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1962 if (!expected.equals(result))
1963 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1964 assertEquals(expected, result);
1965 }
1966
1967 @Test
jrose10f3b682010-01-07 16:16:45 -08001968 public void testFilterArguments() throws Throwable {
1969 if (CAN_SKIP_WORKING) return;
1970 startTest("filterArguments");
1971 for (int nargs = 1; nargs <= 6; nargs++) {
1972 for (int pos = 0; pos < nargs; pos++) {
1973 testFilterArguments(nargs, pos);
1974 }
1975 }
1976 }
1977
1978 void testFilterArguments(int nargs, int pos) throws Throwable {
1979 countTest();
jroseadc650a2011-02-11 01:26:28 -08001980 MethodHandle target = varargsList(nargs);
1981 MethodHandle filter = varargsList(1);
jrose9b82ad62011-05-26 17:37:36 -07001982 filter = filter.asType(filter.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001983 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001984 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001985 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001986 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001987 // Simulate expected effect of filter on arglist:
1988 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001989 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001990 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001991 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001992 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001993 System.out.println("result: "+result);
1994 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001995 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001996 assertEquals(expected, result);
1997 }
1998
1999 @Test
2000 public void testFoldArguments() throws Throwable {
2001 if (CAN_SKIP_WORKING) return;
2002 startTest("foldArguments");
2003 for (int nargs = 0; nargs <= 4; nargs++) {
2004 for (int fold = 0; fold <= nargs; fold++) {
2005 for (int pos = 0; pos <= nargs; pos++) {
2006 testFoldArguments(nargs, pos, fold);
2007 }
2008 }
2009 }
2010 }
2011
2012 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
2013 if (pos != 0) return; // can fold only at pos=0 for now
2014 countTest();
jroseadc650a2011-02-11 01:26:28 -08002015 MethodHandle target = varargsList(1 + nargs);
2016 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08002017 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07002018 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002019 System.out.println("fold "+target+" with "+combine);
2020 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
2021 // Simulate expected effect of combiner on arglist:
jrose49494522012-01-18 17:34:29 -08002022 List<Object> expected = new ArrayList<>(argsToPass);
jrose10f3b682010-01-07 16:16:45 -08002023 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07002024 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002025 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07002026 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08002027 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07002028 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07002029 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002030 System.out.println("result: "+result);
2031 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08002032 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08002033 assertEquals(expected, result);
2034 }
2035
2036 @Test
2037 public void testDropArguments() throws Throwable {
2038 if (CAN_SKIP_WORKING) return;
2039 startTest("dropArguments");
2040 for (int nargs = 0; nargs <= 4; nargs++) {
2041 for (int drop = 1; drop <= 4; drop++) {
2042 for (int pos = 0; pos <= nargs; pos++) {
2043 testDropArguments(nargs, pos, drop);
2044 }
2045 }
2046 }
2047 }
2048
2049 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
2050 countTest();
jroseadc650a2011-02-11 01:26:28 -08002051 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08002052 Object[] args = randomArgs(target.type().parameterArray());
2053 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
jrose49494522012-01-18 17:34:29 -08002054 Collections.nCopies(drop, Object.class).toArray(new Class<?>[0]));
jrose10f3b682010-01-07 16:16:45 -08002055 List<Object> resList = Arrays.asList(args);
jrose49494522012-01-18 17:34:29 -08002056 List<Object> argsToDrop = new ArrayList<>(resList);
jrose10f3b682010-01-07 16:16:45 -08002057 for (int i = drop; i > 0; i--) {
2058 argsToDrop.add(pos, "blort#"+i);
2059 }
jrose900bafd2010-10-30 21:08:23 -07002060 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08002061 Object res2List = Arrays.asList((Object[])res2);
2062 //if (!resList.equals(res2List))
2063 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
2064 assertEquals(resList, res2List);
2065 }
2066
twisti10d37ec2012-07-24 10:47:44 -07002067 @Test // SLOW
jrose10f3b682010-01-07 16:16:45 -08002068 public void testInvokers() throws Throwable {
2069 if (CAN_SKIP_WORKING) return;
2070 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
2071 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
jrose49494522012-01-18 17:34:29 -08002072 Set<MethodType> done = new HashSet<>();
jrose10f3b682010-01-07 16:16:45 -08002073 for (int i = 0; i <= 6; i++) {
jroseb4be0262011-07-16 15:44:33 -07002074 if (CAN_TEST_LIGHTLY && i > 3) break;
jrose10f3b682010-01-07 16:16:45 -08002075 MethodType gtype = MethodType.genericMethodType(i);
jrose49494522012-01-18 17:34:29 -08002076 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose10f3b682010-01-07 16:16:45 -08002077 for (int j = -1; j < i; j++) {
2078 MethodType type = gtype;
2079 if (j < 0)
2080 type = type.changeReturnType(argType);
2081 else if (argType == void.class)
2082 continue;
2083 else
2084 type = type.changeParameterType(j, argType);
jrose10f3b682010-01-07 16:16:45 -08002085 if (done.add(type))
2086 testInvokers(type);
2087 MethodType vtype = type.changeReturnType(void.class);
2088 if (done.add(vtype))
2089 testInvokers(vtype);
2090 }
2091 }
2092 }
2093 }
2094
2095 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07002096 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002097 System.out.println("test invokers for "+type);
2098 int nargs = type.parameterCount();
2099 boolean testRetCode = type.returnType() != void.class;
2100 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
2101 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08002102 assertTrue(target.isVarargsCollector());
2103 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08002104 Object[] args = randomArgs(type.parameterArray());
jrose49494522012-01-18 17:34:29 -08002105 List<Object> targetPlusArgs = new ArrayList<>(Arrays.asList(args));
jrose10f3b682010-01-07 16:16:45 -08002106 targetPlusArgs.add(0, target);
2107 int code = (Integer) invokee(args);
2108 Object log = logEntry("invokee", args);
2109 assertEquals(log.hashCode(), code);
2110 assertCalled("invokee", args);
2111 MethodHandle inv;
2112 Object result;
2113 // exact invoker
2114 countTest();
2115 calledLog.clear();
2116 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07002117 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08002118 if (testRetCode) assertEquals(code, result);
2119 assertCalled("invokee", args);
2120 // generic invoker
2121 countTest();
jrose79e0a6c2011-05-12 19:27:33 -07002122 inv = MethodHandles.invoker(type);
jrose9b82ad62011-05-26 17:37:36 -07002123 if (nargs <= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002124 calledLog.clear();
2125 switch (nargs) {
2126 case 0:
jrose2cc9c832010-04-30 23:48:23 -07002127 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08002128 break;
2129 case 1:
jrose2cc9c832010-04-30 23:48:23 -07002130 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08002131 break;
2132 case 2:
jrose2cc9c832010-04-30 23:48:23 -07002133 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08002134 break;
2135 case 3:
jrose2cc9c832010-04-30 23:48:23 -07002136 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08002137 break;
2138 }
2139 if (testRetCode) assertEquals(code, result);
2140 assertCalled("invokee", args);
2141 }
2142 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07002143 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08002144 if (testRetCode) assertEquals(code, result);
2145 assertCalled("invokee", args);
2146 // varargs invoker #0
2147 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002148 inv = MethodHandles.spreadInvoker(type, 0);
jrose9b82ad62011-05-26 17:37:36 -07002149 if (type.returnType() == Object.class) {
2150 result = inv.invokeExact(target, args);
2151 } else if (type.returnType() == void.class) {
2152 result = null; inv.invokeExact(target, args);
2153 } else {
2154 result = inv.invokeWithArguments(target, (Object) args);
2155 }
jrose10f3b682010-01-07 16:16:45 -08002156 if (testRetCode) assertEquals(code, result);
2157 assertCalled("invokee", args);
jrose9b82ad62011-05-26 17:37:36 -07002158 if (nargs >= 1 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002159 // varargs invoker #1
2160 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002161 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07002162 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08002163 if (testRetCode) assertEquals(code, result);
2164 assertCalled("invokee", args);
2165 }
jrose9b82ad62011-05-26 17:37:36 -07002166 if (nargs >= 2 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002167 // varargs invoker #2
2168 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002169 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07002170 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08002171 if (testRetCode) assertEquals(code, result);
2172 assertCalled("invokee", args);
2173 }
jrose9b82ad62011-05-26 17:37:36 -07002174 if (nargs >= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002175 // varargs invoker #3
2176 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002177 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07002178 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08002179 if (testRetCode) assertEquals(code, result);
2180 assertCalled("invokee", args);
2181 }
2182 for (int k = 0; k <= nargs; k++) {
2183 // varargs invoker #0..N
jroseb4be0262011-07-16 15:44:33 -07002184 if (CAN_TEST_LIGHTLY && (k > 1 || k < nargs - 1)) continue;
jrose10f3b682010-01-07 16:16:45 -08002185 countTest();
2186 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002187 inv = MethodHandles.spreadInvoker(type, k);
jrose9b82ad62011-05-26 17:37:36 -07002188 MethodType expType = (type.dropParameterTypes(k, nargs)
2189 .appendParameterTypes(Object[].class)
2190 .insertParameterTypes(0, MethodHandle.class));
2191 assertEquals(expType, inv.type());
jrose49494522012-01-18 17:34:29 -08002192 List<Object> targetPlusVarArgs = new ArrayList<>(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08002193 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
2194 Object[] tail = tailList.toArray();
2195 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07002196 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08002197 if (testRetCode) assertEquals(code, result);
2198 assertCalled("invokee", args);
2199 }
jrose900bafd2010-10-30 21:08:23 -07002200
jrose10f3b682010-01-07 16:16:45 -08002201 // dynamic invoker
2202 countTest();
jroseb90d2e72010-12-16 15:59:27 -08002203 CallSite site = new MutableCallSite(type);
2204 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07002205
2206 // see if we get the result of the original target:
2207 try {
2208 result = inv.invokeWithArguments(args);
2209 assertTrue("should not reach here", false);
2210 } catch (IllegalStateException ex) {
2211 String msg = ex.getMessage();
2212 assertTrue(msg, msg.contains("site"));
2213 }
2214
2215 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08002216 site.setTarget(target);
2217 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07002218 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08002219 if (testRetCode) assertEquals(code, result);
2220 assertCalled("invokee", args);
2221 }
2222
2223 static Object invokee(Object... args) {
2224 return called("invokee", args).hashCode();
2225 }
2226
jrose55220c32009-10-21 23:19:48 -07002227 private static final String MISSING_ARG = "missingArg";
jroseb4be0262011-07-16 15:44:33 -07002228 private static final String MISSING_ARG_2 = "missingArg#2";
jrose55220c32009-10-21 23:19:48 -07002229 static Object targetIfEquals() {
2230 return called("targetIfEquals");
2231 }
2232 static Object fallbackIfNotEquals() {
2233 return called("fallbackIfNotEquals");
2234 }
2235 static Object targetIfEquals(Object x) {
2236 assertEquals(x, MISSING_ARG);
2237 return called("targetIfEquals", x);
2238 }
2239 static Object fallbackIfNotEquals(Object x) {
2240 assertFalse(x.toString(), x.equals(MISSING_ARG));
2241 return called("fallbackIfNotEquals", x);
2242 }
2243 static Object targetIfEquals(Object x, Object y) {
2244 assertEquals(x, y);
2245 return called("targetIfEquals", x, y);
2246 }
2247 static Object fallbackIfNotEquals(Object x, Object y) {
2248 assertFalse(x.toString(), x.equals(y));
2249 return called("fallbackIfNotEquals", x, y);
2250 }
2251 static Object targetIfEquals(Object x, Object y, Object z) {
2252 assertEquals(x, y);
2253 return called("targetIfEquals", x, y, z);
2254 }
2255 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
2256 assertFalse(x.toString(), x.equals(y));
2257 return called("fallbackIfNotEquals", x, y, z);
2258 }
2259
jrose10f3b682010-01-07 16:16:45 -08002260 @Test
2261 public void testGuardWithTest() throws Throwable {
2262 if (CAN_SKIP_WORKING) return;
2263 startTest("guardWithTest");
jroseb4be0262011-07-16 15:44:33 -07002264 for (int nargs = 0; nargs <= 50; nargs++) {
2265 if (CAN_TEST_LIGHTLY && nargs > 7) break;
jrose10f3b682010-01-07 16:16:45 -08002266 testGuardWithTest(nargs, Object.class);
2267 testGuardWithTest(nargs, String.class);
2268 }
2269 }
2270 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07002271 testGuardWithTest(nargs, 0, argClass);
2272 if (nargs <= 5 || nargs % 10 == 3) {
2273 for (int testDrops = 1; testDrops <= nargs; testDrops++)
2274 testGuardWithTest(nargs, testDrops, argClass);
2275 }
2276 }
2277 void testGuardWithTest(int nargs, int testDrops, Class<?> argClass) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002278 countTest();
jroseb4be0262011-07-16 15:44:33 -07002279 int nargs1 = Math.min(3, nargs);
jrose10f3b682010-01-07 16:16:45 -08002280 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
jroseb4be0262011-07-16 15:44:33 -07002281 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs1));
2282 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs1));
jrose10f3b682010-01-07 16:16:45 -08002283 while (test.type().parameterCount() > nargs)
jroseb4be0262011-07-16 15:44:33 -07002284 // 0: test = constant(MISSING_ARG.equals(MISSING_ARG))
2285 // 1: test = lambda (_) MISSING_ARG.equals(_)
jrose10f3b682010-01-07 16:16:45 -08002286 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
2287 if (argClass != Object.class) {
2288 test = changeArgTypes(test, argClass);
2289 target = changeArgTypes(target, argClass);
2290 fallback = changeArgTypes(fallback, argClass);
2291 }
jroseb4be0262011-07-16 15:44:33 -07002292 int testArgs = nargs - testDrops;
2293 assert(testArgs >= 0);
2294 test = addTrailingArgs(test, Math.min(testArgs, nargs), argClass);
2295 target = addTrailingArgs(target, nargs, argClass);
2296 fallback = addTrailingArgs(fallback, nargs, argClass);
jrose10f3b682010-01-07 16:16:45 -08002297 Object[][] argLists = {
2298 { },
2299 { "foo" }, { MISSING_ARG },
2300 { "foo", "foo" }, { "foo", "bar" },
2301 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
2302 };
2303 for (Object[] argList : argLists) {
jroseb4be0262011-07-16 15:44:33 -07002304 Object[] argList1 = argList;
2305 if (argList.length != nargs) {
2306 if (argList.length != nargs1) continue;
2307 argList1 = Arrays.copyOf(argList, nargs);
2308 Arrays.fill(argList1, nargs1, nargs, MISSING_ARG_2);
2309 }
2310 MethodHandle test1 = test;
2311 if (test1.type().parameterCount() > testArgs) {
2312 int pc = test1.type().parameterCount();
2313 test1 = MethodHandles.insertArguments(test, testArgs, Arrays.copyOfRange(argList1, testArgs, pc));
2314 }
2315 MethodHandle mh = MethodHandles.guardWithTest(test1, target, fallback);
2316 assertEquals(target.type(), mh.type());
jrose10f3b682010-01-07 16:16:45 -08002317 boolean equals;
2318 switch (nargs) {
2319 case 0: equals = true; break;
2320 case 1: equals = MISSING_ARG.equals(argList[0]); break;
2321 default: equals = argList[0].equals(argList[1]); break;
2322 }
2323 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07002324 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002325 System.out.println(logEntry(willCall, argList));
jroseb4be0262011-07-16 15:44:33 -07002326 Object result = mh.invokeWithArguments(argList1);
jrose10f3b682010-01-07 16:16:45 -08002327 assertCalled(willCall, argList);
2328 }
2329 }
2330
2331 @Test
2332 public void testCatchException() throws Throwable {
2333 if (CAN_SKIP_WORKING) return;
2334 startTest("catchException");
jroseb4be0262011-07-16 15:44:33 -07002335 for (int nargs = 0; nargs < 40; nargs++) {
twisti10d37ec2012-07-24 10:47:44 -07002336 if (CAN_TEST_LIGHTLY && nargs > 11) break;
jroseb4be0262011-07-16 15:44:33 -07002337 for (int throwMode = 0; throwMode < THROW_MODE_LIMIT; throwMode++) {
2338 testCatchException(int.class, new ClassCastException("testing"), throwMode, nargs);
2339 if (CAN_TEST_LIGHTLY && nargs > 3) continue;
2340 testCatchException(void.class, new java.io.IOException("testing"), throwMode, nargs);
2341 testCatchException(String.class, new LinkageError("testing"), throwMode, nargs);
jrose10f3b682010-01-07 16:16:45 -08002342 }
2343 }
2344 }
2345
jroseb4be0262011-07-16 15:44:33 -07002346 static final int THROW_NOTHING = 0, THROW_CAUGHT = 1, THROW_UNCAUGHT = 2, THROW_THROUGH_ADAPTER = 3, THROW_MODE_LIMIT = 4;
2347
2348 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs) throws Throwable {
2349 testCatchException(returnType, thrown, throwMode, nargs, 0);
2350 if (nargs <= 5 || nargs % 10 == 3) {
2351 for (int catchDrops = 1; catchDrops <= nargs; catchDrops++)
2352 testCatchException(returnType, thrown, throwMode, nargs, catchDrops);
2353 }
2354 }
2355
jrose10f3b682010-01-07 16:16:45 -08002356 private static <T extends Throwable>
2357 Object throwOrReturn(Object normal, T exception) throws T {
jroseb4be0262011-07-16 15:44:33 -07002358 if (exception != null) {
2359 called("throwOrReturn/throw", normal, exception);
2360 throw exception;
2361 }
2362 called("throwOrReturn/normal", normal, exception);
jrose10f3b682010-01-07 16:16:45 -08002363 return normal;
2364 }
jroseb4be0262011-07-16 15:44:33 -07002365 private int fakeIdentityCount;
2366 private Object fakeIdentity(Object x) {
2367 System.out.println("should throw through this!");
2368 fakeIdentityCount++;
2369 return x;
2370 }
jrose10f3b682010-01-07 16:16:45 -08002371
jroseb4be0262011-07-16 15:44:33 -07002372 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs, int catchDrops) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002373 countTest();
jrose2cc9c832010-04-30 23:48:23 -07002374 if (verbosity >= 3)
jroseb4be0262011-07-16 15:44:33 -07002375 System.out.println("catchException rt="+returnType+" throw="+throwMode+" nargs="+nargs+" drops="+catchDrops);
jrose10f3b682010-01-07 16:16:45 -08002376 Class<? extends Throwable> exType = thrown.getClass();
jroseb4be0262011-07-16 15:44:33 -07002377 if (throwMode > THROW_CAUGHT) thrown = new UnsupportedOperationException("do not catch this");
jrose10f3b682010-01-07 16:16:45 -08002378 MethodHandle throwOrReturn
2379 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2380 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb4be0262011-07-16 15:44:33 -07002381 if (throwMode == THROW_THROUGH_ADAPTER) {
2382 MethodHandle fakeIdentity
2383 = PRIVATE.findVirtual(MethodHandlesTest.class, "fakeIdentity",
2384 MethodType.methodType(Object.class, Object.class)).bindTo(this);
2385 for (int i = 0; i < 10; i++)
2386 throwOrReturn = MethodHandles.filterReturnValue(throwOrReturn, fakeIdentity);
2387 }
2388 int nargs1 = Math.max(2, nargs);
jroseb90d2e72010-12-16 15:59:27 -08002389 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jroseb4be0262011-07-16 15:44:33 -07002390 thrower = addTrailingArgs(thrower, nargs, Object.class);
2391 int catchArgc = 1 + nargs - catchDrops;
2392 MethodHandle catcher = varargsList(catchArgc).asType(MethodType.genericMethodType(catchArgc));
jrose10f3b682010-01-07 16:16:45 -08002393 Object[] args = randomArgs(nargs, Object.class);
jroseb4be0262011-07-16 15:44:33 -07002394 Object arg0 = MISSING_ARG;
2395 Object arg1 = (throwMode == THROW_NOTHING) ? (Throwable) null : thrown;
2396 if (nargs > 0) arg0 = args[0];
2397 if (nargs > 1) args[1] = arg1;
2398 assertEquals(nargs1, thrower.type().parameterCount());
2399 if (nargs < nargs1) {
2400 Object[] appendArgs = { arg0, arg1 };
2401 appendArgs = Arrays.copyOfRange(appendArgs, nargs, nargs1);
2402 thrower = MethodHandles.insertArguments(thrower, nargs, appendArgs);
2403 }
2404 assertEquals(nargs, thrower.type().parameterCount());
2405 MethodHandle target = MethodHandles.catchException(thrower, exType, catcher);
2406 assertEquals(thrower.type(), target.type());
2407 assertEquals(nargs, target.type().parameterCount());
2408 //System.out.println("catching with "+target+" : "+throwOrReturn);
2409 Object returned;
2410 try {
2411 returned = target.invokeWithArguments(args);
2412 } catch (Throwable ex) {
2413 assertSame("must get the out-of-band exception", thrown, ex);
2414 if (throwMode <= THROW_CAUGHT)
2415 assertEquals(THROW_UNCAUGHT, throwMode);
2416 returned = ex;
2417 }
2418 assertCalled("throwOrReturn/"+(throwMode == THROW_NOTHING ? "normal" : "throw"), arg0, arg1);
jrose10f3b682010-01-07 16:16:45 -08002419 //System.out.println("return from "+target+" : "+returned);
jroseb4be0262011-07-16 15:44:33 -07002420 if (throwMode == THROW_NOTHING) {
2421 assertSame(arg0, returned);
2422 } else if (throwMode == THROW_CAUGHT) {
jrose49494522012-01-18 17:34:29 -08002423 List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
jroseb4be0262011-07-16 15:44:33 -07002424 // catcher receives an initial subsequence of target arguments:
2425 catchArgs.subList(nargs - catchDrops, nargs).clear();
2426 // catcher also receives the exception, prepended:
jrose10f3b682010-01-07 16:16:45 -08002427 catchArgs.add(0, thrown);
2428 assertEquals(catchArgs, returned);
2429 }
jroseb4be0262011-07-16 15:44:33 -07002430 assertEquals(0, fakeIdentityCount);
jrose10f3b682010-01-07 16:16:45 -08002431 }
2432
2433 @Test
2434 public void testThrowException() throws Throwable {
2435 if (CAN_SKIP_WORKING) return;
2436 startTest("throwException");
2437 testThrowException(int.class, new ClassCastException("testing"));
2438 testThrowException(void.class, new java.io.IOException("testing"));
2439 testThrowException(String.class, new LinkageError("testing"));
2440 }
2441
2442 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2443 countTest();
2444 Class<? extends Throwable> exType = thrown.getClass();
2445 MethodHandle target = MethodHandles.throwException(returnType, exType);
2446 //System.out.println("throwing with "+target+" : "+thrown);
2447 MethodType expectedType = MethodType.methodType(returnType, exType);
2448 assertEquals(expectedType, target.type());
jrose9b82ad62011-05-26 17:37:36 -07002449 target = target.asType(target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08002450 Throwable caught = null;
2451 try {
jrose2cc9c832010-04-30 23:48:23 -07002452 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08002453 fail("got "+res+" instead of throwing "+thrown);
2454 } catch (Throwable ex) {
2455 if (ex != thrown) {
2456 if (ex instanceof Error) throw (Error)ex;
2457 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2458 }
2459 caught = ex;
2460 }
2461 assertSame(thrown, caught);
2462 }
2463
jrose4f019ca2012-08-17 13:42:25 -07002464 @Test
jroseb4be0262011-07-16 15:44:33 -07002465 public void testInterfaceCast() throws Throwable {
twisti10d37ec2012-07-24 10:47:44 -07002466 //if (CAN_SKIP_WORKING) return;
2467 startTest("interfaceCast");
jrose4f019ca2012-08-17 13:42:25 -07002468 assert( (((Object)"foo") instanceof CharSequence));
2469 assert(!(((Object)"foo") instanceof Iterable));
2470 for (MethodHandle mh : new MethodHandle[]{
2471 MethodHandles.identity(String.class),
2472 MethodHandles.identity(CharSequence.class),
2473 MethodHandles.identity(Iterable.class)
2474 }) {
2475 if (verbosity > 0) System.out.println("-- mh = "+mh);
2476 for (Class<?> ctype : new Class<?>[]{
2477 Object.class, String.class, CharSequence.class,
2478 Number.class, Iterable.class
2479 }) {
2480 if (verbosity > 0) System.out.println("---- ctype = "+ctype.getName());
2481 // doret docast
2482 testInterfaceCast(mh, ctype, false, false);
2483 testInterfaceCast(mh, ctype, true, false);
2484 testInterfaceCast(mh, ctype, false, true);
2485 testInterfaceCast(mh, ctype, true, true);
2486 }
jroseb4be0262011-07-16 15:44:33 -07002487 }
2488 }
jrose4f019ca2012-08-17 13:42:25 -07002489 private static Class<?> i2o(Class<?> c) {
2490 return (c.isInterface() ? Object.class : c);
2491 }
2492 public void testInterfaceCast(MethodHandle mh, Class<?> ctype,
2493 boolean doret, boolean docast) throws Throwable {
2494 MethodHandle mh0 = mh;
2495 if (verbosity > 1)
2496 System.out.println("mh="+mh+", ctype="+ctype.getName()+", doret="+doret+", docast="+docast);
2497 String normalRetVal = "normal return value";
jroseb4be0262011-07-16 15:44:33 -07002498 MethodType mt = mh.type();
jrose4f019ca2012-08-17 13:42:25 -07002499 MethodType mt0 = mt;
jroseb4be0262011-07-16 15:44:33 -07002500 if (doret) mt = mt.changeReturnType(ctype);
2501 else mt = mt.changeParameterType(0, ctype);
2502 if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
2503 else mh = mh.asType(mt);
jrose4f019ca2012-08-17 13:42:25 -07002504 assertEquals(mt, mh.type());
2505 MethodType mt1 = mt;
jroseb4be0262011-07-16 15:44:33 -07002506 // this bit is needed to make the interface types disappear for invokeWithArguments:
2507 mh = MethodHandles.explicitCastArguments(mh, mt.generic());
jrose4f019ca2012-08-17 13:42:25 -07002508 Class<?>[] step = {
2509 mt1.parameterType(0), // param as passed to mh at first
2510 mt0.parameterType(0), // param after incoming cast
2511 mt0.returnType(), // return value before cast
2512 mt1.returnType(), // return value after outgoing cast
2513 };
2514 // where might a checkCast occur?
2515 boolean[] checkCast = new boolean[step.length];
2516 // the string value must pass each step without causing an exception
2517 if (!docast) {
2518 if (!doret) {
2519 if (step[0] != step[1])
2520 checkCast[1] = true; // incoming value is cast
2521 } else {
2522 if (step[2] != step[3])
2523 checkCast[3] = true; // outgoing value is cast
2524 }
jroseb4be0262011-07-16 15:44:33 -07002525 }
jrose4f019ca2012-08-17 13:42:25 -07002526 boolean expectFail = false;
2527 for (int i = 0; i < step.length; i++) {
2528 Class<?> c = step[i];
2529 if (!checkCast[i]) c = i2o(c);
2530 if (!c.isInstance(normalRetVal)) {
2531 if (verbosity > 3)
2532 System.out.println("expect failure at step "+i+" in "+Arrays.toString(step)+Arrays.toString(checkCast));
2533 expectFail = true;
2534 break;
2535 }
2536 }
2537 countTest(!expectFail);
2538 if (verbosity > 2)
2539 System.out.println("expectFail="+expectFail+", mt="+mt);
jroseb4be0262011-07-16 15:44:33 -07002540 Object res;
2541 try {
jrose4f019ca2012-08-17 13:42:25 -07002542 res = mh.invokeWithArguments(normalRetVal);
jroseb4be0262011-07-16 15:44:33 -07002543 } catch (Exception ex) {
2544 res = ex;
2545 }
2546 boolean sawFail = !(res instanceof String);
2547 if (sawFail != expectFail) {
jrose4f019ca2012-08-17 13:42:25 -07002548 System.out.println("*** testInterfaceCast: mh0 = "+mh0);
2549 System.out.println(" retype using "+(docast ? "explicitCastArguments" : "asType")+" to "+mt+" => "+mh);
2550 System.out.println(" call returned "+res);
2551 System.out.println(" expected "+(expectFail ? "an exception" : normalRetVal));
jroseb4be0262011-07-16 15:44:33 -07002552 }
jrose4f019ca2012-08-17 13:42:25 -07002553 if (!expectFail) {
2554 assertFalse(res.toString(), sawFail);
2555 assertEquals(normalRetVal, res);
jroseb4be0262011-07-16 15:44:33 -07002556 } else {
jrose4f019ca2012-08-17 13:42:25 -07002557 assertTrue(res.toString(), sawFail);
jroseb4be0262011-07-16 15:44:33 -07002558 }
2559 }
2560
twisti10d37ec2012-07-24 10:47:44 -07002561 @Test // SLOW
jrose10f3b682010-01-07 16:16:45 -08002562 public void testCastFailure() throws Throwable {
2563 if (CAN_SKIP_WORKING) return;
2564 startTest("testCastFailure");
2565 testCastFailure("cast/argument", 11000);
twisti10d37ec2012-07-24 10:47:44 -07002566 if (CAN_TEST_LIGHTLY) return;
jrose10f3b682010-01-07 16:16:45 -08002567 testCastFailure("unbox/argument", 11000);
2568 testCastFailure("cast/return", 11000);
2569 testCastFailure("unbox/return", 11000);
2570 }
2571
jrose900bafd2010-10-30 21:08:23 -07002572 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07002573 public MethodHandle asMethodHandle() {
2574 return VALUE.bindTo(this);
2575 }
jrose10f3b682010-01-07 16:16:45 -08002576 Object value(Object x) {
2577 trace("value", x);
2578 if (boo != null) return boo;
2579 return x;
2580 }
2581 Object boo;
2582 void boo(Object x) { boo = x; }
2583
2584 static void trace(String x, Object y) {
2585 if (verbosity > 8) System.out.println(x+"="+y);
2586 }
2587 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2588 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2589 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07002590 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
2591 static {
2592 try {
2593 VALUE = PRIVATE.findVirtual(
2594 Surprise.class, "value",
2595 MethodType.methodType(Object.class, Object.class));
2596 REF_IDENTITY = PRIVATE.findStatic(
2597 Surprise.class, "refIdentity",
2598 MethodType.methodType(Object.class, Object.class));
2599 BOX_IDENTITY = PRIVATE.findStatic(
2600 Surprise.class, "boxIdentity",
2601 MethodType.methodType(Integer.class, Integer.class));
2602 INT_IDENTITY = PRIVATE.findStatic(
2603 Surprise.class, "intIdentity",
2604 MethodType.methodType(int.class, int.class));
jrose49494522012-01-18 17:34:29 -08002605 } catch (NoSuchMethodException | IllegalAccessException ex) {
jrosea1ebbe62010-09-08 18:40:23 -07002606 throw new RuntimeException(ex);
2607 }
2608 }
jrose10f3b682010-01-07 16:16:45 -08002609 }
2610
jrose49494522012-01-18 17:34:29 -08002611 @SuppressWarnings("ConvertToStringSwitch")
jrose10f3b682010-01-07 16:16:45 -08002612 void testCastFailure(String mode, int okCount) throws Throwable {
2613 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07002614 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002615 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002616 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002617 if (mode.endsWith("/return")) {
2618 if (mode.equals("unbox/return")) {
2619 // fail on return to ((Integer)surprise).intValue
jrose9b82ad62011-05-26 17:37:36 -07002620 surprise = surprise.asType(MethodType.methodType(int.class, Object.class));
2621 identity = identity.asType(MethodType.methodType(int.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002622 } else if (mode.equals("cast/return")) {
2623 // fail on return to (Integer)surprise
jrose9b82ad62011-05-26 17:37:36 -07002624 surprise = surprise.asType(MethodType.methodType(Integer.class, Object.class));
2625 identity = identity.asType(MethodType.methodType(Integer.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002626 }
2627 } else if (mode.endsWith("/argument")) {
2628 MethodHandle callee = null;
2629 if (mode.equals("unbox/argument")) {
2630 // fail on handing surprise to int argument
2631 callee = Surprise.INT_IDENTITY;
2632 } else if (mode.equals("cast/argument")) {
2633 // fail on handing surprise to Integer argument
2634 callee = Surprise.BOX_IDENTITY;
2635 }
2636 if (callee != null) {
jrose9b82ad62011-05-26 17:37:36 -07002637 callee = callee.asType(MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002638 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2639 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002640 }
2641 }
jrosea1ebbe62010-09-08 18:40:23 -07002642 assertNotSame(mode, surprise, surprise0);
jrose9b82ad62011-05-26 17:37:36 -07002643 identity = identity.asType(MethodType.genericMethodType(1));
2644 surprise = surprise.asType(MethodType.genericMethodType(1));
jrose10f3b682010-01-07 16:16:45 -08002645 Object x = 42;
2646 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002647 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002648 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002649 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002650 assertEquals(x, z);
2651 }
2652 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002653 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002654 assertEquals(x, y);
2655 try {
jrose2cc9c832010-04-30 23:48:23 -07002656 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002657 System.out.println("Failed to throw; got z="+z);
2658 assertTrue(false);
jrose320b7692011-05-12 19:27:49 -07002659 } catch (ClassCastException ex) {
jrose10f3b682010-01-07 16:16:45 -08002660 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002661 System.out.println("caught "+ex);
2662 if (verbosity > 3)
twisti10d37ec2012-07-24 10:47:44 -07002663 ex.printStackTrace(System.out);
jrose320b7692011-05-12 19:27:49 -07002664 assertTrue(true); // all is well
jrose10f3b682010-01-07 16:16:45 -08002665 }
2666 }
2667
jrose45b7a332010-05-03 23:32:47 -07002668 static Example userMethod(Object o, String s, int i) {
2669 called("userMethod", o, s, i);
2670 return null;
2671 }
2672
2673 @Test
2674 public void testUserClassInSignature() throws Throwable {
2675 if (CAN_SKIP_WORKING) return;
2676 startTest("testUserClassInSignature");
2677 Lookup lookup = MethodHandles.lookup();
2678 String name; MethodType mt; MethodHandle mh;
2679 Object[] args;
2680
2681 // Try a static method.
2682 name = "userMethod";
2683 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2684 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2685 assertEquals(mt, mh.type());
2686 assertEquals(Example.class, mh.type().returnType());
2687 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002688 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002689 assertCalled(name, args);
2690
2691 // Try a virtual method.
2692 name = "v2";
2693 mt = MethodType.methodType(Object.class, Object.class, int.class);
2694 mh = lookup.findVirtual(Example.class, name, mt);
2695 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2696 assertTrue(mh.type().parameterList().contains(Example.class));
2697 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002698 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002699 assertCalled(name, args);
2700 }
jrosebe2db602010-09-08 18:40:34 -07002701
2702 static void runForRunnable() {
2703 called("runForRunnable");
2704 }
jroseaf751942011-06-14 22:47:12 -07002705 public interface Fooable {
jroseb4be0262011-07-16 15:44:33 -07002706 // overloads:
jrose49494522012-01-18 17:34:29 -08002707 Object foo(Object x, String y);
2708 List<?> foo(String x, int y);
2709 Object foo(String x);
jrosebe2db602010-09-08 18:40:34 -07002710 }
jroseb4be0262011-07-16 15:44:33 -07002711 static Object fooForFooable(String x, Object... y) {
2712 return called("fooForFooable/"+x, y);
jrosebe2db602010-09-08 18:40:34 -07002713 }
jrose49494522012-01-18 17:34:29 -08002714 @SuppressWarnings("serial") // not really a public API, just a test case
jroseaf751942011-06-14 22:47:12 -07002715 public static class MyCheckedException extends Exception {
jrosebe2db602010-09-08 18:40:34 -07002716 }
jroseaf751942011-06-14 22:47:12 -07002717 public interface WillThrow {
jrosebe2db602010-09-08 18:40:34 -07002718 void willThrow() throws MyCheckedException;
2719 }
jroseb4be0262011-07-16 15:44:33 -07002720 /*non-public*/ interface PrivateRunnable {
2721 public void run();
2722 }
jrosebe2db602010-09-08 18:40:34 -07002723
2724 @Test
jroseb4be0262011-07-16 15:44:33 -07002725 public void testAsInterfaceInstance() throws Throwable {
jrosebe2db602010-09-08 18:40:34 -07002726 if (CAN_SKIP_WORKING) return;
twisti10d37ec2012-07-24 10:47:44 -07002727 startTest("asInterfaceInstance");
jrosebe2db602010-09-08 18:40:34 -07002728 Lookup lookup = MethodHandles.lookup();
jroseb4be0262011-07-16 15:44:33 -07002729 // test typical case: Runnable.run
jrosebe2db602010-09-08 18:40:34 -07002730 {
jroseb4be0262011-07-16 15:44:33 -07002731 countTest();
2732 if (verbosity >= 2) System.out.println("Runnable");
jrosebe2db602010-09-08 18:40:34 -07002733 MethodType mt = MethodType.methodType(void.class);
2734 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
jrose9b82ad62011-05-26 17:37:36 -07002735 Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002736 proxy.run();
2737 assertCalled("runForRunnable");
2738 }
jroseb4be0262011-07-16 15:44:33 -07002739 // well known single-name overloaded interface: Appendable.append
jrosebe2db602010-09-08 18:40:34 -07002740 {
jroseb4be0262011-07-16 15:44:33 -07002741 countTest();
2742 if (verbosity >= 2) System.out.println("Appendable");
jrose49494522012-01-18 17:34:29 -08002743 ArrayList<List<?>> appendResults = new ArrayList<>();
jroseb4be0262011-07-16 15:44:33 -07002744 MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
2745 append = append.asType(MethodType.methodType(void.class, List.class)); // specialize the type
2746 MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
2747 MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
2748 Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
2749 proxy.append("one");
2750 proxy.append("two", 3, 4);
2751 proxy.append('5');
2752 assertEquals(Arrays.asList(Arrays.asList("one"),
2753 Arrays.asList("two", 3, 4),
2754 Arrays.asList('5')),
2755 appendResults);
2756 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
2757 appendResults.clear();
2758 Formatter formatter = new Formatter(proxy);
2759 String fmt = "foo str=%s char='%c' num=%d";
2760 Object[] fmtArgs = { "str!", 'C', 42 };
2761 String expect = String.format(fmt, fmtArgs);
2762 formatter.format(fmt, fmtArgs);
2763 String actual = "";
2764 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
jrose49494522012-01-18 17:34:29 -08002765 for (List<?> l : appendResults) {
jroseb4be0262011-07-16 15:44:33 -07002766 Object x = l.get(0);
2767 switch (l.size()) {
2768 case 1: actual += x; continue;
jrose49494522012-01-18 17:34:29 -08002769 case 3: actual += ((String)x).substring((int)(Object)l.get(1), (int)(Object)l.get(2)); continue;
jroseb4be0262011-07-16 15:44:33 -07002770 }
2771 actual += l;
2772 }
2773 if (verbosity >= 3) System.out.println("expect="+expect);
2774 if (verbosity >= 3) System.out.println("actual="+actual);
2775 assertEquals(expect, actual);
jrosebe2db602010-09-08 18:40:34 -07002776 }
jroseb4be0262011-07-16 15:44:33 -07002777 // test case of an single name which is overloaded: Fooable.foo(...)
2778 {
2779 if (verbosity >= 2) System.out.println("Fooable");
2780 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable",
2781 MethodType.methodType(Object.class, String.class, Object[].class));
2782 Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
2783 for (Method m : Fooable.class.getDeclaredMethods()) {
2784 countTest();
2785 assertSame("foo", m.getName());
2786 if (verbosity > 3)
2787 System.out.println("calling "+m);
2788 MethodHandle invoker = lookup.unreflect(m);
2789 MethodType mt = invoker.type();
2790 Class<?>[] types = mt.parameterArray();
2791 types[0] = int.class; // placeholder
2792 Object[] args = randomArgs(types);
2793 args[0] = proxy;
2794 if (verbosity > 3)
2795 System.out.println("calling "+m+" on "+Arrays.asList(args));
2796 Object result = invoker.invokeWithArguments(args);
2797 if (verbosity > 4)
2798 System.out.println("result = "+result);
2799 String name = "fooForFooable/"+args[1];
2800 Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
2801 assertCalled(name, argTail);
2802 assertEquals(result, logEntry(name, argTail));
2803 }
2804 }
2805 // test processing of thrown exceptions:
jrosebe2db602010-09-08 18:40:34 -07002806 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2807 new InternalError("ok"),
2808 new Throwable("fail"),
2809 new Exception("fail"),
2810 new MyCheckedException()
2811 }) {
2812 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2813 mh = MethodHandles.insertArguments(mh, 0, ex);
jrose9b82ad62011-05-26 17:37:36 -07002814 WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002815 try {
jroseb4be0262011-07-16 15:44:33 -07002816 countTest();
jrosebe2db602010-09-08 18:40:34 -07002817 proxy.willThrow();
2818 System.out.println("Failed to throw: "+ex);
2819 assertTrue(false);
2820 } catch (Throwable ex1) {
jroseb4be0262011-07-16 15:44:33 -07002821 if (verbosity > 3) {
jrosebe2db602010-09-08 18:40:34 -07002822 System.out.println("throw "+ex);
2823 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2824 }
2825 if (ex instanceof RuntimeException ||
2826 ex instanceof Error) {
2827 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2828 } else if (ex instanceof MyCheckedException) {
2829 assertSame("must pass declared exception out without wrapping", ex, ex1);
2830 } else {
2831 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
jroseaf751942011-06-14 22:47:12 -07002832 if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
twisti10d37ec2012-07-24 10:47:44 -07002833 ex1.printStackTrace(System.out);
jroseaf751942011-06-14 22:47:12 -07002834 }
2835 assertSame(ex, ex1.getCause());
jrosebe2db602010-09-08 18:40:34 -07002836 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
jrosebe2db602010-09-08 18:40:34 -07002837 }
2838 }
2839 }
jroseb4be0262011-07-16 15:44:33 -07002840 // Test error checking on bad interfaces:
jrose49494522012-01-18 17:34:29 -08002841 for (Class<?> nonSMI : new Class<?>[] { Object.class,
jrosebe2db602010-09-08 18:40:34 -07002842 String.class,
2843 CharSequence.class,
jroseb4be0262011-07-16 15:44:33 -07002844 java.io.Serializable.class,
2845 PrivateRunnable.class,
jrosebe2db602010-09-08 18:40:34 -07002846 Example.class }) {
jroseb4be0262011-07-16 15:44:33 -07002847 if (verbosity > 2) System.out.println(nonSMI.getName());
jrosebe2db602010-09-08 18:40:34 -07002848 try {
jroseb4be0262011-07-16 15:44:33 -07002849 countTest(false);
2850 MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
2851 assertTrue("Failed to throw on "+nonSMI.getName(), false);
jrosebe2db602010-09-08 18:40:34 -07002852 } catch (IllegalArgumentException ex) {
jroseb4be0262011-07-16 15:44:33 -07002853 if (verbosity > 2) System.out.println(nonSMI.getSimpleName()+": "+ex);
2854 // Object: java.lang.IllegalArgumentException:
2855 // not a public interface: java.lang.Object
2856 // String: java.lang.IllegalArgumentException:
2857 // not a public interface: java.lang.String
2858 // CharSequence: java.lang.IllegalArgumentException:
2859 // not a single-method interface: java.lang.CharSequence
2860 // Serializable: java.lang.IllegalArgumentException:
2861 // not a single-method interface: java.io.Serializable
2862 // PrivateRunnable: java.lang.IllegalArgumentException:
2863 // not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
2864 // Example: java.lang.IllegalArgumentException:
2865 // not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
2866 }
2867 }
2868 // Test error checking on interfaces with the wrong method type:
jrose49494522012-01-18 17:34:29 -08002869 for (Class<?> intfc : new Class<?>[] { Runnable.class /*arity 0*/,
jroseb4be0262011-07-16 15:44:33 -07002870 Fooable.class /*arity 1 & 2*/ }) {
2871 int badArity = 1; // known to be incompatible
2872 if (verbosity > 2) System.out.println(intfc.getName());
2873 try {
2874 countTest(false);
2875 MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
2876 assertTrue("Failed to throw on "+intfc.getName(), false);
2877 } catch (WrongMethodTypeException ex) {
2878 if (verbosity > 2) System.out.println(intfc.getSimpleName()+": "+ex);
2879 // Runnable: java.lang.invoke.WrongMethodTypeException:
2880 // cannot convert MethodHandle(Object)Object[] to ()void
2881 // Fooable: java.lang.invoke.WrongMethodTypeException:
2882 // cannot convert MethodHandle(Object)Object[] to (Object,String)Object
jrosebe2db602010-09-08 18:40:34 -07002883 }
2884 }
2885 }
jrose43b8c122011-07-16 15:40:13 -07002886
2887 @Test
2888 public void testRunnableProxy() throws Throwable {
2889 if (CAN_SKIP_WORKING) return;
2890 startTest("testRunnableProxy");
2891 MethodHandles.Lookup lookup = MethodHandles.lookup();
2892 MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
2893 Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
2894 testRunnableProxy(r);
2895 assertCalled("runForRunnable");
2896 }
2897 private static void testRunnableProxy(Runnable r) {
2898 //7058630: JSR 292 method handle proxy violates contract for Object methods
2899 r.run();
2900 Object o = r;
2901 r = null;
2902 boolean eq = (o == o);
2903 int hc = System.identityHashCode(o);
2904 String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
2905 Object expect = Arrays.asList(st, eq, hc);
2906 if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
2907 Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
2908 if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
2909 assertEquals(expect, actual);
2910 }
jrose55220c32009-10-21 23:19:48 -07002911}
jroseada69fa2011-03-23 23:02:31 -07002912// Local abbreviated copy of sun.invoke.util.ValueConversions
twisti10d37ec2012-07-24 10:47:44 -07002913// This guy tests access from outside the same package member, but inside
2914// the package itself.
jrose55220c32009-10-21 23:19:48 -07002915class ValueConversions {
2916 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2917 private static final Object[] NO_ARGS_ARRAY = {};
2918 private static Object[] makeArray(Object... args) { return args; }
2919 private static Object[] array() { return NO_ARGS_ARRAY; }
2920 private static Object[] array(Object a0)
2921 { return makeArray(a0); }
2922 private static Object[] array(Object a0, Object a1)
2923 { return makeArray(a0, a1); }
2924 private static Object[] array(Object a0, Object a1, Object a2)
2925 { return makeArray(a0, a1, a2); }
2926 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2927 { return makeArray(a0, a1, a2, a3); }
2928 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2929 Object a4)
2930 { return makeArray(a0, a1, a2, a3, a4); }
2931 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2932 Object a4, Object a5)
2933 { return makeArray(a0, a1, a2, a3, a4, a5); }
2934 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2935 Object a4, Object a5, Object a6)
2936 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2937 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2938 Object a4, Object a5, Object a6, Object a7)
2939 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2940 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2941 Object a4, Object a5, Object a6, Object a7,
2942 Object a8)
2943 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2944 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2945 Object a4, Object a5, Object a6, Object a7,
2946 Object a8, Object a9)
2947 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2948 static MethodHandle[] makeArrays() {
jrose49494522012-01-18 17:34:29 -08002949 ArrayList<MethodHandle> arrays = new ArrayList<>();
jrose55220c32009-10-21 23:19:48 -07002950 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2951 for (;;) {
2952 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002953 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002954 String name = "array";
2955 MethodHandle array = null;
2956 try {
2957 array = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002958 } catch (ReflectiveOperationException ex) {
2959 // break from loop!
jrose55220c32009-10-21 23:19:48 -07002960 }
2961 if (array == null) break;
2962 arrays.add(array);
2963 }
jrosef15905c2011-02-11 01:26:32 -08002964 assertTrue(arrays.size() == 11); // current number of methods
jrose55220c32009-10-21 23:19:48 -07002965 return arrays.toArray(new MethodHandle[0]);
2966 }
2967 static final MethodHandle[] ARRAYS = makeArrays();
2968
2969 /** Return a method handle that takes the indicated number of Object
2970 * arguments and returns an Object array of them, as if for varargs.
2971 */
2972 public static MethodHandle varargsArray(int nargs) {
2973 if (nargs < ARRAYS.length)
2974 return ARRAYS[nargs];
jroseaf751942011-06-14 22:47:12 -07002975 return MethodHandles.identity(Object[].class).asCollector(Object[].class, nargs);
jrose55220c32009-10-21 23:19:48 -07002976 }
jrose320b7692011-05-12 19:27:49 -07002977 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
2978 Class<?> elemType = arrayType.getComponentType();
2979 MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
2980 MethodHandle mh = varargsArray(nargs);
2981 if (arrayType != Object[].class)
2982 mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
2983 return mh.asType(vaType);
2984 }
2985 static Object changeArrayType(Class<?> arrayType, Object[] a) {
2986 Class<?> elemType = arrayType.getComponentType();
2987 if (!elemType.isPrimitive())
2988 return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
2989 Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
2990 for (int i = 0; i < a.length; i++)
2991 java.lang.reflect.Array.set(b, i, a[i]);
2992 return b;
2993 }
2994 private static final MethodHandle CHANGE_ARRAY_TYPE;
2995 static {
2996 try {
2997 CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
2998 MethodType.methodType(Object.class, Class.class, Object[].class));
2999 } catch (NoSuchMethodException | IllegalAccessException ex) {
3000 Error err = new InternalError("uncaught exception");
3001 err.initCause(ex);
3002 throw err;
3003 }
3004 }
jrose10f3b682010-01-07 16:16:45 -08003005
3006 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
3007 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
3008 private static List<Object> list() { return NO_ARGS_LIST; }
3009 private static List<Object> list(Object a0)
3010 { return makeList(a0); }
3011 private static List<Object> list(Object a0, Object a1)
3012 { return makeList(a0, a1); }
3013 private static List<Object> list(Object a0, Object a1, Object a2)
3014 { return makeList(a0, a1, a2); }
3015 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
3016 { return makeList(a0, a1, a2, a3); }
3017 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
3018 Object a4)
3019 { return makeList(a0, a1, a2, a3, a4); }
3020 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
3021 Object a4, Object a5)
3022 { return makeList(a0, a1, a2, a3, a4, a5); }
3023 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
3024 Object a4, Object a5, Object a6)
3025 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
3026 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
3027 Object a4, Object a5, Object a6, Object a7)
3028 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
3029 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
3030 Object a4, Object a5, Object a6, Object a7,
3031 Object a8)
3032 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
3033 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
3034 Object a4, Object a5, Object a6, Object a7,
3035 Object a8, Object a9)
3036 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
3037 static MethodHandle[] makeLists() {
jrose49494522012-01-18 17:34:29 -08003038 ArrayList<MethodHandle> lists = new ArrayList<>();
jrose10f3b682010-01-07 16:16:45 -08003039 MethodHandles.Lookup lookup = IMPL_LOOKUP;
3040 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08003041 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08003042 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
3043 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08003044 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08003045 try {
jroseadc650a2011-02-11 01:26:28 -08003046 list = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08003047 } catch (ReflectiveOperationException ex) {
3048 // break from loop!
jrose10f3b682010-01-07 16:16:45 -08003049 }
jroseadc650a2011-02-11 01:26:28 -08003050 if (list == null) break;
3051 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08003052 }
jrosef15905c2011-02-11 01:26:32 -08003053 assertTrue(lists.size() == 11); // current number of methods
jroseadc650a2011-02-11 01:26:28 -08003054 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08003055 }
3056 static final MethodHandle[] LISTS = makeLists();
jroseaf751942011-06-14 22:47:12 -07003057 static final MethodHandle AS_LIST;
3058 static {
3059 try {
3060 AS_LIST = IMPL_LOOKUP.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
jrose49494522012-01-18 17:34:29 -08003061 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseaf751942011-06-14 22:47:12 -07003062 }
jrose10f3b682010-01-07 16:16:45 -08003063
3064 /** Return a method handle that takes the indicated number of Object
3065 * arguments and returns List.
3066 */
3067 public static MethodHandle varargsList(int nargs) {
3068 if (nargs < LISTS.length)
3069 return LISTS[nargs];
jroseaf751942011-06-14 22:47:12 -07003070 return AS_LIST.asCollector(Object[].class, nargs);
jrose10f3b682010-01-07 16:16:45 -08003071 }
jrose55220c32009-10-21 23:19:48 -07003072}
3073// This guy tests access from outside the same package member, but inside
3074// the package itself.
3075class PackageSibling {
3076 static Lookup lookup() {
3077 return MethodHandles.lookup();
3078 }
3079}