blob: bea81b6ddac2490e863253616ceef8fbaae06187 [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
179 static List<Object> calledLog = new ArrayList<Object>();
180 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
214 static Object castToWrapperOrNull(long value, Class<?> dst) {
215 if (dst == int.class || dst == Integer.class)
216 return (int)(value);
217 if (dst == long.class || dst == Long.class)
218 return (long)(value);
219 if (dst == char.class || dst == Character.class)
220 return (char)(value);
221 if (dst == short.class || dst == Short.class)
222 return (short)(value);
223 if (dst == float.class || dst == Float.class)
224 return (float)(value);
225 if (dst == double.class || dst == Double.class)
226 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800227 if (dst == byte.class || dst == Byte.class)
228 return (byte)(value);
229 if (dst == boolean.class || dst == boolean.class)
230 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700231 return null;
232 }
233
jrose2cc9c832010-04-30 23:48:23 -0700234 static final int ONE_MILLION = (1000*1000), // first int value
235 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
236 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
237 static long nextArgVal;
238 static long nextArg(boolean moreBits) {
239 long val = nextArgVal++;
240 long sign = -(val & 1); // alternate signs
241 val >>= 1;
242 if (moreBits)
243 // Guarantee some bits in the high word.
244 // In any case keep the decimal representation simple-looking,
245 // with lots of zeroes, so as not to make the printed decimal
246 // strings unnecessarily noisy.
247 val += (val % ONE_MILLION) * TEN_BILLION;
248 return val ^ sign;
249 }
250 static int nextArg() {
251 // Produce a 32-bit result something like ONE_MILLION+(smallint).
252 // Example: 1_000_042.
253 return (int) nextArg(false);
254 }
255 static long nextArg(Class<?> kind) {
256 if (kind == long.class || kind == Long.class ||
257 kind == double.class || kind == Double.class)
258 // produce a 64-bit result something like
259 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
260 // Example: 10_000_420_001_000_042.
261 return nextArg(true);
262 return (long) nextArg();
263 }
264
jrose55220c32009-10-21 23:19:48 -0700265 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700266 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700267 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700268 return wrap;
269 }
jroseada69fa2011-03-23 23:02:31 -0700270// import sun.invoke.util.Wrapper;
jrose55220c32009-10-21 23:19:48 -0700271// Wrapper wrap = Wrapper.forBasicType(dst);
272// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
273// wrap = Wrapper.forWrapperType(dst);
274// if (wrap != Wrapper.OBJECT)
275// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700276 if (param.isInterface()) {
277 for (Class<?> c : param.getClasses()) {
278 if (param.isAssignableFrom(c) && !c.isInterface())
279 { param = c; break; }
280 }
281 }
jrose55220c32009-10-21 23:19:48 -0700282 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700283 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700284 else
285 try {
286 return param.newInstance();
287 } catch (InstantiationException ex) {
288 } catch (IllegalAccessException ex) {
289 }
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
305 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
306 return Arrays.copyOf(a, a.length, atype);
307 }
308 static <T> T[] cat(T[] a, T... b) {
309 int alen = a.length, blen = b.length;
310 if (blen == 0) return a;
311 T[] c = Arrays.copyOf(a, alen + blen);
312 System.arraycopy(b, 0, c, alen, blen);
313 return c;
314 }
315 static Integer[] boxAll(int... vx) {
316 Integer[] res = new Integer[vx.length];
317 for (int i = 0; i < res.length; i++) {
318 res[i] = vx[i];
319 }
320 return res;
321 }
322 static Object getClasses(Object x) {
323 if (x == null) return x;
324 if (x instanceof String) return x; // keep the name
325 if (x instanceof List) {
326 // recursively report classes of the list elements
327 Object[] xa = ((List)x).toArray();
328 for (int i = 0; i < xa.length; i++)
329 xa[i] = getClasses(xa[i]);
330 return Arrays.asList(xa);
331 }
332 return x.getClass().getSimpleName();
333 }
334
jroseadc650a2011-02-11 01:26:28 -0800335 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
336 static MethodHandle varargsList(int arity) {
337 return ValueConversions.varargsList(arity);
338 }
339 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
340 static MethodHandle varargsArray(int arity) {
341 return ValueConversions.varargsArray(arity);
342 }
jrose320b7692011-05-12 19:27:49 -0700343 static MethodHandle varargsArray(Class<?> arrayType, int arity) {
344 return ValueConversions.varargsArray(arrayType, arity);
345 }
jroseadc650a2011-02-11 01:26:28 -0800346 /** Variation of varargsList, but with the given rtype. */
347 static MethodHandle varargsList(int arity, Class<?> rtype) {
348 MethodHandle list = varargsList(arity);
349 MethodType listType = list.type().changeReturnType(rtype);
350 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
351 // OK
352 } else if (rtype.isAssignableFrom(String.class)) {
353 if (LIST_TO_STRING == null)
354 try {
355 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
356 MethodType.methodType(String.class, List.class));
357 } catch (Exception ex) { throw new RuntimeException(ex); }
358 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
359 } else if (rtype.isPrimitive()) {
360 if (LIST_TO_INT == null)
361 try {
362 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
363 MethodType.methodType(int.class, List.class));
364 } catch (Exception ex) { throw new RuntimeException(ex); }
365 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
366 list = MethodHandles.explicitCastArguments(list, listType);
367 } else {
368 throw new RuntimeException("varargsList: "+rtype);
369 }
370 return list.asType(listType);
371 }
372 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
373 private static String listToString(List x) { return x.toString(); }
374 private static int listToInt(List x) { return x.toString().hashCode(); }
375
jrose55220c32009-10-21 23:19:48 -0700376 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
377 return changeArgTypes(target, 0, 999, argType);
378 }
379 static MethodHandle changeArgTypes(MethodHandle target,
380 int beg, int end, Class<?> argType) {
381 MethodType targetType = target.type();
382 end = Math.min(end, targetType.parameterCount());
383 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
384 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800385 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose9b82ad62011-05-26 17:37:36 -0700386 return target.asType(ttype2);
jrose55220c32009-10-21 23:19:48 -0700387 }
jroseb4be0262011-07-16 15:44:33 -0700388 static MethodHandle addTrailingArgs(MethodHandle target, int nargs, Class<?> argClass) {
389 int targetLen = target.type().parameterCount();
390 int extra = (nargs - targetLen);
391 if (extra <= 0) return target;
392 List<Class<?>> fakeArgs = Collections.<Class<?>>nCopies(extra, argClass);
393 return MethodHandles.dropArguments(target, targetLen, fakeArgs);
394 }
jrose55220c32009-10-21 23:19:48 -0700395
396 // This lookup is good for all members in and under MethodHandlesTest.
397 static final Lookup PRIVATE = MethodHandles.lookup();
398 // This lookup is good for package-private members but not private ones.
399 static final Lookup PACKAGE = PackageSibling.lookup();
400 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800401 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700402
403 // Subject methods...
404 static class Example implements IntExample {
405 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700406 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700407 protected Example(String name) { this.name = name; }
408 protected Example(int x) { this(); called("protected <init>", this, x); }
409 @Override public String toString() { return name; }
410
411 public void v0() { called("v0", this); }
412 void pkg_v0() { called("pkg_v0", this); }
413 private void pri_v0() { called("pri_v0", this); }
414 public static void s0() { called("s0"); }
415 static void pkg_s0() { called("pkg_s0"); }
416 private static void pri_s0() { called("pri_s0"); }
417
418 public Object v1(Object x) { return called("v1", this, x); }
419 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
420 public Object v2(Object x, int y) { return called("v2", this, x, y); }
421 public Object v2(int x, Object y) { return called("v2", this, x, y); }
422 public Object v2(int x, int y) { return called("v2", this, x, y); }
423 public static Object s1(Object x) { return called("s1", x); }
424 public static Object s2(int x) { return called("s2", x); }
425 public static Object s3(long x) { return called("s3", x); }
426 public static Object s4(int x, int y) { return called("s4", x, y); }
427 public static Object s5(long x, int y) { return called("s5", x, y); }
428 public static Object s6(int x, long y) { return called("s6", x, y); }
429 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700430
jroseb4be0262011-07-16 15:44:33 -0700431 // for testing findConstructor:
432 public Example(String x, int y) { this.name = x+y; called("Example.<init>", x, y); }
433 public Example(int x, String y) { this.name = x+y; called("Example.<init>", x, y); }
434
jrose2cc9c832010-04-30 23:48:23 -0700435 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700436 }
jrose2cc9c832010-04-30 23:48:23 -0700437 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700438 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700439 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700440 }
441 static class SubExample extends Example {
442 @Override public void v0() { called("Sub/v0", this); }
443 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
444 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700445 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700446 }
447 public static interface IntExample {
448 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700449 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700450 public void v0() { called("Int/v0", this); }
451 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700452 public Impl() { name = "Impl#"+nextArg(); }
453 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700454 }
455 }
456
457 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700458 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
459 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
460 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
461 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700462 };
463
jrose2cc9c832010-04-30 23:48:23 -0700464 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
465 Object[][] cases;
466 if (name.contains("pri_") || isSpecial) {
467 cases = ACCESS_CASES[1]; // PRIVATE only
468 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
469 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800470 } else {
471 assertTrue(name.indexOf('_') < 0);
472 boolean pubc = Modifier.isPublic(defc.getModifiers());
473 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700474 cases = ACCESS_CASES[3]; // all access levels
475 else
476 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800477 }
jrose2cc9c832010-04-30 23:48:23 -0700478 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
479 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
480 return cases;
481 }
482 static Object[][] accessCases(Class<?> defc, String name) {
483 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700484 }
485
486 @Test
487 public void testFindStatic() throws Throwable {
488 if (CAN_SKIP_WORKING) return;
489 startTest("findStatic");
490 testFindStatic(PubExample.class, void.class, "s0");
491 testFindStatic(Example.class, void.class, "s0");
492 testFindStatic(Example.class, void.class, "pkg_s0");
493 testFindStatic(Example.class, void.class, "pri_s0");
494
495 testFindStatic(Example.class, Object.class, "s1", Object.class);
496 testFindStatic(Example.class, Object.class, "s2", int.class);
497 testFindStatic(Example.class, Object.class, "s3", long.class);
498 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
499 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
500 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
501 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
502
503 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
504 }
505
506 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
507 for (Object[] ac : accessCases(defc, name)) {
508 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
509 }
510 }
511 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
512 testFindStatic(true, lookup, defc, ret, name, params);
513 }
514 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
515 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800516 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700517 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700518 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700519 try {
jrose2cc9c832010-04-30 23:48:23 -0700520 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700521 target = lookup.in(defc).findStatic(defc, name, type);
jrosef15905c2011-02-11 01:26:32 -0800522 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700523 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800524 if (name.contains("bogus"))
525 assertTrue(noAccess instanceof NoSuchMethodException);
526 else
527 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700528 }
jrose2cc9c832010-04-30 23:48:23 -0700529 if (verbosity >= 3)
530 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700531 +(noAccess == null ? "" : " !! "+noAccess));
532 if (positive && noAccess != null) throw noAccess;
533 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
534 if (!positive) return; // negative test failed as expected
535 assertEquals(type, target.type());
jrose900bafd2010-10-30 21:08:23 -0700536 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700537 Object[] args = randomArgs(params);
538 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700539 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700540 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700541 if (verbosity >= 1)
542 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700543 }
544
jrose73016262011-05-17 19:48:19 -0700545 static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
546
jrose900bafd2010-10-30 21:08:23 -0700547 // rough check of name string
jrose73016262011-05-17 19:48:19 -0700548 static void assertNameStringContains(MethodHandle x, String s) {
549 if (!DEBUG_METHOD_HANDLE_NAMES) {
550 // ignore s
551 assertEquals("MethodHandle"+x.type(), x.toString());
552 return;
553 }
jrose900bafd2010-10-30 21:08:23 -0700554 if (x.toString().contains(s)) return;
555 assertEquals(s, x);
556 }
557
jrose55220c32009-10-21 23:19:48 -0700558 @Test
559 public void testFindVirtual() throws Throwable {
560 if (CAN_SKIP_WORKING) return;
561 startTest("findVirtual");
562 testFindVirtual(Example.class, void.class, "v0");
563 testFindVirtual(Example.class, void.class, "pkg_v0");
564 testFindVirtual(Example.class, void.class, "pri_v0");
565 testFindVirtual(Example.class, Object.class, "v1", Object.class);
566 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
567 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
568 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
569 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
570 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
571 // test dispatch
572 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
573 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
574 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
575 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
576 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
577 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
578 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
579 }
580
581 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
582 Class<?> rcvc = defc;
583 testFindVirtual(rcvc, defc, ret, name, params);
584 }
585 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
586 for (Object[] ac : accessCases(defc, name)) {
587 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
588 }
589 }
590 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
591 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
592 }
593 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
594 countTest(positive);
595 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800596 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700597 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700598 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700599 try {
jrose2cc9c832010-04-30 23:48:23 -0700600 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700601 target = lookup.in(defc).findVirtual(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800602 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700603 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800604 if (name.contains("bogus"))
605 assertTrue(noAccess instanceof NoSuchMethodException);
606 else
607 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700608 }
jrose2cc9c832010-04-30 23:48:23 -0700609 if (verbosity >= 3)
610 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700611 +(noAccess == null ? "" : " !! "+noAccess));
612 if (positive && noAccess != null) throw noAccess;
613 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
614 if (!positive) return; // negative test failed as expected
615 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800616 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700617 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700618 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700619 Object[] argsWithSelf = randomArgs(paramsWithSelf);
620 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
621 printCalled(target, name, argsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700622 target.invokeWithArguments(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700623 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700624 if (verbosity >= 1)
625 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700626 }
627
628 @Test
629 public void testFindSpecial() throws Throwable {
630 if (CAN_SKIP_WORKING) return;
631 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700632 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
633 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
634 // Do some negative testing:
jrosef15905c2011-02-11 01:26:32 -0800635 testFindSpecial(false, EXAMPLE, SubExample.class, Example.class, void.class, "bogus");
636 testFindSpecial(false, PRIVATE, SubExample.class, Example.class, void.class, "bogus");
jrose2cc9c832010-04-30 23:48:23 -0700637 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
638 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
639 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
640 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
jrose2cc9c832010-04-30 23:48:23 -0700641 }
jrose55220c32009-10-21 23:19:48 -0700642 }
643
jrose2cc9c832010-04-30 23:48:23 -0700644 void testFindSpecial(Class<?> specialCaller,
645 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
646 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
647 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
648 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
649 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700650 }
jrose2cc9c832010-04-30 23:48:23 -0700651 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
652 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700653 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800654 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700655 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700656 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700657 try {
jrose2cc9c832010-04-30 23:48:23 -0700658 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700659 if (verbosity >= 5) System.out.println(" lookup => "+lookup.in(specialCaller));
660 target = lookup.in(specialCaller).findSpecial(defc, name, type, specialCaller);
jrosef15905c2011-02-11 01:26:32 -0800661 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700662 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800663 if (name.contains("bogus"))
664 assertTrue(noAccess instanceof NoSuchMethodException);
665 else
666 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700667 }
jrose2cc9c832010-04-30 23:48:23 -0700668 if (verbosity >= 3)
669 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
670 +(target == null ? "" : target.type())
671 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700672 if (positive && noAccess != null) throw noAccess;
673 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
674 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700675 assertEquals(specialCaller, target.type().parameterType(0));
676 assertEquals(type, target.type().dropParameterTypes(0,1));
677 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800678 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700679 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700680 Object[] args = randomArgs(paramsWithSelf);
681 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700682 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700683 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700684 }
685
686 @Test
jroseb4be0262011-07-16 15:44:33 -0700687 public void testFindConstructor() throws Throwable {
688 if (CAN_SKIP_WORKING) return;
689 startTest("findConstructor");
690 testFindConstructor(true, EXAMPLE, Example.class);
691 testFindConstructor(true, EXAMPLE, Example.class, int.class);
692 testFindConstructor(true, EXAMPLE, Example.class, String.class);
693 }
694 void testFindConstructor(boolean positive, Lookup lookup,
695 Class<?> defc, Class<?>... params) throws Throwable {
696 countTest(positive);
697 MethodType type = MethodType.methodType(void.class, params);
698 MethodHandle target = null;
699 Exception noAccess = null;
700 try {
701 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" <init>"+type);
702 target = lookup.findConstructor(defc, type);
703 } catch (ReflectiveOperationException ex) {
704 noAccess = ex;
705 assertTrue(noAccess instanceof IllegalAccessException);
706 }
707 if (verbosity >= 3)
708 System.out.println("findConstructor "+defc.getName()+".<init>/"+type+" => "+target
709 +(target == null ? "" : target.type())
710 +(noAccess == null ? "" : " !! "+noAccess));
711 if (positive && noAccess != null) throw noAccess;
712 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
713 if (!positive) return; // negative test failed as expected
714 assertEquals(type.changeReturnType(defc), target.type());
715 Object[] args = randomArgs(params);
716 printCalled(target, defc.getSimpleName(), args);
717 Object obj = target.invokeWithArguments(args);
718 if (!(defc == Example.class && params.length < 2))
719 assertCalled(defc.getSimpleName()+".<init>", args);
720 assertTrue("instance of "+defc.getName(), defc.isInstance(obj));
721 }
722
723 @Test
jrose55220c32009-10-21 23:19:48 -0700724 public void testBind() throws Throwable {
725 if (CAN_SKIP_WORKING) return;
726 startTest("bind");
727 testBind(Example.class, void.class, "v0");
728 testBind(Example.class, void.class, "pkg_v0");
729 testBind(Example.class, void.class, "pri_v0");
730 testBind(Example.class, Object.class, "v1", Object.class);
731 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
732 testBind(Example.class, Object.class, "v2", Object.class, int.class);
733 testBind(Example.class, Object.class, "v2", int.class, Object.class);
734 testBind(Example.class, Object.class, "v2", int.class, int.class);
735 testBind(false, PRIVATE, Example.class, void.class, "bogus");
736 testBind(SubExample.class, void.class, "Sub/v0");
737 testBind(SubExample.class, void.class, "Sub/pkg_v0");
738 testBind(IntExample.Impl.class, void.class, "Int/v0");
739 }
740
741 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
742 for (Object[] ac : accessCases(defc, name)) {
743 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
744 }
745 }
746
747 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
748 countTest(positive);
749 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800750 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700751 Object receiver = randomArg(defc);
752 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700753 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700754 try {
jrose2cc9c832010-04-30 23:48:23 -0700755 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700756 target = lookup.in(defc).bind(receiver, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800757 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700758 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800759 if (name.contains("bogus"))
760 assertTrue(noAccess instanceof NoSuchMethodException);
761 else
762 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700763 }
jrose2cc9c832010-04-30 23:48:23 -0700764 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700765 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
766 +(noAccess == null ? "" : " !! "+noAccess));
767 if (positive && noAccess != null) throw noAccess;
768 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
769 if (!positive) return; // negative test failed as expected
770 assertEquals(type, target.type());
771 Object[] args = randomArgs(params);
772 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700773 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700774 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
775 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700776 if (verbosity >= 1)
777 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700778 }
779
780 @Test
781 public void testUnreflect() throws Throwable {
782 if (CAN_SKIP_WORKING) return;
783 startTest("unreflect");
784 testUnreflect(Example.class, true, void.class, "s0");
785 testUnreflect(Example.class, true, void.class, "pkg_s0");
786 testUnreflect(Example.class, true, void.class, "pri_s0");
787
788 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
789 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700790 testUnreflect(Example.class, true, Object.class, "s3", long.class);
791 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
792 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
793 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700794
795 testUnreflect(Example.class, false, void.class, "v0");
796 testUnreflect(Example.class, false, void.class, "pkg_v0");
797 testUnreflect(Example.class, false, void.class, "pri_v0");
798 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
799 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
800 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
801 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
802 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
803 }
804
805 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
806 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700807 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700808 }
809 }
jrose2cc9c832010-04-30 23:48:23 -0700810 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
811 for (Object[] ac : accessCases(defc, name)) {
812 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
813 }
814 }
815 void testUnreflectMaybeSpecial(Class<?> specialCaller,
816 boolean positive, Lookup lookup,
817 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700818 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800819 MethodType type = MethodType.methodType(ret, params);
jrosef15905c2011-02-11 01:26:32 -0800820 Method rmethod = defc.getDeclaredMethod(name, params);
jrose55220c32009-10-21 23:19:48 -0700821 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700822 Exception noAccess = null;
jrose2cc9c832010-04-30 23:48:23 -0700823 boolean isStatic = (rcvc == null);
824 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700825 try {
jrose2cc9c832010-04-30 23:48:23 -0700826 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
827 if (isSpecial)
jrose900bafd2010-10-30 21:08:23 -0700828 target = lookup.in(specialCaller).unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700829 else
jrose900bafd2010-10-30 21:08:23 -0700830 target = lookup.in(defc).unreflect(rmethod);
jrosef15905c2011-02-11 01:26:32 -0800831 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700832 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800833 if (name.contains("bogus"))
834 assertTrue(noAccess instanceof NoSuchMethodException);
835 else
836 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700837 }
jrose2cc9c832010-04-30 23:48:23 -0700838 if (verbosity >= 3)
839 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
840 +(!isSpecial ? "" : " specialCaller="+specialCaller)
841 +( isStatic ? "" : " receiver="+rcvc)
842 +" => "+target
843 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700844 if (positive && noAccess != null) throw noAccess;
845 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
846 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700847 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700848 Class<?>[] paramsMaybeWithSelf = params;
849 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700850 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700851 }
jrose10f3b682010-01-07 16:16:45 -0800852 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700853 if (isStatic) {
854 assertEquals(typeMaybeWithSelf, target.type());
855 } else {
jrose2cc9c832010-04-30 23:48:23 -0700856 if (isSpecial)
857 assertEquals(specialCaller, target.type().parameterType(0));
858 else
859 assertEquals(defc, target.type().parameterType(0));
860 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
861 }
jrose55220c32009-10-21 23:19:48 -0700862 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
863 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700864 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700865 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700866 if (verbosity >= 1)
867 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700868 }
869
jrose2cc9c832010-04-30 23:48:23 -0700870 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
871 for (Object[] ac : accessCases(defc, name, true)) {
872 Class<?> specialCaller = rcvc;
873 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
874 }
875 }
876
877 @Test
jrose55220c32009-10-21 23:19:48 -0700878 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700879 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700880 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700881 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
882 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
883 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
884 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
885 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
886 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
887 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700888 }
889
jrose10f3b682010-01-07 16:16:45 -0800890 public static class HasFields {
891 boolean fZ = false;
892 byte fB = (byte)'B';
893 short fS = (short)'S';
894 char fC = 'C';
895 int fI = 'I';
896 long fJ = 'J';
897 float fF = 'F';
898 double fD = 'D';
899 static boolean sZ = true;
900 static byte sB = 1+(byte)'B';
901 static short sS = 1+(short)'S';
902 static char sC = 1+'C';
903 static int sI = 1+'I';
904 static long sJ = 1+'J';
905 static float sF = 1+'F';
906 static double sD = 1+'D';
907
908 Object fL = 'L';
909 String fR = "R";
910 static Object sL = 'M';
911 static String sR = "S";
912
913 static final Object[][] CASES;
914 static {
915 ArrayList<Object[]> cases = new ArrayList<Object[]>();
916 Object types[][] = {
917 {'L',Object.class}, {'R',String.class},
918 {'I',int.class}, {'J',long.class},
919 {'F',float.class}, {'D',double.class},
920 {'Z',boolean.class}, {'B',byte.class},
921 {'S',short.class}, {'C',char.class},
922 };
923 HasFields fields = new HasFields();
924 for (Object[] t : types) {
925 for (int kind = 0; kind <= 1; kind++) {
926 boolean isStatic = (kind != 0);
927 char btc = (Character)t[0];
928 String name = (isStatic ? "s" : "f") + btc;
929 Class<?> type = (Class<?>) t[1];
930 Object value;
931 Field field;
jrose320b7692011-05-12 19:27:49 -0700932 try {
jrose10f3b682010-01-07 16:16:45 -0800933 field = HasFields.class.getDeclaredField(name);
934 } catch (Exception ex) {
935 throw new InternalError("no field HasFields."+name);
936 }
937 try {
938 value = field.get(fields);
939 } catch (Exception ex) {
940 throw new InternalError("cannot fetch field HasFields."+name);
941 }
942 if (type == float.class) {
943 float v = 'F';
944 if (isStatic) v++;
jrosef15905c2011-02-11 01:26:32 -0800945 assertTrue(value.equals(v));
jrose10f3b682010-01-07 16:16:45 -0800946 }
jrosef15905c2011-02-11 01:26:32 -0800947 assertTrue(name.equals(field.getName()));
948 assertTrue(type.equals(field.getType()));
949 assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
jrose10f3b682010-01-07 16:16:45 -0800950 cases.add(new Object[]{ field, value });
951 }
952 }
jrosef15905c2011-02-11 01:26:32 -0800953 cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
954 cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
jrose10f3b682010-01-07 16:16:45 -0800955 CASES = cases.toArray(new Object[0][]);
956 }
957 }
958
jrosef15905c2011-02-11 01:26:32 -0800959 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10;
jrosecf98d422010-06-08 23:08:56 -0700960 static boolean testModeMatches(int testMode, boolean isStatic) {
961 switch (testMode) {
jrosef15905c2011-02-11 01:26:32 -0800962 case TEST_FIND_STATIC: return isStatic;
jrosecf98d422010-06-08 23:08:56 -0700963 case TEST_FIND_FIELD: return !isStatic;
jrosef15905c2011-02-11 01:26:32 -0800964 case TEST_UNREFLECT: return true; // unreflect matches both
jrosecf98d422010-06-08 23:08:56 -0700965 }
jrosef15905c2011-02-11 01:26:32 -0800966 throw new InternalError("testMode="+testMode);
jrosecf98d422010-06-08 23:08:56 -0700967 }
968
jrose10f3b682010-01-07 16:16:45 -0800969 @Test
jrose55220c32009-10-21 23:19:48 -0700970 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700971 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700972 testGetter(TEST_UNREFLECT);
973 }
974 @Test
975 public void testFindGetter() throws Throwable {
976 startTest("findGetter");
977 testGetter(TEST_FIND_FIELD);
978 }
979 @Test
980 public void testFindStaticGetter() throws Throwable {
981 startTest("findStaticGetter");
jrosef15905c2011-02-11 01:26:32 -0800982 testGetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -0700983 }
984 public void testGetter(int testMode) throws Throwable {
985 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800986 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -0800987 boolean positive = (c[1] != Error.class);
988 testGetter(positive, lookup, c[0], c[1], testMode);
989 }
990 testGetter(true, lookup,
991 new Object[]{ true, System.class, "out", java.io.PrintStream.class },
992 System.out, testMode);
993 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
994 testGetter(false, lookup,
995 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
996 null, testMode);
jrose10f3b682010-01-07 16:16:45 -0800997 }
998 }
jrosef15905c2011-02-11 01:26:32 -0800999 public void testGetter(boolean positive, MethodHandles.Lookup lookup,
1000 Object fieldRef, Object value, int testMode) throws Throwable {
1001 testAccessor(positive, lookup, fieldRef, value, testMode);
1002 }
1003
1004 public void testAccessor(boolean positive, MethodHandles.Lookup lookup,
1005 Object fieldRef, Object value, int testMode0) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07001006 if (verbosity >= 4)
1007 System.out.println("testAccessor"+Arrays.asList(positive, lookup, fieldRef, value, testMode0));
jrosef15905c2011-02-11 01:26:32 -08001008 boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
1009 int testMode = testMode0 & ~TEST_SETTER;
1010 boolean isStatic;
1011 Class<?> fclass;
1012 String fname;
1013 Class<?> ftype;
1014 Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
1015 if (f != null) {
1016 isStatic = Modifier.isStatic(f.getModifiers());
1017 fclass = f.getDeclaringClass();
1018 fname = f.getName();
1019 ftype = f.getType();
1020 } else {
1021 Object[] scnt = (Object[]) fieldRef;
1022 isStatic = (Boolean) scnt[0];
1023 fclass = (Class<?>) scnt[1];
1024 fname = (String) scnt[2];
1025 ftype = (Class<?>) scnt[3];
1026 try {
1027 f = fclass.getDeclaredField(fname);
1028 } catch (ReflectiveOperationException ex) {
1029 f = null;
1030 }
1031 }
jrosecf98d422010-06-08 23:08:56 -07001032 if (!testModeMatches(testMode, isStatic)) return;
jrosef15905c2011-02-11 01:26:32 -08001033 if (f == null && testMode == TEST_UNREFLECT) return;
1034 countTest(positive);
1035 MethodType expType;
1036 if (isGetter)
1037 expType = MethodType.methodType(ftype, HasFields.class);
1038 else
1039 expType = MethodType.methodType(void.class, HasFields.class, ftype);
jrose10f3b682010-01-07 16:16:45 -08001040 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosef15905c2011-02-11 01:26:32 -08001041 Exception noAccess = null;
1042 MethodHandle mh;
1043 try {
1044 switch (testMode0) {
1045 case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
1046 case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
1047 case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
1048 case TEST_SETTER|
1049 TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
1050 case TEST_SETTER|
1051 TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
1052 case TEST_SETTER|
1053 TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
1054 default:
1055 throw new InternalError("testMode="+testMode);
1056 }
1057 } catch (ReflectiveOperationException ex) {
1058 mh = null;
1059 noAccess = ex;
1060 if (fname.contains("bogus"))
1061 assertTrue(noAccess instanceof NoSuchFieldException);
1062 else
1063 assertTrue(noAccess instanceof IllegalAccessException);
1064 }
1065 if (verbosity >= 3)
1066 System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
1067 +" => "+mh
1068 +(noAccess == null ? "" : " !! "+noAccess));
1069 if (positive && noAccess != null) throw new RuntimeException(noAccess);
1070 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, mh != null);
1071 if (!positive) return; // negative test failed as expected
1072 assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
1073
1074
jrose10f3b682010-01-07 16:16:45 -08001075 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -07001076 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -08001077 HasFields fields = new HasFields();
1078 Object sawValue;
jrosef15905c2011-02-11 01:26:32 -08001079 Class<?> vtype = ftype;
1080 if (ftype != int.class) vtype = Object.class;
1081 if (isGetter) {
jrose9b82ad62011-05-26 17:37:36 -07001082 mh = mh.asType(mh.type().generic()
1083 .changeReturnType(vtype));
jrosef15905c2011-02-11 01:26:32 -08001084 } else {
1085 int last = mh.type().parameterCount() - 1;
jrose9b82ad62011-05-26 17:37:36 -07001086 mh = mh.asType(mh.type().generic()
1087 .changeReturnType(void.class)
1088 .changeParameterType(last, vtype));
jrose10f3b682010-01-07 16:16:45 -08001089 }
jrosef15905c2011-02-11 01:26:32 -08001090 if (f != null && f.getDeclaringClass() == HasFields.class) {
1091 assertEquals(f.get(fields), value); // clean to start with
1092 }
1093 if (isGetter) {
1094 Object expValue = value;
1095 for (int i = 0; i <= 1; i++) {
1096 if (isStatic) {
1097 if (ftype == int.class)
1098 sawValue = (int) mh.invokeExact(); // do these exactly
1099 else
1100 sawValue = mh.invokeExact();
1101 } else {
1102 if (ftype == int.class)
1103 sawValue = (int) mh.invokeExact((Object) fields);
1104 else
1105 sawValue = mh.invokeExact((Object) fields);
1106 }
1107 assertEquals(sawValue, expValue);
1108 if (f != null && f.getDeclaringClass() == HasFields.class
1109 && !Modifier.isFinal(f.getModifiers())) {
1110 Object random = randomArg(ftype);
1111 f.set(fields, random);
1112 expValue = random;
1113 } else {
1114 break;
1115 }
1116 }
1117 } else {
1118 for (int i = 0; i <= 1; i++) {
1119 Object putValue = randomArg(ftype);
1120 if (isStatic) {
1121 if (ftype == int.class)
1122 mh.invokeExact((int)putValue); // do these exactly
1123 else
1124 mh.invokeExact(putValue);
1125 } else {
1126 if (ftype == int.class)
1127 mh.invokeExact((Object) fields, (int)putValue);
1128 else
1129 mh.invokeExact((Object) fields, putValue);
1130 }
1131 if (f != null && f.getDeclaringClass() == HasFields.class) {
1132 assertEquals(f.get(fields), putValue);
1133 }
1134 }
1135 }
1136 if (f != null && f.getDeclaringClass() == HasFields.class) {
1137 f.set(fields, value); // put it back
1138 }
jrose55220c32009-10-21 23:19:48 -07001139 }
1140
jrose10f3b682010-01-07 16:16:45 -08001141
1142 @Test
jrose55220c32009-10-21 23:19:48 -07001143 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -07001144 startTest("unreflectSetter");
1145 testSetter(TEST_UNREFLECT);
1146 }
1147 @Test
1148 public void testFindSetter() throws Throwable {
1149 startTest("findSetter");
1150 testSetter(TEST_FIND_FIELD);
1151 }
1152 @Test
1153 public void testFindStaticSetter() throws Throwable {
1154 startTest("findStaticSetter");
jrosef15905c2011-02-11 01:26:32 -08001155 testSetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001156 }
1157 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001158 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
1159 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -08001160 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001161 boolean positive = (c[1] != Error.class);
1162 testSetter(positive, lookup, c[0], c[1], testMode);
1163 }
1164 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1165 testSetter(false, lookup,
1166 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1167 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001168 }
1169 }
jrosef15905c2011-02-11 01:26:32 -08001170 public void testSetter(boolean positive, MethodHandles.Lookup lookup,
1171 Object fieldRef, Object value, int testMode) throws Throwable {
1172 testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
jrose55220c32009-10-21 23:19:48 -07001173 }
1174
jrose10f3b682010-01-07 16:16:45 -08001175 @Test
jrose55220c32009-10-21 23:19:48 -07001176 public void testArrayElementGetter() throws Throwable {
1177 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001178 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001179 }
1180
jrose10f3b682010-01-07 16:16:45 -08001181 @Test
jrose55220c32009-10-21 23:19:48 -07001182 public void testArrayElementSetter() throws Throwable {
1183 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001184 testArrayElementGetterSetter(true);
1185 }
1186
1187 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
1188 testArrayElementGetterSetter(new Object[10], testSetter);
1189 testArrayElementGetterSetter(new String[10], testSetter);
1190 testArrayElementGetterSetter(new boolean[10], testSetter);
1191 testArrayElementGetterSetter(new byte[10], testSetter);
1192 testArrayElementGetterSetter(new char[10], testSetter);
1193 testArrayElementGetterSetter(new short[10], testSetter);
1194 testArrayElementGetterSetter(new int[10], testSetter);
1195 testArrayElementGetterSetter(new float[10], testSetter);
1196 testArrayElementGetterSetter(new long[10], testSetter);
1197 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -08001198 }
1199
1200 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
1201 countTest(true);
jroseb4be0262011-07-16 15:44:33 -07001202 if (verbosity > 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -08001203 Class<?> arrayType = array.getClass();
1204 Class<?> elemType = arrayType.getComponentType();
1205 MethodType expType = !testSetter
1206 ? MethodType.methodType(elemType, arrayType, int.class)
1207 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1208 MethodHandle mh = !testSetter
1209 ? MethodHandles.arrayElementGetter(arrayType)
1210 : MethodHandles.arrayElementSetter(arrayType);
1211 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001212 if (elemType != int.class && elemType != boolean.class) {
jrose320b7692011-05-12 19:27:49 -07001213 // FIXME: change Integer.class and (Integer) below to int.class and (int) below.
1214 MethodType gtype = mh.type().generic().changeParameterType(1, Integer.class);
1215 if (testSetter) gtype = gtype.changeReturnType(void.class);
jrose9b82ad62011-05-26 17:37:36 -07001216 mh = mh.asType(gtype);
jrose2cc9c832010-04-30 23:48:23 -07001217 }
jrose10f3b682010-01-07 16:16:45 -08001218 Object sawValue, expValue;
1219 List<Object> model = array2list(array);
1220 int length = Array.getLength(array);
1221 for (int i = 0; i < length; i++) {
1222 // update array element
1223 Object random = randomArg(elemType);
1224 model.set(i, random);
1225 if (testSetter) {
1226 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001227 mh.invokeExact((int[]) array, i, (int)random);
jrose2cc9c832010-04-30 23:48:23 -07001228 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001229 mh.invokeExact((boolean[]) array, i, (boolean)random);
jrose10f3b682010-01-07 16:16:45 -08001230 else
jrose320b7692011-05-12 19:27:49 -07001231 mh.invokeExact(array, (Integer)i, random);
jrose10f3b682010-01-07 16:16:45 -08001232 assertEquals(model, array2list(array));
1233 } else {
1234 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001235 }
1236 if (verbosity >= 5) {
1237 List<Object> array2list = array2list(array);
1238 System.out.println("a["+i+"]="+random+" => "+array2list);
1239 if (!array2list.equals(model))
1240 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001241 }
1242 // observe array element
1243 sawValue = Array.get(array, i);
1244 if (!testSetter) {
1245 expValue = sawValue;
1246 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001247 sawValue = (int) mh.invokeExact((int[]) array, i);
jrose2cc9c832010-04-30 23:48:23 -07001248 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001249 sawValue = (boolean) mh.invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -08001250 else
jrose320b7692011-05-12 19:27:49 -07001251 sawValue = mh.invokeExact(array, (Integer)i);
jrose10f3b682010-01-07 16:16:45 -08001252 assertEquals(sawValue, expValue);
1253 assertEquals(model, array2list(array));
1254 }
1255 }
1256 }
1257
1258 List<Object> array2list(Object array) {
1259 int length = Array.getLength(array);
1260 ArrayList<Object> model = new ArrayList<Object>(length);
1261 for (int i = 0; i < length; i++)
1262 model.add(Array.get(array, i));
1263 return model;
jrose55220c32009-10-21 23:19:48 -07001264 }
1265
1266 static class Callee {
1267 static Object id() { return called("id"); }
1268 static Object id(Object x) { return called("id", x); }
1269 static Object id(Object x, Object y) { return called("id", x, y); }
1270 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1271 static Object id(Object... vx) { return called("id", vx); }
1272 static MethodHandle ofType(int n) {
1273 return ofType(Object.class, n);
1274 }
1275 static MethodHandle ofType(Class<?> rtype, int n) {
1276 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001277 return ofType(MethodType.methodType(rtype, Object[].class));
1278 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001279 }
1280 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001281 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001282 }
1283 static MethodHandle ofType(MethodType type) {
1284 Class<?> rtype = type.returnType();
1285 String pfx = "";
1286 if (rtype != Object.class)
1287 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1288 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001289 try {
1290 return PRIVATE.findStatic(Callee.class, name, type);
1291 } catch (Exception ex) {
1292 throw new RuntimeException(ex);
1293 }
jrose55220c32009-10-21 23:19:48 -07001294 }
1295 }
1296
1297 @Test
1298 public void testConvertArguments() throws Throwable {
1299 if (CAN_SKIP_WORKING) return;
1300 startTest("convertArguments");
1301 testConvert(Callee.ofType(1), null, "id", int.class);
1302 testConvert(Callee.ofType(1), null, "id", String.class);
1303 testConvert(Callee.ofType(1), null, "id", Integer.class);
1304 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001305 testConvert(Callee.ofType(1), null, "id", char.class);
1306 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001307 }
1308
1309 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -07001310 testConvert(true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001311 }
1312
jrose9b82ad62011-05-26 17:37:36 -07001313 void testConvert(boolean positive,
jrose900bafd2010-10-30 21:08:23 -07001314 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001315 countTest(positive);
1316 MethodType idType = id.type();
1317 if (rtype == null) rtype = idType.returnType();
1318 for (int i = 0; i < params.length; i++) {
1319 if (params[i] == null) params[i] = idType.parameterType(i);
1320 }
1321 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001322 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001323 Object[] args = randomArgs(newType.parameterArray());
1324 Object[] convArgs = args.clone();
1325 for (int i = 0; i < args.length; i++) {
1326 Class<?> src = newType.parameterType(i);
1327 Class<?> dst = idType.parameterType(i);
1328 if (src != dst)
1329 convArgs[i] = castToWrapper(convArgs[i], dst);
1330 }
jrose900bafd2010-10-30 21:08:23 -07001331 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001332 {
1333 Class<?> dst = newType.returnType();
1334 Class<?> src = idType.returnType();
1335 if (src != dst)
1336 convResult = castToWrapper(convResult, dst);
1337 }
1338 MethodHandle target = null;
1339 RuntimeException error = null;
1340 try {
jrose9b82ad62011-05-26 17:37:36 -07001341 target = id.asType(newType);
jrose55220c32009-10-21 23:19:48 -07001342 } catch (RuntimeException ex) {
1343 error = ex;
1344 }
jrose2cc9c832010-04-30 23:48:23 -07001345 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001346 System.out.println("convert "+id+ " to "+newType+" => "+target
1347 +(error == null ? "" : " !! "+error));
1348 if (positive && error != null) throw error;
1349 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1350 if (!positive) return; // negative test failed as expected
1351 assertEquals(newType, target.type());
1352 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001353 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001354 assertCalled(name, convArgs);
1355 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001356 if (verbosity >= 1)
1357 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001358 }
1359
1360 @Test
jrosef108fc02011-02-11 01:26:24 -08001361 public void testVarargsCollector() throws Throwable {
1362 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1363 MethodType.methodType(Object.class, String.class, Object[].class));
1364 vac0 = vac0.bindTo("vac");
1365 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -07001366 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1367 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
jrosef108fc02011-02-11 01:26:24 -08001368 for (Class<?> at : new Class[] { Object.class, String.class, Integer.class }) {
jrose9b82ad62011-05-26 17:37:36 -07001369 testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1370 testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
jrosef108fc02011-02-11 01:26:24 -08001371 }
1372 }
1373
1374 @Test
jrose10f3b682010-01-07 16:16:45 -08001375 public void testPermuteArguments() throws Throwable {
1376 if (CAN_SKIP_WORKING) return;
1377 startTest("permuteArguments");
jroseb4be0262011-07-16 15:44:33 -07001378 testPermuteArguments(4, Integer.class, 2, long.class, 6);
1379 if (CAN_TEST_LIGHTLY) return;
jrose10f3b682010-01-07 16:16:45 -08001380 testPermuteArguments(4, Integer.class, 2, String.class, 0);
jrose9b82ad62011-05-26 17:37:36 -07001381 testPermuteArguments(6, Integer.class, 0, null, 30);
jrose10f3b682010-01-07 16:16:45 -08001382 }
1383 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001384 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001385 System.out.println("permuteArguments "+max+"*"+type1.getName()
1386 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1387 +(dilution > 0 ? " with dilution "+dilution : ""));
1388 int t2pos = t2c == 0 ? 0 : 1;
1389 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1390 Class<?>[] types = new Class<?>[inargs];
1391 Arrays.fill(types, type1);
1392 if (t2c != 0) {
1393 // Fill in a middle range with type2:
1394 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1395 }
1396 Object[] args = randomArgs(types);
1397 int numcases = 1;
1398 for (int outargs = 0; outargs <= max; outargs++) {
1399 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
jrose10f3b682010-01-07 16:16:45 -08001400 int casStep = dilution + 1;
1401 // Avoid some common factors:
1402 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1403 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1404 casStep++;
jrose320b7692011-05-12 19:27:49 -07001405 testPermuteArguments(args, types, outargs, numcases, casStep);
jrose10f3b682010-01-07 16:16:45 -08001406 numcases *= inargs;
jroseb4be0262011-07-16 15:44:33 -07001407 if (CAN_TEST_LIGHTLY && outargs < max-2) continue;
jrose10f3b682010-01-07 16:16:45 -08001408 if (dilution > 10 && outargs >= 4) {
jroseb4be0262011-07-16 15:44:33 -07001409 if (CAN_TEST_LIGHTLY) continue;
jrose320b7692011-05-12 19:27:49 -07001410 int[] reorder = new int[outargs];
jrose10f3b682010-01-07 16:16:45 -08001411 // Do some special patterns, which we probably missed.
1412 // Replication of a single argument or argument pair.
1413 for (int i = 0; i < inargs; i++) {
1414 Arrays.fill(reorder, i);
1415 testPermuteArguments(args, types, reorder);
1416 for (int d = 1; d <= 2; d++) {
1417 if (i + d >= inargs) continue;
1418 for (int j = 1; j < outargs; j += 2)
1419 reorder[j] += 1;
1420 testPermuteArguments(args, types, reorder);
1421 testPermuteArguments(args, types, reverse(reorder));
1422 }
1423 }
1424 // Repetition of a sequence of 3 or more arguments.
1425 for (int i = 1; i < inargs; i++) {
1426 for (int len = 3; len <= inargs; len++) {
1427 for (int j = 0; j < outargs; j++)
1428 reorder[j] = (i + (j % len)) % inargs;
1429 testPermuteArguments(args, types, reorder);
1430 testPermuteArguments(args, types, reverse(reorder));
1431 }
1432 }
1433 }
1434 }
1435 }
1436 }
1437
jrose320b7692011-05-12 19:27:49 -07001438 public void testPermuteArguments(Object[] args, Class<?>[] types,
1439 int outargs, int numcases, int casStep) throws Throwable {
1440 int inargs = args.length;
1441 int[] reorder = new int[outargs];
1442 for (int cas = 0; cas < numcases; cas += casStep) {
1443 for (int i = 0, c = cas; i < outargs; i++) {
1444 reorder[i] = c % inargs;
1445 c /= inargs;
1446 }
jroseb4be0262011-07-16 15:44:33 -07001447 if (CAN_TEST_LIGHTLY && outargs >= 3 && (reorder[0] == reorder[1] || reorder[1] == reorder[2])) continue;
jrose320b7692011-05-12 19:27:49 -07001448 testPermuteArguments(args, types, reorder);
1449 }
1450 }
1451
jrose10f3b682010-01-07 16:16:45 -08001452 static int[] reverse(int[] reorder) {
1453 reorder = reorder.clone();
1454 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1455 int j = reorder.length - 1 - i;
1456 int tem = reorder[i];
1457 reorder[i] = reorder[j];
1458 reorder[j] = tem;
1459 }
1460 return reorder;
1461 }
1462
1463 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1464 countTest();
1465 if (args == null && types == null) {
1466 int max = 0;
1467 for (int j : reorder) {
1468 if (max < j) max = j;
1469 }
1470 args = randomArgs(max+1, Integer.class);
1471 }
1472 if (args == null) {
1473 args = randomArgs(types);
1474 }
1475 if (types == null) {
1476 types = new Class<?>[args.length];
1477 for (int i = 0; i < args.length; i++)
1478 types[i] = args[i].getClass();
1479 }
1480 int inargs = args.length, outargs = reorder.length;
jrosef15905c2011-02-11 01:26:32 -08001481 assertTrue(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001482 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001483 System.out.println("permuteArguments "+Arrays.toString(reorder));
1484 Object[] permArgs = new Object[outargs];
1485 Class<?>[] permTypes = new Class<?>[outargs];
1486 for (int i = 0; i < outargs; i++) {
1487 permArgs[i] = args[reorder[i]];
1488 permTypes[i] = types[reorder[i]];
1489 }
jrose2cc9c832010-04-30 23:48:23 -07001490 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001491 System.out.println("in args: "+Arrays.asList(args));
1492 System.out.println("out args: "+Arrays.asList(permArgs));
1493 System.out.println("in types: "+Arrays.asList(types));
1494 System.out.println("out types: "+Arrays.asList(permTypes));
1495 }
1496 MethodType inType = MethodType.methodType(Object.class, types);
1497 MethodType outType = MethodType.methodType(Object.class, permTypes);
jrose9b82ad62011-05-26 17:37:36 -07001498 MethodHandle target = varargsList(outargs).asType(outType);
jrose10f3b682010-01-07 16:16:45 -08001499 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose9b82ad62011-05-26 17:37:36 -07001500 if (verbosity >= 5) System.out.println("newTarget = "+newTarget);
jrose900bafd2010-10-30 21:08:23 -07001501 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001502 Object expected = Arrays.asList(permArgs);
jrose320b7692011-05-12 19:27:49 -07001503 if (!expected.equals(result)) {
1504 System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
1505 System.out.println("in args: "+Arrays.asList(args));
1506 System.out.println("out args: "+expected);
1507 System.out.println("bad args: "+result);
1508 }
jrose10f3b682010-01-07 16:16:45 -08001509 assertEquals(expected, result);
1510 }
1511
1512
1513 @Test
1514 public void testSpreadArguments() throws Throwable {
1515 if (CAN_SKIP_WORKING) return;
1516 startTest("spreadArguments");
1517 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001518 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001519 System.out.println("spreadArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001520 for (int nargs = 0; nargs < 50; nargs++) {
1521 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1522 for (int pos = 0; pos <= nargs; pos++) {
1523 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1524 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1525 continue;
1526 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001527 }
1528 }
1529 }
1530 }
1531 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1532 countTest();
jrose320b7692011-05-12 19:27:49 -07001533 Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
1534 MethodHandle target2 = varargsArray(arrayType, nargs);
1535 MethodHandle target = target2.asType(target2.type().generic());
jrose2cc9c832010-04-30 23:48:23 -07001536 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001537 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1538 Object[] args = randomArgs(target2.type().parameterArray());
1539 // make sure the target does what we think it does:
jrose320b7692011-05-12 19:27:49 -07001540 if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
1541 Object[] check = (Object[]) (Object) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001542 assertArrayEquals(args, check);
1543 switch (nargs) {
1544 case 0:
jrose320b7692011-05-12 19:27:49 -07001545 check = (Object[]) (Object) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001546 assertArrayEquals(args, check);
1547 break;
1548 case 1:
jrose320b7692011-05-12 19:27:49 -07001549 check = (Object[]) (Object) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001550 assertArrayEquals(args, check);
1551 break;
1552 case 2:
jrose320b7692011-05-12 19:27:49 -07001553 check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001554 assertArrayEquals(args, check);
1555 break;
1556 }
1557 }
1558 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1559 { // modify newParams in place
1560 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
jrose320b7692011-05-12 19:27:49 -07001561 spreadParams.clear(); spreadParams.add(arrayType);
jrose10f3b682010-01-07 16:16:45 -08001562 }
jrose320b7692011-05-12 19:27:49 -07001563 MethodType newType = MethodType.methodType(arrayType, newParams);
1564 MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
1565 assert(result.type() == newType) : Arrays.asList(result, newType);
1566 result = result.asType(newType.generic());
1567 Object returnValue;
jrose10f3b682010-01-07 16:16:45 -08001568 if (pos == 0) {
jrose320b7692011-05-12 19:27:49 -07001569 Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1570 returnValue = result.invokeExact(args2);
jrose10f3b682010-01-07 16:16:45 -08001571 } else {
1572 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
jrose320b7692011-05-12 19:27:49 -07001573 args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1574 returnValue = result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001575 }
jrose320b7692011-05-12 19:27:49 -07001576 String argstr = Arrays.toString(args);
1577 if (!argType.isPrimitive()) {
1578 Object[] rv = (Object[]) returnValue;
1579 String rvs = Arrays.toString(rv);
1580 if (!Arrays.equals(args, rv)) {
1581 System.out.println("method: "+result);
1582 System.out.println("expected: "+argstr);
1583 System.out.println("returned: "+rvs);
1584 assertArrayEquals(args, rv);
1585 }
1586 } else if (argType == int.class) {
1587 String rvs = Arrays.toString((int[]) returnValue);
1588 if (!argstr.equals(rvs)) {
1589 System.out.println("method: "+result);
1590 System.out.println("expected: "+argstr);
1591 System.out.println("returned: "+rvs);
1592 assertEquals(argstr, rvs);
1593 }
1594 } else if (argType == long.class) {
1595 String rvs = Arrays.toString((long[]) returnValue);
1596 if (!argstr.equals(rvs)) {
1597 System.out.println("method: "+result);
1598 System.out.println("expected: "+argstr);
1599 System.out.println("returned: "+rvs);
1600 assertEquals(argstr, rvs);
1601 }
1602 } else {
1603 // cannot test...
1604 }
jrose10f3b682010-01-07 16:16:45 -08001605 }
1606
1607 @Test
1608 public void testCollectArguments() throws Throwable {
1609 if (CAN_SKIP_WORKING) return;
1610 startTest("collectArguments");
1611 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001612 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001613 System.out.println("collectArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001614 for (int nargs = 0; nargs < 50; nargs++) {
1615 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1616 for (int pos = 0; pos <= nargs; pos++) {
1617 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1618 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1619 continue;
jrose10f3b682010-01-07 16:16:45 -08001620 testCollectArguments(argType, pos, nargs);
1621 }
1622 }
1623 }
1624 }
1625 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1626 countTest();
1627 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001628 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001629 fake = changeArgTypes(fake, argType);
1630 MethodType newType = fake.type();
1631 Object[] args = randomArgs(newType.parameterArray());
1632 // here is what should happen:
1633 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1634 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1635 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001636 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001637 target = changeArgTypes(target, 0, pos, argType);
1638 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001639 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001640 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001641 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001642 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001643// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1644// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1645// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1646 assertArrayEquals(collectedArgs, returnValue);
1647 }
1648
1649 @Test
jrose55220c32009-10-21 23:19:48 -07001650 public void testInsertArguments() throws Throwable {
1651 if (CAN_SKIP_WORKING) return;
1652 startTest("insertArguments");
jroseb4be0262011-07-16 15:44:33 -07001653 for (int nargs = 0; nargs < 50; nargs++) {
1654 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1655 for (int ins = 0; ins <= nargs; ins++) {
1656 if (nargs > 10 && ins > 4 && ins < nargs-4 && ins % 10 != 3)
1657 continue;
jrose55220c32009-10-21 23:19:48 -07001658 for (int pos = 0; pos <= nargs; pos++) {
jroseb4be0262011-07-16 15:44:33 -07001659 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1660 continue;
1661 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
jrose55220c32009-10-21 23:19:48 -07001662 testInsertArguments(nargs, pos, ins);
1663 }
1664 }
1665 }
1666 }
1667
1668 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001669 countTest();
jroseadc650a2011-02-11 01:26:28 -08001670 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001671 Object[] args = randomArgs(target.type().parameterArray());
1672 List<Object> resList = Arrays.asList(args);
1673 List<Object> argsToPass = new ArrayList<Object>(resList);
1674 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001675 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001676 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001677 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1678 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001679 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001680 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001681 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001682 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001683 System.out.println("result: "+res2List);
1684 //if (!resList.equals(res2List))
1685 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1686 assertEquals(resList, res2List);
1687 }
1688
jrose10f3b682010-01-07 16:16:45 -08001689 @Test
jroseadc650a2011-02-11 01:26:28 -08001690 public void testFilterReturnValue() throws Throwable {
1691 if (CAN_SKIP_WORKING) return;
1692 startTest("filterReturnValue");
1693 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1694 assertTrue(List.class.isAssignableFrom(classOfVCList));
1695 for (int nargs = 0; nargs <= 3; nargs++) {
1696 for (Class<?> rtype : new Class[] { Object.class,
1697 List.class,
1698 int.class,
jroseb4be0262011-07-16 15:44:33 -07001699 byte.class,
1700 long.class,
jroseadc650a2011-02-11 01:26:28 -08001701 CharSequence.class,
1702 String.class }) {
1703 testFilterReturnValue(nargs, rtype);
1704 }
1705 }
1706 }
1707
1708 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1709 countTest();
1710 MethodHandle target = varargsList(nargs, rtype);
1711 MethodHandle filter;
1712 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1713 filter = varargsList(1); // add another layer of list-ness
1714 else
1715 filter = MethodHandles.identity(rtype);
1716 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1717 Object[] argsToPass = randomArgs(nargs, Object.class);
1718 if (verbosity >= 3)
1719 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1720 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1721 if (verbosity >= 4)
1722 System.out.println("filtered target: "+target2);
1723 // Simulate expected effect of filter on return value:
1724 Object unfiltered = target.invokeWithArguments(argsToPass);
1725 Object expected = filter.invokeWithArguments(unfiltered);
1726 if (verbosity >= 4)
1727 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1728 if (verbosity >= 4)
1729 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1730 Object result = target2.invokeWithArguments(argsToPass);
1731 if (verbosity >= 3)
1732 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1733 if (!expected.equals(result))
1734 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1735 assertEquals(expected, result);
1736 }
1737
1738 @Test
jrose10f3b682010-01-07 16:16:45 -08001739 public void testFilterArguments() throws Throwable {
1740 if (CAN_SKIP_WORKING) return;
1741 startTest("filterArguments");
1742 for (int nargs = 1; nargs <= 6; nargs++) {
1743 for (int pos = 0; pos < nargs; pos++) {
1744 testFilterArguments(nargs, pos);
1745 }
1746 }
1747 }
1748
1749 void testFilterArguments(int nargs, int pos) throws Throwable {
1750 countTest();
jroseadc650a2011-02-11 01:26:28 -08001751 MethodHandle target = varargsList(nargs);
1752 MethodHandle filter = varargsList(1);
jrose9b82ad62011-05-26 17:37:36 -07001753 filter = filter.asType(filter.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001754 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001755 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001756 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001757 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001758 // Simulate expected effect of filter on arglist:
1759 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001760 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001761 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001762 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001763 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001764 System.out.println("result: "+result);
1765 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001766 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001767 assertEquals(expected, result);
1768 }
1769
1770 @Test
1771 public void testFoldArguments() throws Throwable {
1772 if (CAN_SKIP_WORKING) return;
1773 startTest("foldArguments");
1774 for (int nargs = 0; nargs <= 4; nargs++) {
1775 for (int fold = 0; fold <= nargs; fold++) {
1776 for (int pos = 0; pos <= nargs; pos++) {
1777 testFoldArguments(nargs, pos, fold);
1778 }
1779 }
1780 }
1781 }
1782
1783 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1784 if (pos != 0) return; // can fold only at pos=0 for now
1785 countTest();
jroseadc650a2011-02-11 01:26:28 -08001786 MethodHandle target = varargsList(1 + nargs);
1787 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08001788 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001789 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001790 System.out.println("fold "+target+" with "+combine);
1791 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1792 // Simulate expected effect of combiner on arglist:
1793 List<Object> expected = new ArrayList<Object>(argsToPass);
1794 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001795 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001796 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07001797 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08001798 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07001799 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001800 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001801 System.out.println("result: "+result);
1802 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001803 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001804 assertEquals(expected, result);
1805 }
1806
1807 @Test
1808 public void testDropArguments() throws Throwable {
1809 if (CAN_SKIP_WORKING) return;
1810 startTest("dropArguments");
1811 for (int nargs = 0; nargs <= 4; nargs++) {
1812 for (int drop = 1; drop <= 4; drop++) {
1813 for (int pos = 0; pos <= nargs; pos++) {
1814 testDropArguments(nargs, pos, drop);
1815 }
1816 }
1817 }
1818 }
1819
1820 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1821 countTest();
jroseadc650a2011-02-11 01:26:28 -08001822 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001823 Object[] args = randomArgs(target.type().parameterArray());
1824 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1825 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1826 List<Object> resList = Arrays.asList(args);
1827 List<Object> argsToDrop = new ArrayList<Object>(resList);
1828 for (int i = drop; i > 0; i--) {
1829 argsToDrop.add(pos, "blort#"+i);
1830 }
jrose900bafd2010-10-30 21:08:23 -07001831 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08001832 Object res2List = Arrays.asList((Object[])res2);
1833 //if (!resList.equals(res2List))
1834 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1835 assertEquals(resList, res2List);
1836 }
1837
1838 @Test
1839 public void testInvokers() throws Throwable {
1840 if (CAN_SKIP_WORKING) return;
1841 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1842 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1843 Set<MethodType> done = new HashSet<MethodType>();
1844 for (int i = 0; i <= 6; i++) {
jroseb4be0262011-07-16 15:44:33 -07001845 if (CAN_TEST_LIGHTLY && i > 3) break;
jrose10f3b682010-01-07 16:16:45 -08001846 MethodType gtype = MethodType.genericMethodType(i);
1847 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1848 for (int j = -1; j < i; j++) {
1849 MethodType type = gtype;
1850 if (j < 0)
1851 type = type.changeReturnType(argType);
1852 else if (argType == void.class)
1853 continue;
1854 else
1855 type = type.changeParameterType(j, argType);
jrose10f3b682010-01-07 16:16:45 -08001856 if (done.add(type))
1857 testInvokers(type);
1858 MethodType vtype = type.changeReturnType(void.class);
1859 if (done.add(vtype))
1860 testInvokers(vtype);
1861 }
1862 }
1863 }
1864 }
1865
1866 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001867 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001868 System.out.println("test invokers for "+type);
1869 int nargs = type.parameterCount();
1870 boolean testRetCode = type.returnType() != void.class;
1871 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1872 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08001873 assertTrue(target.isVarargsCollector());
1874 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08001875 Object[] args = randomArgs(type.parameterArray());
1876 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1877 targetPlusArgs.add(0, target);
1878 int code = (Integer) invokee(args);
1879 Object log = logEntry("invokee", args);
1880 assertEquals(log.hashCode(), code);
1881 assertCalled("invokee", args);
1882 MethodHandle inv;
1883 Object result;
1884 // exact invoker
1885 countTest();
1886 calledLog.clear();
1887 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07001888 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001889 if (testRetCode) assertEquals(code, result);
1890 assertCalled("invokee", args);
1891 // generic invoker
1892 countTest();
jrose79e0a6c2011-05-12 19:27:33 -07001893 inv = MethodHandles.invoker(type);
jrose9b82ad62011-05-26 17:37:36 -07001894 if (nargs <= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001895 calledLog.clear();
1896 switch (nargs) {
1897 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001898 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001899 break;
1900 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001901 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001902 break;
1903 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001904 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001905 break;
1906 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001907 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001908 break;
1909 }
1910 if (testRetCode) assertEquals(code, result);
1911 assertCalled("invokee", args);
1912 }
1913 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001914 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001915 if (testRetCode) assertEquals(code, result);
1916 assertCalled("invokee", args);
1917 // varargs invoker #0
1918 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001919 inv = MethodHandles.spreadInvoker(type, 0);
jrose9b82ad62011-05-26 17:37:36 -07001920 if (type.returnType() == Object.class) {
1921 result = inv.invokeExact(target, args);
1922 } else if (type.returnType() == void.class) {
1923 result = null; inv.invokeExact(target, args);
1924 } else {
1925 result = inv.invokeWithArguments(target, (Object) args);
1926 }
jrose10f3b682010-01-07 16:16:45 -08001927 if (testRetCode) assertEquals(code, result);
1928 assertCalled("invokee", args);
jrose9b82ad62011-05-26 17:37:36 -07001929 if (nargs >= 1 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001930 // varargs invoker #1
1931 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001932 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001933 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001934 if (testRetCode) assertEquals(code, result);
1935 assertCalled("invokee", args);
1936 }
jrose9b82ad62011-05-26 17:37:36 -07001937 if (nargs >= 2 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001938 // varargs invoker #2
1939 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001940 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001941 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001942 if (testRetCode) assertEquals(code, result);
1943 assertCalled("invokee", args);
1944 }
jrose9b82ad62011-05-26 17:37:36 -07001945 if (nargs >= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001946 // varargs invoker #3
1947 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001948 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001949 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001950 if (testRetCode) assertEquals(code, result);
1951 assertCalled("invokee", args);
1952 }
1953 for (int k = 0; k <= nargs; k++) {
1954 // varargs invoker #0..N
jroseb4be0262011-07-16 15:44:33 -07001955 if (CAN_TEST_LIGHTLY && (k > 1 || k < nargs - 1)) continue;
jrose10f3b682010-01-07 16:16:45 -08001956 countTest();
1957 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001958 inv = MethodHandles.spreadInvoker(type, k);
jrose9b82ad62011-05-26 17:37:36 -07001959 MethodType expType = (type.dropParameterTypes(k, nargs)
1960 .appendParameterTypes(Object[].class)
1961 .insertParameterTypes(0, MethodHandle.class));
1962 assertEquals(expType, inv.type());
jrose10f3b682010-01-07 16:16:45 -08001963 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1964 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1965 Object[] tail = tailList.toArray();
1966 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07001967 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08001968 if (testRetCode) assertEquals(code, result);
1969 assertCalled("invokee", args);
1970 }
jrose900bafd2010-10-30 21:08:23 -07001971
jrose10f3b682010-01-07 16:16:45 -08001972 // dynamic invoker
1973 countTest();
jroseb90d2e72010-12-16 15:59:27 -08001974 CallSite site = new MutableCallSite(type);
1975 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07001976
1977 // see if we get the result of the original target:
1978 try {
1979 result = inv.invokeWithArguments(args);
1980 assertTrue("should not reach here", false);
1981 } catch (IllegalStateException ex) {
1982 String msg = ex.getMessage();
1983 assertTrue(msg, msg.contains("site"));
1984 }
1985
1986 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08001987 site.setTarget(target);
1988 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001989 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001990 if (testRetCode) assertEquals(code, result);
1991 assertCalled("invokee", args);
1992 }
1993
1994 static Object invokee(Object... args) {
1995 return called("invokee", args).hashCode();
1996 }
1997
jrose55220c32009-10-21 23:19:48 -07001998 private static final String MISSING_ARG = "missingArg";
jroseb4be0262011-07-16 15:44:33 -07001999 private static final String MISSING_ARG_2 = "missingArg#2";
jrose55220c32009-10-21 23:19:48 -07002000 static Object targetIfEquals() {
2001 return called("targetIfEquals");
2002 }
2003 static Object fallbackIfNotEquals() {
2004 return called("fallbackIfNotEquals");
2005 }
2006 static Object targetIfEquals(Object x) {
2007 assertEquals(x, MISSING_ARG);
2008 return called("targetIfEquals", x);
2009 }
2010 static Object fallbackIfNotEquals(Object x) {
2011 assertFalse(x.toString(), x.equals(MISSING_ARG));
2012 return called("fallbackIfNotEquals", x);
2013 }
2014 static Object targetIfEquals(Object x, Object y) {
2015 assertEquals(x, y);
2016 return called("targetIfEquals", x, y);
2017 }
2018 static Object fallbackIfNotEquals(Object x, Object y) {
2019 assertFalse(x.toString(), x.equals(y));
2020 return called("fallbackIfNotEquals", x, y);
2021 }
2022 static Object targetIfEquals(Object x, Object y, Object z) {
2023 assertEquals(x, y);
2024 return called("targetIfEquals", x, y, z);
2025 }
2026 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
2027 assertFalse(x.toString(), x.equals(y));
2028 return called("fallbackIfNotEquals", x, y, z);
2029 }
2030
jrose10f3b682010-01-07 16:16:45 -08002031 @Test
2032 public void testGuardWithTest() throws Throwable {
2033 if (CAN_SKIP_WORKING) return;
2034 startTest("guardWithTest");
jroseb4be0262011-07-16 15:44:33 -07002035 for (int nargs = 0; nargs <= 50; nargs++) {
2036 if (CAN_TEST_LIGHTLY && nargs > 7) break;
jrose10f3b682010-01-07 16:16:45 -08002037 testGuardWithTest(nargs, Object.class);
2038 testGuardWithTest(nargs, String.class);
2039 }
2040 }
2041 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07002042 testGuardWithTest(nargs, 0, argClass);
2043 if (nargs <= 5 || nargs % 10 == 3) {
2044 for (int testDrops = 1; testDrops <= nargs; testDrops++)
2045 testGuardWithTest(nargs, testDrops, argClass);
2046 }
2047 }
2048 void testGuardWithTest(int nargs, int testDrops, Class<?> argClass) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002049 countTest();
jroseb4be0262011-07-16 15:44:33 -07002050 int nargs1 = Math.min(3, nargs);
jrose10f3b682010-01-07 16:16:45 -08002051 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
jroseb4be0262011-07-16 15:44:33 -07002052 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs1));
2053 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs1));
jrose10f3b682010-01-07 16:16:45 -08002054 while (test.type().parameterCount() > nargs)
jroseb4be0262011-07-16 15:44:33 -07002055 // 0: test = constant(MISSING_ARG.equals(MISSING_ARG))
2056 // 1: test = lambda (_) MISSING_ARG.equals(_)
jrose10f3b682010-01-07 16:16:45 -08002057 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
2058 if (argClass != Object.class) {
2059 test = changeArgTypes(test, argClass);
2060 target = changeArgTypes(target, argClass);
2061 fallback = changeArgTypes(fallback, argClass);
2062 }
jroseb4be0262011-07-16 15:44:33 -07002063 int testArgs = nargs - testDrops;
2064 assert(testArgs >= 0);
2065 test = addTrailingArgs(test, Math.min(testArgs, nargs), argClass);
2066 target = addTrailingArgs(target, nargs, argClass);
2067 fallback = addTrailingArgs(fallback, nargs, argClass);
jrose10f3b682010-01-07 16:16:45 -08002068 Object[][] argLists = {
2069 { },
2070 { "foo" }, { MISSING_ARG },
2071 { "foo", "foo" }, { "foo", "bar" },
2072 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
2073 };
2074 for (Object[] argList : argLists) {
jroseb4be0262011-07-16 15:44:33 -07002075 Object[] argList1 = argList;
2076 if (argList.length != nargs) {
2077 if (argList.length != nargs1) continue;
2078 argList1 = Arrays.copyOf(argList, nargs);
2079 Arrays.fill(argList1, nargs1, nargs, MISSING_ARG_2);
2080 }
2081 MethodHandle test1 = test;
2082 if (test1.type().parameterCount() > testArgs) {
2083 int pc = test1.type().parameterCount();
2084 test1 = MethodHandles.insertArguments(test, testArgs, Arrays.copyOfRange(argList1, testArgs, pc));
2085 }
2086 MethodHandle mh = MethodHandles.guardWithTest(test1, target, fallback);
2087 assertEquals(target.type(), mh.type());
jrose10f3b682010-01-07 16:16:45 -08002088 boolean equals;
2089 switch (nargs) {
2090 case 0: equals = true; break;
2091 case 1: equals = MISSING_ARG.equals(argList[0]); break;
2092 default: equals = argList[0].equals(argList[1]); break;
2093 }
2094 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07002095 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002096 System.out.println(logEntry(willCall, argList));
jroseb4be0262011-07-16 15:44:33 -07002097 Object result = mh.invokeWithArguments(argList1);
jrose10f3b682010-01-07 16:16:45 -08002098 assertCalled(willCall, argList);
2099 }
2100 }
2101
2102 @Test
2103 public void testCatchException() throws Throwable {
2104 if (CAN_SKIP_WORKING) return;
2105 startTest("catchException");
jroseb4be0262011-07-16 15:44:33 -07002106 for (int nargs = 0; nargs < 40; nargs++) {
2107 if (CAN_TEST_LIGHTLY && nargs > 7) break;
2108 for (int throwMode = 0; throwMode < THROW_MODE_LIMIT; throwMode++) {
2109 testCatchException(int.class, new ClassCastException("testing"), throwMode, nargs);
2110 if (CAN_TEST_LIGHTLY && nargs > 3) continue;
2111 testCatchException(void.class, new java.io.IOException("testing"), throwMode, nargs);
2112 testCatchException(String.class, new LinkageError("testing"), throwMode, nargs);
jrose10f3b682010-01-07 16:16:45 -08002113 }
2114 }
2115 }
2116
jroseb4be0262011-07-16 15:44:33 -07002117 static final int THROW_NOTHING = 0, THROW_CAUGHT = 1, THROW_UNCAUGHT = 2, THROW_THROUGH_ADAPTER = 3, THROW_MODE_LIMIT = 4;
2118
2119 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs) throws Throwable {
2120 testCatchException(returnType, thrown, throwMode, nargs, 0);
2121 if (nargs <= 5 || nargs % 10 == 3) {
2122 for (int catchDrops = 1; catchDrops <= nargs; catchDrops++)
2123 testCatchException(returnType, thrown, throwMode, nargs, catchDrops);
2124 }
2125 }
2126
jrose10f3b682010-01-07 16:16:45 -08002127 private static <T extends Throwable>
2128 Object throwOrReturn(Object normal, T exception) throws T {
jroseb4be0262011-07-16 15:44:33 -07002129 if (exception != null) {
2130 called("throwOrReturn/throw", normal, exception);
2131 throw exception;
2132 }
2133 called("throwOrReturn/normal", normal, exception);
jrose10f3b682010-01-07 16:16:45 -08002134 return normal;
2135 }
jroseb4be0262011-07-16 15:44:33 -07002136 private int fakeIdentityCount;
2137 private Object fakeIdentity(Object x) {
2138 System.out.println("should throw through this!");
2139 fakeIdentityCount++;
2140 return x;
2141 }
jrose10f3b682010-01-07 16:16:45 -08002142
jroseb4be0262011-07-16 15:44:33 -07002143 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs, int catchDrops) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002144 countTest();
jrose2cc9c832010-04-30 23:48:23 -07002145 if (verbosity >= 3)
jroseb4be0262011-07-16 15:44:33 -07002146 System.out.println("catchException rt="+returnType+" throw="+throwMode+" nargs="+nargs+" drops="+catchDrops);
jrose10f3b682010-01-07 16:16:45 -08002147 Class<? extends Throwable> exType = thrown.getClass();
jroseb4be0262011-07-16 15:44:33 -07002148 if (throwMode > THROW_CAUGHT) thrown = new UnsupportedOperationException("do not catch this");
jrose10f3b682010-01-07 16:16:45 -08002149 MethodHandle throwOrReturn
2150 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2151 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb4be0262011-07-16 15:44:33 -07002152 if (throwMode == THROW_THROUGH_ADAPTER) {
2153 MethodHandle fakeIdentity
2154 = PRIVATE.findVirtual(MethodHandlesTest.class, "fakeIdentity",
2155 MethodType.methodType(Object.class, Object.class)).bindTo(this);
2156 for (int i = 0; i < 10; i++)
2157 throwOrReturn = MethodHandles.filterReturnValue(throwOrReturn, fakeIdentity);
2158 }
2159 int nargs1 = Math.max(2, nargs);
jroseb90d2e72010-12-16 15:59:27 -08002160 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jroseb4be0262011-07-16 15:44:33 -07002161 thrower = addTrailingArgs(thrower, nargs, Object.class);
2162 int catchArgc = 1 + nargs - catchDrops;
2163 MethodHandle catcher = varargsList(catchArgc).asType(MethodType.genericMethodType(catchArgc));
jrose10f3b682010-01-07 16:16:45 -08002164 Object[] args = randomArgs(nargs, Object.class);
jroseb4be0262011-07-16 15:44:33 -07002165 Object arg0 = MISSING_ARG;
2166 Object arg1 = (throwMode == THROW_NOTHING) ? (Throwable) null : thrown;
2167 if (nargs > 0) arg0 = args[0];
2168 if (nargs > 1) args[1] = arg1;
2169 assertEquals(nargs1, thrower.type().parameterCount());
2170 if (nargs < nargs1) {
2171 Object[] appendArgs = { arg0, arg1 };
2172 appendArgs = Arrays.copyOfRange(appendArgs, nargs, nargs1);
2173 thrower = MethodHandles.insertArguments(thrower, nargs, appendArgs);
2174 }
2175 assertEquals(nargs, thrower.type().parameterCount());
2176 MethodHandle target = MethodHandles.catchException(thrower, exType, catcher);
2177 assertEquals(thrower.type(), target.type());
2178 assertEquals(nargs, target.type().parameterCount());
2179 //System.out.println("catching with "+target+" : "+throwOrReturn);
2180 Object returned;
2181 try {
2182 returned = target.invokeWithArguments(args);
2183 } catch (Throwable ex) {
2184 assertSame("must get the out-of-band exception", thrown, ex);
2185 if (throwMode <= THROW_CAUGHT)
2186 assertEquals(THROW_UNCAUGHT, throwMode);
2187 returned = ex;
2188 }
2189 assertCalled("throwOrReturn/"+(throwMode == THROW_NOTHING ? "normal" : "throw"), arg0, arg1);
jrose10f3b682010-01-07 16:16:45 -08002190 //System.out.println("return from "+target+" : "+returned);
jroseb4be0262011-07-16 15:44:33 -07002191 if (throwMode == THROW_NOTHING) {
2192 assertSame(arg0, returned);
2193 } else if (throwMode == THROW_CAUGHT) {
jrose10f3b682010-01-07 16:16:45 -08002194 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
jroseb4be0262011-07-16 15:44:33 -07002195 // catcher receives an initial subsequence of target arguments:
2196 catchArgs.subList(nargs - catchDrops, nargs).clear();
2197 // catcher also receives the exception, prepended:
jrose10f3b682010-01-07 16:16:45 -08002198 catchArgs.add(0, thrown);
2199 assertEquals(catchArgs, returned);
2200 }
jroseb4be0262011-07-16 15:44:33 -07002201 assertEquals(0, fakeIdentityCount);
jrose10f3b682010-01-07 16:16:45 -08002202 }
2203
2204 @Test
2205 public void testThrowException() throws Throwable {
2206 if (CAN_SKIP_WORKING) return;
2207 startTest("throwException");
2208 testThrowException(int.class, new ClassCastException("testing"));
2209 testThrowException(void.class, new java.io.IOException("testing"));
2210 testThrowException(String.class, new LinkageError("testing"));
2211 }
2212
2213 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2214 countTest();
2215 Class<? extends Throwable> exType = thrown.getClass();
2216 MethodHandle target = MethodHandles.throwException(returnType, exType);
2217 //System.out.println("throwing with "+target+" : "+thrown);
2218 MethodType expectedType = MethodType.methodType(returnType, exType);
2219 assertEquals(expectedType, target.type());
jrose9b82ad62011-05-26 17:37:36 -07002220 target = target.asType(target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08002221 Throwable caught = null;
2222 try {
jrose2cc9c832010-04-30 23:48:23 -07002223 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08002224 fail("got "+res+" instead of throwing "+thrown);
2225 } catch (Throwable ex) {
2226 if (ex != thrown) {
2227 if (ex instanceof Error) throw (Error)ex;
2228 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2229 }
2230 caught = ex;
2231 }
2232 assertSame(thrown, caught);
2233 }
2234
2235 @Test
jroseb4be0262011-07-16 15:44:33 -07002236 public void testInterfaceCast() throws Throwable {
2237 for (Class<?> ctype : new Class<?>[]{ Object.class, String.class, CharSequence.class, Number.class, Iterable.class}) {
2238 testInterfaceCast(ctype, false, false);
2239 testInterfaceCast(ctype, true, false);
2240 testInterfaceCast(ctype, false, true);
2241 testInterfaceCast(ctype, true, true);
2242 }
2243 }
2244 public void testInterfaceCast(Class<?> ctype, boolean doret, boolean docast) throws Throwable {
2245 String str = "normal return value";
2246 MethodHandle mh = MethodHandles.identity(String.class);
2247 MethodType mt = mh.type();
2248 if (doret) mt = mt.changeReturnType(ctype);
2249 else mt = mt.changeParameterType(0, ctype);
2250 if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
2251 else mh = mh.asType(mt);
2252 // this bit is needed to make the interface types disappear for invokeWithArguments:
2253 mh = MethodHandles.explicitCastArguments(mh, mt.generic());
2254 boolean expectFail = !ctype.isInstance(str);
2255 if (ctype.isInterface()) {
2256 // special rules: interfaces slide by more frequently
2257 if (docast || !doret) expectFail = false;
2258 }
2259 Object res;
2260 try {
2261 res = mh.invokeWithArguments(str);
2262 } catch (Exception ex) {
2263 res = ex;
2264 }
2265 boolean sawFail = !(res instanceof String);
2266 if (sawFail != expectFail) {
2267 System.out.println("*** testInterfaceCast: "+mh+" was "+mt+" => "+res+(docast ? " (explicitCastArguments)" : ""));
2268 }
2269 if (!sawFail) {
2270 assertFalse(res.toString(), expectFail);
2271 assertEquals(str, res);
2272 } else {
2273 assertTrue(res.toString(), expectFail);
2274 }
2275 }
2276
2277 @Test
jrose10f3b682010-01-07 16:16:45 -08002278 public void testCastFailure() throws Throwable {
2279 if (CAN_SKIP_WORKING) return;
2280 startTest("testCastFailure");
2281 testCastFailure("cast/argument", 11000);
2282 testCastFailure("unbox/argument", 11000);
2283 testCastFailure("cast/return", 11000);
2284 testCastFailure("unbox/return", 11000);
2285 }
2286
jrose900bafd2010-10-30 21:08:23 -07002287 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07002288 public MethodHandle asMethodHandle() {
2289 return VALUE.bindTo(this);
2290 }
jrose10f3b682010-01-07 16:16:45 -08002291 Object value(Object x) {
2292 trace("value", x);
2293 if (boo != null) return boo;
2294 return x;
2295 }
2296 Object boo;
2297 void boo(Object x) { boo = x; }
2298
2299 static void trace(String x, Object y) {
2300 if (verbosity > 8) System.out.println(x+"="+y);
2301 }
2302 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2303 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2304 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07002305 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
2306 static {
2307 try {
2308 VALUE = PRIVATE.findVirtual(
2309 Surprise.class, "value",
2310 MethodType.methodType(Object.class, Object.class));
2311 REF_IDENTITY = PRIVATE.findStatic(
2312 Surprise.class, "refIdentity",
2313 MethodType.methodType(Object.class, Object.class));
2314 BOX_IDENTITY = PRIVATE.findStatic(
2315 Surprise.class, "boxIdentity",
2316 MethodType.methodType(Integer.class, Integer.class));
2317 INT_IDENTITY = PRIVATE.findStatic(
2318 Surprise.class, "intIdentity",
2319 MethodType.methodType(int.class, int.class));
2320 } catch (Exception ex) {
2321 throw new RuntimeException(ex);
2322 }
2323 }
jrose10f3b682010-01-07 16:16:45 -08002324 }
2325
2326 void testCastFailure(String mode, int okCount) throws Throwable {
2327 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07002328 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002329 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002330 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002331 if (mode.endsWith("/return")) {
2332 if (mode.equals("unbox/return")) {
2333 // fail on return to ((Integer)surprise).intValue
jrose9b82ad62011-05-26 17:37:36 -07002334 surprise = surprise.asType(MethodType.methodType(int.class, Object.class));
2335 identity = identity.asType(MethodType.methodType(int.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002336 } else if (mode.equals("cast/return")) {
2337 // fail on return to (Integer)surprise
jrose9b82ad62011-05-26 17:37:36 -07002338 surprise = surprise.asType(MethodType.methodType(Integer.class, Object.class));
2339 identity = identity.asType(MethodType.methodType(Integer.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002340 }
2341 } else if (mode.endsWith("/argument")) {
2342 MethodHandle callee = null;
2343 if (mode.equals("unbox/argument")) {
2344 // fail on handing surprise to int argument
2345 callee = Surprise.INT_IDENTITY;
2346 } else if (mode.equals("cast/argument")) {
2347 // fail on handing surprise to Integer argument
2348 callee = Surprise.BOX_IDENTITY;
2349 }
2350 if (callee != null) {
jrose9b82ad62011-05-26 17:37:36 -07002351 callee = callee.asType(MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002352 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2353 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002354 }
2355 }
jrosea1ebbe62010-09-08 18:40:23 -07002356 assertNotSame(mode, surprise, surprise0);
jrose9b82ad62011-05-26 17:37:36 -07002357 identity = identity.asType(MethodType.genericMethodType(1));
2358 surprise = surprise.asType(MethodType.genericMethodType(1));
jrose10f3b682010-01-07 16:16:45 -08002359 Object x = 42;
2360 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002361 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002362 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002363 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002364 assertEquals(x, z);
2365 }
2366 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002367 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002368 assertEquals(x, y);
2369 try {
jrose2cc9c832010-04-30 23:48:23 -07002370 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002371 System.out.println("Failed to throw; got z="+z);
2372 assertTrue(false);
jrose320b7692011-05-12 19:27:49 -07002373 } catch (ClassCastException ex) {
jrose10f3b682010-01-07 16:16:45 -08002374 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002375 System.out.println("caught "+ex);
2376 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08002377 ex.printStackTrace();
jrose320b7692011-05-12 19:27:49 -07002378 assertTrue(true); // all is well
jrose10f3b682010-01-07 16:16:45 -08002379 }
2380 }
2381
jrose45b7a332010-05-03 23:32:47 -07002382 static Example userMethod(Object o, String s, int i) {
2383 called("userMethod", o, s, i);
2384 return null;
2385 }
2386
2387 @Test
2388 public void testUserClassInSignature() throws Throwable {
2389 if (CAN_SKIP_WORKING) return;
2390 startTest("testUserClassInSignature");
2391 Lookup lookup = MethodHandles.lookup();
2392 String name; MethodType mt; MethodHandle mh;
2393 Object[] args;
2394
2395 // Try a static method.
2396 name = "userMethod";
2397 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2398 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2399 assertEquals(mt, mh.type());
2400 assertEquals(Example.class, mh.type().returnType());
2401 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002402 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002403 assertCalled(name, args);
2404
2405 // Try a virtual method.
2406 name = "v2";
2407 mt = MethodType.methodType(Object.class, Object.class, int.class);
2408 mh = lookup.findVirtual(Example.class, name, mt);
2409 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2410 assertTrue(mh.type().parameterList().contains(Example.class));
2411 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002412 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002413 assertCalled(name, args);
2414 }
jrosebe2db602010-09-08 18:40:34 -07002415
2416 static void runForRunnable() {
2417 called("runForRunnable");
2418 }
jroseaf751942011-06-14 22:47:12 -07002419 public interface Fooable {
jroseb4be0262011-07-16 15:44:33 -07002420 // overloads:
2421 Object foo(Object x, String y);
2422 List foo(String x, int y);
2423 Object foo(String x);
jrosebe2db602010-09-08 18:40:34 -07002424 }
jroseb4be0262011-07-16 15:44:33 -07002425 static Object fooForFooable(String x, Object... y) {
2426 return called("fooForFooable/"+x, y);
jrosebe2db602010-09-08 18:40:34 -07002427 }
jroseaf751942011-06-14 22:47:12 -07002428 public static class MyCheckedException extends Exception {
jrosebe2db602010-09-08 18:40:34 -07002429 }
jroseaf751942011-06-14 22:47:12 -07002430 public interface WillThrow {
jrosebe2db602010-09-08 18:40:34 -07002431 void willThrow() throws MyCheckedException;
2432 }
jroseb4be0262011-07-16 15:44:33 -07002433 /*non-public*/ interface PrivateRunnable {
2434 public void run();
2435 }
jrosebe2db602010-09-08 18:40:34 -07002436
2437 @Test
jroseb4be0262011-07-16 15:44:33 -07002438 public void testAsInterfaceInstance() throws Throwable {
jrosebe2db602010-09-08 18:40:34 -07002439 if (CAN_SKIP_WORKING) return;
jroseb4be0262011-07-16 15:44:33 -07002440 startTest("testAsInterfaceInstance");
jrosebe2db602010-09-08 18:40:34 -07002441 Lookup lookup = MethodHandles.lookup();
jroseb4be0262011-07-16 15:44:33 -07002442 // test typical case: Runnable.run
jrosebe2db602010-09-08 18:40:34 -07002443 {
jroseb4be0262011-07-16 15:44:33 -07002444 countTest();
2445 if (verbosity >= 2) System.out.println("Runnable");
jrosebe2db602010-09-08 18:40:34 -07002446 MethodType mt = MethodType.methodType(void.class);
2447 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
jrose9b82ad62011-05-26 17:37:36 -07002448 Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002449 proxy.run();
2450 assertCalled("runForRunnable");
2451 }
jroseb4be0262011-07-16 15:44:33 -07002452 // well known single-name overloaded interface: Appendable.append
jrosebe2db602010-09-08 18:40:34 -07002453 {
jroseb4be0262011-07-16 15:44:33 -07002454 countTest();
2455 if (verbosity >= 2) System.out.println("Appendable");
2456 ArrayList<List> appendResults = new ArrayList<List>();
2457 MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
2458 append = append.asType(MethodType.methodType(void.class, List.class)); // specialize the type
2459 MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
2460 MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
2461 Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
2462 proxy.append("one");
2463 proxy.append("two", 3, 4);
2464 proxy.append('5');
2465 assertEquals(Arrays.asList(Arrays.asList("one"),
2466 Arrays.asList("two", 3, 4),
2467 Arrays.asList('5')),
2468 appendResults);
2469 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
2470 appendResults.clear();
2471 Formatter formatter = new Formatter(proxy);
2472 String fmt = "foo str=%s char='%c' num=%d";
2473 Object[] fmtArgs = { "str!", 'C', 42 };
2474 String expect = String.format(fmt, fmtArgs);
2475 formatter.format(fmt, fmtArgs);
2476 String actual = "";
2477 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
2478 for (List l : appendResults) {
2479 Object x = l.get(0);
2480 switch (l.size()) {
2481 case 1: actual += x; continue;
2482 case 3: actual += ((String)x).substring((int)l.get(1), (int)l.get(2)); continue;
2483 }
2484 actual += l;
2485 }
2486 if (verbosity >= 3) System.out.println("expect="+expect);
2487 if (verbosity >= 3) System.out.println("actual="+actual);
2488 assertEquals(expect, actual);
jrosebe2db602010-09-08 18:40:34 -07002489 }
jroseb4be0262011-07-16 15:44:33 -07002490 // test case of an single name which is overloaded: Fooable.foo(...)
2491 {
2492 if (verbosity >= 2) System.out.println("Fooable");
2493 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable",
2494 MethodType.methodType(Object.class, String.class, Object[].class));
2495 Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
2496 for (Method m : Fooable.class.getDeclaredMethods()) {
2497 countTest();
2498 assertSame("foo", m.getName());
2499 if (verbosity > 3)
2500 System.out.println("calling "+m);
2501 MethodHandle invoker = lookup.unreflect(m);
2502 MethodType mt = invoker.type();
2503 Class<?>[] types = mt.parameterArray();
2504 types[0] = int.class; // placeholder
2505 Object[] args = randomArgs(types);
2506 args[0] = proxy;
2507 if (verbosity > 3)
2508 System.out.println("calling "+m+" on "+Arrays.asList(args));
2509 Object result = invoker.invokeWithArguments(args);
2510 if (verbosity > 4)
2511 System.out.println("result = "+result);
2512 String name = "fooForFooable/"+args[1];
2513 Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
2514 assertCalled(name, argTail);
2515 assertEquals(result, logEntry(name, argTail));
2516 }
2517 }
2518 // test processing of thrown exceptions:
jrosebe2db602010-09-08 18:40:34 -07002519 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2520 new InternalError("ok"),
2521 new Throwable("fail"),
2522 new Exception("fail"),
2523 new MyCheckedException()
2524 }) {
2525 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2526 mh = MethodHandles.insertArguments(mh, 0, ex);
jrose9b82ad62011-05-26 17:37:36 -07002527 WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002528 try {
jroseb4be0262011-07-16 15:44:33 -07002529 countTest();
jrosebe2db602010-09-08 18:40:34 -07002530 proxy.willThrow();
2531 System.out.println("Failed to throw: "+ex);
2532 assertTrue(false);
2533 } catch (Throwable ex1) {
jroseb4be0262011-07-16 15:44:33 -07002534 if (verbosity > 3) {
jrosebe2db602010-09-08 18:40:34 -07002535 System.out.println("throw "+ex);
2536 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2537 }
2538 if (ex instanceof RuntimeException ||
2539 ex instanceof Error) {
2540 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2541 } else if (ex instanceof MyCheckedException) {
2542 assertSame("must pass declared exception out without wrapping", ex, ex1);
2543 } else {
2544 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
jroseaf751942011-06-14 22:47:12 -07002545 if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
2546 ex1.printStackTrace();
2547 }
2548 assertSame(ex, ex1.getCause());
jrosebe2db602010-09-08 18:40:34 -07002549 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
jrosebe2db602010-09-08 18:40:34 -07002550 }
2551 }
2552 }
jroseb4be0262011-07-16 15:44:33 -07002553 // Test error checking on bad interfaces:
2554 for (Class<?> nonSMI : new Class[] { Object.class,
jrosebe2db602010-09-08 18:40:34 -07002555 String.class,
2556 CharSequence.class,
jroseb4be0262011-07-16 15:44:33 -07002557 java.io.Serializable.class,
2558 PrivateRunnable.class,
jrosebe2db602010-09-08 18:40:34 -07002559 Example.class }) {
jroseb4be0262011-07-16 15:44:33 -07002560 if (verbosity > 2) System.out.println(nonSMI.getName());
jrosebe2db602010-09-08 18:40:34 -07002561 try {
jroseb4be0262011-07-16 15:44:33 -07002562 countTest(false);
2563 MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
2564 assertTrue("Failed to throw on "+nonSMI.getName(), false);
jrosebe2db602010-09-08 18:40:34 -07002565 } catch (IllegalArgumentException ex) {
jroseb4be0262011-07-16 15:44:33 -07002566 if (verbosity > 2) System.out.println(nonSMI.getSimpleName()+": "+ex);
2567 // Object: java.lang.IllegalArgumentException:
2568 // not a public interface: java.lang.Object
2569 // String: java.lang.IllegalArgumentException:
2570 // not a public interface: java.lang.String
2571 // CharSequence: java.lang.IllegalArgumentException:
2572 // not a single-method interface: java.lang.CharSequence
2573 // Serializable: java.lang.IllegalArgumentException:
2574 // not a single-method interface: java.io.Serializable
2575 // PrivateRunnable: java.lang.IllegalArgumentException:
2576 // not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
2577 // Example: java.lang.IllegalArgumentException:
2578 // not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
2579 }
2580 }
2581 // Test error checking on interfaces with the wrong method type:
2582 for (Class<?> intfc : new Class[] { Runnable.class /*arity 0*/,
2583 Fooable.class /*arity 1 & 2*/ }) {
2584 int badArity = 1; // known to be incompatible
2585 if (verbosity > 2) System.out.println(intfc.getName());
2586 try {
2587 countTest(false);
2588 MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
2589 assertTrue("Failed to throw on "+intfc.getName(), false);
2590 } catch (WrongMethodTypeException ex) {
2591 if (verbosity > 2) System.out.println(intfc.getSimpleName()+": "+ex);
2592 // Runnable: java.lang.invoke.WrongMethodTypeException:
2593 // cannot convert MethodHandle(Object)Object[] to ()void
2594 // Fooable: java.lang.invoke.WrongMethodTypeException:
2595 // cannot convert MethodHandle(Object)Object[] to (Object,String)Object
jrosebe2db602010-09-08 18:40:34 -07002596 }
2597 }
2598 }
jrose43b8c122011-07-16 15:40:13 -07002599
2600 @Test
2601 public void testRunnableProxy() throws Throwable {
2602 if (CAN_SKIP_WORKING) return;
2603 startTest("testRunnableProxy");
2604 MethodHandles.Lookup lookup = MethodHandles.lookup();
2605 MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
2606 Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
2607 testRunnableProxy(r);
2608 assertCalled("runForRunnable");
2609 }
2610 private static void testRunnableProxy(Runnable r) {
2611 //7058630: JSR 292 method handle proxy violates contract for Object methods
2612 r.run();
2613 Object o = r;
2614 r = null;
2615 boolean eq = (o == o);
2616 int hc = System.identityHashCode(o);
2617 String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
2618 Object expect = Arrays.asList(st, eq, hc);
2619 if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
2620 Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
2621 if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
2622 assertEquals(expect, actual);
2623 }
jrose55220c32009-10-21 23:19:48 -07002624}
jroseada69fa2011-03-23 23:02:31 -07002625// Local abbreviated copy of sun.invoke.util.ValueConversions
jrose55220c32009-10-21 23:19:48 -07002626class ValueConversions {
2627 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2628 private static final Object[] NO_ARGS_ARRAY = {};
2629 private static Object[] makeArray(Object... args) { return args; }
2630 private static Object[] array() { return NO_ARGS_ARRAY; }
2631 private static Object[] array(Object a0)
2632 { return makeArray(a0); }
2633 private static Object[] array(Object a0, Object a1)
2634 { return makeArray(a0, a1); }
2635 private static Object[] array(Object a0, Object a1, Object a2)
2636 { return makeArray(a0, a1, a2); }
2637 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2638 { return makeArray(a0, a1, a2, a3); }
2639 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2640 Object a4)
2641 { return makeArray(a0, a1, a2, a3, a4); }
2642 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2643 Object a4, Object a5)
2644 { return makeArray(a0, a1, a2, a3, a4, a5); }
2645 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2646 Object a4, Object a5, Object a6)
2647 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2648 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2649 Object a4, Object a5, Object a6, Object a7)
2650 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2651 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2652 Object a4, Object a5, Object a6, Object a7,
2653 Object a8)
2654 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2655 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2656 Object a4, Object a5, Object a6, Object a7,
2657 Object a8, Object a9)
2658 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2659 static MethodHandle[] makeArrays() {
2660 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
2661 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2662 for (;;) {
2663 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002664 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002665 String name = "array";
2666 MethodHandle array = null;
2667 try {
2668 array = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002669 } catch (ReflectiveOperationException ex) {
2670 // break from loop!
jrose55220c32009-10-21 23:19:48 -07002671 }
2672 if (array == null) break;
2673 arrays.add(array);
2674 }
jrosef15905c2011-02-11 01:26:32 -08002675 assertTrue(arrays.size() == 11); // current number of methods
jrose55220c32009-10-21 23:19:48 -07002676 return arrays.toArray(new MethodHandle[0]);
2677 }
2678 static final MethodHandle[] ARRAYS = makeArrays();
2679
2680 /** Return a method handle that takes the indicated number of Object
2681 * arguments and returns an Object array of them, as if for varargs.
2682 */
2683 public static MethodHandle varargsArray(int nargs) {
2684 if (nargs < ARRAYS.length)
2685 return ARRAYS[nargs];
jroseaf751942011-06-14 22:47:12 -07002686 return MethodHandles.identity(Object[].class).asCollector(Object[].class, nargs);
jrose55220c32009-10-21 23:19:48 -07002687 }
jrose320b7692011-05-12 19:27:49 -07002688 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
2689 Class<?> elemType = arrayType.getComponentType();
2690 MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
2691 MethodHandle mh = varargsArray(nargs);
2692 if (arrayType != Object[].class)
2693 mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
2694 return mh.asType(vaType);
2695 }
2696 static Object changeArrayType(Class<?> arrayType, Object[] a) {
2697 Class<?> elemType = arrayType.getComponentType();
2698 if (!elemType.isPrimitive())
2699 return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
2700 Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
2701 for (int i = 0; i < a.length; i++)
2702 java.lang.reflect.Array.set(b, i, a[i]);
2703 return b;
2704 }
2705 private static final MethodHandle CHANGE_ARRAY_TYPE;
2706 static {
2707 try {
2708 CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
2709 MethodType.methodType(Object.class, Class.class, Object[].class));
2710 } catch (NoSuchMethodException | IllegalAccessException ex) {
2711 Error err = new InternalError("uncaught exception");
2712 err.initCause(ex);
2713 throw err;
2714 }
2715 }
jrose10f3b682010-01-07 16:16:45 -08002716
2717 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2718 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2719 private static List<Object> list() { return NO_ARGS_LIST; }
2720 private static List<Object> list(Object a0)
2721 { return makeList(a0); }
2722 private static List<Object> list(Object a0, Object a1)
2723 { return makeList(a0, a1); }
2724 private static List<Object> list(Object a0, Object a1, Object a2)
2725 { return makeList(a0, a1, a2); }
2726 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2727 { return makeList(a0, a1, a2, a3); }
2728 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2729 Object a4)
2730 { return makeList(a0, a1, a2, a3, a4); }
2731 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2732 Object a4, Object a5)
2733 { return makeList(a0, a1, a2, a3, a4, a5); }
2734 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2735 Object a4, Object a5, Object a6)
2736 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2737 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2738 Object a4, Object a5, Object a6, Object a7)
2739 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2740 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2741 Object a4, Object a5, Object a6, Object a7,
2742 Object a8)
2743 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2744 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2745 Object a4, Object a5, Object a6, Object a7,
2746 Object a8, Object a9)
2747 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2748 static MethodHandle[] makeLists() {
jroseadc650a2011-02-11 01:26:28 -08002749 ArrayList<MethodHandle> lists = new ArrayList<MethodHandle>();
jrose10f3b682010-01-07 16:16:45 -08002750 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2751 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08002752 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08002753 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2754 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08002755 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08002756 try {
jroseadc650a2011-02-11 01:26:28 -08002757 list = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002758 } catch (ReflectiveOperationException ex) {
2759 // break from loop!
jrose10f3b682010-01-07 16:16:45 -08002760 }
jroseadc650a2011-02-11 01:26:28 -08002761 if (list == null) break;
2762 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08002763 }
jrosef15905c2011-02-11 01:26:32 -08002764 assertTrue(lists.size() == 11); // current number of methods
jroseadc650a2011-02-11 01:26:28 -08002765 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08002766 }
2767 static final MethodHandle[] LISTS = makeLists();
jroseaf751942011-06-14 22:47:12 -07002768 static final MethodHandle AS_LIST;
2769 static {
2770 try {
2771 AS_LIST = IMPL_LOOKUP.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
2772 } catch (Exception ex) { throw new RuntimeException(ex); }
2773 }
jrose10f3b682010-01-07 16:16:45 -08002774
2775 /** Return a method handle that takes the indicated number of Object
2776 * arguments and returns List.
2777 */
2778 public static MethodHandle varargsList(int nargs) {
2779 if (nargs < LISTS.length)
2780 return LISTS[nargs];
jroseaf751942011-06-14 22:47:12 -07002781 return AS_LIST.asCollector(Object[].class, nargs);
jrose10f3b682010-01-07 16:16:45 -08002782 }
jrose55220c32009-10-21 23:19:48 -07002783}
2784// This guy tests access from outside the same package member, but inside
2785// the package itself.
2786class PackageSibling {
2787 static Lookup lookup() {
2788 return MethodHandles.lookup();
2789 }
2790}