blob: 2f8bfdc32506fa4ba8ccad4125a2ad975fb2081d [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
serb9adafbe2013-11-12 20:24:25 +04007 * published by the Free Software Foundation.
jrose900bafd2010-10-30 21:08:23 -07008 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/* @test
jroseada69fa2011-03-23 23:02:31 -070025 * @summary example code used in javadoc for java.lang.invoke API
jrose9633f5f2011-04-07 22:07:06 -070026 * @compile JavaDocExamplesTest.java
henryjenf6613f42013-08-12 12:11:04 -070027 * @run testng/othervm test.java.lang.invoke.JavaDocExamplesTest
jrose900bafd2010-10-30 21:08:23 -070028 */
29
jroseada69fa2011-03-23 23:02:31 -070030package test.java.lang.invoke;
jrose900bafd2010-10-30 21:08:23 -070031
jroseada69fa2011-03-23 23:02:31 -070032import java.lang.invoke.*;
33import static java.lang.invoke.MethodHandles.*;
34import static java.lang.invoke.MethodType.*;
jrose900bafd2010-10-30 21:08:23 -070035
jrose900bafd2010-10-30 21:08:23 -070036import java.util.*;
37
henryjenf6613f42013-08-12 12:11:04 -070038import org.testng.*;
39import static org.testng.AssertJUnit.*;
40import org.testng.annotations.*;
jrose900bafd2010-10-30 21:08:23 -070041
42/**
43 * @author jrose
44 */
45public class JavaDocExamplesTest {
henryjenf6613f42013-08-12 12:11:04 -070046 /** Wrapper for running the TestNG tests in this module.
47 * Put TestNG on the classpath!
jrose900bafd2010-10-30 21:08:23 -070048 */
jrose9b82ad62011-05-26 17:37:36 -070049 public static void main(String... ignore) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -070050 new JavaDocExamplesTest().run();
51 }
henryjenf6613f42013-08-12 12:11:04 -070052
jrose9b82ad62011-05-26 17:37:36 -070053 public void run() throws Throwable {
jrose942f3d32013-10-05 05:30:39 -070054 testMisc();
55 testFindStatic();
56 testFindConstructor();
jrose9b82ad62011-05-26 17:37:36 -070057 testFindVirtual();
jrose942f3d32013-10-05 05:30:39 -070058 testFindSpecial();
jrose9b82ad62011-05-26 17:37:36 -070059 testPermuteArguments();
60 testDropArguments();
61 testFilterArguments();
62 testFoldArguments();
jroseb4be0262011-07-16 15:44:33 -070063 testFoldArguments2();
jrose9b82ad62011-05-26 17:37:36 -070064 testMethodHandlesSummary();
65 testAsSpreader();
66 testAsCollector();
67 testAsVarargsCollector();
68 testAsFixedArity();
69 testAsTypeCornerCases();
70 testMutableCallSite();
jrose900bafd2010-10-30 21:08:23 -070071 }
72 // How much output?
jrose9b82ad62011-05-26 17:37:36 -070073 static final Class<?> THIS_CLASS = JavaDocExamplesTest.class;
74 static int verbosity = Integer.getInteger(THIS_CLASS.getSimpleName()+".verbosity", 0);
75
jrose900bafd2010-10-30 21:08:23 -070076
77{}
78static final private Lookup LOOKUP = lookup();
79// static final private MethodHandle CONCAT_1 = LOOKUP.findVirtual(String.class,
80// "concat", methodType(String.class, String.class));
81// static final private MethodHandle HASHCODE_1 = LOOKUP.findVirtual(Object.class,
82// "hashCode", methodType(int.class));
83
jrosef15905c2011-02-11 01:26:32 -080084// form required if ReflectiveOperationException is intercepted:
jrose9b82ad62011-05-26 17:37:36 -070085 static final private MethodHandle CONCAT_2, HASHCODE_2, ADD_2, SUB_2;
jrose900bafd2010-10-30 21:08:23 -070086static {
87 try {
jrose9b82ad62011-05-26 17:37:36 -070088 Class<?> THIS_CLASS = LOOKUP.lookupClass();
jrose900bafd2010-10-30 21:08:23 -070089 CONCAT_2 = LOOKUP.findVirtual(String.class,
90 "concat", methodType(String.class, String.class));
91 HASHCODE_2 = LOOKUP.findVirtual(Object.class,
92 "hashCode", methodType(int.class));
jrose9b82ad62011-05-26 17:37:36 -070093 ADD_2 = LOOKUP.findStatic(THIS_CLASS, "add", methodType(int.class, int.class, int.class));
94 SUB_2 = LOOKUP.findStatic(THIS_CLASS, "sub", methodType(int.class, int.class, int.class));
jrosef15905c2011-02-11 01:26:32 -080095 } catch (ReflectiveOperationException ex) {
jrose900bafd2010-10-30 21:08:23 -070096 throw new RuntimeException(ex);
97 }
98}
jrose9b82ad62011-05-26 17:37:36 -070099 static int add(int x, int y) { return x + y; }
100 static int sub(int x, int y) { return x - y; }
101
jrose900bafd2010-10-30 21:08:23 -0700102{}
103
jrose942f3d32013-10-05 05:30:39 -0700104 @Test public void testMisc() throws Throwable {
105// Extra tests, not from javadoc:
jrose900bafd2010-10-30 21:08:23 -0700106{}
107MethodHandle CONCAT_3 = LOOKUP.findVirtual(String.class,
108 "concat", methodType(String.class, String.class));
109MethodHandle HASHCODE_3 = LOOKUP.findVirtual(Object.class,
110 "hashCode", methodType(int.class));
111//assertEquals("xy", (String) CONCAT_1.invokeExact("x", "y"));
jrose1c1bfac2010-11-22 22:41:31 -0800112assertEquals("xy", (String) CONCAT_2.invokeExact("x", "y"));
113assertEquals("xy", (String) CONCAT_3.invokeExact("x", "y"));
114//assertEquals("xy".hashCode(), (int) HASHCODE_1.invokeExact((Object)"xy"));
115assertEquals("xy".hashCode(), (int) HASHCODE_2.invokeExact((Object)"xy"));
116assertEquals("xy".hashCode(), (int) HASHCODE_3.invokeExact((Object)"xy"));
jrose900bafd2010-10-30 21:08:23 -0700117{}
118 }
jrose9b82ad62011-05-26 17:37:36 -0700119
jrose942f3d32013-10-05 05:30:39 -0700120 @Test public void testFindStatic() throws Throwable {
121{}
122MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
123 "asList", methodType(List.class, Object[].class));
124assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
125{}
126 }
127
128 @Test public void testFindVirtual() throws Throwable {
129{}
130MethodHandle MH_concat = publicLookup().findVirtual(String.class,
131 "concat", methodType(String.class, String.class));
132MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
133 "hashCode", methodType(int.class));
134MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
135 "hashCode", methodType(int.class));
136assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
137assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
138assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
139// interface method:
140MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
141 "subSequence", methodType(CharSequence.class, int.class, int.class));
142assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
143// constructor "internal method" must be accessed differently:
144MethodType MT_newString = methodType(void.class); //()V for new String()
145try { assertEquals("impossible", lookup()
146 .findVirtual(String.class, "<init>", MT_newString));
147 } catch (NoSuchMethodException ex) { } // OK
148MethodHandle MH_newString = publicLookup()
149 .findConstructor(String.class, MT_newString);
150assertEquals("", (String) MH_newString.invokeExact());
151{}
152 }
153
154 @Test public void testFindConstructor() throws Throwable {
155{}
156MethodHandle MH_newArrayList = publicLookup().findConstructor(
157 ArrayList.class, methodType(void.class, Collection.class));
158Collection orig = Arrays.asList("x", "y");
159Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
160assert(orig != copy);
161assertEquals(orig, copy);
162// a variable-arity constructor:
163MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
164 ProcessBuilder.class, methodType(void.class, String[].class));
165ProcessBuilder pb = (ProcessBuilder)
166 MH_newProcessBuilder.invoke("x", "y", "z");
167assertEquals("[x, y, z]", pb.command().toString());
168{}
169 }
170
171// for testFindSpecial
172{}
173static class Listie extends ArrayList {
174 public String toString() { return "[wee Listie]"; }
175 static Lookup lookup() { return MethodHandles.lookup(); }
176}
177{}
178
179 @Test public void testFindSpecial() throws Throwable {
180{}
181// no access to constructor via invokeSpecial:
182MethodHandle MH_newListie = Listie.lookup()
183 .findConstructor(Listie.class, methodType(void.class));
184Listie l = (Listie) MH_newListie.invokeExact();
185try { assertEquals("impossible", Listie.lookup().findSpecial(
186 Listie.class, "<init>", methodType(void.class), Listie.class));
187 } catch (NoSuchMethodException ex) { } // OK
188// access to super and self methods via invokeSpecial:
189MethodHandle MH_super = Listie.lookup().findSpecial(
190 ArrayList.class, "toString" , methodType(String.class), Listie.class);
191MethodHandle MH_this = Listie.lookup().findSpecial(
192 Listie.class, "toString" , methodType(String.class), Listie.class);
193MethodHandle MH_duper = Listie.lookup().findSpecial(
194 Object.class, "toString" , methodType(String.class), Listie.class);
195assertEquals("[]", (String) MH_super.invokeExact(l));
196assertEquals(""+l, (String) MH_this.invokeExact(l));
197assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
198try { assertEquals("inaccessible", Listie.lookup().findSpecial(
199 String.class, "toString", methodType(String.class), Listie.class));
200 } catch (IllegalAccessException ex) { } // OK
201Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
202assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
203{}
204 }
205
jrose9b82ad62011-05-26 17:37:36 -0700206 @Test public void testPermuteArguments() throws Throwable {
207 {{
208{} /// JAVADOC
209MethodType intfn1 = methodType(int.class, int.class);
210MethodType intfn2 = methodType(int.class, int.class, int.class);
211MethodHandle sub = SUB_2;// ... {int x, int y => x-y} ...;
212assert(sub.type().equals(intfn2));
213MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
214MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
215assert((int)rsub.invokeExact(1, 100) == 99);
216MethodHandle add = ADD_2;// ... {int x, int y => x+y} ...;
217assert(add.type().equals(intfn2));
218MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
219assert(twice.type().equals(intfn1));
220assert((int)twice.invokeExact(21) == 42);
221 }}
222 {{
223{} /// JAVADOC
224MethodHandle cat = lookup().findVirtual(String.class,
225 "concat", methodType(String.class, String.class));
226assertEquals("xy", (String) cat.invokeExact("x", "y"));
227MethodHandle d0 = dropArguments(cat, 0, String.class);
228assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
229MethodHandle d1 = dropArguments(cat, 1, String.class);
230assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
231MethodHandle d2 = dropArguments(cat, 2, String.class);
232assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
233MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
234assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
235 }}
236 }
237
jrose900bafd2010-10-30 21:08:23 -0700238 @Test public void testDropArguments() throws Throwable {
239 {{
240{} /// JAVADOC
241MethodHandle cat = lookup().findVirtual(String.class,
242 "concat", methodType(String.class, String.class));
jroseb90d2e72010-12-16 15:59:27 -0800243assertEquals("xy", (String) cat.invokeExact("x", "y"));
jroseada69fa2011-03-23 23:02:31 -0700244MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
245MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
246assertEquals(bigType, d0.type());
247assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
248 }}
249 {{
250{} /// JAVADOC
251MethodHandle cat = lookup().findVirtual(String.class,
252 "concat", methodType(String.class, String.class));
253assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700254MethodHandle d0 = dropArguments(cat, 0, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800255assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700256MethodHandle d1 = dropArguments(cat, 1, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800257assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700258MethodHandle d2 = dropArguments(cat, 2, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800259assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700260MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
jroseb90d2e72010-12-16 15:59:27 -0800261assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
jrose900bafd2010-10-30 21:08:23 -0700262 }}
263 }
264
265 @Test public void testFilterArguments() throws Throwable {
266 {{
267{} /// JAVADOC
268MethodHandle cat = lookup().findVirtual(String.class,
269 "concat", methodType(String.class, String.class));
jrose900bafd2010-10-30 21:08:23 -0700270MethodHandle upcase = lookup().findVirtual(String.class,
271 "toUpperCase", methodType(String.class));
jroseb90d2e72010-12-16 15:59:27 -0800272assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700273MethodHandle f0 = filterArguments(cat, 0, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800274assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
jrose900bafd2010-10-30 21:08:23 -0700275MethodHandle f1 = filterArguments(cat, 1, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800276assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
jrose900bafd2010-10-30 21:08:23 -0700277MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800278assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
jrose900bafd2010-10-30 21:08:23 -0700279 }}
280 }
281
jrose1ccb8a72013-10-05 05:30:39 -0700282 @Test public void testCollectArguments() throws Throwable {
283 {{
284{} /// JAVADOC
285MethodHandle deepToString = publicLookup()
286 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
287MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
288assertEquals("[strange]", (String) ts1.invokeExact("strange"));
289MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
290assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
291MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
292MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
293assertEquals("[top, [up, down], strange]",
294 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
295MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
296assertEquals("[top, [up, down], [strange]]",
297 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
298MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
299assertEquals("[top, [[up, down, strange], charm], bottom]",
300 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
301 }}
302 }
303
jrose9b82ad62011-05-26 17:37:36 -0700304 @Test public void testFoldArguments() throws Throwable {
305 {{
306{} /// JAVADOC
307MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
308 "println", methodType(void.class, String.class))
309 .bindTo(System.out);
310MethodHandle cat = lookup().findVirtual(String.class,
311 "concat", methodType(String.class, String.class));
312assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
313MethodHandle catTrace = foldArguments(cat, trace);
314// also prints "boo":
315assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
316 }}
317 }
318
jrose900bafd2010-10-30 21:08:23 -0700319 static void assertEquals(Object exp, Object act) {
320 if (verbosity > 0)
321 System.out.println("result: "+act);
322 Assert.assertEquals(exp, act);
323 }
324
jrosef108fc02011-02-11 01:26:24 -0800325 @Test public void testMethodHandlesSummary() throws Throwable {
jrose900bafd2010-10-30 21:08:23 -0700326 {{
327{} /// JAVADOC
jrosef108fc02011-02-11 01:26:24 -0800328Object x, y; String s; int i;
329MethodType mt; MethodHandle mh;
330MethodHandles.Lookup lookup = MethodHandles.lookup();
331// mt is (char,char)String
332mt = MethodType.methodType(String.class, char.class, char.class);
333mh = lookup.findVirtual(String.class, "replace", mt);
jrosef108fc02011-02-11 01:26:24 -0800334s = (String) mh.invokeExact("daddy",'d','n');
jroseadc650a2011-02-11 01:26:28 -0800335// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jrose9b82ad62011-05-26 17:37:36 -0700336assertEquals(s, "nanny");
jrosef108fc02011-02-11 01:26:24 -0800337// weakly typed invocation (using MHs.invoke)
338s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jrose9b82ad62011-05-26 17:37:36 -0700339assertEquals(s, "savvy");
jrosef108fc02011-02-11 01:26:24 -0800340// mt is (Object[])List
341mt = MethodType.methodType(java.util.List.class, Object[].class);
342mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
343assert(mh.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700344x = mh.invoke("one", "two");
345// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700346assertEquals(x, java.util.Arrays.asList("one","two"));
jrosef108fc02011-02-11 01:26:24 -0800347// mt is (Object,Object,Object)Object
348mt = MethodType.genericMethodType(3);
jroseadc650a2011-02-11 01:26:28 -0800349mh = mh.asType(mt);
jrosef108fc02011-02-11 01:26:24 -0800350x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jroseadc650a2011-02-11 01:26:28 -0800351// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700352assertEquals(x, java.util.Arrays.asList(1,2,3));
353// mt is ()int
jrosef108fc02011-02-11 01:26:24 -0800354mt = MethodType.methodType(int.class);
355mh = lookup.findVirtual(java.util.List.class, "size", mt);
jrosef108fc02011-02-11 01:26:24 -0800356i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jroseadc650a2011-02-11 01:26:28 -0800357// invokeExact(Ljava/util/List;)I
jrosef108fc02011-02-11 01:26:24 -0800358assert(i == 3);
359mt = MethodType.methodType(void.class, String.class);
360mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
361mh.invokeExact(System.out, "Hello, world.");
jroseadc650a2011-02-11 01:26:28 -0800362// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jrosef108fc02011-02-11 01:26:24 -0800363{}
jrose900bafd2010-10-30 21:08:23 -0700364 }}
365 }
366
jrose9b82ad62011-05-26 17:37:36 -0700367 @Test public void testAsSpreader() throws Throwable {
368 {{
369{} /// JAVADOC
370MethodHandle equals = publicLookup()
371 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
372assert( (boolean) equals.invokeExact("me", (Object)"me"));
373assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
374// spread both arguments from a 2-array:
375MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
376assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
377assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
jrose70feaa92013-10-05 05:30:39 -0700378// try to spread from anything but a 2-array:
379for (int n = 0; n <= 10; n++) {
380 Object[] badArityArgs = (n == 2 ? null : new Object[n]);
381 try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
382 catch (IllegalArgumentException ex) { } // OK
383}
jrose9b82ad62011-05-26 17:37:36 -0700384// spread both arguments from a String array:
385MethodHandle eq2s = equals.asSpreader(String[].class, 2);
386assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
387assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
388// spread second arguments from a 1-array:
389MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
390assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
391assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
392// spread no arguments from a 0-array or null:
393MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
394assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
395assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
396// asSpreader and asCollector are approximate inverses:
397for (int n = 0; n <= 2; n++) {
398 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
399 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
400 assert( (boolean) equals2.invokeWithArguments("me", "me"));
401 assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
402 }
403}
404MethodHandle caToString = publicLookup()
405 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
406assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
407MethodHandle caString3 = caToString.asCollector(char[].class, 3);
408assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
409MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
410assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
411 }}
412 }
413
414 @Test public void testAsCollector() throws Throwable {
415 {{
416{} /// JAVADOC
417MethodHandle deepToString = publicLookup()
418 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
419assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"}));
420MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
421assertEquals(methodType(String.class, Object.class), ts1.type());
422//assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL
423assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
424// arrayType can be a subtype of Object[]
425MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
426assertEquals(methodType(String.class, String.class, String.class), ts2.type());
427assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
428MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
429assertEquals("[]", (String) ts0.invokeExact());
430// collectors can be nested, Lisp-style
431MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
432assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
433// arrayType can be any primitive array type
434MethodHandle bytesToString = publicLookup()
435 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
436 .asCollector(byte[].class, 3);
437assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
438MethodHandle longsToString = publicLookup()
439 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
440 .asCollector(long[].class, 1);
441assertEquals("[123]", (String) longsToString.invokeExact((long)123));
442 }}
443 }
444
jrose49494522012-01-18 17:34:29 -0800445 @SuppressWarnings("rawtypes")
jrosef108fc02011-02-11 01:26:24 -0800446 @Test public void testAsVarargsCollector() throws Throwable {
447 {{
448{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700449MethodHandle deepToString = publicLookup()
450 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
451MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
452assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"}));
453assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"}));
454assertEquals("[won]", (String) ts1.invoke( "won" ));
455assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
456// findStatic of Arrays.asList(...) produces a variable arity method handle:
jrosef108fc02011-02-11 01:26:24 -0800457MethodHandle asList = publicLookup()
jrose9b82ad62011-05-26 17:37:36 -0700458 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
459assertEquals(methodType(List.class, Object[].class), asList.type());
460assert(asList.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700461assertEquals("[]", asList.invoke().toString());
462assertEquals("[1]", asList.invoke(1).toString());
463assertEquals("[two, too]", asList.invoke("two", "too").toString());
jrose9b82ad62011-05-26 17:37:36 -0700464String[] argv = { "three", "thee", "tee" };
jrose79e0a6c2011-05-12 19:27:33 -0700465assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jrose9b82ad62011-05-26 17:37:36 -0700466assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jrose79e0a6c2011-05-12 19:27:33 -0700467List ls = (List) asList.invoke((Object)argv);
jrosef108fc02011-02-11 01:26:24 -0800468assertEquals(1, ls.size());
469assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
470 }}
471 }
jrose900bafd2010-10-30 21:08:23 -0700472
jrose9b82ad62011-05-26 17:37:36 -0700473 @Test public void testAsFixedArity() throws Throwable {
jrosef108fc02011-02-11 01:26:24 -0800474 {{
475{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700476MethodHandle asListVar = publicLookup()
jrosef108fc02011-02-11 01:26:24 -0800477 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
478 .asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -0700479MethodHandle asListFix = asListVar.asFixedArity();
480assertEquals("[1]", asListVar.invoke(1).toString());
481Exception caught = null;
482try { asListFix.invoke((Object)1); }
483catch (Exception ex) { caught = ex; }
484assert(caught instanceof ClassCastException);
485assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
486try { asListFix.invoke("two", "too"); }
487catch (Exception ex) { caught = ex; }
488assert(caught instanceof WrongMethodTypeException);
489Object[] argv = { "three", "thee", "tee" };
490assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
491assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
492assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
493assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
494 }}
495 }
496
497 @Test public void testAsTypeCornerCases() throws Throwable {
498 {{
499{} /// JAVADOC
500MethodHandle i2s = publicLookup()
501 .findVirtual(Integer.class, "toString", methodType(String.class));
502i2s = i2s.asType(i2s.type().unwrap());
503MethodHandle l2s = publicLookup()
504 .findVirtual(Long.class, "toString", methodType(String.class));
505l2s = l2s.asType(l2s.type().unwrap());
506
507Exception caught = null;
508try { i2s.asType(methodType(String.class, String.class)); }
509catch (Exception ex) { caught = ex; }
510assert(caught instanceof WrongMethodTypeException);
511
512i2s.asType(methodType(String.class, byte.class));
513i2s.asType(methodType(String.class, Byte.class));
514i2s.asType(methodType(String.class, Character.class));
515i2s.asType(methodType(String.class, Integer.class));
516l2s.asType(methodType(String.class, byte.class));
517l2s.asType(methodType(String.class, Byte.class));
518l2s.asType(methodType(String.class, Character.class));
519l2s.asType(methodType(String.class, Integer.class));
520l2s.asType(methodType(String.class, Long.class));
521
522caught = null;
523try { i2s.asType(methodType(String.class, Long.class)); }
524catch (Exception ex) { caught = ex; }
525assert(caught instanceof WrongMethodTypeException);
526
527MethodHandle i2sGen = i2s.asType(methodType(String.class, Object.class));
528MethodHandle l2sGen = l2s.asType(methodType(String.class, Object.class));
529
530i2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
531i2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
532l2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
533l2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
534l2sGen.invoke(0x420000000L);
535
536caught = null;
537try { i2sGen.invoke(0x420000000L); } // long -> Long -> Object -> Integer CCE
538catch (Exception ex) { caught = ex; }
539assert(caught instanceof ClassCastException);
540
541caught = null;
542try { i2sGen.invoke("asdf"); } // String -> Object -> Integer CCE
543catch (Exception ex) { caught = ex; }
544assert(caught instanceof ClassCastException);
jrosef108fc02011-02-11 01:26:24 -0800545{}
546 }}
547 }
jrose9b82ad62011-05-26 17:37:36 -0700548
549 @Test public void testMutableCallSite() throws Throwable {
550 {{
551{} /// JAVADOC
552MutableCallSite name = new MutableCallSite(MethodType.methodType(String.class));
553MethodHandle MH_name = name.dynamicInvoker();
554MethodType MT_str1 = MethodType.methodType(String.class);
555MethodHandle MH_upcase = MethodHandles.lookup()
556 .findVirtual(String.class, "toUpperCase", MT_str1);
557MethodHandle worker1 = MethodHandles.filterReturnValue(MH_name, MH_upcase);
558name.setTarget(MethodHandles.constant(String.class, "Rocky"));
559assertEquals("ROCKY", (String) worker1.invokeExact());
560name.setTarget(MethodHandles.constant(String.class, "Fred"));
561assertEquals("FRED", (String) worker1.invokeExact());
562// (mutation can be continued indefinitely)
563/*
564 * </pre></blockquote>
565 * <p>
566 * The same call site may be used in several places at once.
567 * <blockquote><pre>
568 */
569MethodType MT_str2 = MethodType.methodType(String.class, String.class);
570MethodHandle MH_cat = lookup().findVirtual(String.class,
571 "concat", methodType(String.class, String.class));
572MethodHandle MH_dear = MethodHandles.insertArguments(MH_cat, 1, ", dear?");
573MethodHandle worker2 = MethodHandles.filterReturnValue(MH_name, MH_dear);
574assertEquals("Fred, dear?", (String) worker2.invokeExact());
575name.setTarget(MethodHandles.constant(String.class, "Wilma"));
576assertEquals("WILMA", (String) worker1.invokeExact());
577assertEquals("Wilma, dear?", (String) worker2.invokeExact());
578{}
579 }}
580 }
581
582 @Test public void testSwitchPoint() throws Throwable {
583 {{
584{} /// JAVADOC
585MethodHandle MH_strcat = MethodHandles.lookup()
586 .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class));
587SwitchPoint spt = new SwitchPoint();
jrosecd1d97b2011-06-03 11:20:20 -0700588assert(!spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700589// the following steps may be repeated to re-use the same switch point:
590MethodHandle worker1 = MH_strcat;
591MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0);
592MethodHandle worker = spt.guardWithTest(worker1, worker2);
593assertEquals("method", (String) worker.invokeExact("met", "hod"));
594SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
jrosecd1d97b2011-06-03 11:20:20 -0700595assert(spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700596assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
597{}
598 }}
599 }
600
jroseb4be0262011-07-16 15:44:33 -0700601 @Test public void testFoldArguments2() throws Throwable {
602 {{
603{} /// JAVADOC
604// argument-based dispatch for methods of the form boolean x.___(y: String)
605Lookup lookup = publicLookup();
606// first, a tracing hack:
607MethodHandle println = lookup.findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class));
608MethodHandle arrayToString = lookup.findStatic(Arrays.class, "toString", methodType(String.class, Object[].class));
609MethodHandle concat = lookup.findVirtual(String.class, "concat", methodType(String.class, String.class));
610MethodHandle arrayToString_DIS = filterReturnValue(arrayToString, concat.bindTo("DIS:"));
611MethodHandle arrayToString_INV = filterReturnValue(arrayToString, concat.bindTo("INV:"));
612MethodHandle printArgs_DIS = filterReturnValue(arrayToString_DIS, println.bindTo(System.out)).asVarargsCollector(Object[].class);
613MethodHandle printArgs_INV = filterReturnValue(arrayToString_INV, println.bindTo(System.out)).asVarargsCollector(Object[].class);
614// metaobject protocol:
615MethodType mtype = methodType(boolean.class, String.class);
616MethodHandle findVirtual = lookup.findVirtual(Lookup.class,
617 "findVirtual", methodType(MethodHandle.class, Class.class, String.class, MethodType.class));
618MethodHandle getClass = lookup.findVirtual(Object.class,
619 "getClass", methodType(Class.class));
620MethodHandle dispatch = findVirtual;
621dispatch = filterArguments(dispatch, 1, getClass);
622dispatch = insertArguments(dispatch, 3, mtype);
623dispatch = dispatch.bindTo(lookup);
624assertEquals(methodType(MethodHandle.class, Object.class, String.class), dispatch.type());
625MethodHandle invoker = invoker(mtype.insertParameterTypes(0, Object.class));
626// wrap tracing around the dispatch and invoke steps:
627dispatch = foldArguments(dispatch, printArgs_DIS.asType(dispatch.type().changeReturnType(void.class)));
628invoker = foldArguments(invoker, printArgs_INV.asType(invoker.type().changeReturnType(void.class)));
629invoker = dropArguments(invoker, 2, String.class); // ignore selector
630// compose the dispatcher and the invoker:
631MethodHandle invokeDispatched = foldArguments(invoker, dispatch);
632Object x = "football", y = new java.util.Scanner("bar");
633assert( (boolean) invokeDispatched.invokeExact(x, "startsWith", "foo"));
634assert(!(boolean) invokeDispatched.invokeExact(x, "startsWith", "#"));
635assert( (boolean) invokeDispatched.invokeExact(x, "endsWith", "all"));
636assert(!(boolean) invokeDispatched.invokeExact(x, "endsWith", "foo"));
637assert( (boolean) invokeDispatched.invokeExact(y, "hasNext", "[abc]+[rst]"));
638assert(!(boolean) invokeDispatched.invokeExact(y, "hasNext", "[123]+[789]"));
639 }}
640 }
641
jrose9b82ad62011-05-26 17:37:36 -0700642 /* ---- TEMPLATE ----
643 @Test public void testFoo() throws Throwable {
644 {{
645{} /// JAVADOC
646{}
647 }}
648 }
649 */
jrose900bafd2010-10-30 21:08:23 -0700650}