blob: 7f04ee07550c41bdc000af8c49f2ebcb04108f6a [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
jrosef108fc02011-02-11 01:26:24 -08002 * Copyright (c) 2009, 2011, 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
jrose9633f5f2011-04-07 22:07:06 -070028 * @compile -source 7 -target 7 MethodHandlesTest.java
29 * @run junit/othervm 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
jroseada69fa2011-03-23 23:02:31 -070034import java.lang.invoke.*;
35import java.lang.invoke.MethodHandles.Lookup;
jrose55220c32009-10-21 23:19:48 -070036import java.lang.reflect.*;
37import java.util.*;
38import org.junit.*;
39import static org.junit.Assert.*;
jrose55220c32009-10-21 23:19:48 -070040
41
42/**
43 *
44 * @author jrose
45 */
46public class MethodHandlesTest {
jroseb4be0262011-07-16 15:44:33 -070047 static final Class<?> THIS_CLASS = MethodHandlesTest.class;
jrose55220c32009-10-21 23:19:48 -070048 // How much output?
jrose2cc9c832010-04-30 23:48:23 -070049 static int verbosity = 0;
jrosecf98d422010-06-08 23:08:56 -070050 static {
jroseb4be0262011-07-16 15:44:33 -070051 String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".verbosity");
52 if (vstr == null)
53 vstr = System.getProperty(THIS_CLASS.getName()+".verbosity");
jrosecf98d422010-06-08 23:08:56 -070054 if (vstr != null) verbosity = Integer.parseInt(vstr);
55 }
jrose55220c32009-10-21 23:19:48 -070056
57 // Set this true during development if you want to fast-forward to
58 // a particular new, non-working test. Tests which are known to
59 // work (or have recently worked) test this flag and return on true.
60 static boolean CAN_SKIP_WORKING = false;
61 //static { CAN_SKIP_WORKING = true; }
62
jroseb4be0262011-07-16 15:44:33 -070063 // Set 'true' to do about 15x fewer tests, especially those redundant with RicochetTest.
64 // This might be useful with -Xcomp stress tests that compile all method handles.
65 static boolean CAN_TEST_LIGHTLY = Boolean.getBoolean(THIS_CLASS.getName()+".CAN_TEST_LIGHTLY");
jrose55220c32009-10-21 23:19:48 -070066
jrose55220c32009-10-21 23:19:48 -070067 @Test
68 public void testFirst() throws Throwable {
69 verbosity += 9; try {
70 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070071 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070072 }
73
jrose10f3b682010-01-07 16:16:45 -080074 // current failures
jroseb4be0262011-07-16 15:44:33 -070075 @Test //@Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
jrose10f3b682010-01-07 16:16:45 -080076 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070077 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080078 testSpreadArguments(int.class, 0, 6);
79 }
jroseb4be0262011-07-16 15:44:33 -070080 @Test //@Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080081 public void testFail_2() throws Throwable {
82 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
83 testSpreadArguments(Object.class, 0, 2);
84 }
jroseb4be0262011-07-16 15:44:33 -070085 @Test //@Ignore("IllArgEx failure in call to ToGeneric.make")
jrose10f3b682010-01-07 16:16:45 -080086 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070087 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080088 testSpreadArguments(int.class, 1, 2);
89 }
jroseb4be0262011-07-16 15:44:33 -070090 @Test //@Ignore("IllArgEx failure in call to ToGeneric.make")
jrose10f3b682010-01-07 16:16:45 -080091 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070092 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080093 testCollectArguments(int.class, 1, 2);
94 }
jroseb4be0262011-07-16 15:44:33 -070095 @Test //@Ignore("cannot collect leading primitive types")
jrose10f3b682010-01-07 16:16:45 -080096 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070097 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080098 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
99 }
jroseb4be0262011-07-16 15:44:33 -0700100 @Test //@Ignore("should not insert arguments beyond MethodHandlePushLimit")
jrose10f3b682010-01-07 16:16:45 -0800101 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700102 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
103 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -0800104 }
jroseb4be0262011-07-16 15:44:33 -0700105 @Test //@Ignore("permuteArguments has trouble with double slots")
jrose9b82ad62011-05-26 17:37:36 -0700106 public void testFail_7() throws Throwable {
107 testPermuteArguments(new Object[]{10, 200L},
108 new Class<?>[]{Integer.class, long.class},
109 new int[]{1,0});
110 testPermuteArguments(new Object[]{10, 200L, 5000L},
111 new Class<?>[]{Integer.class, long.class, long.class},
112 new int[]{2,0,1}); //rot
113 testPermuteArguments(new Object[]{10, 200L, 5000L},
114 new Class<?>[]{Integer.class, long.class, long.class},
115 new int[]{1,2,0}); //rot
116 testPermuteArguments(new Object[]{10, 200L, 5000L},
117 new Class<?>[]{Integer.class, long.class, long.class},
118 new int[]{2,1,0}); //swap
119 testPermuteArguments(new Object[]{10, 200L, 5000L},
120 new Class<?>[]{Integer.class, long.class, long.class},
121 new int[]{0,1,2,2}); //dup
122 testPermuteArguments(new Object[]{10, 200L, 5000L},
123 new Class<?>[]{Integer.class, long.class, long.class},
124 new int[]{2,0,1,2});
125 testPermuteArguments(new Object[]{10, 200L, 5000L},
126 new Class<?>[]{Integer.class, long.class, long.class},
127 new int[]{2,2,0,1});
jroseb4be0262011-07-16 15:44:33 -0700128 //testPermuteArguments(4, Integer.class, 2, long.class, 6);
jrose9b82ad62011-05-26 17:37:36 -0700129 }
jrose55220c32009-10-21 23:19:48 -0700130 static final int MAX_ARG_INCREASE = 3;
131
132 public MethodHandlesTest() {
133 }
134
jrose55220c32009-10-21 23:19:48 -0700135 String testName;
jrosecf98d422010-06-08 23:08:56 -0700136 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -0700137 int posTests, negTests;
138 @After
139 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700140 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700141 System.out.println();
142 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
143 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -0700144 allPosTests += posTests;
145 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -0700146 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700147 }
148 }
149 void countTest(boolean positive) {
150 if (positive) ++posTests;
151 else ++negTests;
152 }
153 void countTest() { countTest(true); }
154 void startTest(String name) {
155 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700156 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700157 System.out.println(name);
158 posTests = negTests = 0;
159 testName = name;
160 }
161
162 @BeforeClass
163 public static void setUpClass() throws Exception {
164 calledLog.clear();
165 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700166 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700167 }
168
169 @AfterClass
170 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700171 int posTests = allPosTests, negTests = allNegTests;
jroseb4be0262011-07-16 15:44:33 -0700172 if (verbosity >= 0 && (posTests | negTests) != 0) {
jrosecf98d422010-06-08 23:08:56 -0700173 System.out.println();
174 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
175 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
176 }
jrose55220c32009-10-21 23:19:48 -0700177 }
178
jrose49494522012-01-18 17:34:29 -0800179 static List<Object> calledLog = new ArrayList<>();
jrose55220c32009-10-21 23:19:48 -0700180 static Object logEntry(String name, Object... args) {
181 return Arrays.asList(name, Arrays.asList(args));
182 }
183 static Object called(String name, Object... args) {
184 Object entry = logEntry(name, args);
185 calledLog.add(entry);
186 return entry;
187 }
188 static void assertCalled(String name, Object... args) {
189 Object expected = logEntry(name, args);
190 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700191 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700192 System.out.println("assertCalled "+name+":");
193 System.out.println("expected: "+expected);
194 System.out.println("actual: "+actual);
195 System.out.println("ex. types: "+getClasses(expected));
196 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700197 assertEquals("previous method call", expected, actual);
198 }
199 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700200 if (verbosity >= 3)
201 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700202 }
203
204 static Object castToWrapper(Object value, Class<?> dst) {
205 Object wrap = null;
206 if (value instanceof Number)
207 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
208 if (value instanceof Character)
209 wrap = castToWrapperOrNull((char)(Character)value, dst);
210 if (wrap != null) return wrap;
211 return dst.cast(value);
212 }
213
jrose49494522012-01-18 17:34:29 -0800214 @SuppressWarnings("cast") // primitive cast to (long) is part of the pattern
jrose55220c32009-10-21 23:19:48 -0700215 static Object castToWrapperOrNull(long value, Class<?> dst) {
216 if (dst == int.class || dst == Integer.class)
217 return (int)(value);
218 if (dst == long.class || dst == Long.class)
219 return (long)(value);
220 if (dst == char.class || dst == Character.class)
221 return (char)(value);
222 if (dst == short.class || dst == Short.class)
223 return (short)(value);
224 if (dst == float.class || dst == Float.class)
225 return (float)(value);
226 if (dst == double.class || dst == Double.class)
227 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800228 if (dst == byte.class || dst == Byte.class)
229 return (byte)(value);
230 if (dst == boolean.class || dst == boolean.class)
231 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700232 return null;
233 }
234
jrose2cc9c832010-04-30 23:48:23 -0700235 static final int ONE_MILLION = (1000*1000), // first int value
236 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
237 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
238 static long nextArgVal;
239 static long nextArg(boolean moreBits) {
240 long val = nextArgVal++;
241 long sign = -(val & 1); // alternate signs
242 val >>= 1;
243 if (moreBits)
244 // Guarantee some bits in the high word.
245 // In any case keep the decimal representation simple-looking,
246 // with lots of zeroes, so as not to make the printed decimal
247 // strings unnecessarily noisy.
248 val += (val % ONE_MILLION) * TEN_BILLION;
249 return val ^ sign;
250 }
251 static int nextArg() {
252 // Produce a 32-bit result something like ONE_MILLION+(smallint).
253 // Example: 1_000_042.
254 return (int) nextArg(false);
255 }
256 static long nextArg(Class<?> kind) {
257 if (kind == long.class || kind == Long.class ||
258 kind == double.class || kind == Double.class)
259 // produce a 64-bit result something like
260 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
261 // Example: 10_000_420_001_000_042.
262 return nextArg(true);
263 return (long) nextArg();
264 }
265
jrose55220c32009-10-21 23:19:48 -0700266 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700267 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700268 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700269 return wrap;
270 }
jroseada69fa2011-03-23 23:02:31 -0700271// import sun.invoke.util.Wrapper;
jrose55220c32009-10-21 23:19:48 -0700272// Wrapper wrap = Wrapper.forBasicType(dst);
273// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
274// wrap = Wrapper.forWrapperType(dst);
275// if (wrap != Wrapper.OBJECT)
276// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700277 if (param.isInterface()) {
278 for (Class<?> c : param.getClasses()) {
279 if (param.isAssignableFrom(c) && !c.isInterface())
280 { param = c; break; }
281 }
282 }
jrose55220c32009-10-21 23:19:48 -0700283 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700284 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700285 else
286 try {
287 return param.newInstance();
jrose49494522012-01-18 17:34:29 -0800288 } catch (InstantiationException | IllegalAccessException ex) {
jrose55220c32009-10-21 23:19:48 -0700289 }
290 return null; // random class not Object, String, Integer, etc.
291 }
292 static Object[] randomArgs(Class<?>... params) {
293 Object[] args = new Object[params.length];
294 for (int i = 0; i < args.length; i++)
295 args[i] = randomArg(params[i]);
296 return args;
297 }
298 static Object[] randomArgs(int nargs, Class<?> param) {
299 Object[] args = new Object[nargs];
300 for (int i = 0; i < args.length; i++)
301 args[i] = randomArg(param);
302 return args;
303 }
304
jrose49494522012-01-18 17:34:29 -0800305 @SafeVarargs @SuppressWarnings("varargs")
jrose55220c32009-10-21 23:19:48 -0700306 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
307 return Arrays.copyOf(a, a.length, atype);
308 }
jrose49494522012-01-18 17:34:29 -0800309 @SafeVarargs @SuppressWarnings("varargs")
jrose55220c32009-10-21 23:19:48 -0700310 static <T> T[] cat(T[] a, T... b) {
311 int alen = a.length, blen = b.length;
312 if (blen == 0) return a;
313 T[] c = Arrays.copyOf(a, alen + blen);
314 System.arraycopy(b, 0, c, alen, blen);
315 return c;
316 }
317 static Integer[] boxAll(int... vx) {
318 Integer[] res = new Integer[vx.length];
319 for (int i = 0; i < res.length; i++) {
320 res[i] = vx[i];
321 }
322 return res;
323 }
324 static Object getClasses(Object x) {
325 if (x == null) return x;
326 if (x instanceof String) return x; // keep the name
327 if (x instanceof List) {
328 // recursively report classes of the list elements
329 Object[] xa = ((List)x).toArray();
330 for (int i = 0; i < xa.length; i++)
331 xa[i] = getClasses(xa[i]);
332 return Arrays.asList(xa);
333 }
334 return x.getClass().getSimpleName();
335 }
336
jroseadc650a2011-02-11 01:26:28 -0800337 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
338 static MethodHandle varargsList(int arity) {
339 return ValueConversions.varargsList(arity);
340 }
341 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
342 static MethodHandle varargsArray(int arity) {
343 return ValueConversions.varargsArray(arity);
344 }
jrose320b7692011-05-12 19:27:49 -0700345 static MethodHandle varargsArray(Class<?> arrayType, int arity) {
346 return ValueConversions.varargsArray(arrayType, arity);
347 }
jroseadc650a2011-02-11 01:26:28 -0800348 /** Variation of varargsList, but with the given rtype. */
349 static MethodHandle varargsList(int arity, Class<?> rtype) {
350 MethodHandle list = varargsList(arity);
351 MethodType listType = list.type().changeReturnType(rtype);
352 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
353 // OK
354 } else if (rtype.isAssignableFrom(String.class)) {
355 if (LIST_TO_STRING == null)
356 try {
357 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
358 MethodType.methodType(String.class, List.class));
jrose49494522012-01-18 17:34:29 -0800359 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseadc650a2011-02-11 01:26:28 -0800360 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
361 } else if (rtype.isPrimitive()) {
362 if (LIST_TO_INT == null)
363 try {
364 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
365 MethodType.methodType(int.class, List.class));
jrose49494522012-01-18 17:34:29 -0800366 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseadc650a2011-02-11 01:26:28 -0800367 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
368 list = MethodHandles.explicitCastArguments(list, listType);
369 } else {
370 throw new RuntimeException("varargsList: "+rtype);
371 }
372 return list.asType(listType);
373 }
374 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
jrose49494522012-01-18 17:34:29 -0800375 private static String listToString(List<?> x) { return x.toString(); }
376 private static int listToInt(List<?> x) { return x.toString().hashCode(); }
jroseadc650a2011-02-11 01:26:28 -0800377
jrose55220c32009-10-21 23:19:48 -0700378 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
379 return changeArgTypes(target, 0, 999, argType);
380 }
381 static MethodHandle changeArgTypes(MethodHandle target,
382 int beg, int end, Class<?> argType) {
383 MethodType targetType = target.type();
384 end = Math.min(end, targetType.parameterCount());
jrose49494522012-01-18 17:34:29 -0800385 ArrayList<Class<?>> argTypes = new ArrayList<>(targetType.parameterList());
jrose55220c32009-10-21 23:19:48 -0700386 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800387 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose9b82ad62011-05-26 17:37:36 -0700388 return target.asType(ttype2);
jrose55220c32009-10-21 23:19:48 -0700389 }
jroseb4be0262011-07-16 15:44:33 -0700390 static MethodHandle addTrailingArgs(MethodHandle target, int nargs, Class<?> argClass) {
391 int targetLen = target.type().parameterCount();
392 int extra = (nargs - targetLen);
393 if (extra <= 0) return target;
394 List<Class<?>> fakeArgs = Collections.<Class<?>>nCopies(extra, argClass);
395 return MethodHandles.dropArguments(target, targetLen, fakeArgs);
396 }
jrose55220c32009-10-21 23:19:48 -0700397
398 // This lookup is good for all members in and under MethodHandlesTest.
399 static final Lookup PRIVATE = MethodHandles.lookup();
400 // This lookup is good for package-private members but not private ones.
401 static final Lookup PACKAGE = PackageSibling.lookup();
402 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800403 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700404
405 // Subject methods...
406 static class Example implements IntExample {
407 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700408 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700409 protected Example(String name) { this.name = name; }
jrose49494522012-01-18 17:34:29 -0800410 @SuppressWarnings("LeakingThisInConstructor")
jrose55220c32009-10-21 23:19:48 -0700411 protected Example(int x) { this(); called("protected <init>", this, x); }
412 @Override public String toString() { return name; }
413
414 public void v0() { called("v0", this); }
415 void pkg_v0() { called("pkg_v0", this); }
416 private void pri_v0() { called("pri_v0", this); }
417 public static void s0() { called("s0"); }
418 static void pkg_s0() { called("pkg_s0"); }
419 private static void pri_s0() { called("pri_s0"); }
420
421 public Object v1(Object x) { return called("v1", this, x); }
422 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
423 public Object v2(Object x, int y) { return called("v2", this, x, y); }
424 public Object v2(int x, Object y) { return called("v2", this, x, y); }
425 public Object v2(int x, int y) { return called("v2", this, x, y); }
426 public static Object s1(Object x) { return called("s1", x); }
427 public static Object s2(int x) { return called("s2", x); }
428 public static Object s3(long x) { return called("s3", x); }
429 public static Object s4(int x, int y) { return called("s4", x, y); }
430 public static Object s5(long x, int y) { return called("s5", x, y); }
431 public static Object s6(int x, long y) { return called("s6", x, y); }
432 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700433
jroseb4be0262011-07-16 15:44:33 -0700434 // for testing findConstructor:
435 public Example(String x, int y) { this.name = x+y; called("Example.<init>", x, y); }
436 public Example(int x, String y) { this.name = x+y; called("Example.<init>", x, y); }
437
jrose2cc9c832010-04-30 23:48:23 -0700438 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700439 }
jrose2cc9c832010-04-30 23:48:23 -0700440 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700441 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700442 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700443 }
444 static class SubExample extends Example {
445 @Override public void v0() { called("Sub/v0", this); }
446 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
jrose49494522012-01-18 17:34:29 -0800447 @SuppressWarnings("LeakingThisInConstructor")
jrose55220c32009-10-21 23:19:48 -0700448 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700449 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700450 }
451 public static interface IntExample {
452 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700453 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700454 public void v0() { called("Int/v0", this); }
455 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700456 public Impl() { name = "Impl#"+nextArg(); }
457 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700458 }
459 }
460
461 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700462 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
463 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
464 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
465 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700466 };
467
jrose2cc9c832010-04-30 23:48:23 -0700468 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
469 Object[][] cases;
470 if (name.contains("pri_") || isSpecial) {
471 cases = ACCESS_CASES[1]; // PRIVATE only
472 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
473 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800474 } else {
475 assertTrue(name.indexOf('_') < 0);
476 boolean pubc = Modifier.isPublic(defc.getModifiers());
477 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700478 cases = ACCESS_CASES[3]; // all access levels
479 else
480 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800481 }
jrose2cc9c832010-04-30 23:48:23 -0700482 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
483 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
484 return cases;
485 }
486 static Object[][] accessCases(Class<?> defc, String name) {
487 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700488 }
489
490 @Test
491 public void testFindStatic() throws Throwable {
492 if (CAN_SKIP_WORKING) return;
493 startTest("findStatic");
494 testFindStatic(PubExample.class, void.class, "s0");
495 testFindStatic(Example.class, void.class, "s0");
496 testFindStatic(Example.class, void.class, "pkg_s0");
497 testFindStatic(Example.class, void.class, "pri_s0");
498
499 testFindStatic(Example.class, Object.class, "s1", Object.class);
500 testFindStatic(Example.class, Object.class, "s2", int.class);
501 testFindStatic(Example.class, Object.class, "s3", long.class);
502 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
503 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
504 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
505 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
506
507 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
508 }
509
510 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
511 for (Object[] ac : accessCases(defc, name)) {
512 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
513 }
514 }
515 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
516 testFindStatic(true, lookup, defc, ret, name, params);
517 }
518 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
519 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800520 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700521 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700522 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700523 try {
jrose2cc9c832010-04-30 23:48:23 -0700524 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700525 target = lookup.in(defc).findStatic(defc, name, type);
jrosef15905c2011-02-11 01:26:32 -0800526 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700527 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800528 if (name.contains("bogus"))
529 assertTrue(noAccess instanceof NoSuchMethodException);
530 else
531 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700532 }
jrose2cc9c832010-04-30 23:48:23 -0700533 if (verbosity >= 3)
534 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700535 +(noAccess == null ? "" : " !! "+noAccess));
536 if (positive && noAccess != null) throw noAccess;
537 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
538 if (!positive) return; // negative test failed as expected
539 assertEquals(type, target.type());
jrose900bafd2010-10-30 21:08:23 -0700540 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700541 Object[] args = randomArgs(params);
542 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700543 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700544 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700545 if (verbosity >= 1)
546 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700547 }
548
jrose73016262011-05-17 19:48:19 -0700549 static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
550
jrose900bafd2010-10-30 21:08:23 -0700551 // rough check of name string
jrose73016262011-05-17 19:48:19 -0700552 static void assertNameStringContains(MethodHandle x, String s) {
553 if (!DEBUG_METHOD_HANDLE_NAMES) {
554 // ignore s
555 assertEquals("MethodHandle"+x.type(), x.toString());
556 return;
557 }
jrose900bafd2010-10-30 21:08:23 -0700558 if (x.toString().contains(s)) return;
559 assertEquals(s, x);
560 }
561
jrose55220c32009-10-21 23:19:48 -0700562 @Test
563 public void testFindVirtual() throws Throwable {
564 if (CAN_SKIP_WORKING) return;
565 startTest("findVirtual");
566 testFindVirtual(Example.class, void.class, "v0");
567 testFindVirtual(Example.class, void.class, "pkg_v0");
568 testFindVirtual(Example.class, void.class, "pri_v0");
569 testFindVirtual(Example.class, Object.class, "v1", Object.class);
570 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
571 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
572 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
573 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
574 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
575 // test dispatch
576 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
577 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
578 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
579 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
580 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
581 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
582 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
583 }
584
585 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
586 Class<?> rcvc = defc;
587 testFindVirtual(rcvc, defc, ret, name, params);
588 }
589 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
590 for (Object[] ac : accessCases(defc, name)) {
591 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
592 }
593 }
594 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
595 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
596 }
597 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
598 countTest(positive);
599 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800600 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700601 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700602 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700603 try {
jrose2cc9c832010-04-30 23:48:23 -0700604 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700605 target = lookup.in(defc).findVirtual(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800606 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700607 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800608 if (name.contains("bogus"))
609 assertTrue(noAccess instanceof NoSuchMethodException);
610 else
611 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700612 }
jrose2cc9c832010-04-30 23:48:23 -0700613 if (verbosity >= 3)
614 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700615 +(noAccess == null ? "" : " !! "+noAccess));
616 if (positive && noAccess != null) throw noAccess;
617 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
618 if (!positive) return; // negative test failed as expected
619 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800620 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700621 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700622 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700623 Object[] argsWithSelf = randomArgs(paramsWithSelf);
624 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
625 printCalled(target, name, argsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700626 target.invokeWithArguments(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700627 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700628 if (verbosity >= 1)
629 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700630 }
631
632 @Test
633 public void testFindSpecial() throws Throwable {
634 if (CAN_SKIP_WORKING) return;
635 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700636 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
637 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
638 // Do some negative testing:
jrosef15905c2011-02-11 01:26:32 -0800639 testFindSpecial(false, EXAMPLE, SubExample.class, Example.class, void.class, "bogus");
640 testFindSpecial(false, PRIVATE, SubExample.class, Example.class, void.class, "bogus");
jrose2cc9c832010-04-30 23:48:23 -0700641 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
642 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
643 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
644 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
jrose2cc9c832010-04-30 23:48:23 -0700645 }
jrose55220c32009-10-21 23:19:48 -0700646 }
647
jrose2cc9c832010-04-30 23:48:23 -0700648 void testFindSpecial(Class<?> specialCaller,
649 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
650 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
651 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
652 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
653 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700654 }
jrose2cc9c832010-04-30 23:48:23 -0700655 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
656 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700657 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800658 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700659 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700660 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700661 try {
jrose2cc9c832010-04-30 23:48:23 -0700662 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700663 if (verbosity >= 5) System.out.println(" lookup => "+lookup.in(specialCaller));
664 target = lookup.in(specialCaller).findSpecial(defc, name, type, specialCaller);
jrosef15905c2011-02-11 01:26:32 -0800665 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700666 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800667 if (name.contains("bogus"))
668 assertTrue(noAccess instanceof NoSuchMethodException);
669 else
670 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700671 }
jrose2cc9c832010-04-30 23:48:23 -0700672 if (verbosity >= 3)
673 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
674 +(target == null ? "" : target.type())
675 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700676 if (positive && noAccess != null) throw noAccess;
677 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
678 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700679 assertEquals(specialCaller, target.type().parameterType(0));
680 assertEquals(type, target.type().dropParameterTypes(0,1));
681 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800682 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700683 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700684 Object[] args = randomArgs(paramsWithSelf);
685 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700686 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700687 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700688 }
689
690 @Test
jroseb4be0262011-07-16 15:44:33 -0700691 public void testFindConstructor() throws Throwable {
692 if (CAN_SKIP_WORKING) return;
693 startTest("findConstructor");
694 testFindConstructor(true, EXAMPLE, Example.class);
695 testFindConstructor(true, EXAMPLE, Example.class, int.class);
696 testFindConstructor(true, EXAMPLE, Example.class, String.class);
697 }
698 void testFindConstructor(boolean positive, Lookup lookup,
699 Class<?> defc, Class<?>... params) throws Throwable {
700 countTest(positive);
701 MethodType type = MethodType.methodType(void.class, params);
702 MethodHandle target = null;
703 Exception noAccess = null;
704 try {
705 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" <init>"+type);
706 target = lookup.findConstructor(defc, type);
707 } catch (ReflectiveOperationException ex) {
708 noAccess = ex;
709 assertTrue(noAccess instanceof IllegalAccessException);
710 }
711 if (verbosity >= 3)
712 System.out.println("findConstructor "+defc.getName()+".<init>/"+type+" => "+target
713 +(target == null ? "" : target.type())
714 +(noAccess == null ? "" : " !! "+noAccess));
715 if (positive && noAccess != null) throw noAccess;
716 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
717 if (!positive) return; // negative test failed as expected
718 assertEquals(type.changeReturnType(defc), target.type());
719 Object[] args = randomArgs(params);
720 printCalled(target, defc.getSimpleName(), args);
721 Object obj = target.invokeWithArguments(args);
722 if (!(defc == Example.class && params.length < 2))
723 assertCalled(defc.getSimpleName()+".<init>", args);
724 assertTrue("instance of "+defc.getName(), defc.isInstance(obj));
725 }
726
727 @Test
jrose55220c32009-10-21 23:19:48 -0700728 public void testBind() throws Throwable {
729 if (CAN_SKIP_WORKING) return;
730 startTest("bind");
731 testBind(Example.class, void.class, "v0");
732 testBind(Example.class, void.class, "pkg_v0");
733 testBind(Example.class, void.class, "pri_v0");
734 testBind(Example.class, Object.class, "v1", Object.class);
735 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
736 testBind(Example.class, Object.class, "v2", Object.class, int.class);
737 testBind(Example.class, Object.class, "v2", int.class, Object.class);
738 testBind(Example.class, Object.class, "v2", int.class, int.class);
739 testBind(false, PRIVATE, Example.class, void.class, "bogus");
740 testBind(SubExample.class, void.class, "Sub/v0");
741 testBind(SubExample.class, void.class, "Sub/pkg_v0");
742 testBind(IntExample.Impl.class, void.class, "Int/v0");
743 }
744
745 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
746 for (Object[] ac : accessCases(defc, name)) {
747 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
748 }
749 }
750
751 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
752 countTest(positive);
753 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800754 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700755 Object receiver = randomArg(defc);
756 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700757 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700758 try {
jrose2cc9c832010-04-30 23:48:23 -0700759 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700760 target = lookup.in(defc).bind(receiver, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800761 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700762 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800763 if (name.contains("bogus"))
764 assertTrue(noAccess instanceof NoSuchMethodException);
765 else
766 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700767 }
jrose2cc9c832010-04-30 23:48:23 -0700768 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700769 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
770 +(noAccess == null ? "" : " !! "+noAccess));
771 if (positive && noAccess != null) throw noAccess;
772 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
773 if (!positive) return; // negative test failed as expected
774 assertEquals(type, target.type());
775 Object[] args = randomArgs(params);
776 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700777 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700778 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
779 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700780 if (verbosity >= 1)
781 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700782 }
783
784 @Test
785 public void testUnreflect() throws Throwable {
786 if (CAN_SKIP_WORKING) return;
787 startTest("unreflect");
788 testUnreflect(Example.class, true, void.class, "s0");
789 testUnreflect(Example.class, true, void.class, "pkg_s0");
790 testUnreflect(Example.class, true, void.class, "pri_s0");
791
792 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
793 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700794 testUnreflect(Example.class, true, Object.class, "s3", long.class);
795 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
796 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
797 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700798
799 testUnreflect(Example.class, false, void.class, "v0");
800 testUnreflect(Example.class, false, void.class, "pkg_v0");
801 testUnreflect(Example.class, false, void.class, "pri_v0");
802 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
803 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
804 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
805 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
806 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
807 }
808
809 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
810 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700811 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700812 }
813 }
jrose2cc9c832010-04-30 23:48:23 -0700814 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
815 for (Object[] ac : accessCases(defc, name)) {
816 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
817 }
818 }
819 void testUnreflectMaybeSpecial(Class<?> specialCaller,
820 boolean positive, Lookup lookup,
821 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700822 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800823 MethodType type = MethodType.methodType(ret, params);
jrosef15905c2011-02-11 01:26:32 -0800824 Method rmethod = defc.getDeclaredMethod(name, params);
jrose55220c32009-10-21 23:19:48 -0700825 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700826 Exception noAccess = null;
jrose2cc9c832010-04-30 23:48:23 -0700827 boolean isStatic = (rcvc == null);
828 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700829 try {
jrose2cc9c832010-04-30 23:48:23 -0700830 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
831 if (isSpecial)
jrose900bafd2010-10-30 21:08:23 -0700832 target = lookup.in(specialCaller).unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700833 else
jrose900bafd2010-10-30 21:08:23 -0700834 target = lookup.in(defc).unreflect(rmethod);
jrosef15905c2011-02-11 01:26:32 -0800835 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700836 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800837 if (name.contains("bogus"))
838 assertTrue(noAccess instanceof NoSuchMethodException);
839 else
840 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700841 }
jrose2cc9c832010-04-30 23:48:23 -0700842 if (verbosity >= 3)
843 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
844 +(!isSpecial ? "" : " specialCaller="+specialCaller)
845 +( isStatic ? "" : " receiver="+rcvc)
846 +" => "+target
847 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700848 if (positive && noAccess != null) throw noAccess;
849 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
850 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700851 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700852 Class<?>[] paramsMaybeWithSelf = params;
853 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700854 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700855 }
jrose10f3b682010-01-07 16:16:45 -0800856 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700857 if (isStatic) {
858 assertEquals(typeMaybeWithSelf, target.type());
859 } else {
jrose2cc9c832010-04-30 23:48:23 -0700860 if (isSpecial)
861 assertEquals(specialCaller, target.type().parameterType(0));
862 else
863 assertEquals(defc, target.type().parameterType(0));
864 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
865 }
jrose55220c32009-10-21 23:19:48 -0700866 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
867 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700868 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700869 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700870 if (verbosity >= 1)
871 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700872 }
873
jrose2cc9c832010-04-30 23:48:23 -0700874 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
875 for (Object[] ac : accessCases(defc, name, true)) {
876 Class<?> specialCaller = rcvc;
877 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
878 }
879 }
880
881 @Test
jrose55220c32009-10-21 23:19:48 -0700882 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700883 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700884 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700885 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
886 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
887 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
888 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
889 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
890 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
891 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700892 }
893
jrose10f3b682010-01-07 16:16:45 -0800894 public static class HasFields {
895 boolean fZ = false;
896 byte fB = (byte)'B';
897 short fS = (short)'S';
898 char fC = 'C';
899 int fI = 'I';
900 long fJ = 'J';
901 float fF = 'F';
902 double fD = 'D';
903 static boolean sZ = true;
904 static byte sB = 1+(byte)'B';
905 static short sS = 1+(short)'S';
906 static char sC = 1+'C';
907 static int sI = 1+'I';
908 static long sJ = 1+'J';
909 static float sF = 1+'F';
910 static double sD = 1+'D';
911
912 Object fL = 'L';
913 String fR = "R";
914 static Object sL = 'M';
915 static String sR = "S";
916
917 static final Object[][] CASES;
918 static {
jrose49494522012-01-18 17:34:29 -0800919 ArrayList<Object[]> cases = new ArrayList<>();
jrose10f3b682010-01-07 16:16:45 -0800920 Object types[][] = {
921 {'L',Object.class}, {'R',String.class},
922 {'I',int.class}, {'J',long.class},
923 {'F',float.class}, {'D',double.class},
924 {'Z',boolean.class}, {'B',byte.class},
925 {'S',short.class}, {'C',char.class},
926 };
927 HasFields fields = new HasFields();
928 for (Object[] t : types) {
929 for (int kind = 0; kind <= 1; kind++) {
930 boolean isStatic = (kind != 0);
931 char btc = (Character)t[0];
932 String name = (isStatic ? "s" : "f") + btc;
933 Class<?> type = (Class<?>) t[1];
934 Object value;
935 Field field;
jrose320b7692011-05-12 19:27:49 -0700936 try {
jrose10f3b682010-01-07 16:16:45 -0800937 field = HasFields.class.getDeclaredField(name);
jrose49494522012-01-18 17:34:29 -0800938 } catch (NoSuchFieldException | SecurityException ex) {
jrose10f3b682010-01-07 16:16:45 -0800939 throw new InternalError("no field HasFields."+name);
940 }
941 try {
942 value = field.get(fields);
jrose49494522012-01-18 17:34:29 -0800943 } catch (IllegalArgumentException | IllegalAccessException ex) {
jrose10f3b682010-01-07 16:16:45 -0800944 throw new InternalError("cannot fetch field HasFields."+name);
945 }
946 if (type == float.class) {
947 float v = 'F';
948 if (isStatic) v++;
jrosef15905c2011-02-11 01:26:32 -0800949 assertTrue(value.equals(v));
jrose10f3b682010-01-07 16:16:45 -0800950 }
jrosef15905c2011-02-11 01:26:32 -0800951 assertTrue(name.equals(field.getName()));
952 assertTrue(type.equals(field.getType()));
953 assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
jrose10f3b682010-01-07 16:16:45 -0800954 cases.add(new Object[]{ field, value });
955 }
956 }
jrosef15905c2011-02-11 01:26:32 -0800957 cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
958 cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
jrose10f3b682010-01-07 16:16:45 -0800959 CASES = cases.toArray(new Object[0][]);
960 }
961 }
962
jrosef15905c2011-02-11 01:26:32 -0800963 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10;
jrosecf98d422010-06-08 23:08:56 -0700964 static boolean testModeMatches(int testMode, boolean isStatic) {
965 switch (testMode) {
jrosef15905c2011-02-11 01:26:32 -0800966 case TEST_FIND_STATIC: return isStatic;
jrosecf98d422010-06-08 23:08:56 -0700967 case TEST_FIND_FIELD: return !isStatic;
jrosef15905c2011-02-11 01:26:32 -0800968 case TEST_UNREFLECT: return true; // unreflect matches both
jrosecf98d422010-06-08 23:08:56 -0700969 }
jrosef15905c2011-02-11 01:26:32 -0800970 throw new InternalError("testMode="+testMode);
jrosecf98d422010-06-08 23:08:56 -0700971 }
972
jrose10f3b682010-01-07 16:16:45 -0800973 @Test
jrose55220c32009-10-21 23:19:48 -0700974 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700975 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700976 testGetter(TEST_UNREFLECT);
977 }
978 @Test
979 public void testFindGetter() throws Throwable {
980 startTest("findGetter");
981 testGetter(TEST_FIND_FIELD);
982 }
983 @Test
984 public void testFindStaticGetter() throws Throwable {
985 startTest("findStaticGetter");
jrosef15905c2011-02-11 01:26:32 -0800986 testGetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -0700987 }
988 public void testGetter(int testMode) throws Throwable {
989 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800990 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -0800991 boolean positive = (c[1] != Error.class);
992 testGetter(positive, lookup, c[0], c[1], testMode);
993 }
994 testGetter(true, lookup,
995 new Object[]{ true, System.class, "out", java.io.PrintStream.class },
996 System.out, testMode);
997 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
998 testGetter(false, lookup,
999 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1000 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001001 }
1002 }
jrosef15905c2011-02-11 01:26:32 -08001003 public void testGetter(boolean positive, MethodHandles.Lookup lookup,
1004 Object fieldRef, Object value, int testMode) throws Throwable {
1005 testAccessor(positive, lookup, fieldRef, value, testMode);
1006 }
1007
1008 public void testAccessor(boolean positive, MethodHandles.Lookup lookup,
1009 Object fieldRef, Object value, int testMode0) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07001010 if (verbosity >= 4)
1011 System.out.println("testAccessor"+Arrays.asList(positive, lookup, fieldRef, value, testMode0));
jrosef15905c2011-02-11 01:26:32 -08001012 boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
1013 int testMode = testMode0 & ~TEST_SETTER;
1014 boolean isStatic;
1015 Class<?> fclass;
1016 String fname;
1017 Class<?> ftype;
1018 Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
1019 if (f != null) {
1020 isStatic = Modifier.isStatic(f.getModifiers());
1021 fclass = f.getDeclaringClass();
1022 fname = f.getName();
1023 ftype = f.getType();
1024 } else {
1025 Object[] scnt = (Object[]) fieldRef;
1026 isStatic = (Boolean) scnt[0];
1027 fclass = (Class<?>) scnt[1];
1028 fname = (String) scnt[2];
1029 ftype = (Class<?>) scnt[3];
1030 try {
1031 f = fclass.getDeclaredField(fname);
1032 } catch (ReflectiveOperationException ex) {
1033 f = null;
1034 }
1035 }
jrosecf98d422010-06-08 23:08:56 -07001036 if (!testModeMatches(testMode, isStatic)) return;
jrosef15905c2011-02-11 01:26:32 -08001037 if (f == null && testMode == TEST_UNREFLECT) return;
1038 countTest(positive);
1039 MethodType expType;
1040 if (isGetter)
1041 expType = MethodType.methodType(ftype, HasFields.class);
1042 else
1043 expType = MethodType.methodType(void.class, HasFields.class, ftype);
jrose10f3b682010-01-07 16:16:45 -08001044 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosef15905c2011-02-11 01:26:32 -08001045 Exception noAccess = null;
1046 MethodHandle mh;
1047 try {
1048 switch (testMode0) {
1049 case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
1050 case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
1051 case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
1052 case TEST_SETTER|
1053 TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
1054 case TEST_SETTER|
1055 TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
1056 case TEST_SETTER|
1057 TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
1058 default:
1059 throw new InternalError("testMode="+testMode);
1060 }
1061 } catch (ReflectiveOperationException ex) {
1062 mh = null;
1063 noAccess = ex;
1064 if (fname.contains("bogus"))
1065 assertTrue(noAccess instanceof NoSuchFieldException);
1066 else
1067 assertTrue(noAccess instanceof IllegalAccessException);
1068 }
1069 if (verbosity >= 3)
1070 System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
1071 +" => "+mh
1072 +(noAccess == null ? "" : " !! "+noAccess));
1073 if (positive && noAccess != null) throw new RuntimeException(noAccess);
1074 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, mh != null);
1075 if (!positive) return; // negative test failed as expected
1076 assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
1077
1078
jrose10f3b682010-01-07 16:16:45 -08001079 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -07001080 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -08001081 HasFields fields = new HasFields();
1082 Object sawValue;
jrosef15905c2011-02-11 01:26:32 -08001083 Class<?> vtype = ftype;
1084 if (ftype != int.class) vtype = Object.class;
1085 if (isGetter) {
jrose9b82ad62011-05-26 17:37:36 -07001086 mh = mh.asType(mh.type().generic()
1087 .changeReturnType(vtype));
jrosef15905c2011-02-11 01:26:32 -08001088 } else {
1089 int last = mh.type().parameterCount() - 1;
jrose9b82ad62011-05-26 17:37:36 -07001090 mh = mh.asType(mh.type().generic()
1091 .changeReturnType(void.class)
1092 .changeParameterType(last, vtype));
jrose10f3b682010-01-07 16:16:45 -08001093 }
jrosef15905c2011-02-11 01:26:32 -08001094 if (f != null && f.getDeclaringClass() == HasFields.class) {
1095 assertEquals(f.get(fields), value); // clean to start with
1096 }
1097 if (isGetter) {
1098 Object expValue = value;
1099 for (int i = 0; i <= 1; i++) {
1100 if (isStatic) {
1101 if (ftype == int.class)
1102 sawValue = (int) mh.invokeExact(); // do these exactly
1103 else
1104 sawValue = mh.invokeExact();
1105 } else {
1106 if (ftype == int.class)
1107 sawValue = (int) mh.invokeExact((Object) fields);
1108 else
1109 sawValue = mh.invokeExact((Object) fields);
1110 }
1111 assertEquals(sawValue, expValue);
1112 if (f != null && f.getDeclaringClass() == HasFields.class
1113 && !Modifier.isFinal(f.getModifiers())) {
1114 Object random = randomArg(ftype);
1115 f.set(fields, random);
1116 expValue = random;
1117 } else {
1118 break;
1119 }
1120 }
1121 } else {
1122 for (int i = 0; i <= 1; i++) {
1123 Object putValue = randomArg(ftype);
1124 if (isStatic) {
1125 if (ftype == int.class)
1126 mh.invokeExact((int)putValue); // do these exactly
1127 else
1128 mh.invokeExact(putValue);
1129 } else {
1130 if (ftype == int.class)
1131 mh.invokeExact((Object) fields, (int)putValue);
1132 else
1133 mh.invokeExact((Object) fields, putValue);
1134 }
1135 if (f != null && f.getDeclaringClass() == HasFields.class) {
1136 assertEquals(f.get(fields), putValue);
1137 }
1138 }
1139 }
1140 if (f != null && f.getDeclaringClass() == HasFields.class) {
1141 f.set(fields, value); // put it back
1142 }
jrose55220c32009-10-21 23:19:48 -07001143 }
1144
jrose10f3b682010-01-07 16:16:45 -08001145
1146 @Test
jrose55220c32009-10-21 23:19:48 -07001147 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -07001148 startTest("unreflectSetter");
1149 testSetter(TEST_UNREFLECT);
1150 }
1151 @Test
1152 public void testFindSetter() throws Throwable {
1153 startTest("findSetter");
1154 testSetter(TEST_FIND_FIELD);
1155 }
1156 @Test
1157 public void testFindStaticSetter() throws Throwable {
1158 startTest("findStaticSetter");
jrosef15905c2011-02-11 01:26:32 -08001159 testSetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001160 }
1161 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001162 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
1163 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -08001164 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001165 boolean positive = (c[1] != Error.class);
1166 testSetter(positive, lookup, c[0], c[1], testMode);
1167 }
1168 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1169 testSetter(false, lookup,
1170 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1171 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001172 }
1173 }
jrosef15905c2011-02-11 01:26:32 -08001174 public void testSetter(boolean positive, MethodHandles.Lookup lookup,
1175 Object fieldRef, Object value, int testMode) throws Throwable {
1176 testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
jrose55220c32009-10-21 23:19:48 -07001177 }
1178
jrose10f3b682010-01-07 16:16:45 -08001179 @Test
jrose55220c32009-10-21 23:19:48 -07001180 public void testArrayElementGetter() throws Throwable {
1181 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001182 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001183 }
1184
jrose10f3b682010-01-07 16:16:45 -08001185 @Test
jrose55220c32009-10-21 23:19:48 -07001186 public void testArrayElementSetter() throws Throwable {
1187 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001188 testArrayElementGetterSetter(true);
1189 }
1190
1191 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
1192 testArrayElementGetterSetter(new Object[10], testSetter);
1193 testArrayElementGetterSetter(new String[10], testSetter);
1194 testArrayElementGetterSetter(new boolean[10], testSetter);
1195 testArrayElementGetterSetter(new byte[10], testSetter);
1196 testArrayElementGetterSetter(new char[10], testSetter);
1197 testArrayElementGetterSetter(new short[10], testSetter);
1198 testArrayElementGetterSetter(new int[10], testSetter);
1199 testArrayElementGetterSetter(new float[10], testSetter);
1200 testArrayElementGetterSetter(new long[10], testSetter);
1201 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -08001202 }
1203
1204 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
1205 countTest(true);
jroseb4be0262011-07-16 15:44:33 -07001206 if (verbosity > 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -08001207 Class<?> arrayType = array.getClass();
1208 Class<?> elemType = arrayType.getComponentType();
1209 MethodType expType = !testSetter
1210 ? MethodType.methodType(elemType, arrayType, int.class)
1211 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1212 MethodHandle mh = !testSetter
1213 ? MethodHandles.arrayElementGetter(arrayType)
1214 : MethodHandles.arrayElementSetter(arrayType);
1215 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001216 if (elemType != int.class && elemType != boolean.class) {
jrose320b7692011-05-12 19:27:49 -07001217 // FIXME: change Integer.class and (Integer) below to int.class and (int) below.
1218 MethodType gtype = mh.type().generic().changeParameterType(1, Integer.class);
1219 if (testSetter) gtype = gtype.changeReturnType(void.class);
jrose9b82ad62011-05-26 17:37:36 -07001220 mh = mh.asType(gtype);
jrose2cc9c832010-04-30 23:48:23 -07001221 }
jrose10f3b682010-01-07 16:16:45 -08001222 Object sawValue, expValue;
1223 List<Object> model = array2list(array);
1224 int length = Array.getLength(array);
1225 for (int i = 0; i < length; i++) {
1226 // update array element
1227 Object random = randomArg(elemType);
1228 model.set(i, random);
1229 if (testSetter) {
1230 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001231 mh.invokeExact((int[]) array, i, (int)random);
jrose2cc9c832010-04-30 23:48:23 -07001232 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001233 mh.invokeExact((boolean[]) array, i, (boolean)random);
jrose10f3b682010-01-07 16:16:45 -08001234 else
jrose320b7692011-05-12 19:27:49 -07001235 mh.invokeExact(array, (Integer)i, random);
jrose10f3b682010-01-07 16:16:45 -08001236 assertEquals(model, array2list(array));
1237 } else {
1238 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001239 }
1240 if (verbosity >= 5) {
1241 List<Object> array2list = array2list(array);
1242 System.out.println("a["+i+"]="+random+" => "+array2list);
1243 if (!array2list.equals(model))
1244 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001245 }
1246 // observe array element
1247 sawValue = Array.get(array, i);
1248 if (!testSetter) {
1249 expValue = sawValue;
1250 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001251 sawValue = (int) mh.invokeExact((int[]) array, i);
jrose2cc9c832010-04-30 23:48:23 -07001252 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001253 sawValue = (boolean) mh.invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -08001254 else
jrose320b7692011-05-12 19:27:49 -07001255 sawValue = mh.invokeExact(array, (Integer)i);
jrose10f3b682010-01-07 16:16:45 -08001256 assertEquals(sawValue, expValue);
1257 assertEquals(model, array2list(array));
1258 }
1259 }
1260 }
1261
1262 List<Object> array2list(Object array) {
1263 int length = Array.getLength(array);
jrose49494522012-01-18 17:34:29 -08001264 ArrayList<Object> model = new ArrayList<>(length);
jrose10f3b682010-01-07 16:16:45 -08001265 for (int i = 0; i < length; i++)
1266 model.add(Array.get(array, i));
1267 return model;
jrose55220c32009-10-21 23:19:48 -07001268 }
1269
1270 static class Callee {
1271 static Object id() { return called("id"); }
1272 static Object id(Object x) { return called("id", x); }
1273 static Object id(Object x, Object y) { return called("id", x, y); }
1274 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1275 static Object id(Object... vx) { return called("id", vx); }
1276 static MethodHandle ofType(int n) {
1277 return ofType(Object.class, n);
1278 }
1279 static MethodHandle ofType(Class<?> rtype, int n) {
1280 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001281 return ofType(MethodType.methodType(rtype, Object[].class));
1282 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001283 }
1284 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001285 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001286 }
1287 static MethodHandle ofType(MethodType type) {
1288 Class<?> rtype = type.returnType();
1289 String pfx = "";
1290 if (rtype != Object.class)
1291 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1292 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001293 try {
1294 return PRIVATE.findStatic(Callee.class, name, type);
jrose49494522012-01-18 17:34:29 -08001295 } catch (NoSuchMethodException | IllegalAccessException ex) {
jrosea1ebbe62010-09-08 18:40:23 -07001296 throw new RuntimeException(ex);
1297 }
jrose55220c32009-10-21 23:19:48 -07001298 }
1299 }
1300
1301 @Test
1302 public void testConvertArguments() throws Throwable {
1303 if (CAN_SKIP_WORKING) return;
1304 startTest("convertArguments");
1305 testConvert(Callee.ofType(1), null, "id", int.class);
1306 testConvert(Callee.ofType(1), null, "id", String.class);
1307 testConvert(Callee.ofType(1), null, "id", Integer.class);
1308 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001309 testConvert(Callee.ofType(1), null, "id", char.class);
1310 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001311 }
1312
1313 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -07001314 testConvert(true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001315 }
1316
jrose9b82ad62011-05-26 17:37:36 -07001317 void testConvert(boolean positive,
jrose900bafd2010-10-30 21:08:23 -07001318 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001319 countTest(positive);
1320 MethodType idType = id.type();
1321 if (rtype == null) rtype = idType.returnType();
1322 for (int i = 0; i < params.length; i++) {
1323 if (params[i] == null) params[i] = idType.parameterType(i);
1324 }
1325 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001326 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001327 Object[] args = randomArgs(newType.parameterArray());
1328 Object[] convArgs = args.clone();
1329 for (int i = 0; i < args.length; i++) {
1330 Class<?> src = newType.parameterType(i);
1331 Class<?> dst = idType.parameterType(i);
1332 if (src != dst)
1333 convArgs[i] = castToWrapper(convArgs[i], dst);
1334 }
jrose900bafd2010-10-30 21:08:23 -07001335 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001336 {
1337 Class<?> dst = newType.returnType();
1338 Class<?> src = idType.returnType();
1339 if (src != dst)
1340 convResult = castToWrapper(convResult, dst);
1341 }
1342 MethodHandle target = null;
1343 RuntimeException error = null;
1344 try {
jrose9b82ad62011-05-26 17:37:36 -07001345 target = id.asType(newType);
jrose55220c32009-10-21 23:19:48 -07001346 } catch (RuntimeException ex) {
1347 error = ex;
1348 }
jrose2cc9c832010-04-30 23:48:23 -07001349 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001350 System.out.println("convert "+id+ " to "+newType+" => "+target
1351 +(error == null ? "" : " !! "+error));
1352 if (positive && error != null) throw error;
1353 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1354 if (!positive) return; // negative test failed as expected
1355 assertEquals(newType, target.type());
1356 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001357 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001358 assertCalled(name, convArgs);
1359 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001360 if (verbosity >= 1)
1361 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001362 }
1363
1364 @Test
jrosef108fc02011-02-11 01:26:24 -08001365 public void testVarargsCollector() throws Throwable {
1366 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1367 MethodType.methodType(Object.class, String.class, Object[].class));
1368 vac0 = vac0.bindTo("vac");
1369 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -07001370 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1371 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
jrose49494522012-01-18 17:34:29 -08001372 for (Class<?> at : new Class<?>[] { Object.class, String.class, Integer.class }) {
jrose9b82ad62011-05-26 17:37:36 -07001373 testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1374 testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
jrosef108fc02011-02-11 01:26:24 -08001375 }
1376 }
1377
1378 @Test
jrose10f3b682010-01-07 16:16:45 -08001379 public void testPermuteArguments() throws Throwable {
1380 if (CAN_SKIP_WORKING) return;
1381 startTest("permuteArguments");
jroseb4be0262011-07-16 15:44:33 -07001382 testPermuteArguments(4, Integer.class, 2, long.class, 6);
1383 if (CAN_TEST_LIGHTLY) return;
jrose10f3b682010-01-07 16:16:45 -08001384 testPermuteArguments(4, Integer.class, 2, String.class, 0);
jrose9b82ad62011-05-26 17:37:36 -07001385 testPermuteArguments(6, Integer.class, 0, null, 30);
jrose10f3b682010-01-07 16:16:45 -08001386 }
1387 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001388 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001389 System.out.println("permuteArguments "+max+"*"+type1.getName()
1390 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1391 +(dilution > 0 ? " with dilution "+dilution : ""));
1392 int t2pos = t2c == 0 ? 0 : 1;
1393 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1394 Class<?>[] types = new Class<?>[inargs];
1395 Arrays.fill(types, type1);
1396 if (t2c != 0) {
1397 // Fill in a middle range with type2:
1398 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1399 }
1400 Object[] args = randomArgs(types);
1401 int numcases = 1;
1402 for (int outargs = 0; outargs <= max; outargs++) {
1403 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
jrose10f3b682010-01-07 16:16:45 -08001404 int casStep = dilution + 1;
1405 // Avoid some common factors:
1406 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1407 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1408 casStep++;
jrose320b7692011-05-12 19:27:49 -07001409 testPermuteArguments(args, types, outargs, numcases, casStep);
jrose10f3b682010-01-07 16:16:45 -08001410 numcases *= inargs;
jroseb4be0262011-07-16 15:44:33 -07001411 if (CAN_TEST_LIGHTLY && outargs < max-2) continue;
jrose10f3b682010-01-07 16:16:45 -08001412 if (dilution > 10 && outargs >= 4) {
jroseb4be0262011-07-16 15:44:33 -07001413 if (CAN_TEST_LIGHTLY) continue;
jrose320b7692011-05-12 19:27:49 -07001414 int[] reorder = new int[outargs];
jrose10f3b682010-01-07 16:16:45 -08001415 // Do some special patterns, which we probably missed.
1416 // Replication of a single argument or argument pair.
1417 for (int i = 0; i < inargs; i++) {
1418 Arrays.fill(reorder, i);
1419 testPermuteArguments(args, types, reorder);
1420 for (int d = 1; d <= 2; d++) {
1421 if (i + d >= inargs) continue;
1422 for (int j = 1; j < outargs; j += 2)
1423 reorder[j] += 1;
1424 testPermuteArguments(args, types, reorder);
1425 testPermuteArguments(args, types, reverse(reorder));
1426 }
1427 }
1428 // Repetition of a sequence of 3 or more arguments.
1429 for (int i = 1; i < inargs; i++) {
1430 for (int len = 3; len <= inargs; len++) {
1431 for (int j = 0; j < outargs; j++)
1432 reorder[j] = (i + (j % len)) % inargs;
1433 testPermuteArguments(args, types, reorder);
1434 testPermuteArguments(args, types, reverse(reorder));
1435 }
1436 }
1437 }
1438 }
1439 }
1440 }
1441
jrose320b7692011-05-12 19:27:49 -07001442 public void testPermuteArguments(Object[] args, Class<?>[] types,
1443 int outargs, int numcases, int casStep) throws Throwable {
1444 int inargs = args.length;
1445 int[] reorder = new int[outargs];
1446 for (int cas = 0; cas < numcases; cas += casStep) {
1447 for (int i = 0, c = cas; i < outargs; i++) {
1448 reorder[i] = c % inargs;
1449 c /= inargs;
1450 }
jroseb4be0262011-07-16 15:44:33 -07001451 if (CAN_TEST_LIGHTLY && outargs >= 3 && (reorder[0] == reorder[1] || reorder[1] == reorder[2])) continue;
jrose320b7692011-05-12 19:27:49 -07001452 testPermuteArguments(args, types, reorder);
1453 }
1454 }
1455
jrose10f3b682010-01-07 16:16:45 -08001456 static int[] reverse(int[] reorder) {
1457 reorder = reorder.clone();
1458 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1459 int j = reorder.length - 1 - i;
1460 int tem = reorder[i];
1461 reorder[i] = reorder[j];
1462 reorder[j] = tem;
1463 }
1464 return reorder;
1465 }
1466
1467 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1468 countTest();
1469 if (args == null && types == null) {
1470 int max = 0;
1471 for (int j : reorder) {
1472 if (max < j) max = j;
1473 }
1474 args = randomArgs(max+1, Integer.class);
1475 }
1476 if (args == null) {
1477 args = randomArgs(types);
1478 }
1479 if (types == null) {
1480 types = new Class<?>[args.length];
1481 for (int i = 0; i < args.length; i++)
1482 types[i] = args[i].getClass();
1483 }
1484 int inargs = args.length, outargs = reorder.length;
jrosef15905c2011-02-11 01:26:32 -08001485 assertTrue(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001486 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001487 System.out.println("permuteArguments "+Arrays.toString(reorder));
1488 Object[] permArgs = new Object[outargs];
1489 Class<?>[] permTypes = new Class<?>[outargs];
1490 for (int i = 0; i < outargs; i++) {
1491 permArgs[i] = args[reorder[i]];
1492 permTypes[i] = types[reorder[i]];
1493 }
jrose2cc9c832010-04-30 23:48:23 -07001494 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001495 System.out.println("in args: "+Arrays.asList(args));
1496 System.out.println("out args: "+Arrays.asList(permArgs));
1497 System.out.println("in types: "+Arrays.asList(types));
1498 System.out.println("out types: "+Arrays.asList(permTypes));
1499 }
1500 MethodType inType = MethodType.methodType(Object.class, types);
1501 MethodType outType = MethodType.methodType(Object.class, permTypes);
jrose9b82ad62011-05-26 17:37:36 -07001502 MethodHandle target = varargsList(outargs).asType(outType);
jrose10f3b682010-01-07 16:16:45 -08001503 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose9b82ad62011-05-26 17:37:36 -07001504 if (verbosity >= 5) System.out.println("newTarget = "+newTarget);
jrose900bafd2010-10-30 21:08:23 -07001505 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001506 Object expected = Arrays.asList(permArgs);
jrose320b7692011-05-12 19:27:49 -07001507 if (!expected.equals(result)) {
1508 System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
1509 System.out.println("in args: "+Arrays.asList(args));
1510 System.out.println("out args: "+expected);
1511 System.out.println("bad args: "+result);
1512 }
jrose10f3b682010-01-07 16:16:45 -08001513 assertEquals(expected, result);
1514 }
1515
1516
1517 @Test
1518 public void testSpreadArguments() throws Throwable {
1519 if (CAN_SKIP_WORKING) return;
1520 startTest("spreadArguments");
jrose49494522012-01-18 17:34:29 -08001521 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001522 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001523 System.out.println("spreadArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001524 for (int nargs = 0; nargs < 50; nargs++) {
1525 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1526 for (int pos = 0; pos <= nargs; pos++) {
1527 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1528 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1529 continue;
1530 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001531 }
1532 }
1533 }
1534 }
1535 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1536 countTest();
jrose320b7692011-05-12 19:27:49 -07001537 Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
1538 MethodHandle target2 = varargsArray(arrayType, nargs);
1539 MethodHandle target = target2.asType(target2.type().generic());
jrose2cc9c832010-04-30 23:48:23 -07001540 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001541 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1542 Object[] args = randomArgs(target2.type().parameterArray());
1543 // make sure the target does what we think it does:
jrose320b7692011-05-12 19:27:49 -07001544 if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
jrose49494522012-01-18 17:34:29 -08001545 Object[] check = (Object[]) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001546 assertArrayEquals(args, check);
1547 switch (nargs) {
1548 case 0:
jrose320b7692011-05-12 19:27:49 -07001549 check = (Object[]) (Object) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001550 assertArrayEquals(args, check);
1551 break;
1552 case 1:
jrose320b7692011-05-12 19:27:49 -07001553 check = (Object[]) (Object) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001554 assertArrayEquals(args, check);
1555 break;
1556 case 2:
jrose320b7692011-05-12 19:27:49 -07001557 check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001558 assertArrayEquals(args, check);
1559 break;
1560 }
1561 }
jrose49494522012-01-18 17:34:29 -08001562 List<Class<?>> newParams = new ArrayList<>(target2.type().parameterList());
jrose10f3b682010-01-07 16:16:45 -08001563 { // modify newParams in place
1564 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
jrose320b7692011-05-12 19:27:49 -07001565 spreadParams.clear(); spreadParams.add(arrayType);
jrose10f3b682010-01-07 16:16:45 -08001566 }
jrose320b7692011-05-12 19:27:49 -07001567 MethodType newType = MethodType.methodType(arrayType, newParams);
1568 MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
1569 assert(result.type() == newType) : Arrays.asList(result, newType);
1570 result = result.asType(newType.generic());
1571 Object returnValue;
jrose10f3b682010-01-07 16:16:45 -08001572 if (pos == 0) {
jrose320b7692011-05-12 19:27:49 -07001573 Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1574 returnValue = result.invokeExact(args2);
jrose10f3b682010-01-07 16:16:45 -08001575 } else {
1576 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
jrose320b7692011-05-12 19:27:49 -07001577 args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1578 returnValue = result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001579 }
jrose320b7692011-05-12 19:27:49 -07001580 String argstr = Arrays.toString(args);
1581 if (!argType.isPrimitive()) {
1582 Object[] rv = (Object[]) returnValue;
1583 String rvs = Arrays.toString(rv);
1584 if (!Arrays.equals(args, rv)) {
1585 System.out.println("method: "+result);
1586 System.out.println("expected: "+argstr);
1587 System.out.println("returned: "+rvs);
1588 assertArrayEquals(args, rv);
1589 }
1590 } else if (argType == int.class) {
1591 String rvs = Arrays.toString((int[]) returnValue);
1592 if (!argstr.equals(rvs)) {
1593 System.out.println("method: "+result);
1594 System.out.println("expected: "+argstr);
1595 System.out.println("returned: "+rvs);
1596 assertEquals(argstr, rvs);
1597 }
1598 } else if (argType == long.class) {
1599 String rvs = Arrays.toString((long[]) returnValue);
1600 if (!argstr.equals(rvs)) {
1601 System.out.println("method: "+result);
1602 System.out.println("expected: "+argstr);
1603 System.out.println("returned: "+rvs);
1604 assertEquals(argstr, rvs);
1605 }
1606 } else {
1607 // cannot test...
1608 }
jrose10f3b682010-01-07 16:16:45 -08001609 }
1610
1611 @Test
1612 public void testCollectArguments() throws Throwable {
1613 if (CAN_SKIP_WORKING) return;
1614 startTest("collectArguments");
jrose49494522012-01-18 17:34:29 -08001615 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001616 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001617 System.out.println("collectArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001618 for (int nargs = 0; nargs < 50; nargs++) {
1619 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1620 for (int pos = 0; pos <= nargs; pos++) {
1621 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1622 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1623 continue;
jrose10f3b682010-01-07 16:16:45 -08001624 testCollectArguments(argType, pos, nargs);
1625 }
1626 }
1627 }
1628 }
1629 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1630 countTest();
1631 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001632 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001633 fake = changeArgTypes(fake, argType);
1634 MethodType newType = fake.type();
1635 Object[] args = randomArgs(newType.parameterArray());
1636 // here is what should happen:
1637 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1638 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1639 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001640 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001641 target = changeArgTypes(target, 0, pos, argType);
1642 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001643 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001644 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001645 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001646 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001647// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1648// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1649// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1650 assertArrayEquals(collectedArgs, returnValue);
1651 }
1652
1653 @Test
jrose55220c32009-10-21 23:19:48 -07001654 public void testInsertArguments() throws Throwable {
1655 if (CAN_SKIP_WORKING) return;
1656 startTest("insertArguments");
jroseb4be0262011-07-16 15:44:33 -07001657 for (int nargs = 0; nargs < 50; nargs++) {
1658 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1659 for (int ins = 0; ins <= nargs; ins++) {
1660 if (nargs > 10 && ins > 4 && ins < nargs-4 && ins % 10 != 3)
1661 continue;
jrose55220c32009-10-21 23:19:48 -07001662 for (int pos = 0; pos <= nargs; pos++) {
jroseb4be0262011-07-16 15:44:33 -07001663 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1664 continue;
1665 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
jrose55220c32009-10-21 23:19:48 -07001666 testInsertArguments(nargs, pos, ins);
1667 }
1668 }
1669 }
1670 }
1671
1672 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001673 countTest();
jroseadc650a2011-02-11 01:26:28 -08001674 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001675 Object[] args = randomArgs(target.type().parameterArray());
1676 List<Object> resList = Arrays.asList(args);
jrose49494522012-01-18 17:34:29 -08001677 List<Object> argsToPass = new ArrayList<>(resList);
jrose55220c32009-10-21 23:19:48 -07001678 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001679 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001680 System.out.println("insert: "+argsToInsert+" into "+target);
jrose49494522012-01-18 17:34:29 -08001681 @SuppressWarnings("cast") // cast to spread Object... is helpful
jrose10f3b682010-01-07 16:16:45 -08001682 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
jrose49494522012-01-18 17:34:29 -08001683 (Object[]/*...*/) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001684 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001685 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001686 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001687 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001688 System.out.println("result: "+res2List);
1689 //if (!resList.equals(res2List))
1690 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1691 assertEquals(resList, res2List);
1692 }
1693
jrose10f3b682010-01-07 16:16:45 -08001694 @Test
jroseadc650a2011-02-11 01:26:28 -08001695 public void testFilterReturnValue() throws Throwable {
1696 if (CAN_SKIP_WORKING) return;
1697 startTest("filterReturnValue");
1698 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1699 assertTrue(List.class.isAssignableFrom(classOfVCList));
1700 for (int nargs = 0; nargs <= 3; nargs++) {
jrose49494522012-01-18 17:34:29 -08001701 for (Class<?> rtype : new Class<?>[] { Object.class,
jroseadc650a2011-02-11 01:26:28 -08001702 List.class,
1703 int.class,
jroseb4be0262011-07-16 15:44:33 -07001704 byte.class,
1705 long.class,
jroseadc650a2011-02-11 01:26:28 -08001706 CharSequence.class,
1707 String.class }) {
1708 testFilterReturnValue(nargs, rtype);
1709 }
1710 }
1711 }
1712
1713 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1714 countTest();
1715 MethodHandle target = varargsList(nargs, rtype);
1716 MethodHandle filter;
1717 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1718 filter = varargsList(1); // add another layer of list-ness
1719 else
1720 filter = MethodHandles.identity(rtype);
1721 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1722 Object[] argsToPass = randomArgs(nargs, Object.class);
1723 if (verbosity >= 3)
1724 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1725 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1726 if (verbosity >= 4)
1727 System.out.println("filtered target: "+target2);
1728 // Simulate expected effect of filter on return value:
1729 Object unfiltered = target.invokeWithArguments(argsToPass);
1730 Object expected = filter.invokeWithArguments(unfiltered);
1731 if (verbosity >= 4)
1732 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1733 if (verbosity >= 4)
1734 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1735 Object result = target2.invokeWithArguments(argsToPass);
1736 if (verbosity >= 3)
1737 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1738 if (!expected.equals(result))
1739 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1740 assertEquals(expected, result);
1741 }
1742
1743 @Test
jrose10f3b682010-01-07 16:16:45 -08001744 public void testFilterArguments() throws Throwable {
1745 if (CAN_SKIP_WORKING) return;
1746 startTest("filterArguments");
1747 for (int nargs = 1; nargs <= 6; nargs++) {
1748 for (int pos = 0; pos < nargs; pos++) {
1749 testFilterArguments(nargs, pos);
1750 }
1751 }
1752 }
1753
1754 void testFilterArguments(int nargs, int pos) throws Throwable {
1755 countTest();
jroseadc650a2011-02-11 01:26:28 -08001756 MethodHandle target = varargsList(nargs);
1757 MethodHandle filter = varargsList(1);
jrose9b82ad62011-05-26 17:37:36 -07001758 filter = filter.asType(filter.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001759 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001760 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001761 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001762 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001763 // Simulate expected effect of filter on arglist:
1764 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001765 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001766 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001767 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001768 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001769 System.out.println("result: "+result);
1770 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001771 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001772 assertEquals(expected, result);
1773 }
1774
1775 @Test
1776 public void testFoldArguments() throws Throwable {
1777 if (CAN_SKIP_WORKING) return;
1778 startTest("foldArguments");
1779 for (int nargs = 0; nargs <= 4; nargs++) {
1780 for (int fold = 0; fold <= nargs; fold++) {
1781 for (int pos = 0; pos <= nargs; pos++) {
1782 testFoldArguments(nargs, pos, fold);
1783 }
1784 }
1785 }
1786 }
1787
1788 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1789 if (pos != 0) return; // can fold only at pos=0 for now
1790 countTest();
jroseadc650a2011-02-11 01:26:28 -08001791 MethodHandle target = varargsList(1 + nargs);
1792 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08001793 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001794 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001795 System.out.println("fold "+target+" with "+combine);
1796 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1797 // Simulate expected effect of combiner on arglist:
jrose49494522012-01-18 17:34:29 -08001798 List<Object> expected = new ArrayList<>(argsToPass);
jrose10f3b682010-01-07 16:16:45 -08001799 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001800 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001801 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07001802 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08001803 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07001804 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001805 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001806 System.out.println("result: "+result);
1807 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001808 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001809 assertEquals(expected, result);
1810 }
1811
1812 @Test
1813 public void testDropArguments() throws Throwable {
1814 if (CAN_SKIP_WORKING) return;
1815 startTest("dropArguments");
1816 for (int nargs = 0; nargs <= 4; nargs++) {
1817 for (int drop = 1; drop <= 4; drop++) {
1818 for (int pos = 0; pos <= nargs; pos++) {
1819 testDropArguments(nargs, pos, drop);
1820 }
1821 }
1822 }
1823 }
1824
1825 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1826 countTest();
jroseadc650a2011-02-11 01:26:28 -08001827 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001828 Object[] args = randomArgs(target.type().parameterArray());
1829 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
jrose49494522012-01-18 17:34:29 -08001830 Collections.nCopies(drop, Object.class).toArray(new Class<?>[0]));
jrose10f3b682010-01-07 16:16:45 -08001831 List<Object> resList = Arrays.asList(args);
jrose49494522012-01-18 17:34:29 -08001832 List<Object> argsToDrop = new ArrayList<>(resList);
jrose10f3b682010-01-07 16:16:45 -08001833 for (int i = drop; i > 0; i--) {
1834 argsToDrop.add(pos, "blort#"+i);
1835 }
jrose900bafd2010-10-30 21:08:23 -07001836 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08001837 Object res2List = Arrays.asList((Object[])res2);
1838 //if (!resList.equals(res2List))
1839 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1840 assertEquals(resList, res2List);
1841 }
1842
1843 @Test
1844 public void testInvokers() throws Throwable {
1845 if (CAN_SKIP_WORKING) return;
1846 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1847 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
jrose49494522012-01-18 17:34:29 -08001848 Set<MethodType> done = new HashSet<>();
jrose10f3b682010-01-07 16:16:45 -08001849 for (int i = 0; i <= 6; i++) {
jroseb4be0262011-07-16 15:44:33 -07001850 if (CAN_TEST_LIGHTLY && i > 3) break;
jrose10f3b682010-01-07 16:16:45 -08001851 MethodType gtype = MethodType.genericMethodType(i);
jrose49494522012-01-18 17:34:29 -08001852 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose10f3b682010-01-07 16:16:45 -08001853 for (int j = -1; j < i; j++) {
1854 MethodType type = gtype;
1855 if (j < 0)
1856 type = type.changeReturnType(argType);
1857 else if (argType == void.class)
1858 continue;
1859 else
1860 type = type.changeParameterType(j, argType);
jrose10f3b682010-01-07 16:16:45 -08001861 if (done.add(type))
1862 testInvokers(type);
1863 MethodType vtype = type.changeReturnType(void.class);
1864 if (done.add(vtype))
1865 testInvokers(vtype);
1866 }
1867 }
1868 }
1869 }
1870
1871 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001872 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001873 System.out.println("test invokers for "+type);
1874 int nargs = type.parameterCount();
1875 boolean testRetCode = type.returnType() != void.class;
1876 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1877 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08001878 assertTrue(target.isVarargsCollector());
1879 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08001880 Object[] args = randomArgs(type.parameterArray());
jrose49494522012-01-18 17:34:29 -08001881 List<Object> targetPlusArgs = new ArrayList<>(Arrays.asList(args));
jrose10f3b682010-01-07 16:16:45 -08001882 targetPlusArgs.add(0, target);
1883 int code = (Integer) invokee(args);
1884 Object log = logEntry("invokee", args);
1885 assertEquals(log.hashCode(), code);
1886 assertCalled("invokee", args);
1887 MethodHandle inv;
1888 Object result;
1889 // exact invoker
1890 countTest();
1891 calledLog.clear();
1892 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07001893 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001894 if (testRetCode) assertEquals(code, result);
1895 assertCalled("invokee", args);
1896 // generic invoker
1897 countTest();
jrose79e0a6c2011-05-12 19:27:33 -07001898 inv = MethodHandles.invoker(type);
jrose9b82ad62011-05-26 17:37:36 -07001899 if (nargs <= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001900 calledLog.clear();
1901 switch (nargs) {
1902 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001903 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001904 break;
1905 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001906 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001907 break;
1908 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001909 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001910 break;
1911 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001912 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001913 break;
1914 }
1915 if (testRetCode) assertEquals(code, result);
1916 assertCalled("invokee", args);
1917 }
1918 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001919 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001920 if (testRetCode) assertEquals(code, result);
1921 assertCalled("invokee", args);
1922 // varargs invoker #0
1923 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001924 inv = MethodHandles.spreadInvoker(type, 0);
jrose9b82ad62011-05-26 17:37:36 -07001925 if (type.returnType() == Object.class) {
1926 result = inv.invokeExact(target, args);
1927 } else if (type.returnType() == void.class) {
1928 result = null; inv.invokeExact(target, args);
1929 } else {
1930 result = inv.invokeWithArguments(target, (Object) args);
1931 }
jrose10f3b682010-01-07 16:16:45 -08001932 if (testRetCode) assertEquals(code, result);
1933 assertCalled("invokee", args);
jrose9b82ad62011-05-26 17:37:36 -07001934 if (nargs >= 1 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001935 // varargs invoker #1
1936 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001937 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001938 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001939 if (testRetCode) assertEquals(code, result);
1940 assertCalled("invokee", args);
1941 }
jrose9b82ad62011-05-26 17:37:36 -07001942 if (nargs >= 2 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001943 // varargs invoker #2
1944 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001945 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001946 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001947 if (testRetCode) assertEquals(code, result);
1948 assertCalled("invokee", args);
1949 }
jrose9b82ad62011-05-26 17:37:36 -07001950 if (nargs >= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001951 // varargs invoker #3
1952 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001953 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001954 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001955 if (testRetCode) assertEquals(code, result);
1956 assertCalled("invokee", args);
1957 }
1958 for (int k = 0; k <= nargs; k++) {
1959 // varargs invoker #0..N
jroseb4be0262011-07-16 15:44:33 -07001960 if (CAN_TEST_LIGHTLY && (k > 1 || k < nargs - 1)) continue;
jrose10f3b682010-01-07 16:16:45 -08001961 countTest();
1962 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001963 inv = MethodHandles.spreadInvoker(type, k);
jrose9b82ad62011-05-26 17:37:36 -07001964 MethodType expType = (type.dropParameterTypes(k, nargs)
1965 .appendParameterTypes(Object[].class)
1966 .insertParameterTypes(0, MethodHandle.class));
1967 assertEquals(expType, inv.type());
jrose49494522012-01-18 17:34:29 -08001968 List<Object> targetPlusVarArgs = new ArrayList<>(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001969 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1970 Object[] tail = tailList.toArray();
1971 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07001972 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08001973 if (testRetCode) assertEquals(code, result);
1974 assertCalled("invokee", args);
1975 }
jrose900bafd2010-10-30 21:08:23 -07001976
jrose10f3b682010-01-07 16:16:45 -08001977 // dynamic invoker
1978 countTest();
jroseb90d2e72010-12-16 15:59:27 -08001979 CallSite site = new MutableCallSite(type);
1980 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07001981
1982 // see if we get the result of the original target:
1983 try {
1984 result = inv.invokeWithArguments(args);
1985 assertTrue("should not reach here", false);
1986 } catch (IllegalStateException ex) {
1987 String msg = ex.getMessage();
1988 assertTrue(msg, msg.contains("site"));
1989 }
1990
1991 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08001992 site.setTarget(target);
1993 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001994 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001995 if (testRetCode) assertEquals(code, result);
1996 assertCalled("invokee", args);
1997 }
1998
1999 static Object invokee(Object... args) {
2000 return called("invokee", args).hashCode();
2001 }
2002
jrose55220c32009-10-21 23:19:48 -07002003 private static final String MISSING_ARG = "missingArg";
jroseb4be0262011-07-16 15:44:33 -07002004 private static final String MISSING_ARG_2 = "missingArg#2";
jrose55220c32009-10-21 23:19:48 -07002005 static Object targetIfEquals() {
2006 return called("targetIfEquals");
2007 }
2008 static Object fallbackIfNotEquals() {
2009 return called("fallbackIfNotEquals");
2010 }
2011 static Object targetIfEquals(Object x) {
2012 assertEquals(x, MISSING_ARG);
2013 return called("targetIfEquals", x);
2014 }
2015 static Object fallbackIfNotEquals(Object x) {
2016 assertFalse(x.toString(), x.equals(MISSING_ARG));
2017 return called("fallbackIfNotEquals", x);
2018 }
2019 static Object targetIfEquals(Object x, Object y) {
2020 assertEquals(x, y);
2021 return called("targetIfEquals", x, y);
2022 }
2023 static Object fallbackIfNotEquals(Object x, Object y) {
2024 assertFalse(x.toString(), x.equals(y));
2025 return called("fallbackIfNotEquals", x, y);
2026 }
2027 static Object targetIfEquals(Object x, Object y, Object z) {
2028 assertEquals(x, y);
2029 return called("targetIfEquals", x, y, z);
2030 }
2031 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
2032 assertFalse(x.toString(), x.equals(y));
2033 return called("fallbackIfNotEquals", x, y, z);
2034 }
2035
jrose10f3b682010-01-07 16:16:45 -08002036 @Test
2037 public void testGuardWithTest() throws Throwable {
2038 if (CAN_SKIP_WORKING) return;
2039 startTest("guardWithTest");
jroseb4be0262011-07-16 15:44:33 -07002040 for (int nargs = 0; nargs <= 50; nargs++) {
2041 if (CAN_TEST_LIGHTLY && nargs > 7) break;
jrose10f3b682010-01-07 16:16:45 -08002042 testGuardWithTest(nargs, Object.class);
2043 testGuardWithTest(nargs, String.class);
2044 }
2045 }
2046 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07002047 testGuardWithTest(nargs, 0, argClass);
2048 if (nargs <= 5 || nargs % 10 == 3) {
2049 for (int testDrops = 1; testDrops <= nargs; testDrops++)
2050 testGuardWithTest(nargs, testDrops, argClass);
2051 }
2052 }
2053 void testGuardWithTest(int nargs, int testDrops, Class<?> argClass) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002054 countTest();
jroseb4be0262011-07-16 15:44:33 -07002055 int nargs1 = Math.min(3, nargs);
jrose10f3b682010-01-07 16:16:45 -08002056 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
jroseb4be0262011-07-16 15:44:33 -07002057 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs1));
2058 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs1));
jrose10f3b682010-01-07 16:16:45 -08002059 while (test.type().parameterCount() > nargs)
jroseb4be0262011-07-16 15:44:33 -07002060 // 0: test = constant(MISSING_ARG.equals(MISSING_ARG))
2061 // 1: test = lambda (_) MISSING_ARG.equals(_)
jrose10f3b682010-01-07 16:16:45 -08002062 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
2063 if (argClass != Object.class) {
2064 test = changeArgTypes(test, argClass);
2065 target = changeArgTypes(target, argClass);
2066 fallback = changeArgTypes(fallback, argClass);
2067 }
jroseb4be0262011-07-16 15:44:33 -07002068 int testArgs = nargs - testDrops;
2069 assert(testArgs >= 0);
2070 test = addTrailingArgs(test, Math.min(testArgs, nargs), argClass);
2071 target = addTrailingArgs(target, nargs, argClass);
2072 fallback = addTrailingArgs(fallback, nargs, argClass);
jrose10f3b682010-01-07 16:16:45 -08002073 Object[][] argLists = {
2074 { },
2075 { "foo" }, { MISSING_ARG },
2076 { "foo", "foo" }, { "foo", "bar" },
2077 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
2078 };
2079 for (Object[] argList : argLists) {
jroseb4be0262011-07-16 15:44:33 -07002080 Object[] argList1 = argList;
2081 if (argList.length != nargs) {
2082 if (argList.length != nargs1) continue;
2083 argList1 = Arrays.copyOf(argList, nargs);
2084 Arrays.fill(argList1, nargs1, nargs, MISSING_ARG_2);
2085 }
2086 MethodHandle test1 = test;
2087 if (test1.type().parameterCount() > testArgs) {
2088 int pc = test1.type().parameterCount();
2089 test1 = MethodHandles.insertArguments(test, testArgs, Arrays.copyOfRange(argList1, testArgs, pc));
2090 }
2091 MethodHandle mh = MethodHandles.guardWithTest(test1, target, fallback);
2092 assertEquals(target.type(), mh.type());
jrose10f3b682010-01-07 16:16:45 -08002093 boolean equals;
2094 switch (nargs) {
2095 case 0: equals = true; break;
2096 case 1: equals = MISSING_ARG.equals(argList[0]); break;
2097 default: equals = argList[0].equals(argList[1]); break;
2098 }
2099 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07002100 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002101 System.out.println(logEntry(willCall, argList));
jroseb4be0262011-07-16 15:44:33 -07002102 Object result = mh.invokeWithArguments(argList1);
jrose10f3b682010-01-07 16:16:45 -08002103 assertCalled(willCall, argList);
2104 }
2105 }
2106
2107 @Test
2108 public void testCatchException() throws Throwable {
2109 if (CAN_SKIP_WORKING) return;
2110 startTest("catchException");
jroseb4be0262011-07-16 15:44:33 -07002111 for (int nargs = 0; nargs < 40; nargs++) {
2112 if (CAN_TEST_LIGHTLY && nargs > 7) break;
2113 for (int throwMode = 0; throwMode < THROW_MODE_LIMIT; throwMode++) {
2114 testCatchException(int.class, new ClassCastException("testing"), throwMode, nargs);
2115 if (CAN_TEST_LIGHTLY && nargs > 3) continue;
2116 testCatchException(void.class, new java.io.IOException("testing"), throwMode, nargs);
2117 testCatchException(String.class, new LinkageError("testing"), throwMode, nargs);
jrose10f3b682010-01-07 16:16:45 -08002118 }
2119 }
2120 }
2121
jroseb4be0262011-07-16 15:44:33 -07002122 static final int THROW_NOTHING = 0, THROW_CAUGHT = 1, THROW_UNCAUGHT = 2, THROW_THROUGH_ADAPTER = 3, THROW_MODE_LIMIT = 4;
2123
2124 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs) throws Throwable {
2125 testCatchException(returnType, thrown, throwMode, nargs, 0);
2126 if (nargs <= 5 || nargs % 10 == 3) {
2127 for (int catchDrops = 1; catchDrops <= nargs; catchDrops++)
2128 testCatchException(returnType, thrown, throwMode, nargs, catchDrops);
2129 }
2130 }
2131
jrose10f3b682010-01-07 16:16:45 -08002132 private static <T extends Throwable>
2133 Object throwOrReturn(Object normal, T exception) throws T {
jroseb4be0262011-07-16 15:44:33 -07002134 if (exception != null) {
2135 called("throwOrReturn/throw", normal, exception);
2136 throw exception;
2137 }
2138 called("throwOrReturn/normal", normal, exception);
jrose10f3b682010-01-07 16:16:45 -08002139 return normal;
2140 }
jroseb4be0262011-07-16 15:44:33 -07002141 private int fakeIdentityCount;
2142 private Object fakeIdentity(Object x) {
2143 System.out.println("should throw through this!");
2144 fakeIdentityCount++;
2145 return x;
2146 }
jrose10f3b682010-01-07 16:16:45 -08002147
jroseb4be0262011-07-16 15:44:33 -07002148 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs, int catchDrops) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002149 countTest();
jrose2cc9c832010-04-30 23:48:23 -07002150 if (verbosity >= 3)
jroseb4be0262011-07-16 15:44:33 -07002151 System.out.println("catchException rt="+returnType+" throw="+throwMode+" nargs="+nargs+" drops="+catchDrops);
jrose10f3b682010-01-07 16:16:45 -08002152 Class<? extends Throwable> exType = thrown.getClass();
jroseb4be0262011-07-16 15:44:33 -07002153 if (throwMode > THROW_CAUGHT) thrown = new UnsupportedOperationException("do not catch this");
jrose10f3b682010-01-07 16:16:45 -08002154 MethodHandle throwOrReturn
2155 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2156 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb4be0262011-07-16 15:44:33 -07002157 if (throwMode == THROW_THROUGH_ADAPTER) {
2158 MethodHandle fakeIdentity
2159 = PRIVATE.findVirtual(MethodHandlesTest.class, "fakeIdentity",
2160 MethodType.methodType(Object.class, Object.class)).bindTo(this);
2161 for (int i = 0; i < 10; i++)
2162 throwOrReturn = MethodHandles.filterReturnValue(throwOrReturn, fakeIdentity);
2163 }
2164 int nargs1 = Math.max(2, nargs);
jroseb90d2e72010-12-16 15:59:27 -08002165 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jroseb4be0262011-07-16 15:44:33 -07002166 thrower = addTrailingArgs(thrower, nargs, Object.class);
2167 int catchArgc = 1 + nargs - catchDrops;
2168 MethodHandle catcher = varargsList(catchArgc).asType(MethodType.genericMethodType(catchArgc));
jrose10f3b682010-01-07 16:16:45 -08002169 Object[] args = randomArgs(nargs, Object.class);
jroseb4be0262011-07-16 15:44:33 -07002170 Object arg0 = MISSING_ARG;
2171 Object arg1 = (throwMode == THROW_NOTHING) ? (Throwable) null : thrown;
2172 if (nargs > 0) arg0 = args[0];
2173 if (nargs > 1) args[1] = arg1;
2174 assertEquals(nargs1, thrower.type().parameterCount());
2175 if (nargs < nargs1) {
2176 Object[] appendArgs = { arg0, arg1 };
2177 appendArgs = Arrays.copyOfRange(appendArgs, nargs, nargs1);
2178 thrower = MethodHandles.insertArguments(thrower, nargs, appendArgs);
2179 }
2180 assertEquals(nargs, thrower.type().parameterCount());
2181 MethodHandle target = MethodHandles.catchException(thrower, exType, catcher);
2182 assertEquals(thrower.type(), target.type());
2183 assertEquals(nargs, target.type().parameterCount());
2184 //System.out.println("catching with "+target+" : "+throwOrReturn);
2185 Object returned;
2186 try {
2187 returned = target.invokeWithArguments(args);
2188 } catch (Throwable ex) {
2189 assertSame("must get the out-of-band exception", thrown, ex);
2190 if (throwMode <= THROW_CAUGHT)
2191 assertEquals(THROW_UNCAUGHT, throwMode);
2192 returned = ex;
2193 }
2194 assertCalled("throwOrReturn/"+(throwMode == THROW_NOTHING ? "normal" : "throw"), arg0, arg1);
jrose10f3b682010-01-07 16:16:45 -08002195 //System.out.println("return from "+target+" : "+returned);
jroseb4be0262011-07-16 15:44:33 -07002196 if (throwMode == THROW_NOTHING) {
2197 assertSame(arg0, returned);
2198 } else if (throwMode == THROW_CAUGHT) {
jrose49494522012-01-18 17:34:29 -08002199 List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
jroseb4be0262011-07-16 15:44:33 -07002200 // catcher receives an initial subsequence of target arguments:
2201 catchArgs.subList(nargs - catchDrops, nargs).clear();
2202 // catcher also receives the exception, prepended:
jrose10f3b682010-01-07 16:16:45 -08002203 catchArgs.add(0, thrown);
2204 assertEquals(catchArgs, returned);
2205 }
jroseb4be0262011-07-16 15:44:33 -07002206 assertEquals(0, fakeIdentityCount);
jrose10f3b682010-01-07 16:16:45 -08002207 }
2208
2209 @Test
2210 public void testThrowException() throws Throwable {
2211 if (CAN_SKIP_WORKING) return;
2212 startTest("throwException");
2213 testThrowException(int.class, new ClassCastException("testing"));
2214 testThrowException(void.class, new java.io.IOException("testing"));
2215 testThrowException(String.class, new LinkageError("testing"));
2216 }
2217
2218 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2219 countTest();
2220 Class<? extends Throwable> exType = thrown.getClass();
2221 MethodHandle target = MethodHandles.throwException(returnType, exType);
2222 //System.out.println("throwing with "+target+" : "+thrown);
2223 MethodType expectedType = MethodType.methodType(returnType, exType);
2224 assertEquals(expectedType, target.type());
jrose9b82ad62011-05-26 17:37:36 -07002225 target = target.asType(target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08002226 Throwable caught = null;
2227 try {
jrose2cc9c832010-04-30 23:48:23 -07002228 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08002229 fail("got "+res+" instead of throwing "+thrown);
2230 } catch (Throwable ex) {
2231 if (ex != thrown) {
2232 if (ex instanceof Error) throw (Error)ex;
2233 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2234 }
2235 caught = ex;
2236 }
2237 assertSame(thrown, caught);
2238 }
2239
2240 @Test
jroseb4be0262011-07-16 15:44:33 -07002241 public void testInterfaceCast() throws Throwable {
2242 for (Class<?> ctype : new Class<?>[]{ Object.class, String.class, CharSequence.class, Number.class, Iterable.class}) {
2243 testInterfaceCast(ctype, false, false);
2244 testInterfaceCast(ctype, true, false);
2245 testInterfaceCast(ctype, false, true);
2246 testInterfaceCast(ctype, true, true);
2247 }
2248 }
2249 public void testInterfaceCast(Class<?> ctype, boolean doret, boolean docast) throws Throwable {
2250 String str = "normal return value";
2251 MethodHandle mh = MethodHandles.identity(String.class);
2252 MethodType mt = mh.type();
2253 if (doret) mt = mt.changeReturnType(ctype);
2254 else mt = mt.changeParameterType(0, ctype);
2255 if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
2256 else mh = mh.asType(mt);
2257 // this bit is needed to make the interface types disappear for invokeWithArguments:
2258 mh = MethodHandles.explicitCastArguments(mh, mt.generic());
2259 boolean expectFail = !ctype.isInstance(str);
2260 if (ctype.isInterface()) {
2261 // special rules: interfaces slide by more frequently
2262 if (docast || !doret) expectFail = false;
2263 }
2264 Object res;
2265 try {
2266 res = mh.invokeWithArguments(str);
2267 } catch (Exception ex) {
2268 res = ex;
2269 }
2270 boolean sawFail = !(res instanceof String);
2271 if (sawFail != expectFail) {
2272 System.out.println("*** testInterfaceCast: "+mh+" was "+mt+" => "+res+(docast ? " (explicitCastArguments)" : ""));
2273 }
2274 if (!sawFail) {
2275 assertFalse(res.toString(), expectFail);
2276 assertEquals(str, res);
2277 } else {
2278 assertTrue(res.toString(), expectFail);
2279 }
2280 }
2281
2282 @Test
jrose10f3b682010-01-07 16:16:45 -08002283 public void testCastFailure() throws Throwable {
2284 if (CAN_SKIP_WORKING) return;
2285 startTest("testCastFailure");
2286 testCastFailure("cast/argument", 11000);
2287 testCastFailure("unbox/argument", 11000);
2288 testCastFailure("cast/return", 11000);
2289 testCastFailure("unbox/return", 11000);
2290 }
2291
jrose900bafd2010-10-30 21:08:23 -07002292 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07002293 public MethodHandle asMethodHandle() {
2294 return VALUE.bindTo(this);
2295 }
jrose10f3b682010-01-07 16:16:45 -08002296 Object value(Object x) {
2297 trace("value", x);
2298 if (boo != null) return boo;
2299 return x;
2300 }
2301 Object boo;
2302 void boo(Object x) { boo = x; }
2303
2304 static void trace(String x, Object y) {
2305 if (verbosity > 8) System.out.println(x+"="+y);
2306 }
2307 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2308 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2309 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07002310 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
2311 static {
2312 try {
2313 VALUE = PRIVATE.findVirtual(
2314 Surprise.class, "value",
2315 MethodType.methodType(Object.class, Object.class));
2316 REF_IDENTITY = PRIVATE.findStatic(
2317 Surprise.class, "refIdentity",
2318 MethodType.methodType(Object.class, Object.class));
2319 BOX_IDENTITY = PRIVATE.findStatic(
2320 Surprise.class, "boxIdentity",
2321 MethodType.methodType(Integer.class, Integer.class));
2322 INT_IDENTITY = PRIVATE.findStatic(
2323 Surprise.class, "intIdentity",
2324 MethodType.methodType(int.class, int.class));
jrose49494522012-01-18 17:34:29 -08002325 } catch (NoSuchMethodException | IllegalAccessException ex) {
jrosea1ebbe62010-09-08 18:40:23 -07002326 throw new RuntimeException(ex);
2327 }
2328 }
jrose10f3b682010-01-07 16:16:45 -08002329 }
2330
jrose49494522012-01-18 17:34:29 -08002331 @SuppressWarnings("ConvertToStringSwitch")
jrose10f3b682010-01-07 16:16:45 -08002332 void testCastFailure(String mode, int okCount) throws Throwable {
2333 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07002334 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002335 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002336 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002337 if (mode.endsWith("/return")) {
2338 if (mode.equals("unbox/return")) {
2339 // fail on return to ((Integer)surprise).intValue
jrose9b82ad62011-05-26 17:37:36 -07002340 surprise = surprise.asType(MethodType.methodType(int.class, Object.class));
2341 identity = identity.asType(MethodType.methodType(int.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002342 } else if (mode.equals("cast/return")) {
2343 // fail on return to (Integer)surprise
jrose9b82ad62011-05-26 17:37:36 -07002344 surprise = surprise.asType(MethodType.methodType(Integer.class, Object.class));
2345 identity = identity.asType(MethodType.methodType(Integer.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002346 }
2347 } else if (mode.endsWith("/argument")) {
2348 MethodHandle callee = null;
2349 if (mode.equals("unbox/argument")) {
2350 // fail on handing surprise to int argument
2351 callee = Surprise.INT_IDENTITY;
2352 } else if (mode.equals("cast/argument")) {
2353 // fail on handing surprise to Integer argument
2354 callee = Surprise.BOX_IDENTITY;
2355 }
2356 if (callee != null) {
jrose9b82ad62011-05-26 17:37:36 -07002357 callee = callee.asType(MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002358 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2359 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002360 }
2361 }
jrosea1ebbe62010-09-08 18:40:23 -07002362 assertNotSame(mode, surprise, surprise0);
jrose9b82ad62011-05-26 17:37:36 -07002363 identity = identity.asType(MethodType.genericMethodType(1));
2364 surprise = surprise.asType(MethodType.genericMethodType(1));
jrose10f3b682010-01-07 16:16:45 -08002365 Object x = 42;
2366 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002367 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002368 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002369 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002370 assertEquals(x, z);
2371 }
2372 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002373 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002374 assertEquals(x, y);
2375 try {
jrose2cc9c832010-04-30 23:48:23 -07002376 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002377 System.out.println("Failed to throw; got z="+z);
2378 assertTrue(false);
jrose320b7692011-05-12 19:27:49 -07002379 } catch (ClassCastException ex) {
jrose10f3b682010-01-07 16:16:45 -08002380 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002381 System.out.println("caught "+ex);
2382 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08002383 ex.printStackTrace();
jrose320b7692011-05-12 19:27:49 -07002384 assertTrue(true); // all is well
jrose10f3b682010-01-07 16:16:45 -08002385 }
2386 }
2387
jrose45b7a332010-05-03 23:32:47 -07002388 static Example userMethod(Object o, String s, int i) {
2389 called("userMethod", o, s, i);
2390 return null;
2391 }
2392
2393 @Test
2394 public void testUserClassInSignature() throws Throwable {
2395 if (CAN_SKIP_WORKING) return;
2396 startTest("testUserClassInSignature");
2397 Lookup lookup = MethodHandles.lookup();
2398 String name; MethodType mt; MethodHandle mh;
2399 Object[] args;
2400
2401 // Try a static method.
2402 name = "userMethod";
2403 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2404 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2405 assertEquals(mt, mh.type());
2406 assertEquals(Example.class, mh.type().returnType());
2407 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002408 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002409 assertCalled(name, args);
2410
2411 // Try a virtual method.
2412 name = "v2";
2413 mt = MethodType.methodType(Object.class, Object.class, int.class);
2414 mh = lookup.findVirtual(Example.class, name, mt);
2415 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2416 assertTrue(mh.type().parameterList().contains(Example.class));
2417 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002418 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002419 assertCalled(name, args);
2420 }
jrosebe2db602010-09-08 18:40:34 -07002421
2422 static void runForRunnable() {
2423 called("runForRunnable");
2424 }
jroseaf751942011-06-14 22:47:12 -07002425 public interface Fooable {
jroseb4be0262011-07-16 15:44:33 -07002426 // overloads:
jrose49494522012-01-18 17:34:29 -08002427 Object foo(Object x, String y);
2428 List<?> foo(String x, int y);
2429 Object foo(String x);
jrosebe2db602010-09-08 18:40:34 -07002430 }
jroseb4be0262011-07-16 15:44:33 -07002431 static Object fooForFooable(String x, Object... y) {
2432 return called("fooForFooable/"+x, y);
jrosebe2db602010-09-08 18:40:34 -07002433 }
jrose49494522012-01-18 17:34:29 -08002434 @SuppressWarnings("serial") // not really a public API, just a test case
jroseaf751942011-06-14 22:47:12 -07002435 public static class MyCheckedException extends Exception {
jrosebe2db602010-09-08 18:40:34 -07002436 }
jroseaf751942011-06-14 22:47:12 -07002437 public interface WillThrow {
jrosebe2db602010-09-08 18:40:34 -07002438 void willThrow() throws MyCheckedException;
2439 }
jroseb4be0262011-07-16 15:44:33 -07002440 /*non-public*/ interface PrivateRunnable {
2441 public void run();
2442 }
jrosebe2db602010-09-08 18:40:34 -07002443
2444 @Test
jroseb4be0262011-07-16 15:44:33 -07002445 public void testAsInterfaceInstance() throws Throwable {
jrosebe2db602010-09-08 18:40:34 -07002446 if (CAN_SKIP_WORKING) return;
jroseb4be0262011-07-16 15:44:33 -07002447 startTest("testAsInterfaceInstance");
jrosebe2db602010-09-08 18:40:34 -07002448 Lookup lookup = MethodHandles.lookup();
jroseb4be0262011-07-16 15:44:33 -07002449 // test typical case: Runnable.run
jrosebe2db602010-09-08 18:40:34 -07002450 {
jroseb4be0262011-07-16 15:44:33 -07002451 countTest();
2452 if (verbosity >= 2) System.out.println("Runnable");
jrosebe2db602010-09-08 18:40:34 -07002453 MethodType mt = MethodType.methodType(void.class);
2454 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
jrose9b82ad62011-05-26 17:37:36 -07002455 Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002456 proxy.run();
2457 assertCalled("runForRunnable");
2458 }
jroseb4be0262011-07-16 15:44:33 -07002459 // well known single-name overloaded interface: Appendable.append
jrosebe2db602010-09-08 18:40:34 -07002460 {
jroseb4be0262011-07-16 15:44:33 -07002461 countTest();
2462 if (verbosity >= 2) System.out.println("Appendable");
jrose49494522012-01-18 17:34:29 -08002463 ArrayList<List<?>> appendResults = new ArrayList<>();
jroseb4be0262011-07-16 15:44:33 -07002464 MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
2465 append = append.asType(MethodType.methodType(void.class, List.class)); // specialize the type
2466 MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
2467 MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
2468 Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
2469 proxy.append("one");
2470 proxy.append("two", 3, 4);
2471 proxy.append('5');
2472 assertEquals(Arrays.asList(Arrays.asList("one"),
2473 Arrays.asList("two", 3, 4),
2474 Arrays.asList('5')),
2475 appendResults);
2476 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
2477 appendResults.clear();
2478 Formatter formatter = new Formatter(proxy);
2479 String fmt = "foo str=%s char='%c' num=%d";
2480 Object[] fmtArgs = { "str!", 'C', 42 };
2481 String expect = String.format(fmt, fmtArgs);
2482 formatter.format(fmt, fmtArgs);
2483 String actual = "";
2484 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
jrose49494522012-01-18 17:34:29 -08002485 for (List<?> l : appendResults) {
jroseb4be0262011-07-16 15:44:33 -07002486 Object x = l.get(0);
2487 switch (l.size()) {
2488 case 1: actual += x; continue;
jrose49494522012-01-18 17:34:29 -08002489 case 3: actual += ((String)x).substring((int)(Object)l.get(1), (int)(Object)l.get(2)); continue;
jroseb4be0262011-07-16 15:44:33 -07002490 }
2491 actual += l;
2492 }
2493 if (verbosity >= 3) System.out.println("expect="+expect);
2494 if (verbosity >= 3) System.out.println("actual="+actual);
2495 assertEquals(expect, actual);
jrosebe2db602010-09-08 18:40:34 -07002496 }
jroseb4be0262011-07-16 15:44:33 -07002497 // test case of an single name which is overloaded: Fooable.foo(...)
2498 {
2499 if (verbosity >= 2) System.out.println("Fooable");
2500 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable",
2501 MethodType.methodType(Object.class, String.class, Object[].class));
2502 Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
2503 for (Method m : Fooable.class.getDeclaredMethods()) {
2504 countTest();
2505 assertSame("foo", m.getName());
2506 if (verbosity > 3)
2507 System.out.println("calling "+m);
2508 MethodHandle invoker = lookup.unreflect(m);
2509 MethodType mt = invoker.type();
2510 Class<?>[] types = mt.parameterArray();
2511 types[0] = int.class; // placeholder
2512 Object[] args = randomArgs(types);
2513 args[0] = proxy;
2514 if (verbosity > 3)
2515 System.out.println("calling "+m+" on "+Arrays.asList(args));
2516 Object result = invoker.invokeWithArguments(args);
2517 if (verbosity > 4)
2518 System.out.println("result = "+result);
2519 String name = "fooForFooable/"+args[1];
2520 Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
2521 assertCalled(name, argTail);
2522 assertEquals(result, logEntry(name, argTail));
2523 }
2524 }
2525 // test processing of thrown exceptions:
jrosebe2db602010-09-08 18:40:34 -07002526 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2527 new InternalError("ok"),
2528 new Throwable("fail"),
2529 new Exception("fail"),
2530 new MyCheckedException()
2531 }) {
2532 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2533 mh = MethodHandles.insertArguments(mh, 0, ex);
jrose9b82ad62011-05-26 17:37:36 -07002534 WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002535 try {
jroseb4be0262011-07-16 15:44:33 -07002536 countTest();
jrosebe2db602010-09-08 18:40:34 -07002537 proxy.willThrow();
2538 System.out.println("Failed to throw: "+ex);
2539 assertTrue(false);
2540 } catch (Throwable ex1) {
jroseb4be0262011-07-16 15:44:33 -07002541 if (verbosity > 3) {
jrosebe2db602010-09-08 18:40:34 -07002542 System.out.println("throw "+ex);
2543 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2544 }
2545 if (ex instanceof RuntimeException ||
2546 ex instanceof Error) {
2547 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2548 } else if (ex instanceof MyCheckedException) {
2549 assertSame("must pass declared exception out without wrapping", ex, ex1);
2550 } else {
2551 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
jroseaf751942011-06-14 22:47:12 -07002552 if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
2553 ex1.printStackTrace();
2554 }
2555 assertSame(ex, ex1.getCause());
jrosebe2db602010-09-08 18:40:34 -07002556 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
jrosebe2db602010-09-08 18:40:34 -07002557 }
2558 }
2559 }
jroseb4be0262011-07-16 15:44:33 -07002560 // Test error checking on bad interfaces:
jrose49494522012-01-18 17:34:29 -08002561 for (Class<?> nonSMI : new Class<?>[] { Object.class,
jrosebe2db602010-09-08 18:40:34 -07002562 String.class,
2563 CharSequence.class,
jroseb4be0262011-07-16 15:44:33 -07002564 java.io.Serializable.class,
2565 PrivateRunnable.class,
jrosebe2db602010-09-08 18:40:34 -07002566 Example.class }) {
jroseb4be0262011-07-16 15:44:33 -07002567 if (verbosity > 2) System.out.println(nonSMI.getName());
jrosebe2db602010-09-08 18:40:34 -07002568 try {
jroseb4be0262011-07-16 15:44:33 -07002569 countTest(false);
2570 MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
2571 assertTrue("Failed to throw on "+nonSMI.getName(), false);
jrosebe2db602010-09-08 18:40:34 -07002572 } catch (IllegalArgumentException ex) {
jroseb4be0262011-07-16 15:44:33 -07002573 if (verbosity > 2) System.out.println(nonSMI.getSimpleName()+": "+ex);
2574 // Object: java.lang.IllegalArgumentException:
2575 // not a public interface: java.lang.Object
2576 // String: java.lang.IllegalArgumentException:
2577 // not a public interface: java.lang.String
2578 // CharSequence: java.lang.IllegalArgumentException:
2579 // not a single-method interface: java.lang.CharSequence
2580 // Serializable: java.lang.IllegalArgumentException:
2581 // not a single-method interface: java.io.Serializable
2582 // PrivateRunnable: java.lang.IllegalArgumentException:
2583 // not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
2584 // Example: java.lang.IllegalArgumentException:
2585 // not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
2586 }
2587 }
2588 // Test error checking on interfaces with the wrong method type:
jrose49494522012-01-18 17:34:29 -08002589 for (Class<?> intfc : new Class<?>[] { Runnable.class /*arity 0*/,
jroseb4be0262011-07-16 15:44:33 -07002590 Fooable.class /*arity 1 & 2*/ }) {
2591 int badArity = 1; // known to be incompatible
2592 if (verbosity > 2) System.out.println(intfc.getName());
2593 try {
2594 countTest(false);
2595 MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
2596 assertTrue("Failed to throw on "+intfc.getName(), false);
2597 } catch (WrongMethodTypeException ex) {
2598 if (verbosity > 2) System.out.println(intfc.getSimpleName()+": "+ex);
2599 // Runnable: java.lang.invoke.WrongMethodTypeException:
2600 // cannot convert MethodHandle(Object)Object[] to ()void
2601 // Fooable: java.lang.invoke.WrongMethodTypeException:
2602 // cannot convert MethodHandle(Object)Object[] to (Object,String)Object
jrosebe2db602010-09-08 18:40:34 -07002603 }
2604 }
2605 }
jrose43b8c122011-07-16 15:40:13 -07002606
2607 @Test
2608 public void testRunnableProxy() throws Throwable {
2609 if (CAN_SKIP_WORKING) return;
2610 startTest("testRunnableProxy");
2611 MethodHandles.Lookup lookup = MethodHandles.lookup();
2612 MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
2613 Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
2614 testRunnableProxy(r);
2615 assertCalled("runForRunnable");
2616 }
2617 private static void testRunnableProxy(Runnable r) {
2618 //7058630: JSR 292 method handle proxy violates contract for Object methods
2619 r.run();
2620 Object o = r;
2621 r = null;
2622 boolean eq = (o == o);
2623 int hc = System.identityHashCode(o);
2624 String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
2625 Object expect = Arrays.asList(st, eq, hc);
2626 if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
2627 Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
2628 if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
2629 assertEquals(expect, actual);
2630 }
jrose55220c32009-10-21 23:19:48 -07002631}
jroseada69fa2011-03-23 23:02:31 -07002632// Local abbreviated copy of sun.invoke.util.ValueConversions
jrose55220c32009-10-21 23:19:48 -07002633class ValueConversions {
2634 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2635 private static final Object[] NO_ARGS_ARRAY = {};
2636 private static Object[] makeArray(Object... args) { return args; }
2637 private static Object[] array() { return NO_ARGS_ARRAY; }
2638 private static Object[] array(Object a0)
2639 { return makeArray(a0); }
2640 private static Object[] array(Object a0, Object a1)
2641 { return makeArray(a0, a1); }
2642 private static Object[] array(Object a0, Object a1, Object a2)
2643 { return makeArray(a0, a1, a2); }
2644 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2645 { return makeArray(a0, a1, a2, a3); }
2646 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2647 Object a4)
2648 { return makeArray(a0, a1, a2, a3, a4); }
2649 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2650 Object a4, Object a5)
2651 { return makeArray(a0, a1, a2, a3, a4, a5); }
2652 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2653 Object a4, Object a5, Object a6)
2654 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2655 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2656 Object a4, Object a5, Object a6, Object a7)
2657 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2658 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2659 Object a4, Object a5, Object a6, Object a7,
2660 Object a8)
2661 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2662 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2663 Object a4, Object a5, Object a6, Object a7,
2664 Object a8, Object a9)
2665 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2666 static MethodHandle[] makeArrays() {
jrose49494522012-01-18 17:34:29 -08002667 ArrayList<MethodHandle> arrays = new ArrayList<>();
jrose55220c32009-10-21 23:19:48 -07002668 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2669 for (;;) {
2670 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002671 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002672 String name = "array";
2673 MethodHandle array = null;
2674 try {
2675 array = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002676 } catch (ReflectiveOperationException ex) {
2677 // break from loop!
jrose55220c32009-10-21 23:19:48 -07002678 }
2679 if (array == null) break;
2680 arrays.add(array);
2681 }
jrosef15905c2011-02-11 01:26:32 -08002682 assertTrue(arrays.size() == 11); // current number of methods
jrose55220c32009-10-21 23:19:48 -07002683 return arrays.toArray(new MethodHandle[0]);
2684 }
2685 static final MethodHandle[] ARRAYS = makeArrays();
2686
2687 /** Return a method handle that takes the indicated number of Object
2688 * arguments and returns an Object array of them, as if for varargs.
2689 */
2690 public static MethodHandle varargsArray(int nargs) {
2691 if (nargs < ARRAYS.length)
2692 return ARRAYS[nargs];
jroseaf751942011-06-14 22:47:12 -07002693 return MethodHandles.identity(Object[].class).asCollector(Object[].class, nargs);
jrose55220c32009-10-21 23:19:48 -07002694 }
jrose320b7692011-05-12 19:27:49 -07002695 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
2696 Class<?> elemType = arrayType.getComponentType();
2697 MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
2698 MethodHandle mh = varargsArray(nargs);
2699 if (arrayType != Object[].class)
2700 mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
2701 return mh.asType(vaType);
2702 }
2703 static Object changeArrayType(Class<?> arrayType, Object[] a) {
2704 Class<?> elemType = arrayType.getComponentType();
2705 if (!elemType.isPrimitive())
2706 return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
2707 Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
2708 for (int i = 0; i < a.length; i++)
2709 java.lang.reflect.Array.set(b, i, a[i]);
2710 return b;
2711 }
2712 private static final MethodHandle CHANGE_ARRAY_TYPE;
2713 static {
2714 try {
2715 CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
2716 MethodType.methodType(Object.class, Class.class, Object[].class));
2717 } catch (NoSuchMethodException | IllegalAccessException ex) {
2718 Error err = new InternalError("uncaught exception");
2719 err.initCause(ex);
2720 throw err;
2721 }
2722 }
jrose10f3b682010-01-07 16:16:45 -08002723
2724 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2725 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2726 private static List<Object> list() { return NO_ARGS_LIST; }
2727 private static List<Object> list(Object a0)
2728 { return makeList(a0); }
2729 private static List<Object> list(Object a0, Object a1)
2730 { return makeList(a0, a1); }
2731 private static List<Object> list(Object a0, Object a1, Object a2)
2732 { return makeList(a0, a1, a2); }
2733 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2734 { return makeList(a0, a1, a2, a3); }
2735 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2736 Object a4)
2737 { return makeList(a0, a1, a2, a3, a4); }
2738 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2739 Object a4, Object a5)
2740 { return makeList(a0, a1, a2, a3, a4, a5); }
2741 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2742 Object a4, Object a5, Object a6)
2743 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2744 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2745 Object a4, Object a5, Object a6, Object a7)
2746 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2747 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2748 Object a4, Object a5, Object a6, Object a7,
2749 Object a8)
2750 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2751 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2752 Object a4, Object a5, Object a6, Object a7,
2753 Object a8, Object a9)
2754 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2755 static MethodHandle[] makeLists() {
jrose49494522012-01-18 17:34:29 -08002756 ArrayList<MethodHandle> lists = new ArrayList<>();
jrose10f3b682010-01-07 16:16:45 -08002757 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2758 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08002759 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08002760 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2761 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08002762 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08002763 try {
jroseadc650a2011-02-11 01:26:28 -08002764 list = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002765 } catch (ReflectiveOperationException ex) {
2766 // break from loop!
jrose10f3b682010-01-07 16:16:45 -08002767 }
jroseadc650a2011-02-11 01:26:28 -08002768 if (list == null) break;
2769 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08002770 }
jrosef15905c2011-02-11 01:26:32 -08002771 assertTrue(lists.size() == 11); // current number of methods
jroseadc650a2011-02-11 01:26:28 -08002772 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08002773 }
2774 static final MethodHandle[] LISTS = makeLists();
jroseaf751942011-06-14 22:47:12 -07002775 static final MethodHandle AS_LIST;
2776 static {
2777 try {
2778 AS_LIST = IMPL_LOOKUP.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
jrose49494522012-01-18 17:34:29 -08002779 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseaf751942011-06-14 22:47:12 -07002780 }
jrose10f3b682010-01-07 16:16:45 -08002781
2782 /** Return a method handle that takes the indicated number of Object
2783 * arguments and returns List.
2784 */
2785 public static MethodHandle varargsList(int nargs) {
2786 if (nargs < LISTS.length)
2787 return LISTS[nargs];
jroseaf751942011-06-14 22:47:12 -07002788 return AS_LIST.asCollector(Object[].class, nargs);
jrose10f3b682010-01-07 16:16:45 -08002789 }
jrose55220c32009-10-21 23:19:48 -07002790}
2791// This guy tests access from outside the same package member, but inside
2792// the package itself.
2793class PackageSibling {
2794 static Lookup lookup() {
2795 return MethodHandles.lookup();
2796 }
2797}