blob: 194564f2f913dde049c25f25f98e64699a51326f [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 {
jrose942f3d32013-10-05 05:30:39 -070056 testMisc();
57 testFindStatic();
58 testFindConstructor();
jrose9b82ad62011-05-26 17:37:36 -070059 testFindVirtual();
jrose942f3d32013-10-05 05:30:39 -070060 testFindSpecial();
jrose9b82ad62011-05-26 17:37:36 -070061 testPermuteArguments();
62 testDropArguments();
63 testFilterArguments();
64 testFoldArguments();
jroseb4be0262011-07-16 15:44:33 -070065 testFoldArguments2();
jrose9b82ad62011-05-26 17:37:36 -070066 testMethodHandlesSummary();
67 testAsSpreader();
68 testAsCollector();
69 testAsVarargsCollector();
70 testAsFixedArity();
71 testAsTypeCornerCases();
72 testMutableCallSite();
jrose900bafd2010-10-30 21:08:23 -070073 }
74 // How much output?
jrose9b82ad62011-05-26 17:37:36 -070075 static final Class<?> THIS_CLASS = JavaDocExamplesTest.class;
76 static int verbosity = Integer.getInteger(THIS_CLASS.getSimpleName()+".verbosity", 0);
77
jrose900bafd2010-10-30 21:08:23 -070078
79{}
80static final private Lookup LOOKUP = lookup();
81// static final private MethodHandle CONCAT_1 = LOOKUP.findVirtual(String.class,
82// "concat", methodType(String.class, String.class));
83// static final private MethodHandle HASHCODE_1 = LOOKUP.findVirtual(Object.class,
84// "hashCode", methodType(int.class));
85
jrosef15905c2011-02-11 01:26:32 -080086// form required if ReflectiveOperationException is intercepted:
jrose9b82ad62011-05-26 17:37:36 -070087 static final private MethodHandle CONCAT_2, HASHCODE_2, ADD_2, SUB_2;
jrose900bafd2010-10-30 21:08:23 -070088static {
89 try {
jrose9b82ad62011-05-26 17:37:36 -070090 Class<?> THIS_CLASS = LOOKUP.lookupClass();
jrose900bafd2010-10-30 21:08:23 -070091 CONCAT_2 = LOOKUP.findVirtual(String.class,
92 "concat", methodType(String.class, String.class));
93 HASHCODE_2 = LOOKUP.findVirtual(Object.class,
94 "hashCode", methodType(int.class));
jrose9b82ad62011-05-26 17:37:36 -070095 ADD_2 = LOOKUP.findStatic(THIS_CLASS, "add", methodType(int.class, int.class, int.class));
96 SUB_2 = LOOKUP.findStatic(THIS_CLASS, "sub", methodType(int.class, int.class, int.class));
jrosef15905c2011-02-11 01:26:32 -080097 } catch (ReflectiveOperationException ex) {
jrose900bafd2010-10-30 21:08:23 -070098 throw new RuntimeException(ex);
99 }
100}
jrose9b82ad62011-05-26 17:37:36 -0700101 static int add(int x, int y) { return x + y; }
102 static int sub(int x, int y) { return x - y; }
103
jrose900bafd2010-10-30 21:08:23 -0700104{}
105
jrose942f3d32013-10-05 05:30:39 -0700106 @Test public void testMisc() throws Throwable {
107// Extra tests, not from javadoc:
jrose900bafd2010-10-30 21:08:23 -0700108{}
109MethodHandle CONCAT_3 = LOOKUP.findVirtual(String.class,
110 "concat", methodType(String.class, String.class));
111MethodHandle HASHCODE_3 = LOOKUP.findVirtual(Object.class,
112 "hashCode", methodType(int.class));
113//assertEquals("xy", (String) CONCAT_1.invokeExact("x", "y"));
jrose1c1bfac2010-11-22 22:41:31 -0800114assertEquals("xy", (String) CONCAT_2.invokeExact("x", "y"));
115assertEquals("xy", (String) CONCAT_3.invokeExact("x", "y"));
116//assertEquals("xy".hashCode(), (int) HASHCODE_1.invokeExact((Object)"xy"));
117assertEquals("xy".hashCode(), (int) HASHCODE_2.invokeExact((Object)"xy"));
118assertEquals("xy".hashCode(), (int) HASHCODE_3.invokeExact((Object)"xy"));
jrose900bafd2010-10-30 21:08:23 -0700119{}
120 }
jrose9b82ad62011-05-26 17:37:36 -0700121
jrose942f3d32013-10-05 05:30:39 -0700122 @Test public void testFindStatic() throws Throwable {
123{}
124MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
125 "asList", methodType(List.class, Object[].class));
126assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
127{}
128 }
129
130 @Test public void testFindVirtual() throws Throwable {
131{}
132MethodHandle MH_concat = publicLookup().findVirtual(String.class,
133 "concat", methodType(String.class, String.class));
134MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
135 "hashCode", methodType(int.class));
136MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
137 "hashCode", methodType(int.class));
138assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
139assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
140assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
141// interface method:
142MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
143 "subSequence", methodType(CharSequence.class, int.class, int.class));
144assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
145// constructor "internal method" must be accessed differently:
146MethodType MT_newString = methodType(void.class); //()V for new String()
147try { assertEquals("impossible", lookup()
148 .findVirtual(String.class, "<init>", MT_newString));
149 } catch (NoSuchMethodException ex) { } // OK
150MethodHandle MH_newString = publicLookup()
151 .findConstructor(String.class, MT_newString);
152assertEquals("", (String) MH_newString.invokeExact());
153{}
154 }
155
156 @Test public void testFindConstructor() throws Throwable {
157{}
158MethodHandle MH_newArrayList = publicLookup().findConstructor(
159 ArrayList.class, methodType(void.class, Collection.class));
160Collection orig = Arrays.asList("x", "y");
161Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
162assert(orig != copy);
163assertEquals(orig, copy);
164// a variable-arity constructor:
165MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
166 ProcessBuilder.class, methodType(void.class, String[].class));
167ProcessBuilder pb = (ProcessBuilder)
168 MH_newProcessBuilder.invoke("x", "y", "z");
169assertEquals("[x, y, z]", pb.command().toString());
170{}
171 }
172
173// for testFindSpecial
174{}
175static class Listie extends ArrayList {
176 public String toString() { return "[wee Listie]"; }
177 static Lookup lookup() { return MethodHandles.lookup(); }
178}
179{}
180
181 @Test public void testFindSpecial() throws Throwable {
182{}
183// no access to constructor via invokeSpecial:
184MethodHandle MH_newListie = Listie.lookup()
185 .findConstructor(Listie.class, methodType(void.class));
186Listie l = (Listie) MH_newListie.invokeExact();
187try { assertEquals("impossible", Listie.lookup().findSpecial(
188 Listie.class, "<init>", methodType(void.class), Listie.class));
189 } catch (NoSuchMethodException ex) { } // OK
190// access to super and self methods via invokeSpecial:
191MethodHandle MH_super = Listie.lookup().findSpecial(
192 ArrayList.class, "toString" , methodType(String.class), Listie.class);
193MethodHandle MH_this = Listie.lookup().findSpecial(
194 Listie.class, "toString" , methodType(String.class), Listie.class);
195MethodHandle MH_duper = Listie.lookup().findSpecial(
196 Object.class, "toString" , methodType(String.class), Listie.class);
197assertEquals("[]", (String) MH_super.invokeExact(l));
198assertEquals(""+l, (String) MH_this.invokeExact(l));
199assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
200try { assertEquals("inaccessible", Listie.lookup().findSpecial(
201 String.class, "toString", methodType(String.class), Listie.class));
202 } catch (IllegalAccessException ex) { } // OK
203Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
204assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
205{}
206 }
207
jrose9b82ad62011-05-26 17:37:36 -0700208 @Test public void testPermuteArguments() throws Throwable {
209 {{
210{} /// JAVADOC
211MethodType intfn1 = methodType(int.class, int.class);
212MethodType intfn2 = methodType(int.class, int.class, int.class);
213MethodHandle sub = SUB_2;// ... {int x, int y => x-y} ...;
214assert(sub.type().equals(intfn2));
215MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
216MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
217assert((int)rsub.invokeExact(1, 100) == 99);
218MethodHandle add = ADD_2;// ... {int x, int y => x+y} ...;
219assert(add.type().equals(intfn2));
220MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
221assert(twice.type().equals(intfn1));
222assert((int)twice.invokeExact(21) == 42);
223 }}
224 {{
225{} /// JAVADOC
226MethodHandle cat = lookup().findVirtual(String.class,
227 "concat", methodType(String.class, String.class));
228assertEquals("xy", (String) cat.invokeExact("x", "y"));
229MethodHandle d0 = dropArguments(cat, 0, String.class);
230assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
231MethodHandle d1 = dropArguments(cat, 1, String.class);
232assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
233MethodHandle d2 = dropArguments(cat, 2, String.class);
234assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
235MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
236assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
237 }}
238 }
239
jrose900bafd2010-10-30 21:08:23 -0700240 @Test public void testDropArguments() throws Throwable {
241 {{
242{} /// JAVADOC
243MethodHandle cat = lookup().findVirtual(String.class,
244 "concat", methodType(String.class, String.class));
jroseb90d2e72010-12-16 15:59:27 -0800245assertEquals("xy", (String) cat.invokeExact("x", "y"));
jroseada69fa2011-03-23 23:02:31 -0700246MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
247MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
248assertEquals(bigType, d0.type());
249assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
250 }}
251 {{
252{} /// JAVADOC
253MethodHandle cat = lookup().findVirtual(String.class,
254 "concat", methodType(String.class, String.class));
255assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700256MethodHandle d0 = dropArguments(cat, 0, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800257assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700258MethodHandle d1 = dropArguments(cat, 1, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800259assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700260MethodHandle d2 = dropArguments(cat, 2, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800261assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700262MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
jroseb90d2e72010-12-16 15:59:27 -0800263assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
jrose900bafd2010-10-30 21:08:23 -0700264 }}
265 }
266
267 @Test public void testFilterArguments() throws Throwable {
268 {{
269{} /// JAVADOC
270MethodHandle cat = lookup().findVirtual(String.class,
271 "concat", methodType(String.class, String.class));
jrose900bafd2010-10-30 21:08:23 -0700272MethodHandle upcase = lookup().findVirtual(String.class,
273 "toUpperCase", methodType(String.class));
jroseb90d2e72010-12-16 15:59:27 -0800274assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700275MethodHandle f0 = filterArguments(cat, 0, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800276assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
jrose900bafd2010-10-30 21:08:23 -0700277MethodHandle f1 = filterArguments(cat, 1, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800278assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
jrose900bafd2010-10-30 21:08:23 -0700279MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800280assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
jrose900bafd2010-10-30 21:08:23 -0700281 }}
282 }
283
jrose1ccb8a72013-10-05 05:30:39 -0700284 @Test public void testCollectArguments() throws Throwable {
285 {{
286{} /// JAVADOC
287MethodHandle deepToString = publicLookup()
288 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
289MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
290assertEquals("[strange]", (String) ts1.invokeExact("strange"));
291MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
292assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
293MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
294MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
295assertEquals("[top, [up, down], strange]",
296 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
297MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
298assertEquals("[top, [up, down], [strange]]",
299 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
300MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
301assertEquals("[top, [[up, down, strange], charm], bottom]",
302 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
303 }}
304 }
305
jrose9b82ad62011-05-26 17:37:36 -0700306 @Test public void testFoldArguments() throws Throwable {
307 {{
308{} /// JAVADOC
309MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
310 "println", methodType(void.class, String.class))
311 .bindTo(System.out);
312MethodHandle cat = lookup().findVirtual(String.class,
313 "concat", methodType(String.class, String.class));
314assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
315MethodHandle catTrace = foldArguments(cat, trace);
316// also prints "boo":
317assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
318 }}
319 }
320
jrose900bafd2010-10-30 21:08:23 -0700321 static void assertEquals(Object exp, Object act) {
322 if (verbosity > 0)
323 System.out.println("result: "+act);
324 Assert.assertEquals(exp, act);
325 }
326
jrosef108fc02011-02-11 01:26:24 -0800327 @Test public void testMethodHandlesSummary() throws Throwable {
jrose900bafd2010-10-30 21:08:23 -0700328 {{
329{} /// JAVADOC
jrosef108fc02011-02-11 01:26:24 -0800330Object x, y; String s; int i;
331MethodType mt; MethodHandle mh;
332MethodHandles.Lookup lookup = MethodHandles.lookup();
333// mt is (char,char)String
334mt = MethodType.methodType(String.class, char.class, char.class);
335mh = lookup.findVirtual(String.class, "replace", mt);
jrosef108fc02011-02-11 01:26:24 -0800336s = (String) mh.invokeExact("daddy",'d','n');
jroseadc650a2011-02-11 01:26:28 -0800337// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jrose9b82ad62011-05-26 17:37:36 -0700338assertEquals(s, "nanny");
jrosef108fc02011-02-11 01:26:24 -0800339// weakly typed invocation (using MHs.invoke)
340s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jrose9b82ad62011-05-26 17:37:36 -0700341assertEquals(s, "savvy");
jrosef108fc02011-02-11 01:26:24 -0800342// mt is (Object[])List
343mt = MethodType.methodType(java.util.List.class, Object[].class);
344mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
345assert(mh.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700346x = mh.invoke("one", "two");
347// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700348assertEquals(x, java.util.Arrays.asList("one","two"));
jrosef108fc02011-02-11 01:26:24 -0800349// mt is (Object,Object,Object)Object
350mt = MethodType.genericMethodType(3);
jroseadc650a2011-02-11 01:26:28 -0800351mh = mh.asType(mt);
jrosef108fc02011-02-11 01:26:24 -0800352x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jroseadc650a2011-02-11 01:26:28 -0800353// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700354assertEquals(x, java.util.Arrays.asList(1,2,3));
355// mt is ()int
jrosef108fc02011-02-11 01:26:24 -0800356mt = MethodType.methodType(int.class);
357mh = lookup.findVirtual(java.util.List.class, "size", mt);
jrosef108fc02011-02-11 01:26:24 -0800358i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jroseadc650a2011-02-11 01:26:28 -0800359// invokeExact(Ljava/util/List;)I
jrosef108fc02011-02-11 01:26:24 -0800360assert(i == 3);
361mt = MethodType.methodType(void.class, String.class);
362mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
363mh.invokeExact(System.out, "Hello, world.");
jroseadc650a2011-02-11 01:26:28 -0800364// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jrosef108fc02011-02-11 01:26:24 -0800365{}
jrose900bafd2010-10-30 21:08:23 -0700366 }}
367 }
368
jrose9b82ad62011-05-26 17:37:36 -0700369 @Test public void testAsSpreader() throws Throwable {
370 {{
371{} /// JAVADOC
372MethodHandle equals = publicLookup()
373 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
374assert( (boolean) equals.invokeExact("me", (Object)"me"));
375assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
376// spread both arguments from a 2-array:
377MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
378assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
379assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
jrose70feaa92013-10-05 05:30:39 -0700380// try to spread from anything but a 2-array:
381for (int n = 0; n <= 10; n++) {
382 Object[] badArityArgs = (n == 2 ? null : new Object[n]);
383 try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
384 catch (IllegalArgumentException ex) { } // OK
385}
jrose9b82ad62011-05-26 17:37:36 -0700386// spread both arguments from a String array:
387MethodHandle eq2s = equals.asSpreader(String[].class, 2);
388assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
389assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
390// spread second arguments from a 1-array:
391MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
392assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
393assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
394// spread no arguments from a 0-array or null:
395MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
396assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
397assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
398// asSpreader and asCollector are approximate inverses:
399for (int n = 0; n <= 2; n++) {
400 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
401 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
402 assert( (boolean) equals2.invokeWithArguments("me", "me"));
403 assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
404 }
405}
406MethodHandle caToString = publicLookup()
407 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
408assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
409MethodHandle caString3 = caToString.asCollector(char[].class, 3);
410assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
411MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
412assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
413 }}
414 }
415
416 @Test public void testAsCollector() throws Throwable {
417 {{
418{} /// JAVADOC
419MethodHandle deepToString = publicLookup()
420 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
421assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"}));
422MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
423assertEquals(methodType(String.class, Object.class), ts1.type());
424//assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL
425assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
426// arrayType can be a subtype of Object[]
427MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
428assertEquals(methodType(String.class, String.class, String.class), ts2.type());
429assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
430MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
431assertEquals("[]", (String) ts0.invokeExact());
432// collectors can be nested, Lisp-style
433MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
434assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
435// arrayType can be any primitive array type
436MethodHandle bytesToString = publicLookup()
437 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
438 .asCollector(byte[].class, 3);
439assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
440MethodHandle longsToString = publicLookup()
441 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
442 .asCollector(long[].class, 1);
443assertEquals("[123]", (String) longsToString.invokeExact((long)123));
444 }}
445 }
446
jrose49494522012-01-18 17:34:29 -0800447 @SuppressWarnings("rawtypes")
jrosef108fc02011-02-11 01:26:24 -0800448 @Test public void testAsVarargsCollector() throws Throwable {
449 {{
450{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700451MethodHandle deepToString = publicLookup()
452 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
453MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
454assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"}));
455assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"}));
456assertEquals("[won]", (String) ts1.invoke( "won" ));
457assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
458// findStatic of Arrays.asList(...) produces a variable arity method handle:
jrosef108fc02011-02-11 01:26:24 -0800459MethodHandle asList = publicLookup()
jrose9b82ad62011-05-26 17:37:36 -0700460 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
461assertEquals(methodType(List.class, Object[].class), asList.type());
462assert(asList.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700463assertEquals("[]", asList.invoke().toString());
464assertEquals("[1]", asList.invoke(1).toString());
465assertEquals("[two, too]", asList.invoke("two", "too").toString());
jrose9b82ad62011-05-26 17:37:36 -0700466String[] argv = { "three", "thee", "tee" };
jrose79e0a6c2011-05-12 19:27:33 -0700467assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jrose9b82ad62011-05-26 17:37:36 -0700468assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jrose79e0a6c2011-05-12 19:27:33 -0700469List ls = (List) asList.invoke((Object)argv);
jrosef108fc02011-02-11 01:26:24 -0800470assertEquals(1, ls.size());
471assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
472 }}
473 }
jrose900bafd2010-10-30 21:08:23 -0700474
jrose9b82ad62011-05-26 17:37:36 -0700475 @Test public void testAsFixedArity() throws Throwable {
jrosef108fc02011-02-11 01:26:24 -0800476 {{
477{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700478MethodHandle asListVar = publicLookup()
jrosef108fc02011-02-11 01:26:24 -0800479 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
480 .asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -0700481MethodHandle asListFix = asListVar.asFixedArity();
482assertEquals("[1]", asListVar.invoke(1).toString());
483Exception caught = null;
484try { asListFix.invoke((Object)1); }
485catch (Exception ex) { caught = ex; }
486assert(caught instanceof ClassCastException);
487assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
488try { asListFix.invoke("two", "too"); }
489catch (Exception ex) { caught = ex; }
490assert(caught instanceof WrongMethodTypeException);
491Object[] argv = { "three", "thee", "tee" };
492assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
493assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
494assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
495assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
496 }}
497 }
498
499 @Test public void testAsTypeCornerCases() throws Throwable {
500 {{
501{} /// JAVADOC
502MethodHandle i2s = publicLookup()
503 .findVirtual(Integer.class, "toString", methodType(String.class));
504i2s = i2s.asType(i2s.type().unwrap());
505MethodHandle l2s = publicLookup()
506 .findVirtual(Long.class, "toString", methodType(String.class));
507l2s = l2s.asType(l2s.type().unwrap());
508
509Exception caught = null;
510try { i2s.asType(methodType(String.class, String.class)); }
511catch (Exception ex) { caught = ex; }
512assert(caught instanceof WrongMethodTypeException);
513
514i2s.asType(methodType(String.class, byte.class));
515i2s.asType(methodType(String.class, Byte.class));
516i2s.asType(methodType(String.class, Character.class));
517i2s.asType(methodType(String.class, Integer.class));
518l2s.asType(methodType(String.class, byte.class));
519l2s.asType(methodType(String.class, Byte.class));
520l2s.asType(methodType(String.class, Character.class));
521l2s.asType(methodType(String.class, Integer.class));
522l2s.asType(methodType(String.class, Long.class));
523
524caught = null;
525try { i2s.asType(methodType(String.class, Long.class)); }
526catch (Exception ex) { caught = ex; }
527assert(caught instanceof WrongMethodTypeException);
528
529MethodHandle i2sGen = i2s.asType(methodType(String.class, Object.class));
530MethodHandle l2sGen = l2s.asType(methodType(String.class, Object.class));
531
532i2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
533i2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
534l2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
535l2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
536l2sGen.invoke(0x420000000L);
537
538caught = null;
539try { i2sGen.invoke(0x420000000L); } // long -> Long -> Object -> Integer CCE
540catch (Exception ex) { caught = ex; }
541assert(caught instanceof ClassCastException);
542
543caught = null;
544try { i2sGen.invoke("asdf"); } // String -> Object -> Integer CCE
545catch (Exception ex) { caught = ex; }
546assert(caught instanceof ClassCastException);
jrosef108fc02011-02-11 01:26:24 -0800547{}
548 }}
549 }
jrose9b82ad62011-05-26 17:37:36 -0700550
551 @Test public void testMutableCallSite() throws Throwable {
552 {{
553{} /// JAVADOC
554MutableCallSite name = new MutableCallSite(MethodType.methodType(String.class));
555MethodHandle MH_name = name.dynamicInvoker();
556MethodType MT_str1 = MethodType.methodType(String.class);
557MethodHandle MH_upcase = MethodHandles.lookup()
558 .findVirtual(String.class, "toUpperCase", MT_str1);
559MethodHandle worker1 = MethodHandles.filterReturnValue(MH_name, MH_upcase);
560name.setTarget(MethodHandles.constant(String.class, "Rocky"));
561assertEquals("ROCKY", (String) worker1.invokeExact());
562name.setTarget(MethodHandles.constant(String.class, "Fred"));
563assertEquals("FRED", (String) worker1.invokeExact());
564// (mutation can be continued indefinitely)
565/*
566 * </pre></blockquote>
567 * <p>
568 * The same call site may be used in several places at once.
569 * <blockquote><pre>
570 */
571MethodType MT_str2 = MethodType.methodType(String.class, String.class);
572MethodHandle MH_cat = lookup().findVirtual(String.class,
573 "concat", methodType(String.class, String.class));
574MethodHandle MH_dear = MethodHandles.insertArguments(MH_cat, 1, ", dear?");
575MethodHandle worker2 = MethodHandles.filterReturnValue(MH_name, MH_dear);
576assertEquals("Fred, dear?", (String) worker2.invokeExact());
577name.setTarget(MethodHandles.constant(String.class, "Wilma"));
578assertEquals("WILMA", (String) worker1.invokeExact());
579assertEquals("Wilma, dear?", (String) worker2.invokeExact());
580{}
581 }}
582 }
583
584 @Test public void testSwitchPoint() throws Throwable {
585 {{
586{} /// JAVADOC
587MethodHandle MH_strcat = MethodHandles.lookup()
588 .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class));
589SwitchPoint spt = new SwitchPoint();
jrosecd1d97b2011-06-03 11:20:20 -0700590assert(!spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700591// the following steps may be repeated to re-use the same switch point:
592MethodHandle worker1 = MH_strcat;
593MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0);
594MethodHandle worker = spt.guardWithTest(worker1, worker2);
595assertEquals("method", (String) worker.invokeExact("met", "hod"));
596SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
jrosecd1d97b2011-06-03 11:20:20 -0700597assert(spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700598assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
599{}
600 }}
601 }
602
jroseb4be0262011-07-16 15:44:33 -0700603 @Test public void testFoldArguments2() throws Throwable {
604 {{
605{} /// JAVADOC
606// argument-based dispatch for methods of the form boolean x.___(y: String)
607Lookup lookup = publicLookup();
608// first, a tracing hack:
609MethodHandle println = lookup.findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class));
610MethodHandle arrayToString = lookup.findStatic(Arrays.class, "toString", methodType(String.class, Object[].class));
611MethodHandle concat = lookup.findVirtual(String.class, "concat", methodType(String.class, String.class));
612MethodHandle arrayToString_DIS = filterReturnValue(arrayToString, concat.bindTo("DIS:"));
613MethodHandle arrayToString_INV = filterReturnValue(arrayToString, concat.bindTo("INV:"));
614MethodHandle printArgs_DIS = filterReturnValue(arrayToString_DIS, println.bindTo(System.out)).asVarargsCollector(Object[].class);
615MethodHandle printArgs_INV = filterReturnValue(arrayToString_INV, println.bindTo(System.out)).asVarargsCollector(Object[].class);
616// metaobject protocol:
617MethodType mtype = methodType(boolean.class, String.class);
618MethodHandle findVirtual = lookup.findVirtual(Lookup.class,
619 "findVirtual", methodType(MethodHandle.class, Class.class, String.class, MethodType.class));
620MethodHandle getClass = lookup.findVirtual(Object.class,
621 "getClass", methodType(Class.class));
622MethodHandle dispatch = findVirtual;
623dispatch = filterArguments(dispatch, 1, getClass);
624dispatch = insertArguments(dispatch, 3, mtype);
625dispatch = dispatch.bindTo(lookup);
626assertEquals(methodType(MethodHandle.class, Object.class, String.class), dispatch.type());
627MethodHandle invoker = invoker(mtype.insertParameterTypes(0, Object.class));
628// wrap tracing around the dispatch and invoke steps:
629dispatch = foldArguments(dispatch, printArgs_DIS.asType(dispatch.type().changeReturnType(void.class)));
630invoker = foldArguments(invoker, printArgs_INV.asType(invoker.type().changeReturnType(void.class)));
631invoker = dropArguments(invoker, 2, String.class); // ignore selector
632// compose the dispatcher and the invoker:
633MethodHandle invokeDispatched = foldArguments(invoker, dispatch);
634Object x = "football", y = new java.util.Scanner("bar");
635assert( (boolean) invokeDispatched.invokeExact(x, "startsWith", "foo"));
636assert(!(boolean) invokeDispatched.invokeExact(x, "startsWith", "#"));
637assert( (boolean) invokeDispatched.invokeExact(x, "endsWith", "all"));
638assert(!(boolean) invokeDispatched.invokeExact(x, "endsWith", "foo"));
639assert( (boolean) invokeDispatched.invokeExact(y, "hasNext", "[abc]+[rst]"));
640assert(!(boolean) invokeDispatched.invokeExact(y, "hasNext", "[123]+[789]"));
641 }}
642 }
643
jrose9b82ad62011-05-26 17:37:36 -0700644 /* ---- TEMPLATE ----
645 @Test public void testFoo() throws Throwable {
646 {{
647{} /// JAVADOC
648{}
649 }}
650 }
651 */
jrose900bafd2010-10-30 21:08:23 -0700652}