blob: dcc31927fae9dc4833b72607ab19634b29543d13 [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.*;
jrose2cc9c832010-04-30 23:48:23 -070040import static org.junit.Assume.*;
jrose55220c32009-10-21 23:19:48 -070041
42
43/**
44 *
45 * @author jrose
46 */
47public class MethodHandlesTest {
48 // How much output?
jrose2cc9c832010-04-30 23:48:23 -070049 static int verbosity = 0;
jrosecf98d422010-06-08 23:08:56 -070050 static {
jroseada69fa2011-03-23 23:02:31 -070051 String vstr = System.getProperty("test.java.lang.invoke.MethodHandlesTest.verbosity");
jrosecf98d422010-06-08 23:08:56 -070052 if (vstr != null) verbosity = Integer.parseInt(vstr);
53 }
jrose55220c32009-10-21 23:19:48 -070054
55 // Set this true during development if you want to fast-forward to
56 // a particular new, non-working test. Tests which are known to
57 // work (or have recently worked) test this flag and return on true.
58 static boolean CAN_SKIP_WORKING = false;
59 //static { CAN_SKIP_WORKING = true; }
60
61 // Set true to test more calls. If false, some tests are just
62 // lookups, without exercising the actual method handle.
jrose2cc9c832010-04-30 23:48:23 -070063 static boolean DO_MORE_CALLS = true;
jrose55220c32009-10-21 23:19:48 -070064
jrose55220c32009-10-21 23:19:48 -070065 @Test
66 public void testFirst() throws Throwable {
67 verbosity += 9; try {
68 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070069 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070070 }
71
jrose10f3b682010-01-07 16:16:45 -080072 // current failures
73 @Test @Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
74 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070075 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080076 testSpreadArguments(int.class, 0, 6);
77 }
jrose2cc9c832010-04-30 23:48:23 -070078 @Test @Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080079 public void testFail_2() throws Throwable {
80 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
81 testSpreadArguments(Object.class, 0, 2);
82 }
83 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
84 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070085 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080086 testSpreadArguments(int.class, 1, 2);
87 }
88 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
89 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070090 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080091 testCollectArguments(int.class, 1, 2);
92 }
93 @Test @Ignore("cannot collect leading primitive types")
94 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070095 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080096 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
97 }
98 @Test @Ignore("should not insert arguments beyond MethodHandlePushLimit")
99 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700100 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
101 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -0800102 }
jrose9b82ad62011-05-26 17:37:36 -0700103 @Test @Ignore("permuteArguments has trouble with double slots")
104 public void testFail_7() throws Throwable {
105 testPermuteArguments(new Object[]{10, 200L},
106 new Class<?>[]{Integer.class, long.class},
107 new int[]{1,0});
108 testPermuteArguments(new Object[]{10, 200L, 5000L},
109 new Class<?>[]{Integer.class, long.class, long.class},
110 new int[]{2,0,1}); //rot
111 testPermuteArguments(new Object[]{10, 200L, 5000L},
112 new Class<?>[]{Integer.class, long.class, long.class},
113 new int[]{1,2,0}); //rot
114 testPermuteArguments(new Object[]{10, 200L, 5000L},
115 new Class<?>[]{Integer.class, long.class, long.class},
116 new int[]{2,1,0}); //swap
117 testPermuteArguments(new Object[]{10, 200L, 5000L},
118 new Class<?>[]{Integer.class, long.class, long.class},
119 new int[]{0,1,2,2}); //dup
120 testPermuteArguments(new Object[]{10, 200L, 5000L},
121 new Class<?>[]{Integer.class, long.class, long.class},
122 new int[]{2,0,1,2});
123 testPermuteArguments(new Object[]{10, 200L, 5000L},
124 new Class<?>[]{Integer.class, long.class, long.class},
125 new int[]{2,2,0,1});
126 testPermuteArguments(4, Integer.class, 2, long.class, 6);
127 }
jrose55220c32009-10-21 23:19:48 -0700128 static final int MAX_ARG_INCREASE = 3;
129
130 public MethodHandlesTest() {
131 }
132
jrose55220c32009-10-21 23:19:48 -0700133 String testName;
jrosecf98d422010-06-08 23:08:56 -0700134 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -0700135 int posTests, negTests;
136 @After
137 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700138 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700139 System.out.println();
140 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
141 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -0700142 allPosTests += posTests;
143 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -0700144 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700145 }
146 }
147 void countTest(boolean positive) {
148 if (positive) ++posTests;
149 else ++negTests;
150 }
151 void countTest() { countTest(true); }
152 void startTest(String name) {
153 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700154 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700155 System.out.println(name);
156 posTests = negTests = 0;
157 testName = name;
158 }
159
160 @BeforeClass
161 public static void setUpClass() throws Exception {
162 calledLog.clear();
163 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700164 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700165 }
166
167 @AfterClass
168 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700169 int posTests = allPosTests, negTests = allNegTests;
170 if (verbosity >= 2 && (posTests | negTests) != 0) {
171 System.out.println();
172 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
173 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
174 }
jrose55220c32009-10-21 23:19:48 -0700175 }
176
177 static List<Object> calledLog = new ArrayList<Object>();
178 static Object logEntry(String name, Object... args) {
179 return Arrays.asList(name, Arrays.asList(args));
180 }
181 static Object called(String name, Object... args) {
182 Object entry = logEntry(name, args);
183 calledLog.add(entry);
184 return entry;
185 }
186 static void assertCalled(String name, Object... args) {
187 Object expected = logEntry(name, args);
188 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700189 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700190 System.out.println("assertCalled "+name+":");
191 System.out.println("expected: "+expected);
192 System.out.println("actual: "+actual);
193 System.out.println("ex. types: "+getClasses(expected));
194 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700195 assertEquals("previous method call", expected, actual);
196 }
197 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700198 if (verbosity >= 3)
199 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700200 }
201
202 static Object castToWrapper(Object value, Class<?> dst) {
203 Object wrap = null;
204 if (value instanceof Number)
205 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
206 if (value instanceof Character)
207 wrap = castToWrapperOrNull((char)(Character)value, dst);
208 if (wrap != null) return wrap;
209 return dst.cast(value);
210 }
211
212 static Object castToWrapperOrNull(long value, Class<?> dst) {
213 if (dst == int.class || dst == Integer.class)
214 return (int)(value);
215 if (dst == long.class || dst == Long.class)
216 return (long)(value);
217 if (dst == char.class || dst == Character.class)
218 return (char)(value);
219 if (dst == short.class || dst == Short.class)
220 return (short)(value);
221 if (dst == float.class || dst == Float.class)
222 return (float)(value);
223 if (dst == double.class || dst == Double.class)
224 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800225 if (dst == byte.class || dst == Byte.class)
226 return (byte)(value);
227 if (dst == boolean.class || dst == boolean.class)
228 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700229 return null;
230 }
231
jrose2cc9c832010-04-30 23:48:23 -0700232 static final int ONE_MILLION = (1000*1000), // first int value
233 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
234 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
235 static long nextArgVal;
236 static long nextArg(boolean moreBits) {
237 long val = nextArgVal++;
238 long sign = -(val & 1); // alternate signs
239 val >>= 1;
240 if (moreBits)
241 // Guarantee some bits in the high word.
242 // In any case keep the decimal representation simple-looking,
243 // with lots of zeroes, so as not to make the printed decimal
244 // strings unnecessarily noisy.
245 val += (val % ONE_MILLION) * TEN_BILLION;
246 return val ^ sign;
247 }
248 static int nextArg() {
249 // Produce a 32-bit result something like ONE_MILLION+(smallint).
250 // Example: 1_000_042.
251 return (int) nextArg(false);
252 }
253 static long nextArg(Class<?> kind) {
254 if (kind == long.class || kind == Long.class ||
255 kind == double.class || kind == Double.class)
256 // produce a 64-bit result something like
257 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
258 // Example: 10_000_420_001_000_042.
259 return nextArg(true);
260 return (long) nextArg();
261 }
262
jrose55220c32009-10-21 23:19:48 -0700263 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700264 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700265 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700266 return wrap;
267 }
jroseada69fa2011-03-23 23:02:31 -0700268// import sun.invoke.util.Wrapper;
jrose55220c32009-10-21 23:19:48 -0700269// Wrapper wrap = Wrapper.forBasicType(dst);
270// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
271// wrap = Wrapper.forWrapperType(dst);
272// if (wrap != Wrapper.OBJECT)
273// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700274 if (param.isInterface()) {
275 for (Class<?> c : param.getClasses()) {
276 if (param.isAssignableFrom(c) && !c.isInterface())
277 { param = c; break; }
278 }
279 }
jrose55220c32009-10-21 23:19:48 -0700280 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700281 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700282 else
283 try {
284 return param.newInstance();
285 } catch (InstantiationException ex) {
286 } catch (IllegalAccessException ex) {
287 }
288 return null; // random class not Object, String, Integer, etc.
289 }
290 static Object[] randomArgs(Class<?>... params) {
291 Object[] args = new Object[params.length];
292 for (int i = 0; i < args.length; i++)
293 args[i] = randomArg(params[i]);
294 return args;
295 }
296 static Object[] randomArgs(int nargs, Class<?> param) {
297 Object[] args = new Object[nargs];
298 for (int i = 0; i < args.length; i++)
299 args[i] = randomArg(param);
300 return args;
301 }
302
303 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
304 return Arrays.copyOf(a, a.length, atype);
305 }
306 static <T> T[] cat(T[] a, T... b) {
307 int alen = a.length, blen = b.length;
308 if (blen == 0) return a;
309 T[] c = Arrays.copyOf(a, alen + blen);
310 System.arraycopy(b, 0, c, alen, blen);
311 return c;
312 }
313 static Integer[] boxAll(int... vx) {
314 Integer[] res = new Integer[vx.length];
315 for (int i = 0; i < res.length; i++) {
316 res[i] = vx[i];
317 }
318 return res;
319 }
320 static Object getClasses(Object x) {
321 if (x == null) return x;
322 if (x instanceof String) return x; // keep the name
323 if (x instanceof List) {
324 // recursively report classes of the list elements
325 Object[] xa = ((List)x).toArray();
326 for (int i = 0; i < xa.length; i++)
327 xa[i] = getClasses(xa[i]);
328 return Arrays.asList(xa);
329 }
330 return x.getClass().getSimpleName();
331 }
332
jroseadc650a2011-02-11 01:26:28 -0800333 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
334 static MethodHandle varargsList(int arity) {
335 return ValueConversions.varargsList(arity);
336 }
337 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
338 static MethodHandle varargsArray(int arity) {
339 return ValueConversions.varargsArray(arity);
340 }
jrose320b7692011-05-12 19:27:49 -0700341 static MethodHandle varargsArray(Class<?> arrayType, int arity) {
342 return ValueConversions.varargsArray(arrayType, arity);
343 }
jroseadc650a2011-02-11 01:26:28 -0800344 /** Variation of varargsList, but with the given rtype. */
345 static MethodHandle varargsList(int arity, Class<?> rtype) {
346 MethodHandle list = varargsList(arity);
347 MethodType listType = list.type().changeReturnType(rtype);
348 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
349 // OK
350 } else if (rtype.isAssignableFrom(String.class)) {
351 if (LIST_TO_STRING == null)
352 try {
353 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
354 MethodType.methodType(String.class, List.class));
355 } catch (Exception ex) { throw new RuntimeException(ex); }
356 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
357 } else if (rtype.isPrimitive()) {
358 if (LIST_TO_INT == null)
359 try {
360 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
361 MethodType.methodType(int.class, List.class));
362 } catch (Exception ex) { throw new RuntimeException(ex); }
363 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
364 list = MethodHandles.explicitCastArguments(list, listType);
365 } else {
366 throw new RuntimeException("varargsList: "+rtype);
367 }
368 return list.asType(listType);
369 }
370 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
371 private static String listToString(List x) { return x.toString(); }
372 private static int listToInt(List x) { return x.toString().hashCode(); }
373
jrose55220c32009-10-21 23:19:48 -0700374 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
375 return changeArgTypes(target, 0, 999, argType);
376 }
377 static MethodHandle changeArgTypes(MethodHandle target,
378 int beg, int end, Class<?> argType) {
379 MethodType targetType = target.type();
380 end = Math.min(end, targetType.parameterCount());
381 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
382 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800383 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose9b82ad62011-05-26 17:37:36 -0700384 return target.asType(ttype2);
jrose55220c32009-10-21 23:19:48 -0700385 }
386
387 // This lookup is good for all members in and under MethodHandlesTest.
388 static final Lookup PRIVATE = MethodHandles.lookup();
389 // This lookup is good for package-private members but not private ones.
390 static final Lookup PACKAGE = PackageSibling.lookup();
391 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800392 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700393
394 // Subject methods...
395 static class Example implements IntExample {
396 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700397 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700398 protected Example(String name) { this.name = name; }
399 protected Example(int x) { this(); called("protected <init>", this, x); }
400 @Override public String toString() { return name; }
401
402 public void v0() { called("v0", this); }
403 void pkg_v0() { called("pkg_v0", this); }
404 private void pri_v0() { called("pri_v0", this); }
405 public static void s0() { called("s0"); }
406 static void pkg_s0() { called("pkg_s0"); }
407 private static void pri_s0() { called("pri_s0"); }
408
409 public Object v1(Object x) { return called("v1", this, x); }
410 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
411 public Object v2(Object x, int y) { return called("v2", this, x, y); }
412 public Object v2(int x, Object y) { return called("v2", this, x, y); }
413 public Object v2(int x, int y) { return called("v2", this, x, y); }
414 public static Object s1(Object x) { return called("s1", x); }
415 public static Object s2(int x) { return called("s2", x); }
416 public static Object s3(long x) { return called("s3", x); }
417 public static Object s4(int x, int y) { return called("s4", x, y); }
418 public static Object s5(long x, int y) { return called("s5", x, y); }
419 public static Object s6(int x, long y) { return called("s6", x, y); }
420 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700421
422 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700423 }
jrose2cc9c832010-04-30 23:48:23 -0700424 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700425 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700426 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700427 }
428 static class SubExample extends Example {
429 @Override public void v0() { called("Sub/v0", this); }
430 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
431 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700432 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700433 }
434 public static interface IntExample {
435 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700436 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700437 public void v0() { called("Int/v0", this); }
438 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700439 public Impl() { name = "Impl#"+nextArg(); }
440 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700441 }
442 }
443
444 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700445 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
446 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
447 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
448 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700449 };
450
jrose2cc9c832010-04-30 23:48:23 -0700451 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
452 Object[][] cases;
453 if (name.contains("pri_") || isSpecial) {
454 cases = ACCESS_CASES[1]; // PRIVATE only
455 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
456 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800457 } else {
458 assertTrue(name.indexOf('_') < 0);
459 boolean pubc = Modifier.isPublic(defc.getModifiers());
460 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700461 cases = ACCESS_CASES[3]; // all access levels
462 else
463 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800464 }
jrose2cc9c832010-04-30 23:48:23 -0700465 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
466 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
467 return cases;
468 }
469 static Object[][] accessCases(Class<?> defc, String name) {
470 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700471 }
472
473 @Test
474 public void testFindStatic() throws Throwable {
475 if (CAN_SKIP_WORKING) return;
476 startTest("findStatic");
477 testFindStatic(PubExample.class, void.class, "s0");
478 testFindStatic(Example.class, void.class, "s0");
479 testFindStatic(Example.class, void.class, "pkg_s0");
480 testFindStatic(Example.class, void.class, "pri_s0");
481
482 testFindStatic(Example.class, Object.class, "s1", Object.class);
483 testFindStatic(Example.class, Object.class, "s2", int.class);
484 testFindStatic(Example.class, Object.class, "s3", long.class);
485 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
486 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
487 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
488 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
489
490 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
491 }
492
493 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
494 for (Object[] ac : accessCases(defc, name)) {
495 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
496 }
497 }
498 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
499 testFindStatic(true, lookup, defc, ret, name, params);
500 }
501 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
502 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800503 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700504 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700505 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700506 try {
jrose2cc9c832010-04-30 23:48:23 -0700507 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700508 target = lookup.in(defc).findStatic(defc, name, type);
jrosef15905c2011-02-11 01:26:32 -0800509 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700510 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800511 if (name.contains("bogus"))
512 assertTrue(noAccess instanceof NoSuchMethodException);
513 else
514 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700515 }
jrose2cc9c832010-04-30 23:48:23 -0700516 if (verbosity >= 3)
517 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700518 +(noAccess == null ? "" : " !! "+noAccess));
519 if (positive && noAccess != null) throw noAccess;
520 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
521 if (!positive) return; // negative test failed as expected
522 assertEquals(type, target.type());
jrose900bafd2010-10-30 21:08:23 -0700523 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700524 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
525 Object[] args = randomArgs(params);
526 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700527 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700528 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700529 if (verbosity >= 1)
530 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700531 }
532
jrose73016262011-05-17 19:48:19 -0700533 static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
534
jrose900bafd2010-10-30 21:08:23 -0700535 // rough check of name string
jrose73016262011-05-17 19:48:19 -0700536 static void assertNameStringContains(MethodHandle x, String s) {
537 if (!DEBUG_METHOD_HANDLE_NAMES) {
538 // ignore s
539 assertEquals("MethodHandle"+x.type(), x.toString());
540 return;
541 }
jrose900bafd2010-10-30 21:08:23 -0700542 if (x.toString().contains(s)) return;
543 assertEquals(s, x);
544 }
545
jrose55220c32009-10-21 23:19:48 -0700546 @Test
547 public void testFindVirtual() throws Throwable {
548 if (CAN_SKIP_WORKING) return;
549 startTest("findVirtual");
550 testFindVirtual(Example.class, void.class, "v0");
551 testFindVirtual(Example.class, void.class, "pkg_v0");
552 testFindVirtual(Example.class, void.class, "pri_v0");
553 testFindVirtual(Example.class, Object.class, "v1", Object.class);
554 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
555 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
556 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
557 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
558 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
559 // test dispatch
560 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
561 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
562 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
563 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
564 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
565 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
566 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
567 }
568
569 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
570 Class<?> rcvc = defc;
571 testFindVirtual(rcvc, defc, ret, name, params);
572 }
573 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
574 for (Object[] ac : accessCases(defc, name)) {
575 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
576 }
577 }
578 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
579 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
580 }
581 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
582 countTest(positive);
583 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800584 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700585 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700586 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700587 try {
jrose2cc9c832010-04-30 23:48:23 -0700588 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700589 target = lookup.in(defc).findVirtual(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800590 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700591 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800592 if (name.contains("bogus"))
593 assertTrue(noAccess instanceof NoSuchMethodException);
594 else
595 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700596 }
jrose2cc9c832010-04-30 23:48:23 -0700597 if (verbosity >= 3)
598 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700599 +(noAccess == null ? "" : " !! "+noAccess));
600 if (positive && noAccess != null) throw noAccess;
601 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
602 if (!positive) return; // negative test failed as expected
603 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800604 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700605 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700606 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700607 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
608 Object[] argsWithSelf = randomArgs(paramsWithSelf);
609 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
610 printCalled(target, name, argsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700611 target.invokeWithArguments(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700612 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700613 if (verbosity >= 1)
614 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700615 }
616
617 @Test
618 public void testFindSpecial() throws Throwable {
619 if (CAN_SKIP_WORKING) return;
620 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700621 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
622 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
623 // Do some negative testing:
jrosef15905c2011-02-11 01:26:32 -0800624 testFindSpecial(false, EXAMPLE, SubExample.class, Example.class, void.class, "bogus");
625 testFindSpecial(false, PRIVATE, SubExample.class, Example.class, void.class, "bogus");
jrose2cc9c832010-04-30 23:48:23 -0700626 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
627 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
628 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
629 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
jrose2cc9c832010-04-30 23:48:23 -0700630 }
jrose55220c32009-10-21 23:19:48 -0700631 }
632
jrose2cc9c832010-04-30 23:48:23 -0700633 void testFindSpecial(Class<?> specialCaller,
634 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
635 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
636 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
637 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
638 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700639 }
jrose2cc9c832010-04-30 23:48:23 -0700640 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
641 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700642 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800643 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700644 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700645 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700646 try {
jrose2cc9c832010-04-30 23:48:23 -0700647 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700648 if (verbosity >= 5) System.out.println(" lookup => "+lookup.in(specialCaller));
649 target = lookup.in(specialCaller).findSpecial(defc, name, type, specialCaller);
jrosef15905c2011-02-11 01:26:32 -0800650 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700651 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800652 if (name.contains("bogus"))
653 assertTrue(noAccess instanceof NoSuchMethodException);
654 else
655 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700656 }
jrose2cc9c832010-04-30 23:48:23 -0700657 if (verbosity >= 3)
658 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
659 +(target == null ? "" : target.type())
660 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700661 if (positive && noAccess != null) throw noAccess;
662 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
663 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700664 assertEquals(specialCaller, target.type().parameterType(0));
665 assertEquals(type, target.type().dropParameterTypes(0,1));
666 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800667 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700668 assertNameStringContains(target, name);
jrose2cc9c832010-04-30 23:48:23 -0700669 if (!DO_MORE_CALLS && lookup != PRIVATE && lookup != EXAMPLE) return;
jrose55220c32009-10-21 23:19:48 -0700670 Object[] args = randomArgs(paramsWithSelf);
671 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700672 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700673 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700674 }
675
676 @Test
677 public void testBind() throws Throwable {
678 if (CAN_SKIP_WORKING) return;
679 startTest("bind");
680 testBind(Example.class, void.class, "v0");
681 testBind(Example.class, void.class, "pkg_v0");
682 testBind(Example.class, void.class, "pri_v0");
683 testBind(Example.class, Object.class, "v1", Object.class);
684 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
685 testBind(Example.class, Object.class, "v2", Object.class, int.class);
686 testBind(Example.class, Object.class, "v2", int.class, Object.class);
687 testBind(Example.class, Object.class, "v2", int.class, int.class);
688 testBind(false, PRIVATE, Example.class, void.class, "bogus");
689 testBind(SubExample.class, void.class, "Sub/v0");
690 testBind(SubExample.class, void.class, "Sub/pkg_v0");
691 testBind(IntExample.Impl.class, void.class, "Int/v0");
692 }
693
694 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
695 for (Object[] ac : accessCases(defc, name)) {
696 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
697 }
698 }
699
700 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
701 countTest(positive);
702 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800703 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700704 Object receiver = randomArg(defc);
705 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700706 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700707 try {
jrose2cc9c832010-04-30 23:48:23 -0700708 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700709 target = lookup.in(defc).bind(receiver, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800710 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700711 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800712 if (name.contains("bogus"))
713 assertTrue(noAccess instanceof NoSuchMethodException);
714 else
715 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700716 }
jrose2cc9c832010-04-30 23:48:23 -0700717 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700718 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
719 +(noAccess == null ? "" : " !! "+noAccess));
720 if (positive && noAccess != null) throw noAccess;
721 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
722 if (!positive) return; // negative test failed as expected
723 assertEquals(type, target.type());
724 Object[] args = randomArgs(params);
725 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700726 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700727 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
728 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700729 if (verbosity >= 1)
730 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700731 }
732
733 @Test
734 public void testUnreflect() throws Throwable {
735 if (CAN_SKIP_WORKING) return;
736 startTest("unreflect");
737 testUnreflect(Example.class, true, void.class, "s0");
738 testUnreflect(Example.class, true, void.class, "pkg_s0");
739 testUnreflect(Example.class, true, void.class, "pri_s0");
740
741 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
742 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700743 testUnreflect(Example.class, true, Object.class, "s3", long.class);
744 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
745 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
746 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700747
748 testUnreflect(Example.class, false, void.class, "v0");
749 testUnreflect(Example.class, false, void.class, "pkg_v0");
750 testUnreflect(Example.class, false, void.class, "pri_v0");
751 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
752 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
753 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
754 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
755 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
756 }
757
758 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
759 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700760 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700761 }
762 }
jrose2cc9c832010-04-30 23:48:23 -0700763 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
764 for (Object[] ac : accessCases(defc, name)) {
765 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
766 }
767 }
768 void testUnreflectMaybeSpecial(Class<?> specialCaller,
769 boolean positive, Lookup lookup,
770 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700771 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800772 MethodType type = MethodType.methodType(ret, params);
jrosef15905c2011-02-11 01:26:32 -0800773 Method rmethod = defc.getDeclaredMethod(name, params);
jrose55220c32009-10-21 23:19:48 -0700774 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700775 Exception noAccess = null;
jrose2cc9c832010-04-30 23:48:23 -0700776 boolean isStatic = (rcvc == null);
777 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700778 try {
jrose2cc9c832010-04-30 23:48:23 -0700779 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
780 if (isSpecial)
jrose900bafd2010-10-30 21:08:23 -0700781 target = lookup.in(specialCaller).unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700782 else
jrose900bafd2010-10-30 21:08:23 -0700783 target = lookup.in(defc).unreflect(rmethod);
jrosef15905c2011-02-11 01:26:32 -0800784 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700785 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800786 if (name.contains("bogus"))
787 assertTrue(noAccess instanceof NoSuchMethodException);
788 else
789 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700790 }
jrose2cc9c832010-04-30 23:48:23 -0700791 if (verbosity >= 3)
792 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
793 +(!isSpecial ? "" : " specialCaller="+specialCaller)
794 +( isStatic ? "" : " receiver="+rcvc)
795 +" => "+target
796 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700797 if (positive && noAccess != null) throw noAccess;
798 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
799 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700800 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700801 Class<?>[] paramsMaybeWithSelf = params;
802 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700803 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700804 }
jrose10f3b682010-01-07 16:16:45 -0800805 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700806 if (isStatic) {
807 assertEquals(typeMaybeWithSelf, target.type());
808 } else {
jrose2cc9c832010-04-30 23:48:23 -0700809 if (isSpecial)
810 assertEquals(specialCaller, target.type().parameterType(0));
811 else
812 assertEquals(defc, target.type().parameterType(0));
813 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
814 }
jrose55220c32009-10-21 23:19:48 -0700815 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
816 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700817 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700818 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700819 if (verbosity >= 1)
820 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700821 }
822
jrose2cc9c832010-04-30 23:48:23 -0700823 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
824 for (Object[] ac : accessCases(defc, name, true)) {
825 Class<?> specialCaller = rcvc;
826 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
827 }
828 }
829
830 @Test
jrose55220c32009-10-21 23:19:48 -0700831 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700832 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700833 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700834 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
835 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
836 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
837 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
838 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
839 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
840 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700841 }
842
jrose10f3b682010-01-07 16:16:45 -0800843 public static class HasFields {
844 boolean fZ = false;
845 byte fB = (byte)'B';
846 short fS = (short)'S';
847 char fC = 'C';
848 int fI = 'I';
849 long fJ = 'J';
850 float fF = 'F';
851 double fD = 'D';
852 static boolean sZ = true;
853 static byte sB = 1+(byte)'B';
854 static short sS = 1+(short)'S';
855 static char sC = 1+'C';
856 static int sI = 1+'I';
857 static long sJ = 1+'J';
858 static float sF = 1+'F';
859 static double sD = 1+'D';
860
861 Object fL = 'L';
862 String fR = "R";
863 static Object sL = 'M';
864 static String sR = "S";
865
866 static final Object[][] CASES;
867 static {
868 ArrayList<Object[]> cases = new ArrayList<Object[]>();
869 Object types[][] = {
870 {'L',Object.class}, {'R',String.class},
871 {'I',int.class}, {'J',long.class},
872 {'F',float.class}, {'D',double.class},
873 {'Z',boolean.class}, {'B',byte.class},
874 {'S',short.class}, {'C',char.class},
875 };
876 HasFields fields = new HasFields();
877 for (Object[] t : types) {
878 for (int kind = 0; kind <= 1; kind++) {
879 boolean isStatic = (kind != 0);
880 char btc = (Character)t[0];
881 String name = (isStatic ? "s" : "f") + btc;
882 Class<?> type = (Class<?>) t[1];
883 Object value;
884 Field field;
jrose320b7692011-05-12 19:27:49 -0700885 try {
jrose10f3b682010-01-07 16:16:45 -0800886 field = HasFields.class.getDeclaredField(name);
887 } catch (Exception ex) {
888 throw new InternalError("no field HasFields."+name);
889 }
890 try {
891 value = field.get(fields);
892 } catch (Exception ex) {
893 throw new InternalError("cannot fetch field HasFields."+name);
894 }
895 if (type == float.class) {
896 float v = 'F';
897 if (isStatic) v++;
jrosef15905c2011-02-11 01:26:32 -0800898 assertTrue(value.equals(v));
jrose10f3b682010-01-07 16:16:45 -0800899 }
jrosef15905c2011-02-11 01:26:32 -0800900 assertTrue(name.equals(field.getName()));
901 assertTrue(type.equals(field.getType()));
902 assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
jrose10f3b682010-01-07 16:16:45 -0800903 cases.add(new Object[]{ field, value });
904 }
905 }
jrosef15905c2011-02-11 01:26:32 -0800906 cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
907 cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
jrose10f3b682010-01-07 16:16:45 -0800908 CASES = cases.toArray(new Object[0][]);
909 }
910 }
911
jrosef15905c2011-02-11 01:26:32 -0800912 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10;
jrosecf98d422010-06-08 23:08:56 -0700913 static boolean testModeMatches(int testMode, boolean isStatic) {
914 switch (testMode) {
jrosef15905c2011-02-11 01:26:32 -0800915 case TEST_FIND_STATIC: return isStatic;
jrosecf98d422010-06-08 23:08:56 -0700916 case TEST_FIND_FIELD: return !isStatic;
jrosef15905c2011-02-11 01:26:32 -0800917 case TEST_UNREFLECT: return true; // unreflect matches both
jrosecf98d422010-06-08 23:08:56 -0700918 }
jrosef15905c2011-02-11 01:26:32 -0800919 throw new InternalError("testMode="+testMode);
jrosecf98d422010-06-08 23:08:56 -0700920 }
921
jrose10f3b682010-01-07 16:16:45 -0800922 @Test
jrose55220c32009-10-21 23:19:48 -0700923 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700924 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700925 testGetter(TEST_UNREFLECT);
926 }
927 @Test
928 public void testFindGetter() throws Throwable {
929 startTest("findGetter");
930 testGetter(TEST_FIND_FIELD);
931 }
932 @Test
933 public void testFindStaticGetter() throws Throwable {
934 startTest("findStaticGetter");
jrosef15905c2011-02-11 01:26:32 -0800935 testGetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -0700936 }
937 public void testGetter(int testMode) throws Throwable {
938 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800939 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -0800940 boolean positive = (c[1] != Error.class);
941 testGetter(positive, lookup, c[0], c[1], testMode);
942 }
943 testGetter(true, lookup,
944 new Object[]{ true, System.class, "out", java.io.PrintStream.class },
945 System.out, testMode);
946 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
947 testGetter(false, lookup,
948 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
949 null, testMode);
jrose10f3b682010-01-07 16:16:45 -0800950 }
951 }
jrosef15905c2011-02-11 01:26:32 -0800952 public void testGetter(boolean positive, MethodHandles.Lookup lookup,
953 Object fieldRef, Object value, int testMode) throws Throwable {
954 testAccessor(positive, lookup, fieldRef, value, testMode);
955 }
956
957 public void testAccessor(boolean positive, MethodHandles.Lookup lookup,
958 Object fieldRef, Object value, int testMode0) throws Throwable {
959 boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
960 int testMode = testMode0 & ~TEST_SETTER;
961 boolean isStatic;
962 Class<?> fclass;
963 String fname;
964 Class<?> ftype;
965 Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
966 if (f != null) {
967 isStatic = Modifier.isStatic(f.getModifiers());
968 fclass = f.getDeclaringClass();
969 fname = f.getName();
970 ftype = f.getType();
971 } else {
972 Object[] scnt = (Object[]) fieldRef;
973 isStatic = (Boolean) scnt[0];
974 fclass = (Class<?>) scnt[1];
975 fname = (String) scnt[2];
976 ftype = (Class<?>) scnt[3];
977 try {
978 f = fclass.getDeclaredField(fname);
979 } catch (ReflectiveOperationException ex) {
980 f = null;
981 }
982 }
jrosecf98d422010-06-08 23:08:56 -0700983 if (!testModeMatches(testMode, isStatic)) return;
jrosef15905c2011-02-11 01:26:32 -0800984 if (f == null && testMode == TEST_UNREFLECT) return;
985 countTest(positive);
986 MethodType expType;
987 if (isGetter)
988 expType = MethodType.methodType(ftype, HasFields.class);
989 else
990 expType = MethodType.methodType(void.class, HasFields.class, ftype);
jrose10f3b682010-01-07 16:16:45 -0800991 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosef15905c2011-02-11 01:26:32 -0800992 Exception noAccess = null;
993 MethodHandle mh;
994 try {
995 switch (testMode0) {
996 case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
997 case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
998 case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
999 case TEST_SETTER|
1000 TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
1001 case TEST_SETTER|
1002 TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
1003 case TEST_SETTER|
1004 TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
1005 default:
1006 throw new InternalError("testMode="+testMode);
1007 }
1008 } catch (ReflectiveOperationException ex) {
1009 mh = null;
1010 noAccess = ex;
1011 if (fname.contains("bogus"))
1012 assertTrue(noAccess instanceof NoSuchFieldException);
1013 else
1014 assertTrue(noAccess instanceof IllegalAccessException);
1015 }
1016 if (verbosity >= 3)
1017 System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
1018 +" => "+mh
1019 +(noAccess == null ? "" : " !! "+noAccess));
1020 if (positive && noAccess != null) throw new RuntimeException(noAccess);
1021 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, mh != null);
1022 if (!positive) return; // negative test failed as expected
1023 assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
1024
1025
jrose10f3b682010-01-07 16:16:45 -08001026 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -07001027 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -08001028 HasFields fields = new HasFields();
1029 Object sawValue;
jrosef15905c2011-02-11 01:26:32 -08001030 Class<?> vtype = ftype;
1031 if (ftype != int.class) vtype = Object.class;
1032 if (isGetter) {
jrose9b82ad62011-05-26 17:37:36 -07001033 mh = mh.asType(mh.type().generic()
1034 .changeReturnType(vtype));
jrosef15905c2011-02-11 01:26:32 -08001035 } else {
1036 int last = mh.type().parameterCount() - 1;
jrose9b82ad62011-05-26 17:37:36 -07001037 mh = mh.asType(mh.type().generic()
1038 .changeReturnType(void.class)
1039 .changeParameterType(last, vtype));
jrose10f3b682010-01-07 16:16:45 -08001040 }
jrosef15905c2011-02-11 01:26:32 -08001041 if (f != null && f.getDeclaringClass() == HasFields.class) {
1042 assertEquals(f.get(fields), value); // clean to start with
1043 }
1044 if (isGetter) {
1045 Object expValue = value;
1046 for (int i = 0; i <= 1; i++) {
1047 if (isStatic) {
1048 if (ftype == int.class)
1049 sawValue = (int) mh.invokeExact(); // do these exactly
1050 else
1051 sawValue = mh.invokeExact();
1052 } else {
1053 if (ftype == int.class)
1054 sawValue = (int) mh.invokeExact((Object) fields);
1055 else
1056 sawValue = mh.invokeExact((Object) fields);
1057 }
1058 assertEquals(sawValue, expValue);
1059 if (f != null && f.getDeclaringClass() == HasFields.class
1060 && !Modifier.isFinal(f.getModifiers())) {
1061 Object random = randomArg(ftype);
1062 f.set(fields, random);
1063 expValue = random;
1064 } else {
1065 break;
1066 }
1067 }
1068 } else {
1069 for (int i = 0; i <= 1; i++) {
1070 Object putValue = randomArg(ftype);
1071 if (isStatic) {
1072 if (ftype == int.class)
1073 mh.invokeExact((int)putValue); // do these exactly
1074 else
1075 mh.invokeExact(putValue);
1076 } else {
1077 if (ftype == int.class)
1078 mh.invokeExact((Object) fields, (int)putValue);
1079 else
1080 mh.invokeExact((Object) fields, putValue);
1081 }
1082 if (f != null && f.getDeclaringClass() == HasFields.class) {
1083 assertEquals(f.get(fields), putValue);
1084 }
1085 }
1086 }
1087 if (f != null && f.getDeclaringClass() == HasFields.class) {
1088 f.set(fields, value); // put it back
1089 }
jrose55220c32009-10-21 23:19:48 -07001090 }
1091
jrose10f3b682010-01-07 16:16:45 -08001092
1093 @Test
jrose55220c32009-10-21 23:19:48 -07001094 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -07001095 startTest("unreflectSetter");
1096 testSetter(TEST_UNREFLECT);
1097 }
1098 @Test
1099 public void testFindSetter() throws Throwable {
1100 startTest("findSetter");
1101 testSetter(TEST_FIND_FIELD);
1102 }
1103 @Test
1104 public void testFindStaticSetter() throws Throwable {
1105 startTest("findStaticSetter");
jrosef15905c2011-02-11 01:26:32 -08001106 testSetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001107 }
1108 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001109 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
1110 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -08001111 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001112 boolean positive = (c[1] != Error.class);
1113 testSetter(positive, lookup, c[0], c[1], testMode);
1114 }
1115 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1116 testSetter(false, lookup,
1117 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1118 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001119 }
1120 }
jrosef15905c2011-02-11 01:26:32 -08001121 public void testSetter(boolean positive, MethodHandles.Lookup lookup,
1122 Object fieldRef, Object value, int testMode) throws Throwable {
1123 testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
jrose55220c32009-10-21 23:19:48 -07001124 }
1125
jrose10f3b682010-01-07 16:16:45 -08001126 @Test
jrose55220c32009-10-21 23:19:48 -07001127 public void testArrayElementGetter() throws Throwable {
1128 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001129 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001130 }
1131
jrose10f3b682010-01-07 16:16:45 -08001132 @Test
jrose55220c32009-10-21 23:19:48 -07001133 public void testArrayElementSetter() throws Throwable {
1134 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001135 testArrayElementGetterSetter(true);
1136 }
1137
1138 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
1139 testArrayElementGetterSetter(new Object[10], testSetter);
1140 testArrayElementGetterSetter(new String[10], testSetter);
1141 testArrayElementGetterSetter(new boolean[10], testSetter);
1142 testArrayElementGetterSetter(new byte[10], testSetter);
1143 testArrayElementGetterSetter(new char[10], testSetter);
1144 testArrayElementGetterSetter(new short[10], testSetter);
1145 testArrayElementGetterSetter(new int[10], testSetter);
1146 testArrayElementGetterSetter(new float[10], testSetter);
1147 testArrayElementGetterSetter(new long[10], testSetter);
1148 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -08001149 }
1150
1151 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
1152 countTest(true);
jrose2cc9c832010-04-30 23:48:23 -07001153 if (verbosity >= 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -08001154 Class<?> arrayType = array.getClass();
1155 Class<?> elemType = arrayType.getComponentType();
1156 MethodType expType = !testSetter
1157 ? MethodType.methodType(elemType, arrayType, int.class)
1158 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1159 MethodHandle mh = !testSetter
1160 ? MethodHandles.arrayElementGetter(arrayType)
1161 : MethodHandles.arrayElementSetter(arrayType);
1162 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001163 if (elemType != int.class && elemType != boolean.class) {
jrose320b7692011-05-12 19:27:49 -07001164 // FIXME: change Integer.class and (Integer) below to int.class and (int) below.
1165 MethodType gtype = mh.type().generic().changeParameterType(1, Integer.class);
1166 if (testSetter) gtype = gtype.changeReturnType(void.class);
jrose9b82ad62011-05-26 17:37:36 -07001167 mh = mh.asType(gtype);
jrose2cc9c832010-04-30 23:48:23 -07001168 }
jrose10f3b682010-01-07 16:16:45 -08001169 Object sawValue, expValue;
1170 List<Object> model = array2list(array);
1171 int length = Array.getLength(array);
1172 for (int i = 0; i < length; i++) {
1173 // update array element
1174 Object random = randomArg(elemType);
1175 model.set(i, random);
1176 if (testSetter) {
1177 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001178 mh.invokeExact((int[]) array, i, (int)random);
jrose2cc9c832010-04-30 23:48:23 -07001179 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001180 mh.invokeExact((boolean[]) array, i, (boolean)random);
jrose10f3b682010-01-07 16:16:45 -08001181 else
jrose320b7692011-05-12 19:27:49 -07001182 mh.invokeExact(array, (Integer)i, random);
jrose10f3b682010-01-07 16:16:45 -08001183 assertEquals(model, array2list(array));
1184 } else {
1185 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001186 }
1187 if (verbosity >= 5) {
1188 List<Object> array2list = array2list(array);
1189 System.out.println("a["+i+"]="+random+" => "+array2list);
1190 if (!array2list.equals(model))
1191 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001192 }
1193 // observe array element
1194 sawValue = Array.get(array, i);
1195 if (!testSetter) {
1196 expValue = sawValue;
1197 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001198 sawValue = (int) mh.invokeExact((int[]) array, i);
jrose2cc9c832010-04-30 23:48:23 -07001199 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001200 sawValue = (boolean) mh.invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -08001201 else
jrose320b7692011-05-12 19:27:49 -07001202 sawValue = mh.invokeExact(array, (Integer)i);
jrose10f3b682010-01-07 16:16:45 -08001203 assertEquals(sawValue, expValue);
1204 assertEquals(model, array2list(array));
1205 }
1206 }
1207 }
1208
1209 List<Object> array2list(Object array) {
1210 int length = Array.getLength(array);
1211 ArrayList<Object> model = new ArrayList<Object>(length);
1212 for (int i = 0; i < length; i++)
1213 model.add(Array.get(array, i));
1214 return model;
jrose55220c32009-10-21 23:19:48 -07001215 }
1216
1217 static class Callee {
1218 static Object id() { return called("id"); }
1219 static Object id(Object x) { return called("id", x); }
1220 static Object id(Object x, Object y) { return called("id", x, y); }
1221 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1222 static Object id(Object... vx) { return called("id", vx); }
1223 static MethodHandle ofType(int n) {
1224 return ofType(Object.class, n);
1225 }
1226 static MethodHandle ofType(Class<?> rtype, int n) {
1227 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001228 return ofType(MethodType.methodType(rtype, Object[].class));
1229 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001230 }
1231 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001232 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001233 }
1234 static MethodHandle ofType(MethodType type) {
1235 Class<?> rtype = type.returnType();
1236 String pfx = "";
1237 if (rtype != Object.class)
1238 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1239 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001240 try {
1241 return PRIVATE.findStatic(Callee.class, name, type);
1242 } catch (Exception ex) {
1243 throw new RuntimeException(ex);
1244 }
jrose55220c32009-10-21 23:19:48 -07001245 }
1246 }
1247
1248 @Test
1249 public void testConvertArguments() throws Throwable {
1250 if (CAN_SKIP_WORKING) return;
1251 startTest("convertArguments");
1252 testConvert(Callee.ofType(1), null, "id", int.class);
1253 testConvert(Callee.ofType(1), null, "id", String.class);
1254 testConvert(Callee.ofType(1), null, "id", Integer.class);
1255 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001256 testConvert(Callee.ofType(1), null, "id", char.class);
1257 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001258 }
1259
1260 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -07001261 testConvert(true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001262 }
1263
jrose9b82ad62011-05-26 17:37:36 -07001264 void testConvert(boolean positive,
jrose900bafd2010-10-30 21:08:23 -07001265 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001266 countTest(positive);
1267 MethodType idType = id.type();
1268 if (rtype == null) rtype = idType.returnType();
1269 for (int i = 0; i < params.length; i++) {
1270 if (params[i] == null) params[i] = idType.parameterType(i);
1271 }
1272 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001273 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001274 Object[] args = randomArgs(newType.parameterArray());
1275 Object[] convArgs = args.clone();
1276 for (int i = 0; i < args.length; i++) {
1277 Class<?> src = newType.parameterType(i);
1278 Class<?> dst = idType.parameterType(i);
1279 if (src != dst)
1280 convArgs[i] = castToWrapper(convArgs[i], dst);
1281 }
jrose900bafd2010-10-30 21:08:23 -07001282 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001283 {
1284 Class<?> dst = newType.returnType();
1285 Class<?> src = idType.returnType();
1286 if (src != dst)
1287 convResult = castToWrapper(convResult, dst);
1288 }
1289 MethodHandle target = null;
1290 RuntimeException error = null;
1291 try {
jrose9b82ad62011-05-26 17:37:36 -07001292 target = id.asType(newType);
jrose55220c32009-10-21 23:19:48 -07001293 } catch (RuntimeException ex) {
1294 error = ex;
1295 }
jrose2cc9c832010-04-30 23:48:23 -07001296 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001297 System.out.println("convert "+id+ " to "+newType+" => "+target
1298 +(error == null ? "" : " !! "+error));
1299 if (positive && error != null) throw error;
1300 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1301 if (!positive) return; // negative test failed as expected
1302 assertEquals(newType, target.type());
1303 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001304 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001305 assertCalled(name, convArgs);
1306 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001307 if (verbosity >= 1)
1308 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001309 }
1310
1311 @Test
jrosef108fc02011-02-11 01:26:24 -08001312 public void testVarargsCollector() throws Throwable {
1313 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1314 MethodType.methodType(Object.class, String.class, Object[].class));
1315 vac0 = vac0.bindTo("vac");
1316 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -07001317 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1318 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
jrosef108fc02011-02-11 01:26:24 -08001319 for (Class<?> at : new Class[] { Object.class, String.class, Integer.class }) {
jrose9b82ad62011-05-26 17:37:36 -07001320 testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1321 testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
jrosef108fc02011-02-11 01:26:24 -08001322 }
1323 }
1324
1325 @Test
jrose10f3b682010-01-07 16:16:45 -08001326 public void testPermuteArguments() throws Throwable {
1327 if (CAN_SKIP_WORKING) return;
1328 startTest("permuteArguments");
1329 testPermuteArguments(4, Integer.class, 2, String.class, 0);
jrose9b82ad62011-05-26 17:37:36 -07001330 testPermuteArguments(6, Integer.class, 0, null, 30);
1331 //testPermuteArguments(4, Integer.class, 2, long.class, 6); // FIXME Fail_7
jrose10f3b682010-01-07 16:16:45 -08001332 }
1333 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001334 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001335 System.out.println("permuteArguments "+max+"*"+type1.getName()
1336 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1337 +(dilution > 0 ? " with dilution "+dilution : ""));
1338 int t2pos = t2c == 0 ? 0 : 1;
1339 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1340 Class<?>[] types = new Class<?>[inargs];
1341 Arrays.fill(types, type1);
1342 if (t2c != 0) {
1343 // Fill in a middle range with type2:
1344 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1345 }
1346 Object[] args = randomArgs(types);
1347 int numcases = 1;
1348 for (int outargs = 0; outargs <= max; outargs++) {
1349 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
jrose10f3b682010-01-07 16:16:45 -08001350 int casStep = dilution + 1;
1351 // Avoid some common factors:
1352 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1353 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1354 casStep++;
jrose320b7692011-05-12 19:27:49 -07001355 testPermuteArguments(args, types, outargs, numcases, casStep);
jrose10f3b682010-01-07 16:16:45 -08001356 numcases *= inargs;
1357 if (dilution > 10 && outargs >= 4) {
jrose320b7692011-05-12 19:27:49 -07001358 int[] reorder = new int[outargs];
jrose10f3b682010-01-07 16:16:45 -08001359 // Do some special patterns, which we probably missed.
1360 // Replication of a single argument or argument pair.
1361 for (int i = 0; i < inargs; i++) {
1362 Arrays.fill(reorder, i);
1363 testPermuteArguments(args, types, reorder);
1364 for (int d = 1; d <= 2; d++) {
1365 if (i + d >= inargs) continue;
1366 for (int j = 1; j < outargs; j += 2)
1367 reorder[j] += 1;
1368 testPermuteArguments(args, types, reorder);
1369 testPermuteArguments(args, types, reverse(reorder));
1370 }
1371 }
1372 // Repetition of a sequence of 3 or more arguments.
1373 for (int i = 1; i < inargs; i++) {
1374 for (int len = 3; len <= inargs; len++) {
1375 for (int j = 0; j < outargs; j++)
1376 reorder[j] = (i + (j % len)) % inargs;
1377 testPermuteArguments(args, types, reorder);
1378 testPermuteArguments(args, types, reverse(reorder));
1379 }
1380 }
1381 }
1382 }
1383 }
1384 }
1385
jrose320b7692011-05-12 19:27:49 -07001386 public void testPermuteArguments(Object[] args, Class<?>[] types,
1387 int outargs, int numcases, int casStep) throws Throwable {
1388 int inargs = args.length;
1389 int[] reorder = new int[outargs];
1390 for (int cas = 0; cas < numcases; cas += casStep) {
1391 for (int i = 0, c = cas; i < outargs; i++) {
1392 reorder[i] = c % inargs;
1393 c /= inargs;
1394 }
1395 testPermuteArguments(args, types, reorder);
1396 }
1397 }
1398
jrose10f3b682010-01-07 16:16:45 -08001399 static int[] reverse(int[] reorder) {
1400 reorder = reorder.clone();
1401 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1402 int j = reorder.length - 1 - i;
1403 int tem = reorder[i];
1404 reorder[i] = reorder[j];
1405 reorder[j] = tem;
1406 }
1407 return reorder;
1408 }
1409
1410 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1411 countTest();
1412 if (args == null && types == null) {
1413 int max = 0;
1414 for (int j : reorder) {
1415 if (max < j) max = j;
1416 }
1417 args = randomArgs(max+1, Integer.class);
1418 }
1419 if (args == null) {
1420 args = randomArgs(types);
1421 }
1422 if (types == null) {
1423 types = new Class<?>[args.length];
1424 for (int i = 0; i < args.length; i++)
1425 types[i] = args[i].getClass();
1426 }
1427 int inargs = args.length, outargs = reorder.length;
jrosef15905c2011-02-11 01:26:32 -08001428 assertTrue(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001429 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001430 System.out.println("permuteArguments "+Arrays.toString(reorder));
1431 Object[] permArgs = new Object[outargs];
1432 Class<?>[] permTypes = new Class<?>[outargs];
1433 for (int i = 0; i < outargs; i++) {
1434 permArgs[i] = args[reorder[i]];
1435 permTypes[i] = types[reorder[i]];
1436 }
jrose2cc9c832010-04-30 23:48:23 -07001437 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001438 System.out.println("in args: "+Arrays.asList(args));
1439 System.out.println("out args: "+Arrays.asList(permArgs));
1440 System.out.println("in types: "+Arrays.asList(types));
1441 System.out.println("out types: "+Arrays.asList(permTypes));
1442 }
1443 MethodType inType = MethodType.methodType(Object.class, types);
1444 MethodType outType = MethodType.methodType(Object.class, permTypes);
jrose9b82ad62011-05-26 17:37:36 -07001445 MethodHandle target = varargsList(outargs).asType(outType);
jrose10f3b682010-01-07 16:16:45 -08001446 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose9b82ad62011-05-26 17:37:36 -07001447 if (verbosity >= 5) System.out.println("newTarget = "+newTarget);
jrose900bafd2010-10-30 21:08:23 -07001448 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001449 Object expected = Arrays.asList(permArgs);
jrose320b7692011-05-12 19:27:49 -07001450 if (!expected.equals(result)) {
1451 System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
1452 System.out.println("in args: "+Arrays.asList(args));
1453 System.out.println("out args: "+expected);
1454 System.out.println("bad args: "+result);
1455 }
jrose10f3b682010-01-07 16:16:45 -08001456 assertEquals(expected, result);
1457 }
1458
1459
1460 @Test
1461 public void testSpreadArguments() throws Throwable {
1462 if (CAN_SKIP_WORKING) return;
1463 startTest("spreadArguments");
1464 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001465 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001466 System.out.println("spreadArguments "+argType);
jrose2cc9c832010-04-30 23:48:23 -07001467 // FIXME: enable _adapter_spread_args and fix Fail_2
jrose10f3b682010-01-07 16:16:45 -08001468 for (int nargs = 0; nargs < 10; nargs++) {
1469 if (argType == int.class && nargs >= 6) continue; // FIXME Fail_1
1470 for (int pos = 0; pos < nargs; pos++) {
1471 if (argType == int.class && pos > 0) continue; // FIXME Fail_3
jrose2cc9c832010-04-30 23:48:23 -07001472 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001473 }
1474 }
1475 }
1476 }
1477 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1478 countTest();
jrose320b7692011-05-12 19:27:49 -07001479 Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
1480 MethodHandle target2 = varargsArray(arrayType, nargs);
1481 MethodHandle target = target2.asType(target2.type().generic());
jrose2cc9c832010-04-30 23:48:23 -07001482 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001483 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1484 Object[] args = randomArgs(target2.type().parameterArray());
1485 // make sure the target does what we think it does:
jrose320b7692011-05-12 19:27:49 -07001486 if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
1487 Object[] check = (Object[]) (Object) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001488 assertArrayEquals(args, check);
1489 switch (nargs) {
1490 case 0:
jrose320b7692011-05-12 19:27:49 -07001491 check = (Object[]) (Object) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001492 assertArrayEquals(args, check);
1493 break;
1494 case 1:
jrose320b7692011-05-12 19:27:49 -07001495 check = (Object[]) (Object) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001496 assertArrayEquals(args, check);
1497 break;
1498 case 2:
jrose320b7692011-05-12 19:27:49 -07001499 check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001500 assertArrayEquals(args, check);
1501 break;
1502 }
1503 }
1504 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1505 { // modify newParams in place
1506 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
jrose320b7692011-05-12 19:27:49 -07001507 spreadParams.clear(); spreadParams.add(arrayType);
jrose10f3b682010-01-07 16:16:45 -08001508 }
jrose320b7692011-05-12 19:27:49 -07001509 MethodType newType = MethodType.methodType(arrayType, newParams);
1510 MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
1511 assert(result.type() == newType) : Arrays.asList(result, newType);
1512 result = result.asType(newType.generic());
1513 Object returnValue;
jrose10f3b682010-01-07 16:16:45 -08001514 if (pos == 0) {
jrose320b7692011-05-12 19:27:49 -07001515 Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1516 returnValue = result.invokeExact(args2);
jrose10f3b682010-01-07 16:16:45 -08001517 } else {
1518 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
jrose320b7692011-05-12 19:27:49 -07001519 args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1520 returnValue = result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001521 }
jrose320b7692011-05-12 19:27:49 -07001522 String argstr = Arrays.toString(args);
1523 if (!argType.isPrimitive()) {
1524 Object[] rv = (Object[]) returnValue;
1525 String rvs = Arrays.toString(rv);
1526 if (!Arrays.equals(args, rv)) {
1527 System.out.println("method: "+result);
1528 System.out.println("expected: "+argstr);
1529 System.out.println("returned: "+rvs);
1530 assertArrayEquals(args, rv);
1531 }
1532 } else if (argType == int.class) {
1533 String rvs = Arrays.toString((int[]) returnValue);
1534 if (!argstr.equals(rvs)) {
1535 System.out.println("method: "+result);
1536 System.out.println("expected: "+argstr);
1537 System.out.println("returned: "+rvs);
1538 assertEquals(argstr, rvs);
1539 }
1540 } else if (argType == long.class) {
1541 String rvs = Arrays.toString((long[]) returnValue);
1542 if (!argstr.equals(rvs)) {
1543 System.out.println("method: "+result);
1544 System.out.println("expected: "+argstr);
1545 System.out.println("returned: "+rvs);
1546 assertEquals(argstr, rvs);
1547 }
1548 } else {
1549 // cannot test...
1550 }
jrose10f3b682010-01-07 16:16:45 -08001551 }
1552
1553 @Test
1554 public void testCollectArguments() throws Throwable {
1555 if (CAN_SKIP_WORKING) return;
1556 startTest("collectArguments");
1557 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001558 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001559 System.out.println("collectArguments "+argType);
1560 for (int nargs = 0; nargs < 10; nargs++) {
1561 for (int pos = 0; pos < nargs; pos++) {
1562 if (argType == int.class) continue; // FIXME Fail_4
1563 testCollectArguments(argType, pos, nargs);
1564 }
1565 }
1566 }
1567 }
1568 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1569 countTest();
1570 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001571 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001572 fake = changeArgTypes(fake, argType);
1573 MethodType newType = fake.type();
1574 Object[] args = randomArgs(newType.parameterArray());
1575 // here is what should happen:
1576 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1577 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1578 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001579 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001580 target = changeArgTypes(target, 0, pos, argType);
1581 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001582 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001583 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001584 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001585 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001586// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1587// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1588// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1589 assertArrayEquals(collectedArgs, returnValue);
1590 }
1591
1592 @Test
jrose55220c32009-10-21 23:19:48 -07001593 public void testInsertArguments() throws Throwable {
1594 if (CAN_SKIP_WORKING) return;
1595 startTest("insertArguments");
1596 for (int nargs = 0; nargs <= 4; nargs++) {
1597 for (int ins = 0; ins <= 4; ins++) {
1598 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
1599 for (int pos = 0; pos <= nargs; pos++) {
1600 testInsertArguments(nargs, pos, ins);
1601 }
1602 }
1603 }
1604 }
1605
1606 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001607 countTest();
jroseadc650a2011-02-11 01:26:28 -08001608 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001609 Object[] args = randomArgs(target.type().parameterArray());
1610 List<Object> resList = Arrays.asList(args);
1611 List<Object> argsToPass = new ArrayList<Object>(resList);
1612 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001613 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001614 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001615 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1616 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001617 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001618 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001619 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001620 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001621 System.out.println("result: "+res2List);
1622 //if (!resList.equals(res2List))
1623 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1624 assertEquals(resList, res2List);
1625 }
1626
jrose10f3b682010-01-07 16:16:45 -08001627 @Test
jroseadc650a2011-02-11 01:26:28 -08001628 public void testFilterReturnValue() throws Throwable {
1629 if (CAN_SKIP_WORKING) return;
1630 startTest("filterReturnValue");
1631 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1632 assertTrue(List.class.isAssignableFrom(classOfVCList));
1633 for (int nargs = 0; nargs <= 3; nargs++) {
1634 for (Class<?> rtype : new Class[] { Object.class,
1635 List.class,
1636 int.class,
1637 //byte.class, //FIXME: add this
1638 //long.class, //FIXME: add this
1639 CharSequence.class,
1640 String.class }) {
1641 testFilterReturnValue(nargs, rtype);
1642 }
1643 }
1644 }
1645
1646 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1647 countTest();
1648 MethodHandle target = varargsList(nargs, rtype);
1649 MethodHandle filter;
1650 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1651 filter = varargsList(1); // add another layer of list-ness
1652 else
1653 filter = MethodHandles.identity(rtype);
1654 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1655 Object[] argsToPass = randomArgs(nargs, Object.class);
1656 if (verbosity >= 3)
1657 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1658 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1659 if (verbosity >= 4)
1660 System.out.println("filtered target: "+target2);
1661 // Simulate expected effect of filter on return value:
1662 Object unfiltered = target.invokeWithArguments(argsToPass);
1663 Object expected = filter.invokeWithArguments(unfiltered);
1664 if (verbosity >= 4)
1665 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1666 if (verbosity >= 4)
1667 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1668 Object result = target2.invokeWithArguments(argsToPass);
1669 if (verbosity >= 3)
1670 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1671 if (!expected.equals(result))
1672 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1673 assertEquals(expected, result);
1674 }
1675
1676 @Test
jrose10f3b682010-01-07 16:16:45 -08001677 public void testFilterArguments() throws Throwable {
1678 if (CAN_SKIP_WORKING) return;
1679 startTest("filterArguments");
1680 for (int nargs = 1; nargs <= 6; nargs++) {
1681 for (int pos = 0; pos < nargs; pos++) {
1682 testFilterArguments(nargs, pos);
1683 }
1684 }
1685 }
1686
1687 void testFilterArguments(int nargs, int pos) throws Throwable {
1688 countTest();
jroseadc650a2011-02-11 01:26:28 -08001689 MethodHandle target = varargsList(nargs);
1690 MethodHandle filter = varargsList(1);
jrose9b82ad62011-05-26 17:37:36 -07001691 filter = filter.asType(filter.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001692 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001693 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001694 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001695 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001696 // Simulate expected effect of filter on arglist:
1697 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001698 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001699 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001700 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001701 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001702 System.out.println("result: "+result);
1703 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001704 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001705 assertEquals(expected, result);
1706 }
1707
1708 @Test
1709 public void testFoldArguments() throws Throwable {
1710 if (CAN_SKIP_WORKING) return;
1711 startTest("foldArguments");
1712 for (int nargs = 0; nargs <= 4; nargs++) {
1713 for (int fold = 0; fold <= nargs; fold++) {
1714 for (int pos = 0; pos <= nargs; pos++) {
1715 testFoldArguments(nargs, pos, fold);
1716 }
1717 }
1718 }
1719 }
1720
1721 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1722 if (pos != 0) return; // can fold only at pos=0 for now
1723 countTest();
jroseadc650a2011-02-11 01:26:28 -08001724 MethodHandle target = varargsList(1 + nargs);
1725 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08001726 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001727 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001728 System.out.println("fold "+target+" with "+combine);
1729 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1730 // Simulate expected effect of combiner on arglist:
1731 List<Object> expected = new ArrayList<Object>(argsToPass);
1732 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001733 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001734 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07001735 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08001736 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07001737 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001738 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001739 System.out.println("result: "+result);
1740 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001741 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001742 assertEquals(expected, result);
1743 }
1744
1745 @Test
1746 public void testDropArguments() throws Throwable {
1747 if (CAN_SKIP_WORKING) return;
1748 startTest("dropArguments");
1749 for (int nargs = 0; nargs <= 4; nargs++) {
1750 for (int drop = 1; drop <= 4; drop++) {
1751 for (int pos = 0; pos <= nargs; pos++) {
1752 testDropArguments(nargs, pos, drop);
1753 }
1754 }
1755 }
1756 }
1757
1758 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1759 countTest();
jroseadc650a2011-02-11 01:26:28 -08001760 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001761 Object[] args = randomArgs(target.type().parameterArray());
1762 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1763 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1764 List<Object> resList = Arrays.asList(args);
1765 List<Object> argsToDrop = new ArrayList<Object>(resList);
1766 for (int i = drop; i > 0; i--) {
1767 argsToDrop.add(pos, "blort#"+i);
1768 }
jrose900bafd2010-10-30 21:08:23 -07001769 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08001770 Object res2List = Arrays.asList((Object[])res2);
1771 //if (!resList.equals(res2List))
1772 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1773 assertEquals(resList, res2List);
1774 }
1775
1776 @Test
1777 public void testInvokers() throws Throwable {
1778 if (CAN_SKIP_WORKING) return;
1779 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1780 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1781 Set<MethodType> done = new HashSet<MethodType>();
1782 for (int i = 0; i <= 6; i++) {
1783 MethodType gtype = MethodType.genericMethodType(i);
1784 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1785 for (int j = -1; j < i; j++) {
1786 MethodType type = gtype;
1787 if (j < 0)
1788 type = type.changeReturnType(argType);
1789 else if (argType == void.class)
1790 continue;
1791 else
1792 type = type.changeParameterType(j, argType);
1793 if (argType.isPrimitive() && j != i-1) continue; // FIXME Fail_5
1794 if (done.add(type))
1795 testInvokers(type);
1796 MethodType vtype = type.changeReturnType(void.class);
1797 if (done.add(vtype))
1798 testInvokers(vtype);
1799 }
1800 }
1801 }
1802 }
1803
1804 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001805 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001806 System.out.println("test invokers for "+type);
1807 int nargs = type.parameterCount();
1808 boolean testRetCode = type.returnType() != void.class;
1809 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1810 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08001811 assertTrue(target.isVarargsCollector());
1812 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08001813 Object[] args = randomArgs(type.parameterArray());
1814 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1815 targetPlusArgs.add(0, target);
1816 int code = (Integer) invokee(args);
1817 Object log = logEntry("invokee", args);
1818 assertEquals(log.hashCode(), code);
1819 assertCalled("invokee", args);
1820 MethodHandle inv;
1821 Object result;
1822 // exact invoker
1823 countTest();
1824 calledLog.clear();
1825 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07001826 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001827 if (testRetCode) assertEquals(code, result);
1828 assertCalled("invokee", args);
1829 // generic invoker
1830 countTest();
jrose79e0a6c2011-05-12 19:27:33 -07001831 inv = MethodHandles.invoker(type);
jrose9b82ad62011-05-26 17:37:36 -07001832 if (nargs <= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001833 calledLog.clear();
1834 switch (nargs) {
1835 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001836 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001837 break;
1838 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001839 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001840 break;
1841 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001842 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001843 break;
1844 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001845 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001846 break;
1847 }
1848 if (testRetCode) assertEquals(code, result);
1849 assertCalled("invokee", args);
1850 }
1851 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001852 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001853 if (testRetCode) assertEquals(code, result);
1854 assertCalled("invokee", args);
1855 // varargs invoker #0
1856 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001857 inv = MethodHandles.spreadInvoker(type, 0);
jrose9b82ad62011-05-26 17:37:36 -07001858 if (type.returnType() == Object.class) {
1859 result = inv.invokeExact(target, args);
1860 } else if (type.returnType() == void.class) {
1861 result = null; inv.invokeExact(target, args);
1862 } else {
1863 result = inv.invokeWithArguments(target, (Object) args);
1864 }
jrose10f3b682010-01-07 16:16:45 -08001865 if (testRetCode) assertEquals(code, result);
1866 assertCalled("invokee", args);
jrose9b82ad62011-05-26 17:37:36 -07001867 if (nargs >= 1 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001868 // varargs invoker #1
1869 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001870 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001871 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001872 if (testRetCode) assertEquals(code, result);
1873 assertCalled("invokee", args);
1874 }
jrose9b82ad62011-05-26 17:37:36 -07001875 if (nargs >= 2 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001876 // varargs invoker #2
1877 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001878 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001879 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001880 if (testRetCode) assertEquals(code, result);
1881 assertCalled("invokee", args);
1882 }
jrose9b82ad62011-05-26 17:37:36 -07001883 if (nargs >= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08001884 // varargs invoker #3
1885 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001886 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001887 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001888 if (testRetCode) assertEquals(code, result);
1889 assertCalled("invokee", args);
1890 }
1891 for (int k = 0; k <= nargs; k++) {
1892 // varargs invoker #0..N
1893 countTest();
1894 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001895 inv = MethodHandles.spreadInvoker(type, k);
jrose9b82ad62011-05-26 17:37:36 -07001896 MethodType expType = (type.dropParameterTypes(k, nargs)
1897 .appendParameterTypes(Object[].class)
1898 .insertParameterTypes(0, MethodHandle.class));
1899 assertEquals(expType, inv.type());
jrose10f3b682010-01-07 16:16:45 -08001900 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1901 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1902 Object[] tail = tailList.toArray();
1903 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07001904 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08001905 if (testRetCode) assertEquals(code, result);
1906 assertCalled("invokee", args);
1907 }
jrose900bafd2010-10-30 21:08:23 -07001908
jrose10f3b682010-01-07 16:16:45 -08001909 // dynamic invoker
1910 countTest();
jroseb90d2e72010-12-16 15:59:27 -08001911 CallSite site = new MutableCallSite(type);
1912 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07001913
1914 // see if we get the result of the original target:
1915 try {
1916 result = inv.invokeWithArguments(args);
1917 assertTrue("should not reach here", false);
1918 } catch (IllegalStateException ex) {
1919 String msg = ex.getMessage();
1920 assertTrue(msg, msg.contains("site"));
1921 }
1922
1923 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08001924 site.setTarget(target);
1925 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001926 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001927 if (testRetCode) assertEquals(code, result);
1928 assertCalled("invokee", args);
1929 }
1930
1931 static Object invokee(Object... args) {
1932 return called("invokee", args).hashCode();
1933 }
1934
jrose55220c32009-10-21 23:19:48 -07001935 private static final String MISSING_ARG = "missingArg";
1936 static Object targetIfEquals() {
1937 return called("targetIfEquals");
1938 }
1939 static Object fallbackIfNotEquals() {
1940 return called("fallbackIfNotEquals");
1941 }
1942 static Object targetIfEquals(Object x) {
1943 assertEquals(x, MISSING_ARG);
1944 return called("targetIfEquals", x);
1945 }
1946 static Object fallbackIfNotEquals(Object x) {
1947 assertFalse(x.toString(), x.equals(MISSING_ARG));
1948 return called("fallbackIfNotEquals", x);
1949 }
1950 static Object targetIfEquals(Object x, Object y) {
1951 assertEquals(x, y);
1952 return called("targetIfEquals", x, y);
1953 }
1954 static Object fallbackIfNotEquals(Object x, Object y) {
1955 assertFalse(x.toString(), x.equals(y));
1956 return called("fallbackIfNotEquals", x, y);
1957 }
1958 static Object targetIfEquals(Object x, Object y, Object z) {
1959 assertEquals(x, y);
1960 return called("targetIfEquals", x, y, z);
1961 }
1962 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
1963 assertFalse(x.toString(), x.equals(y));
1964 return called("fallbackIfNotEquals", x, y, z);
1965 }
1966
jrose10f3b682010-01-07 16:16:45 -08001967 @Test
1968 public void testGuardWithTest() throws Throwable {
1969 if (CAN_SKIP_WORKING) return;
1970 startTest("guardWithTest");
1971 for (int nargs = 0; nargs <= 3; nargs++) {
1972 if (nargs != 2) continue; // FIXME: test more later
1973 testGuardWithTest(nargs, Object.class);
1974 testGuardWithTest(nargs, String.class);
1975 }
1976 }
1977 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
1978 countTest();
1979 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
1980 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs));
1981 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs));
1982 while (test.type().parameterCount() < nargs)
1983 test = MethodHandles.dropArguments(test, test.type().parameterCount()-1, Object.class);
1984 while (test.type().parameterCount() > nargs)
1985 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
1986 if (argClass != Object.class) {
1987 test = changeArgTypes(test, argClass);
1988 target = changeArgTypes(target, argClass);
1989 fallback = changeArgTypes(fallback, argClass);
1990 }
1991 MethodHandle mh = MethodHandles.guardWithTest(test, target, fallback);
1992 assertEquals(target.type(), mh.type());
1993 Object[][] argLists = {
1994 { },
1995 { "foo" }, { MISSING_ARG },
1996 { "foo", "foo" }, { "foo", "bar" },
1997 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
1998 };
1999 for (Object[] argList : argLists) {
2000 if (argList.length != nargs) continue;
2001 boolean equals;
2002 switch (nargs) {
2003 case 0: equals = true; break;
2004 case 1: equals = MISSING_ARG.equals(argList[0]); break;
2005 default: equals = argList[0].equals(argList[1]); break;
2006 }
2007 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07002008 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002009 System.out.println(logEntry(willCall, argList));
jrose900bafd2010-10-30 21:08:23 -07002010 Object result = mh.invokeWithArguments(argList);
jrose10f3b682010-01-07 16:16:45 -08002011 assertCalled(willCall, argList);
2012 }
2013 }
2014
2015 @Test
2016 public void testCatchException() throws Throwable {
2017 if (CAN_SKIP_WORKING) return;
2018 startTest("catchException");
2019 for (int nargs = 2; nargs <= 6; nargs++) {
2020 for (int ti = 0; ti <= 1; ti++) {
2021 boolean throwIt = (ti != 0);
2022 testCatchException(int.class, new ClassCastException("testing"), throwIt, nargs);
2023 testCatchException(void.class, new java.io.IOException("testing"), throwIt, nargs);
2024 testCatchException(String.class, new LinkageError("testing"), throwIt, nargs);
2025 }
2026 }
2027 }
2028
2029 private static <T extends Throwable>
2030 Object throwOrReturn(Object normal, T exception) throws T {
2031 if (exception != null) throw exception;
2032 return normal;
2033 }
2034
2035 void testCatchException(Class<?> returnType, Throwable thrown, boolean throwIt, int nargs) throws Throwable {
2036 countTest();
jrose2cc9c832010-04-30 23:48:23 -07002037 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002038 System.out.println("catchException rt="+returnType+" throw="+throwIt+" nargs="+nargs);
2039 Class<? extends Throwable> exType = thrown.getClass();
2040 MethodHandle throwOrReturn
2041 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2042 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb90d2e72010-12-16 15:59:27 -08002043 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jrose10f3b682010-01-07 16:16:45 -08002044 while (thrower.type().parameterCount() < nargs)
2045 thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
jroseadc650a2011-02-11 01:26:28 -08002046 MethodHandle catcher = varargsList(1+nargs).asType(MethodType.genericMethodType(1+nargs));
jrose10f3b682010-01-07 16:16:45 -08002047 MethodHandle target = MethodHandles.catchException(thrower,
jroseb90d2e72010-12-16 15:59:27 -08002048 thrown.getClass(), catcher);
jrose10f3b682010-01-07 16:16:45 -08002049 assertEquals(thrower.type(), target.type());
2050 //System.out.println("catching with "+target+" : "+throwOrReturn);
2051 Object[] args = randomArgs(nargs, Object.class);
2052 args[1] = (throwIt ? thrown : null);
jrose900bafd2010-10-30 21:08:23 -07002053 Object returned = target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08002054 //System.out.println("return from "+target+" : "+returned);
2055 if (!throwIt) {
2056 assertSame(args[0], returned);
2057 } else {
2058 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
2059 catchArgs.add(0, thrown);
2060 assertEquals(catchArgs, returned);
2061 }
2062 }
2063
2064 @Test
2065 public void testThrowException() throws Throwable {
2066 if (CAN_SKIP_WORKING) return;
2067 startTest("throwException");
2068 testThrowException(int.class, new ClassCastException("testing"));
2069 testThrowException(void.class, new java.io.IOException("testing"));
2070 testThrowException(String.class, new LinkageError("testing"));
2071 }
2072
2073 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2074 countTest();
2075 Class<? extends Throwable> exType = thrown.getClass();
2076 MethodHandle target = MethodHandles.throwException(returnType, exType);
2077 //System.out.println("throwing with "+target+" : "+thrown);
2078 MethodType expectedType = MethodType.methodType(returnType, exType);
2079 assertEquals(expectedType, target.type());
jrose9b82ad62011-05-26 17:37:36 -07002080 target = target.asType(target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08002081 Throwable caught = null;
2082 try {
jrose2cc9c832010-04-30 23:48:23 -07002083 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08002084 fail("got "+res+" instead of throwing "+thrown);
2085 } catch (Throwable ex) {
2086 if (ex != thrown) {
2087 if (ex instanceof Error) throw (Error)ex;
2088 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2089 }
2090 caught = ex;
2091 }
2092 assertSame(thrown, caught);
2093 }
2094
2095 @Test
2096 public void testCastFailure() throws Throwable {
2097 if (CAN_SKIP_WORKING) return;
2098 startTest("testCastFailure");
2099 testCastFailure("cast/argument", 11000);
2100 testCastFailure("unbox/argument", 11000);
2101 testCastFailure("cast/return", 11000);
2102 testCastFailure("unbox/return", 11000);
2103 }
2104
jrose900bafd2010-10-30 21:08:23 -07002105 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07002106 public MethodHandle asMethodHandle() {
2107 return VALUE.bindTo(this);
2108 }
jrose10f3b682010-01-07 16:16:45 -08002109 Object value(Object x) {
2110 trace("value", x);
2111 if (boo != null) return boo;
2112 return x;
2113 }
2114 Object boo;
2115 void boo(Object x) { boo = x; }
2116
2117 static void trace(String x, Object y) {
2118 if (verbosity > 8) System.out.println(x+"="+y);
2119 }
2120 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2121 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2122 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07002123 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
2124 static {
2125 try {
2126 VALUE = PRIVATE.findVirtual(
2127 Surprise.class, "value",
2128 MethodType.methodType(Object.class, Object.class));
2129 REF_IDENTITY = PRIVATE.findStatic(
2130 Surprise.class, "refIdentity",
2131 MethodType.methodType(Object.class, Object.class));
2132 BOX_IDENTITY = PRIVATE.findStatic(
2133 Surprise.class, "boxIdentity",
2134 MethodType.methodType(Integer.class, Integer.class));
2135 INT_IDENTITY = PRIVATE.findStatic(
2136 Surprise.class, "intIdentity",
2137 MethodType.methodType(int.class, int.class));
2138 } catch (Exception ex) {
2139 throw new RuntimeException(ex);
2140 }
2141 }
jrose10f3b682010-01-07 16:16:45 -08002142 }
2143
2144 void testCastFailure(String mode, int okCount) throws Throwable {
2145 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07002146 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002147 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002148 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002149 if (mode.endsWith("/return")) {
2150 if (mode.equals("unbox/return")) {
2151 // fail on return to ((Integer)surprise).intValue
jrose9b82ad62011-05-26 17:37:36 -07002152 surprise = surprise.asType(MethodType.methodType(int.class, Object.class));
2153 identity = identity.asType(MethodType.methodType(int.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002154 } else if (mode.equals("cast/return")) {
2155 // fail on return to (Integer)surprise
jrose9b82ad62011-05-26 17:37:36 -07002156 surprise = surprise.asType(MethodType.methodType(Integer.class, Object.class));
2157 identity = identity.asType(MethodType.methodType(Integer.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002158 }
2159 } else if (mode.endsWith("/argument")) {
2160 MethodHandle callee = null;
2161 if (mode.equals("unbox/argument")) {
2162 // fail on handing surprise to int argument
2163 callee = Surprise.INT_IDENTITY;
2164 } else if (mode.equals("cast/argument")) {
2165 // fail on handing surprise to Integer argument
2166 callee = Surprise.BOX_IDENTITY;
2167 }
2168 if (callee != null) {
jrose9b82ad62011-05-26 17:37:36 -07002169 callee = callee.asType(MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002170 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2171 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002172 }
2173 }
jrosea1ebbe62010-09-08 18:40:23 -07002174 assertNotSame(mode, surprise, surprise0);
jrose9b82ad62011-05-26 17:37:36 -07002175 identity = identity.asType(MethodType.genericMethodType(1));
2176 surprise = surprise.asType(MethodType.genericMethodType(1));
jrose10f3b682010-01-07 16:16:45 -08002177 Object x = 42;
2178 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002179 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002180 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002181 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002182 assertEquals(x, z);
2183 }
2184 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002185 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002186 assertEquals(x, y);
2187 try {
jrose2cc9c832010-04-30 23:48:23 -07002188 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002189 System.out.println("Failed to throw; got z="+z);
2190 assertTrue(false);
jrose320b7692011-05-12 19:27:49 -07002191 } catch (ClassCastException ex) {
jrose10f3b682010-01-07 16:16:45 -08002192 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002193 System.out.println("caught "+ex);
2194 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08002195 ex.printStackTrace();
jrose320b7692011-05-12 19:27:49 -07002196 assertTrue(true); // all is well
jrose10f3b682010-01-07 16:16:45 -08002197 }
2198 }
2199
jrose45b7a332010-05-03 23:32:47 -07002200 static Example userMethod(Object o, String s, int i) {
2201 called("userMethod", o, s, i);
2202 return null;
2203 }
2204
2205 @Test
2206 public void testUserClassInSignature() throws Throwable {
2207 if (CAN_SKIP_WORKING) return;
2208 startTest("testUserClassInSignature");
2209 Lookup lookup = MethodHandles.lookup();
2210 String name; MethodType mt; MethodHandle mh;
2211 Object[] args;
2212
2213 // Try a static method.
2214 name = "userMethod";
2215 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2216 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2217 assertEquals(mt, mh.type());
2218 assertEquals(Example.class, mh.type().returnType());
2219 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002220 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002221 assertCalled(name, args);
2222
2223 // Try a virtual method.
2224 name = "v2";
2225 mt = MethodType.methodType(Object.class, Object.class, int.class);
2226 mh = lookup.findVirtual(Example.class, name, mt);
2227 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2228 assertTrue(mh.type().parameterList().contains(Example.class));
2229 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002230 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002231 assertCalled(name, args);
2232 }
jrosebe2db602010-09-08 18:40:34 -07002233
2234 static void runForRunnable() {
2235 called("runForRunnable");
2236 }
jroseaf751942011-06-14 22:47:12 -07002237 public interface Fooable {
jrosebe2db602010-09-08 18:40:34 -07002238 Object foo(Fooable x, Object y);
2239 // this is for randomArg:
2240 public class Impl implements Fooable {
2241 public Object foo(Fooable x, Object y) {
2242 throw new RuntimeException("do not call");
2243 }
2244 final String name;
2245 public Impl() { name = "Fooable#"+nextArg(); }
2246 @Override public String toString() { return name; }
2247 }
2248 }
2249 static Object fooForFooable(Fooable x, Object y) {
2250 return called("fooForFooable", x, y);
2251 }
jroseaf751942011-06-14 22:47:12 -07002252 public static class MyCheckedException extends Exception {
jrosebe2db602010-09-08 18:40:34 -07002253 }
jroseaf751942011-06-14 22:47:12 -07002254 public interface WillThrow {
jrosebe2db602010-09-08 18:40:34 -07002255 void willThrow() throws MyCheckedException;
2256 }
2257
2258 @Test
2259 public void testAsInstance() throws Throwable {
2260 if (CAN_SKIP_WORKING) return;
2261 Lookup lookup = MethodHandles.lookup();
2262 {
2263 MethodType mt = MethodType.methodType(void.class);
2264 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
jrose9b82ad62011-05-26 17:37:36 -07002265 Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002266 proxy.run();
2267 assertCalled("runForRunnable");
2268 }
2269 {
2270 MethodType mt = MethodType.methodType(Object.class, Fooable.class, Object.class);
2271 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable", mt);
jrose9b82ad62011-05-26 17:37:36 -07002272 Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002273 Object[] args = randomArgs(mt.parameterArray());
2274 Object result = proxy.foo((Fooable) args[0], args[1]);
2275 assertCalled("fooForFooable", args);
2276 assertEquals(result, logEntry("fooForFooable", args));
2277 }
2278 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2279 new InternalError("ok"),
2280 new Throwable("fail"),
2281 new Exception("fail"),
2282 new MyCheckedException()
2283 }) {
2284 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2285 mh = MethodHandles.insertArguments(mh, 0, ex);
jrose9b82ad62011-05-26 17:37:36 -07002286 WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002287 try {
2288 proxy.willThrow();
2289 System.out.println("Failed to throw: "+ex);
2290 assertTrue(false);
2291 } catch (Throwable ex1) {
2292 if (verbosity > 2) {
2293 System.out.println("throw "+ex);
2294 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2295 }
2296 if (ex instanceof RuntimeException ||
2297 ex instanceof Error) {
2298 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2299 } else if (ex instanceof MyCheckedException) {
2300 assertSame("must pass declared exception out without wrapping", ex, ex1);
2301 } else {
2302 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
jroseaf751942011-06-14 22:47:12 -07002303 if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
2304 ex1.printStackTrace();
2305 }
2306 assertSame(ex, ex1.getCause());
jrosebe2db602010-09-08 18:40:34 -07002307 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
jrosebe2db602010-09-08 18:40:34 -07002308 }
2309 }
2310 }
2311 // Test error checking:
jrosebe2db602010-09-08 18:40:34 -07002312 for (Class<?> nonSAM : new Class[] { Object.class,
2313 String.class,
2314 CharSequence.class,
2315 Example.class }) {
2316 try {
jrose9b82ad62011-05-26 17:37:36 -07002317 MethodHandleProxies.asInterfaceInstance(nonSAM, varargsArray(0));
jrosebe2db602010-09-08 18:40:34 -07002318 System.out.println("Failed to throw");
2319 assertTrue(false);
2320 } catch (IllegalArgumentException ex) {
2321 }
2322 }
2323 }
jrose43b8c122011-07-16 15:40:13 -07002324
2325 @Test
2326 public void testRunnableProxy() throws Throwable {
2327 if (CAN_SKIP_WORKING) return;
2328 startTest("testRunnableProxy");
2329 MethodHandles.Lookup lookup = MethodHandles.lookup();
2330 MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
2331 Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
2332 testRunnableProxy(r);
2333 assertCalled("runForRunnable");
2334 }
2335 private static void testRunnableProxy(Runnable r) {
2336 //7058630: JSR 292 method handle proxy violates contract for Object methods
2337 r.run();
2338 Object o = r;
2339 r = null;
2340 boolean eq = (o == o);
2341 int hc = System.identityHashCode(o);
2342 String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
2343 Object expect = Arrays.asList(st, eq, hc);
2344 if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
2345 Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
2346 if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
2347 assertEquals(expect, actual);
2348 }
jrose55220c32009-10-21 23:19:48 -07002349}
jroseada69fa2011-03-23 23:02:31 -07002350// Local abbreviated copy of sun.invoke.util.ValueConversions
jrose55220c32009-10-21 23:19:48 -07002351class ValueConversions {
2352 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2353 private static final Object[] NO_ARGS_ARRAY = {};
2354 private static Object[] makeArray(Object... args) { return args; }
2355 private static Object[] array() { return NO_ARGS_ARRAY; }
2356 private static Object[] array(Object a0)
2357 { return makeArray(a0); }
2358 private static Object[] array(Object a0, Object a1)
2359 { return makeArray(a0, a1); }
2360 private static Object[] array(Object a0, Object a1, Object a2)
2361 { return makeArray(a0, a1, a2); }
2362 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2363 { return makeArray(a0, a1, a2, a3); }
2364 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2365 Object a4)
2366 { return makeArray(a0, a1, a2, a3, a4); }
2367 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2368 Object a4, Object a5)
2369 { return makeArray(a0, a1, a2, a3, a4, a5); }
2370 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2371 Object a4, Object a5, Object a6)
2372 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2373 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2374 Object a4, Object a5, Object a6, Object a7)
2375 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2376 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2377 Object a4, Object a5, Object a6, Object a7,
2378 Object a8)
2379 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2380 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2381 Object a4, Object a5, Object a6, Object a7,
2382 Object a8, Object a9)
2383 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2384 static MethodHandle[] makeArrays() {
2385 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
2386 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2387 for (;;) {
2388 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002389 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002390 String name = "array";
2391 MethodHandle array = null;
2392 try {
2393 array = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002394 } catch (ReflectiveOperationException ex) {
2395 // break from loop!
jrose55220c32009-10-21 23:19:48 -07002396 }
2397 if (array == null) break;
2398 arrays.add(array);
2399 }
jrosef15905c2011-02-11 01:26:32 -08002400 assertTrue(arrays.size() == 11); // current number of methods
jrose55220c32009-10-21 23:19:48 -07002401 return arrays.toArray(new MethodHandle[0]);
2402 }
2403 static final MethodHandle[] ARRAYS = makeArrays();
2404
2405 /** Return a method handle that takes the indicated number of Object
2406 * arguments and returns an Object array of them, as if for varargs.
2407 */
2408 public static MethodHandle varargsArray(int nargs) {
2409 if (nargs < ARRAYS.length)
2410 return ARRAYS[nargs];
jroseaf751942011-06-14 22:47:12 -07002411 return MethodHandles.identity(Object[].class).asCollector(Object[].class, nargs);
jrose55220c32009-10-21 23:19:48 -07002412 }
jrose320b7692011-05-12 19:27:49 -07002413 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
2414 Class<?> elemType = arrayType.getComponentType();
2415 MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
2416 MethodHandle mh = varargsArray(nargs);
2417 if (arrayType != Object[].class)
2418 mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
2419 return mh.asType(vaType);
2420 }
2421 static Object changeArrayType(Class<?> arrayType, Object[] a) {
2422 Class<?> elemType = arrayType.getComponentType();
2423 if (!elemType.isPrimitive())
2424 return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
2425 Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
2426 for (int i = 0; i < a.length; i++)
2427 java.lang.reflect.Array.set(b, i, a[i]);
2428 return b;
2429 }
2430 private static final MethodHandle CHANGE_ARRAY_TYPE;
2431 static {
2432 try {
2433 CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
2434 MethodType.methodType(Object.class, Class.class, Object[].class));
2435 } catch (NoSuchMethodException | IllegalAccessException ex) {
2436 Error err = new InternalError("uncaught exception");
2437 err.initCause(ex);
2438 throw err;
2439 }
2440 }
jrose10f3b682010-01-07 16:16:45 -08002441
2442 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2443 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2444 private static List<Object> list() { return NO_ARGS_LIST; }
2445 private static List<Object> list(Object a0)
2446 { return makeList(a0); }
2447 private static List<Object> list(Object a0, Object a1)
2448 { return makeList(a0, a1); }
2449 private static List<Object> list(Object a0, Object a1, Object a2)
2450 { return makeList(a0, a1, a2); }
2451 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2452 { return makeList(a0, a1, a2, a3); }
2453 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2454 Object a4)
2455 { return makeList(a0, a1, a2, a3, a4); }
2456 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2457 Object a4, Object a5)
2458 { return makeList(a0, a1, a2, a3, a4, a5); }
2459 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2460 Object a4, Object a5, Object a6)
2461 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2462 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2463 Object a4, Object a5, Object a6, Object a7)
2464 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2465 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2466 Object a4, Object a5, Object a6, Object a7,
2467 Object a8)
2468 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2469 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2470 Object a4, Object a5, Object a6, Object a7,
2471 Object a8, Object a9)
2472 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2473 static MethodHandle[] makeLists() {
jroseadc650a2011-02-11 01:26:28 -08002474 ArrayList<MethodHandle> lists = new ArrayList<MethodHandle>();
jrose10f3b682010-01-07 16:16:45 -08002475 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2476 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08002477 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08002478 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2479 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08002480 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08002481 try {
jroseadc650a2011-02-11 01:26:28 -08002482 list = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002483 } catch (ReflectiveOperationException ex) {
2484 // break from loop!
jrose10f3b682010-01-07 16:16:45 -08002485 }
jroseadc650a2011-02-11 01:26:28 -08002486 if (list == null) break;
2487 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08002488 }
jrosef15905c2011-02-11 01:26:32 -08002489 assertTrue(lists.size() == 11); // current number of methods
jroseadc650a2011-02-11 01:26:28 -08002490 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08002491 }
2492 static final MethodHandle[] LISTS = makeLists();
jroseaf751942011-06-14 22:47:12 -07002493 static final MethodHandle AS_LIST;
2494 static {
2495 try {
2496 AS_LIST = IMPL_LOOKUP.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
2497 } catch (Exception ex) { throw new RuntimeException(ex); }
2498 }
jrose10f3b682010-01-07 16:16:45 -08002499
2500 /** Return a method handle that takes the indicated number of Object
2501 * arguments and returns List.
2502 */
2503 public static MethodHandle varargsList(int nargs) {
2504 if (nargs < LISTS.length)
2505 return LISTS[nargs];
jroseaf751942011-06-14 22:47:12 -07002506 return AS_LIST.asCollector(Object[].class, nargs);
jrose10f3b682010-01-07 16:16:45 -08002507 }
jrose55220c32009-10-21 23:19:48 -07002508}
2509// This guy tests access from outside the same package member, but inside
2510// the package itself.
2511class PackageSibling {
2512 static Lookup lookup() {
2513 return MethodHandles.lookup();
2514 }
2515}