blob: b75b8c471a0ce2faa856660144bb6624ee362fbc [file] [log] [blame]
jrose900bafd2010-10-30 21:08:23 -07001/*
alanb0d058232012-11-02 15:50:11 +00002 * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
jrose900bafd2010-10-30 21:08:23 -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
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/* @test
jroseada69fa2011-03-23 23:02:31 -070027 * @summary example code used in javadoc for java.lang.invoke API
jrose9633f5f2011-04-07 22:07:06 -070028 * @compile JavaDocExamplesTest.java
henryjenf6613f42013-08-12 12:11:04 -070029 * @run testng/othervm test.java.lang.invoke.JavaDocExamplesTest
jrose900bafd2010-10-30 21:08:23 -070030 */
31
jroseada69fa2011-03-23 23:02:31 -070032package test.java.lang.invoke;
jrose900bafd2010-10-30 21:08:23 -070033
jroseada69fa2011-03-23 23:02:31 -070034import java.lang.invoke.*;
35import static java.lang.invoke.MethodHandles.*;
36import static java.lang.invoke.MethodType.*;
jrose900bafd2010-10-30 21:08:23 -070037
jrose900bafd2010-10-30 21:08:23 -070038import java.util.*;
39
henryjenf6613f42013-08-12 12:11:04 -070040import org.testng.*;
41import static org.testng.AssertJUnit.*;
42import org.testng.annotations.*;
jrose900bafd2010-10-30 21:08:23 -070043
44/**
45 * @author jrose
46 */
47public class JavaDocExamplesTest {
henryjenf6613f42013-08-12 12:11:04 -070048 /** Wrapper for running the TestNG tests in this module.
49 * Put TestNG on the classpath!
jrose900bafd2010-10-30 21:08:23 -070050 */
jrose9b82ad62011-05-26 17:37:36 -070051 public static void main(String... ignore) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -070052 new JavaDocExamplesTest().run();
53 }
henryjenf6613f42013-08-12 12:11:04 -070054
jrose9b82ad62011-05-26 17:37:36 -070055 public void run() throws Throwable {
56 testFindVirtual();
57 testPermuteArguments();
58 testDropArguments();
59 testFilterArguments();
60 testFoldArguments();
jroseb4be0262011-07-16 15:44:33 -070061 testFoldArguments2();
jrose9b82ad62011-05-26 17:37:36 -070062 testMethodHandlesSummary();
63 testAsSpreader();
64 testAsCollector();
65 testAsVarargsCollector();
66 testAsFixedArity();
67 testAsTypeCornerCases();
68 testMutableCallSite();
jrose900bafd2010-10-30 21:08:23 -070069 }
70 // How much output?
jrose9b82ad62011-05-26 17:37:36 -070071 static final Class<?> THIS_CLASS = JavaDocExamplesTest.class;
72 static int verbosity = Integer.getInteger(THIS_CLASS.getSimpleName()+".verbosity", 0);
73
jrose900bafd2010-10-30 21:08:23 -070074
75{}
76static final private Lookup LOOKUP = lookup();
77// static final private MethodHandle CONCAT_1 = LOOKUP.findVirtual(String.class,
78// "concat", methodType(String.class, String.class));
79// static final private MethodHandle HASHCODE_1 = LOOKUP.findVirtual(Object.class,
80// "hashCode", methodType(int.class));
81
jrosef15905c2011-02-11 01:26:32 -080082// form required if ReflectiveOperationException is intercepted:
jrose9b82ad62011-05-26 17:37:36 -070083 static final private MethodHandle CONCAT_2, HASHCODE_2, ADD_2, SUB_2;
jrose900bafd2010-10-30 21:08:23 -070084static {
85 try {
jrose9b82ad62011-05-26 17:37:36 -070086 Class<?> THIS_CLASS = LOOKUP.lookupClass();
jrose900bafd2010-10-30 21:08:23 -070087 CONCAT_2 = LOOKUP.findVirtual(String.class,
88 "concat", methodType(String.class, String.class));
89 HASHCODE_2 = LOOKUP.findVirtual(Object.class,
90 "hashCode", methodType(int.class));
jrose9b82ad62011-05-26 17:37:36 -070091 ADD_2 = LOOKUP.findStatic(THIS_CLASS, "add", methodType(int.class, int.class, int.class));
92 SUB_2 = LOOKUP.findStatic(THIS_CLASS, "sub", methodType(int.class, int.class, int.class));
jrosef15905c2011-02-11 01:26:32 -080093 } catch (ReflectiveOperationException ex) {
jrose900bafd2010-10-30 21:08:23 -070094 throw new RuntimeException(ex);
95 }
96}
jrose9b82ad62011-05-26 17:37:36 -070097 static int add(int x, int y) { return x + y; }
98 static int sub(int x, int y) { return x - y; }
99
jrose900bafd2010-10-30 21:08:23 -0700100{}
101
102 @Test public void testFindVirtual() throws Throwable {
103{}
104MethodHandle CONCAT_3 = LOOKUP.findVirtual(String.class,
105 "concat", methodType(String.class, String.class));
106MethodHandle HASHCODE_3 = LOOKUP.findVirtual(Object.class,
107 "hashCode", methodType(int.class));
108//assertEquals("xy", (String) CONCAT_1.invokeExact("x", "y"));
jrose1c1bfac2010-11-22 22:41:31 -0800109assertEquals("xy", (String) CONCAT_2.invokeExact("x", "y"));
110assertEquals("xy", (String) CONCAT_3.invokeExact("x", "y"));
111//assertEquals("xy".hashCode(), (int) HASHCODE_1.invokeExact((Object)"xy"));
112assertEquals("xy".hashCode(), (int) HASHCODE_2.invokeExact((Object)"xy"));
113assertEquals("xy".hashCode(), (int) HASHCODE_3.invokeExact((Object)"xy"));
jrose900bafd2010-10-30 21:08:23 -0700114{}
115 }
jrose9b82ad62011-05-26 17:37:36 -0700116
117 @Test public void testPermuteArguments() throws Throwable {
118 {{
119{} /// JAVADOC
120MethodType intfn1 = methodType(int.class, int.class);
121MethodType intfn2 = methodType(int.class, int.class, int.class);
122MethodHandle sub = SUB_2;// ... {int x, int y => x-y} ...;
123assert(sub.type().equals(intfn2));
124MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
125MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
126assert((int)rsub.invokeExact(1, 100) == 99);
127MethodHandle add = ADD_2;// ... {int x, int y => x+y} ...;
128assert(add.type().equals(intfn2));
129MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
130assert(twice.type().equals(intfn1));
131assert((int)twice.invokeExact(21) == 42);
132 }}
133 {{
134{} /// JAVADOC
135MethodHandle cat = lookup().findVirtual(String.class,
136 "concat", methodType(String.class, String.class));
137assertEquals("xy", (String) cat.invokeExact("x", "y"));
138MethodHandle d0 = dropArguments(cat, 0, String.class);
139assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
140MethodHandle d1 = dropArguments(cat, 1, String.class);
141assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
142MethodHandle d2 = dropArguments(cat, 2, String.class);
143assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
144MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
145assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
146 }}
147 }
148
jrose900bafd2010-10-30 21:08:23 -0700149 @Test public void testDropArguments() throws Throwable {
150 {{
151{} /// JAVADOC
152MethodHandle cat = lookup().findVirtual(String.class,
153 "concat", methodType(String.class, String.class));
jroseb90d2e72010-12-16 15:59:27 -0800154assertEquals("xy", (String) cat.invokeExact("x", "y"));
jroseada69fa2011-03-23 23:02:31 -0700155MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
156MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
157assertEquals(bigType, d0.type());
158assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
159 }}
160 {{
161{} /// JAVADOC
162MethodHandle cat = lookup().findVirtual(String.class,
163 "concat", methodType(String.class, String.class));
164assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700165MethodHandle d0 = dropArguments(cat, 0, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800166assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700167MethodHandle d1 = dropArguments(cat, 1, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800168assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700169MethodHandle d2 = dropArguments(cat, 2, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800170assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700171MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
jroseb90d2e72010-12-16 15:59:27 -0800172assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
jrose900bafd2010-10-30 21:08:23 -0700173 }}
174 }
175
176 @Test public void testFilterArguments() throws Throwable {
177 {{
178{} /// JAVADOC
179MethodHandle cat = lookup().findVirtual(String.class,
180 "concat", methodType(String.class, String.class));
jrose900bafd2010-10-30 21:08:23 -0700181MethodHandle upcase = lookup().findVirtual(String.class,
182 "toUpperCase", methodType(String.class));
jroseb90d2e72010-12-16 15:59:27 -0800183assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700184MethodHandle f0 = filterArguments(cat, 0, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800185assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
jrose900bafd2010-10-30 21:08:23 -0700186MethodHandle f1 = filterArguments(cat, 1, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800187assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
jrose900bafd2010-10-30 21:08:23 -0700188MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800189assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
jrose900bafd2010-10-30 21:08:23 -0700190 }}
191 }
192
jrose9b82ad62011-05-26 17:37:36 -0700193 @Test public void testFoldArguments() throws Throwable {
194 {{
195{} /// JAVADOC
196MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
197 "println", methodType(void.class, String.class))
198 .bindTo(System.out);
199MethodHandle cat = lookup().findVirtual(String.class,
200 "concat", methodType(String.class, String.class));
201assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
202MethodHandle catTrace = foldArguments(cat, trace);
203// also prints "boo":
204assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
205 }}
206 }
207
jrose900bafd2010-10-30 21:08:23 -0700208 static void assertEquals(Object exp, Object act) {
209 if (verbosity > 0)
210 System.out.println("result: "+act);
211 Assert.assertEquals(exp, act);
212 }
213
jrosef108fc02011-02-11 01:26:24 -0800214 @Test public void testMethodHandlesSummary() throws Throwable {
jrose900bafd2010-10-30 21:08:23 -0700215 {{
216{} /// JAVADOC
jrosef108fc02011-02-11 01:26:24 -0800217Object x, y; String s; int i;
218MethodType mt; MethodHandle mh;
219MethodHandles.Lookup lookup = MethodHandles.lookup();
220// mt is (char,char)String
221mt = MethodType.methodType(String.class, char.class, char.class);
222mh = lookup.findVirtual(String.class, "replace", mt);
jrosef108fc02011-02-11 01:26:24 -0800223s = (String) mh.invokeExact("daddy",'d','n');
jroseadc650a2011-02-11 01:26:28 -0800224// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jrose9b82ad62011-05-26 17:37:36 -0700225assertEquals(s, "nanny");
jrosef108fc02011-02-11 01:26:24 -0800226// weakly typed invocation (using MHs.invoke)
227s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jrose9b82ad62011-05-26 17:37:36 -0700228assertEquals(s, "savvy");
jrosef108fc02011-02-11 01:26:24 -0800229// mt is (Object[])List
230mt = MethodType.methodType(java.util.List.class, Object[].class);
231mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
232assert(mh.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700233x = mh.invoke("one", "two");
234// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700235assertEquals(x, java.util.Arrays.asList("one","two"));
jrosef108fc02011-02-11 01:26:24 -0800236// mt is (Object,Object,Object)Object
237mt = MethodType.genericMethodType(3);
jroseadc650a2011-02-11 01:26:28 -0800238mh = mh.asType(mt);
jrosef108fc02011-02-11 01:26:24 -0800239x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jroseadc650a2011-02-11 01:26:28 -0800240// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700241assertEquals(x, java.util.Arrays.asList(1,2,3));
242// mt is ()int
jrosef108fc02011-02-11 01:26:24 -0800243mt = MethodType.methodType(int.class);
244mh = lookup.findVirtual(java.util.List.class, "size", mt);
jrosef108fc02011-02-11 01:26:24 -0800245i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jroseadc650a2011-02-11 01:26:28 -0800246// invokeExact(Ljava/util/List;)I
jrosef108fc02011-02-11 01:26:24 -0800247assert(i == 3);
248mt = MethodType.methodType(void.class, String.class);
249mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
250mh.invokeExact(System.out, "Hello, world.");
jroseadc650a2011-02-11 01:26:28 -0800251// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jrosef108fc02011-02-11 01:26:24 -0800252{}
jrose900bafd2010-10-30 21:08:23 -0700253 }}
254 }
255
jrose9b82ad62011-05-26 17:37:36 -0700256 @Test public void testAsSpreader() throws Throwable {
257 {{
258{} /// JAVADOC
259MethodHandle equals = publicLookup()
260 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
261assert( (boolean) equals.invokeExact("me", (Object)"me"));
262assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
263// spread both arguments from a 2-array:
264MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
265assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
266assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
jrose70feaa92013-10-05 05:30:39 -0700267// try to spread from anything but a 2-array:
268for (int n = 0; n <= 10; n++) {
269 Object[] badArityArgs = (n == 2 ? null : new Object[n]);
270 try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
271 catch (IllegalArgumentException ex) { } // OK
272}
jrose9b82ad62011-05-26 17:37:36 -0700273// spread both arguments from a String array:
274MethodHandle eq2s = equals.asSpreader(String[].class, 2);
275assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
276assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
277// spread second arguments from a 1-array:
278MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
279assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
280assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
281// spread no arguments from a 0-array or null:
282MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
283assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
284assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
285// asSpreader and asCollector are approximate inverses:
286for (int n = 0; n <= 2; n++) {
287 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
288 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
289 assert( (boolean) equals2.invokeWithArguments("me", "me"));
290 assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
291 }
292}
293MethodHandle caToString = publicLookup()
294 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
295assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
296MethodHandle caString3 = caToString.asCollector(char[].class, 3);
297assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
298MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
299assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
300 }}
301 }
302
303 @Test public void testAsCollector() throws Throwable {
304 {{
305{} /// JAVADOC
306MethodHandle deepToString = publicLookup()
307 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
308assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"}));
309MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
310assertEquals(methodType(String.class, Object.class), ts1.type());
311//assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL
312assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
313// arrayType can be a subtype of Object[]
314MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
315assertEquals(methodType(String.class, String.class, String.class), ts2.type());
316assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
317MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
318assertEquals("[]", (String) ts0.invokeExact());
319// collectors can be nested, Lisp-style
320MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
321assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
322// arrayType can be any primitive array type
323MethodHandle bytesToString = publicLookup()
324 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
325 .asCollector(byte[].class, 3);
326assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
327MethodHandle longsToString = publicLookup()
328 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
329 .asCollector(long[].class, 1);
330assertEquals("[123]", (String) longsToString.invokeExact((long)123));
331 }}
332 }
333
jrose49494522012-01-18 17:34:29 -0800334 @SuppressWarnings("rawtypes")
jrosef108fc02011-02-11 01:26:24 -0800335 @Test public void testAsVarargsCollector() throws Throwable {
336 {{
337{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700338MethodHandle deepToString = publicLookup()
339 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
340MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
341assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"}));
342assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"}));
343assertEquals("[won]", (String) ts1.invoke( "won" ));
344assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
345// findStatic of Arrays.asList(...) produces a variable arity method handle:
jrosef108fc02011-02-11 01:26:24 -0800346MethodHandle asList = publicLookup()
jrose9b82ad62011-05-26 17:37:36 -0700347 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
348assertEquals(methodType(List.class, Object[].class), asList.type());
349assert(asList.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700350assertEquals("[]", asList.invoke().toString());
351assertEquals("[1]", asList.invoke(1).toString());
352assertEquals("[two, too]", asList.invoke("two", "too").toString());
jrose9b82ad62011-05-26 17:37:36 -0700353String[] argv = { "three", "thee", "tee" };
jrose79e0a6c2011-05-12 19:27:33 -0700354assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jrose9b82ad62011-05-26 17:37:36 -0700355assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jrose79e0a6c2011-05-12 19:27:33 -0700356List ls = (List) asList.invoke((Object)argv);
jrosef108fc02011-02-11 01:26:24 -0800357assertEquals(1, ls.size());
358assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
359 }}
360 }
jrose900bafd2010-10-30 21:08:23 -0700361
jrose9b82ad62011-05-26 17:37:36 -0700362 @Test public void testAsFixedArity() throws Throwable {
jrosef108fc02011-02-11 01:26:24 -0800363 {{
364{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700365MethodHandle asListVar = publicLookup()
jrosef108fc02011-02-11 01:26:24 -0800366 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
367 .asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -0700368MethodHandle asListFix = asListVar.asFixedArity();
369assertEquals("[1]", asListVar.invoke(1).toString());
370Exception caught = null;
371try { asListFix.invoke((Object)1); }
372catch (Exception ex) { caught = ex; }
373assert(caught instanceof ClassCastException);
374assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
375try { asListFix.invoke("two", "too"); }
376catch (Exception ex) { caught = ex; }
377assert(caught instanceof WrongMethodTypeException);
378Object[] argv = { "three", "thee", "tee" };
379assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
380assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
381assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
382assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
383 }}
384 }
385
386 @Test public void testAsTypeCornerCases() throws Throwable {
387 {{
388{} /// JAVADOC
389MethodHandle i2s = publicLookup()
390 .findVirtual(Integer.class, "toString", methodType(String.class));
391i2s = i2s.asType(i2s.type().unwrap());
392MethodHandle l2s = publicLookup()
393 .findVirtual(Long.class, "toString", methodType(String.class));
394l2s = l2s.asType(l2s.type().unwrap());
395
396Exception caught = null;
397try { i2s.asType(methodType(String.class, String.class)); }
398catch (Exception ex) { caught = ex; }
399assert(caught instanceof WrongMethodTypeException);
400
401i2s.asType(methodType(String.class, byte.class));
402i2s.asType(methodType(String.class, Byte.class));
403i2s.asType(methodType(String.class, Character.class));
404i2s.asType(methodType(String.class, Integer.class));
405l2s.asType(methodType(String.class, byte.class));
406l2s.asType(methodType(String.class, Byte.class));
407l2s.asType(methodType(String.class, Character.class));
408l2s.asType(methodType(String.class, Integer.class));
409l2s.asType(methodType(String.class, Long.class));
410
411caught = null;
412try { i2s.asType(methodType(String.class, Long.class)); }
413catch (Exception ex) { caught = ex; }
414assert(caught instanceof WrongMethodTypeException);
415
416MethodHandle i2sGen = i2s.asType(methodType(String.class, Object.class));
417MethodHandle l2sGen = l2s.asType(methodType(String.class, Object.class));
418
419i2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
420i2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
421l2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
422l2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
423l2sGen.invoke(0x420000000L);
424
425caught = null;
426try { i2sGen.invoke(0x420000000L); } // long -> Long -> Object -> Integer CCE
427catch (Exception ex) { caught = ex; }
428assert(caught instanceof ClassCastException);
429
430caught = null;
431try { i2sGen.invoke("asdf"); } // String -> Object -> Integer CCE
432catch (Exception ex) { caught = ex; }
433assert(caught instanceof ClassCastException);
jrosef108fc02011-02-11 01:26:24 -0800434{}
435 }}
436 }
jrose9b82ad62011-05-26 17:37:36 -0700437
438 @Test public void testMutableCallSite() throws Throwable {
439 {{
440{} /// JAVADOC
441MutableCallSite name = new MutableCallSite(MethodType.methodType(String.class));
442MethodHandle MH_name = name.dynamicInvoker();
443MethodType MT_str1 = MethodType.methodType(String.class);
444MethodHandle MH_upcase = MethodHandles.lookup()
445 .findVirtual(String.class, "toUpperCase", MT_str1);
446MethodHandle worker1 = MethodHandles.filterReturnValue(MH_name, MH_upcase);
447name.setTarget(MethodHandles.constant(String.class, "Rocky"));
448assertEquals("ROCKY", (String) worker1.invokeExact());
449name.setTarget(MethodHandles.constant(String.class, "Fred"));
450assertEquals("FRED", (String) worker1.invokeExact());
451// (mutation can be continued indefinitely)
452/*
453 * </pre></blockquote>
454 * <p>
455 * The same call site may be used in several places at once.
456 * <blockquote><pre>
457 */
458MethodType MT_str2 = MethodType.methodType(String.class, String.class);
459MethodHandle MH_cat = lookup().findVirtual(String.class,
460 "concat", methodType(String.class, String.class));
461MethodHandle MH_dear = MethodHandles.insertArguments(MH_cat, 1, ", dear?");
462MethodHandle worker2 = MethodHandles.filterReturnValue(MH_name, MH_dear);
463assertEquals("Fred, dear?", (String) worker2.invokeExact());
464name.setTarget(MethodHandles.constant(String.class, "Wilma"));
465assertEquals("WILMA", (String) worker1.invokeExact());
466assertEquals("Wilma, dear?", (String) worker2.invokeExact());
467{}
468 }}
469 }
470
471 @Test public void testSwitchPoint() throws Throwable {
472 {{
473{} /// JAVADOC
474MethodHandle MH_strcat = MethodHandles.lookup()
475 .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class));
476SwitchPoint spt = new SwitchPoint();
jrosecd1d97b2011-06-03 11:20:20 -0700477assert(!spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700478// the following steps may be repeated to re-use the same switch point:
479MethodHandle worker1 = MH_strcat;
480MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0);
481MethodHandle worker = spt.guardWithTest(worker1, worker2);
482assertEquals("method", (String) worker.invokeExact("met", "hod"));
483SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
jrosecd1d97b2011-06-03 11:20:20 -0700484assert(spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700485assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
486{}
487 }}
488 }
489
jroseb4be0262011-07-16 15:44:33 -0700490 @Test public void testFoldArguments2() throws Throwable {
491 {{
492{} /// JAVADOC
493// argument-based dispatch for methods of the form boolean x.___(y: String)
494Lookup lookup = publicLookup();
495// first, a tracing hack:
496MethodHandle println = lookup.findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class));
497MethodHandle arrayToString = lookup.findStatic(Arrays.class, "toString", methodType(String.class, Object[].class));
498MethodHandle concat = lookup.findVirtual(String.class, "concat", methodType(String.class, String.class));
499MethodHandle arrayToString_DIS = filterReturnValue(arrayToString, concat.bindTo("DIS:"));
500MethodHandle arrayToString_INV = filterReturnValue(arrayToString, concat.bindTo("INV:"));
501MethodHandle printArgs_DIS = filterReturnValue(arrayToString_DIS, println.bindTo(System.out)).asVarargsCollector(Object[].class);
502MethodHandle printArgs_INV = filterReturnValue(arrayToString_INV, println.bindTo(System.out)).asVarargsCollector(Object[].class);
503// metaobject protocol:
504MethodType mtype = methodType(boolean.class, String.class);
505MethodHandle findVirtual = lookup.findVirtual(Lookup.class,
506 "findVirtual", methodType(MethodHandle.class, Class.class, String.class, MethodType.class));
507MethodHandle getClass = lookup.findVirtual(Object.class,
508 "getClass", methodType(Class.class));
509MethodHandle dispatch = findVirtual;
510dispatch = filterArguments(dispatch, 1, getClass);
511dispatch = insertArguments(dispatch, 3, mtype);
512dispatch = dispatch.bindTo(lookup);
513assertEquals(methodType(MethodHandle.class, Object.class, String.class), dispatch.type());
514MethodHandle invoker = invoker(mtype.insertParameterTypes(0, Object.class));
515// wrap tracing around the dispatch and invoke steps:
516dispatch = foldArguments(dispatch, printArgs_DIS.asType(dispatch.type().changeReturnType(void.class)));
517invoker = foldArguments(invoker, printArgs_INV.asType(invoker.type().changeReturnType(void.class)));
518invoker = dropArguments(invoker, 2, String.class); // ignore selector
519// compose the dispatcher and the invoker:
520MethodHandle invokeDispatched = foldArguments(invoker, dispatch);
521Object x = "football", y = new java.util.Scanner("bar");
522assert( (boolean) invokeDispatched.invokeExact(x, "startsWith", "foo"));
523assert(!(boolean) invokeDispatched.invokeExact(x, "startsWith", "#"));
524assert( (boolean) invokeDispatched.invokeExact(x, "endsWith", "all"));
525assert(!(boolean) invokeDispatched.invokeExact(x, "endsWith", "foo"));
526assert( (boolean) invokeDispatched.invokeExact(y, "hasNext", "[abc]+[rst]"));
527assert(!(boolean) invokeDispatched.invokeExact(y, "hasNext", "[123]+[789]"));
528 }}
529 }
530
jrose9b82ad62011-05-26 17:37:36 -0700531 /* ---- TEMPLATE ----
532 @Test public void testFoo() throws Throwable {
533 {{
534{} /// JAVADOC
535{}
536 }}
537 }
538 */
jrose900bafd2010-10-30 21:08:23 -0700539}