1 /*
2 * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
3 * 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.
8 *
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
25 * @summary example code used in javadoc for java.lang.invoke API
26 * @compile JavaDocExamplesTest.java
27 * @run testng/othervm test.java.lang.invoke.JavaDocExamplesTest
28 */
29
30 package test.java.lang.invoke;
31
32 import java.io.StringWriter;
33 import java.lang.invoke.*;
34 import static java.lang.invoke.MethodHandles.*;
35 import static java.lang.invoke.MethodType.*;
36
37 import java.util.*;
38
39 import org.testng.*;
40 import org.testng.annotations.*;
41
42 /**
43 * @author jrose
44 */
45 public class JavaDocExamplesTest {
46 /** Wrapper for running the TestNG tests in this module.
47 * Put TestNG on the classpath!
48 */
main(String... ignore)49 public static void main(String... ignore) throws Throwable {
50 new JavaDocExamplesTest().run();
51 }
52
run()53 public void run() throws Throwable {
54 // Android-removed: not used.
55 /*
56 testMisc();
57 testFindStatic();
58 testFindConstructor();
59 testFindVirtual();
60 testFindSpecial();
61 testPermuteArguments();
62 testZero();
63 testDropArguments();
64 testDropArgumentsToMatch();
65 testFilterArguments();
66 testFoldArguments();
67 testFoldArguments2();
68 testMethodHandlesSummary();
69 testAsSpreader();
70 testAsCollector();
71 testAsVarargsCollector();
72 testAsFixedArity();
73 testAsTypeCornerCases();
74 testMutableCallSite();
75 */
76 }
77 // How much output?
78 static final Class<?> THIS_CLASS = JavaDocExamplesTest.class;
79 static int verbosity = Integer.getInteger(THIS_CLASS.getSimpleName()+".verbosity", 0);
80
81
82 {}
83 private static final Lookup LOOKUP = lookup();
84 // static final private MethodHandle CONCAT_1 = LOOKUP.findVirtual(String.class,
85 // "concat", methodType(String.class, String.class));
86 // static final private MethodHandle HASHCODE_1 = LOOKUP.findVirtual(Object.class,
87 // "hashCode", methodType(int.class));
88
89 // form required if ReflectiveOperationException is intercepted:
90 private static final MethodHandle CONCAT_2, HASHCODE_2, ADD_2, SUB_2;
91 static {
92 try {
93 Class<?> THIS_CLASS = LOOKUP.lookupClass();
94 CONCAT_2 = LOOKUP.findVirtual(String.class,
95 "concat", methodType(String.class, String.class));
96 HASHCODE_2 = LOOKUP.findVirtual(Object.class,
97 "hashCode", methodType(int.class));
98 ADD_2 = LOOKUP.findStatic(THIS_CLASS, "add", methodType(int.class, int.class, int.class));
99 SUB_2 = LOOKUP.findStatic(THIS_CLASS, "sub", methodType(int.class, int.class, int.class));
100 } catch (ReflectiveOperationException ex) {
101 throw new RuntimeException(ex);
102 }
103 }
add(int x, int y)104 static int add(int x, int y) { return x + y; }
sub(int x, int y)105 static int sub(int x, int y) { return x - y; }
106
107 {}
108
testMisc()109 @Test public void testMisc() throws Throwable {
110 // Extra tests, not from javadoc:
111 {}
112 MethodHandle CONCAT_3 = LOOKUP.findVirtual(String.class,
113 "concat", methodType(String.class, String.class));
114 MethodHandle HASHCODE_3 = LOOKUP.findVirtual(Object.class,
115 "hashCode", methodType(int.class));
116 //assertEquals("xy", (String) CONCAT_1.invokeExact("x", "y"));
117 assertEquals("xy", (String) CONCAT_2.invokeExact("x", "y"));
118 assertEquals("xy", (String) CONCAT_3.invokeExact("x", "y"));
119 //assertEquals("xy".hashCode(), (int) HASHCODE_1.invokeExact((Object)"xy"));
120 assertEquals("xy".hashCode(), (int) HASHCODE_2.invokeExact((Object)"xy"));
121 assertEquals("xy".hashCode(), (int) HASHCODE_3.invokeExact((Object)"xy"));
122 {}
123 }
124
testFindStatic()125 @Test public void testFindStatic() throws Throwable {
126 {}
127 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
128 "asList", methodType(List.class, Object[].class));
129 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
130 {}
131 }
132
testFindVirtual()133 @Test public void testFindVirtual() throws Throwable {
134 {}
135 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
136 "concat", methodType(String.class, String.class));
137 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
138 "hashCode", methodType(int.class));
139 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
140 "hashCode", methodType(int.class));
141 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
142 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
143 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
144 // interface method:
145 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
146 "subSequence", methodType(CharSequence.class, int.class, int.class));
147 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
148 // constructor "internal method" must be accessed differently:
149 MethodType MT_newString = methodType(void.class); //()V for new String()
150 try { assertEquals("impossible", lookup()
151 .findVirtual(String.class, "<init>", MT_newString));
152 } catch (NoSuchMethodException ex) { } // OK
153 MethodHandle MH_newString = publicLookup()
154 .findConstructor(String.class, MT_newString);
155 assertEquals("", (String) MH_newString.invokeExact());
156 {}
157 }
158
testFindConstructor()159 @Test public void testFindConstructor() throws Throwable {
160 {}
161 MethodHandle MH_newArrayList = publicLookup().findConstructor(
162 ArrayList.class, methodType(void.class, Collection.class));
163 Collection orig = Arrays.asList("x", "y");
164 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
165 assert(orig != copy);
166 assertEquals(orig, copy);
167 // a variable-arity constructor:
168 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
169 ProcessBuilder.class, methodType(void.class, String[].class));
170 ProcessBuilder pb = (ProcessBuilder)
171 MH_newProcessBuilder.invoke("x", "y", "z");
172 assertEquals("[x, y, z]", pb.command().toString());
173 {}
174 }
175
176 // for testFindSpecial
177 {}
178 static class Listie extends ArrayList {
toString()179 public String toString() { return "[wee Listie]"; }
lookup()180 static Lookup lookup() { return MethodHandles.lookup(); }
181 }
182 {}
183
184 // Android-removed: test fails, needs investigating (b/207844518).
185 /*
186 @Test public void testFindSpecial() throws Throwable {
187 {}
188 // no access to constructor via invokeSpecial:
189 MethodHandle MH_newListie = Listie.lookup()
190 .findConstructor(Listie.class, methodType(void.class));
191 Listie l = (Listie) MH_newListie.invokeExact();
192 try { assertEquals("impossible", Listie.lookup().findSpecial(
193 Listie.class, "<init>", methodType(void.class), Listie.class));
194 } catch (NoSuchMethodException ex) { } // OK
195 // access to super and self methods via invokeSpecial:
196 MethodHandle MH_super = Listie.lookup().findSpecial(
197 ArrayList.class, "toString" , methodType(String.class), Listie.class);
198 MethodHandle MH_this = Listie.lookup().findSpecial(
199 Listie.class, "toString" , methodType(String.class), Listie.class);
200 MethodHandle MH_duper = Listie.lookup().findSpecial(
201 Object.class, "toString" , methodType(String.class), Listie.class);
202 assertEquals("[]", (String) MH_super.invokeExact(l));
203 assertEquals(""+l, (String) MH_this.invokeExact(l));
204 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
205 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
206 String.class, "toString", methodType(String.class), Listie.class));
207 } catch (IllegalAccessException ex) { } // OK
208 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
209 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
210 {}
211 }
212 */
213
testPermuteArguments()214 @Test public void testPermuteArguments() throws Throwable {
215 {{
216 {} /// JAVADOC
217 MethodType intfn1 = methodType(int.class, int.class);
218 MethodType intfn2 = methodType(int.class, int.class, int.class);
219 MethodHandle sub = SUB_2;// ... {int x, int y => x-y} ...;
220 assert(sub.type().equals(intfn2));
221 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
222 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
223 assert((int)rsub.invokeExact(1, 100) == 99);
224 MethodHandle add = ADD_2;// ... {int x, int y => x+y} ...;
225 assert(add.type().equals(intfn2));
226 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
227 assert(twice.type().equals(intfn1));
228 assert((int)twice.invokeExact(21) == 42);
229 }}
230 {{
231 {} /// JAVADOC
232 MethodHandle cat = lookup().findVirtual(String.class,
233 "concat", methodType(String.class, String.class));
234 assertEquals("xy", (String) cat.invokeExact("x", "y"));
235 MethodHandle d0 = dropArguments(cat, 0, String.class);
236 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
237 MethodHandle d1 = dropArguments(cat, 1, String.class);
238 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
239 MethodHandle d2 = dropArguments(cat, 2, String.class);
240 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
241 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
242 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
243 }}
244 }
245
testZero()246 @Test public void testZero() throws Throwable {
247 {{
248 {} /// JAVADOC
249 Class<?> type = Double.class;
250 MethodHandle mh1 = MethodHandles.explicitCastArguments(MethodHandles.constant(Object.class, null), methodType(type));
251 assertEquals("()Double", mh1.type().toString());
252 MethodHandle mh2 = MethodHandles.empty(methodType(type));
253 assertEquals("()Double", mh2.type().toString());
254 }}
255 }
256
testDropArguments()257 @Test public void testDropArguments() throws Throwable {
258 {{
259 {} /// JAVADOC
260 MethodHandle cat = lookup().findVirtual(String.class,
261 "concat", methodType(String.class, String.class));
262 assertEquals("xy", (String) cat.invokeExact("x", "y"));
263 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
264 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
265 assertEquals(bigType, d0.type());
266 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
267 }}
268 {{
269 {} /// JAVADOC
270 MethodHandle cat = lookup().findVirtual(String.class,
271 "concat", methodType(String.class, String.class));
272 assertEquals("xy", (String) cat.invokeExact("x", "y"));
273 MethodHandle d0 = dropArguments(cat, 0, String.class);
274 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
275 MethodHandle d1 = dropArguments(cat, 1, String.class);
276 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
277 MethodHandle d2 = dropArguments(cat, 2, String.class);
278 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
279 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
280 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
281 }}
282 }
283
testDropArgumentsToMatch()284 @Test public void testDropArgumentsToMatch() throws Throwable {
285 {{
286 {} /// JAVADOC
287 MethodHandle h0= constant(boolean.class, true);
288 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
289 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
290 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
291 if (h1.type().parameterCount() < h2.type().parameterCount()) {
292 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1
293 }
294 else {
295 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2
296 }
297 MethodHandle h3 = guardWithTest(h0, h1, h2);
298 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
299 }}
300 }
301
testFilterArguments()302 @Test public void testFilterArguments() throws Throwable {
303 {{
304 {} /// JAVADOC
305 MethodHandle cat = lookup().findVirtual(String.class,
306 "concat", methodType(String.class, String.class));
307 MethodHandle upcase = lookup().findVirtual(String.class,
308 "toUpperCase", methodType(String.class));
309 assertEquals("xy", (String) cat.invokeExact("x", "y"));
310 MethodHandle f0 = filterArguments(cat, 0, upcase);
311 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
312 MethodHandle f1 = filterArguments(cat, 1, upcase);
313 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
314 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
315 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
316 }}
317 }
318
testCollectArguments()319 @Test public void testCollectArguments() throws Throwable {
320 {{
321 {} /// JAVADOC
322 MethodHandle deepToString = publicLookup()
323 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
324 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
325 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
326 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
327 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
328 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
329 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
330 assertEquals("[top, [up, down], strange]",
331 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
332 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
333 assertEquals("[top, [up, down], [strange]]",
334 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
335 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
336 assertEquals("[top, [[up, down, strange], charm], bottom]",
337 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
338 }}
339 }
340
testFoldArguments()341 @Test public void testFoldArguments() throws Throwable {
342 {{
343 {} /// JAVADOC
344 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
345 "println", methodType(void.class, String.class))
346 .bindTo(System.out);
347 MethodHandle cat = lookup().findVirtual(String.class,
348 "concat", methodType(String.class, String.class));
349 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
350 MethodHandle catTrace = foldArguments(cat, trace);
351 // also prints "boo":
352 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
353 }}
354 }
355
assertEquals(Object exp, Object act)356 static void assertEquals(Object exp, Object act) {
357 if (verbosity > 0)
358 System.out.println("result: "+act);
359 Assert.assertEquals(exp, act);
360 }
361
assertTrue(boolean b)362 static void assertTrue(boolean b) {
363 if (verbosity > 0) {
364 System.out.println("result: " + b);
365 }
366 Assert.assertTrue(b);
367 }
368
testMethodHandlesSummary()369 @Test public void testMethodHandlesSummary() throws Throwable {
370 {{
371 {} /// JAVADOC
372 Object x, y; String s; int i;
373 MethodType mt; MethodHandle mh;
374 MethodHandles.Lookup lookup = MethodHandles.lookup();
375 // mt is (char,char)String
376 mt = MethodType.methodType(String.class, char.class, char.class);
377 mh = lookup.findVirtual(String.class, "replace", mt);
378 s = (String) mh.invokeExact("daddy",'d','n');
379 // invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
380 assertEquals(s, "nanny");
381 // weakly typed invocation (using MHs.invoke)
382 s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
383 assertEquals(s, "savvy");
384 // mt is (Object[])List
385 mt = MethodType.methodType(java.util.List.class, Object[].class);
386 mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
387 assert(mh.isVarargsCollector());
388 x = mh.invoke("one", "two");
389 // invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
390 assertEquals(x, java.util.Arrays.asList("one","two"));
391 // mt is (Object,Object,Object)Object
392 mt = MethodType.genericMethodType(3);
393 mh = mh.asType(mt);
394 x = mh.invokeExact((Object)1, (Object)2, (Object)3);
395 // invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
396 assertEquals(x, java.util.Arrays.asList(1,2,3));
397 // mt is ()int
398 mt = MethodType.methodType(int.class);
399 mh = lookup.findVirtual(java.util.List.class, "size", mt);
400 i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
401 // invokeExact(Ljava/util/List;)I
402 assert(i == 3);
403 mt = MethodType.methodType(void.class, String.class);
404 mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
405 mh.invokeExact(System.out, "Hello, world.");
406 // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
407 {}
408 }}
409 }
410
testAsSpreader()411 @Test public void testAsSpreader() throws Throwable {
412 {{
413 {} /// JAVADOC
414 MethodHandle equals = publicLookup()
415 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
416 assert( (boolean) equals.invokeExact("me", (Object)"me"));
417 assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
418 // spread both arguments from a 2-array:
419 MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
420 assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
421 assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
422 // try to spread from anything but a 2-array:
423 for (int n = 0; n <= 10; n++) {
424 Object[] badArityArgs = (n == 2 ? new Object[0] : new Object[n]);
425 try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
426 catch (IllegalArgumentException ex) { } // OK
427 }
428 // spread both arguments from a String array:
429 MethodHandle eq2s = equals.asSpreader(String[].class, 2);
430 assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
431 assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
432 // spread second arguments from a 1-array:
433 MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
434 assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
435 assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
436 // spread no arguments from a 0-array or null:
437 MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
438 assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
439 assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
440 // asSpreader and asCollector are approximate inverses:
441 for (int n = 0; n <= 2; n++) {
442 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
443 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
444 assert( (boolean) equals2.invokeWithArguments("me", "me"));
445 assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
446 }
447 }
448 MethodHandle caToString = publicLookup()
449 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
450 assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
451 MethodHandle caString3 = caToString.asCollector(char[].class, 3);
452 assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
453 MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
454 assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
455 }}
456 }
457
testAsCollector()458 @Test public void testAsCollector() throws Throwable {
459 {{
460 {} /// JAVADOC
461 MethodHandle deepToString = publicLookup()
462 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
463 assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"}));
464 MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
465 assertEquals(methodType(String.class, Object.class), ts1.type());
466 //assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL
467 assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
468 // arrayType can be a subtype of Object[]
469 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
470 assertEquals(methodType(String.class, String.class, String.class), ts2.type());
471 assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
472 MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
473 assertEquals("[]", (String) ts0.invokeExact());
474 // collectors can be nested, Lisp-style
475 MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
476 assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
477 // arrayType can be any primitive array type
478 MethodHandle bytesToString = publicLookup()
479 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
480 .asCollector(byte[].class, 3);
481 assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
482 MethodHandle longsToString = publicLookup()
483 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
484 .asCollector(long[].class, 1);
485 assertEquals("[123]", (String) longsToString.invokeExact((long)123));
486 }}
487 }
488
489 @SuppressWarnings("rawtypes")
testAsVarargsCollector()490 @Test public void testAsVarargsCollector() throws Throwable {
491 {{
492 {} /// JAVADOC
493 MethodHandle deepToString = publicLookup()
494 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
495 MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
496 assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"}));
497 assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"}));
498 assertEquals("[won]", (String) ts1.invoke( "won" ));
499 assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
500 // findStatic of Arrays.asList(...) produces a variable arity method handle:
501 MethodHandle asList = publicLookup()
502 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
503 assertEquals(methodType(List.class, Object[].class), asList.type());
504 assert(asList.isVarargsCollector());
505 assertEquals("[]", asList.invoke().toString());
506 assertEquals("[1]", asList.invoke(1).toString());
507 assertEquals("[two, too]", asList.invoke("two", "too").toString());
508 String[] argv = { "three", "thee", "tee" };
509 assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
510 assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
511 List ls = (List) asList.invoke((Object)argv);
512 assertEquals(1, ls.size());
513 assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
514 }}
515 }
516
testAsFixedArity()517 @Test public void testAsFixedArity() throws Throwable {
518 {{
519 {} /// JAVADOC
520 MethodHandle asListVar = publicLookup()
521 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
522 .asVarargsCollector(Object[].class);
523 MethodHandle asListFix = asListVar.asFixedArity();
524 assertEquals("[1]", asListVar.invoke(1).toString());
525 Exception caught = null;
526 try { asListFix.invoke((Object)1); }
527 catch (Exception ex) { caught = ex; }
528 assert(caught instanceof ClassCastException);
529 assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
530 try { asListFix.invoke("two", "too"); }
531 catch (Exception ex) { caught = ex; }
532 assert(caught instanceof WrongMethodTypeException);
533 Object[] argv = { "three", "thee", "tee" };
534 assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
535 assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
536 assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
537 assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
538 }}
539 }
540
testAsTypeCornerCases()541 @Test public void testAsTypeCornerCases() throws Throwable {
542 {{
543 {} /// JAVADOC
544 MethodHandle i2s = publicLookup()
545 .findVirtual(Integer.class, "toString", methodType(String.class));
546 i2s = i2s.asType(i2s.type().unwrap());
547 MethodHandle l2s = publicLookup()
548 .findVirtual(Long.class, "toString", methodType(String.class));
549 l2s = l2s.asType(l2s.type().unwrap());
550
551 Exception caught = null;
552 try { i2s.asType(methodType(String.class, String.class)); }
553 catch (Exception ex) { caught = ex; }
554 assert(caught instanceof WrongMethodTypeException);
555
556 i2s.asType(methodType(String.class, byte.class));
557 i2s.asType(methodType(String.class, Byte.class));
558 i2s.asType(methodType(String.class, Character.class));
559 i2s.asType(methodType(String.class, Integer.class));
560 l2s.asType(methodType(String.class, byte.class));
561 l2s.asType(methodType(String.class, Byte.class));
562 l2s.asType(methodType(String.class, Character.class));
563 l2s.asType(methodType(String.class, Integer.class));
564 l2s.asType(methodType(String.class, Long.class));
565
566 caught = null;
567 try { i2s.asType(methodType(String.class, Long.class)); }
568 catch (Exception ex) { caught = ex; }
569 assert(caught instanceof WrongMethodTypeException);
570
571 MethodHandle i2sGen = i2s.asType(methodType(String.class, Object.class));
572 MethodHandle l2sGen = l2s.asType(methodType(String.class, Object.class));
573
574 i2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
575 i2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
576 l2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
577 l2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
578 l2sGen.invoke(0x420000000L);
579
580 caught = null;
581 try { i2sGen.invoke(0x420000000L); } // long -> Long -> Object -> Integer CCE
582 catch (Exception ex) { caught = ex; }
583 assert(caught instanceof ClassCastException);
584
585 caught = null;
586 try { i2sGen.invoke("asdf"); } // String -> Object -> Integer CCE
587 catch (Exception ex) { caught = ex; }
588 assert(caught instanceof ClassCastException);
589 {}
590 }}
591 }
592
testMutableCallSite()593 @Test public void testMutableCallSite() throws Throwable {
594 {{
595 {} /// JAVADOC
596 MutableCallSite name = new MutableCallSite(MethodType.methodType(String.class));
597 MethodHandle MH_name = name.dynamicInvoker();
598 MethodType MT_str1 = MethodType.methodType(String.class);
599 MethodHandle MH_upcase = MethodHandles.lookup()
600 .findVirtual(String.class, "toUpperCase", MT_str1);
601 MethodHandle worker1 = MethodHandles.filterReturnValue(MH_name, MH_upcase);
602 name.setTarget(MethodHandles.constant(String.class, "Rocky"));
603 assertEquals("ROCKY", (String) worker1.invokeExact());
604 name.setTarget(MethodHandles.constant(String.class, "Fred"));
605 assertEquals("FRED", (String) worker1.invokeExact());
606 // (mutation can be continued indefinitely)
607 /*
608 * </pre></blockquote>
609 * <p>
610 * The same call site may be used in several places at once.
611 * <blockquote><pre>
612 */
613 MethodType MT_str2 = MethodType.methodType(String.class, String.class);
614 MethodHandle MH_cat = lookup().findVirtual(String.class,
615 "concat", methodType(String.class, String.class));
616 MethodHandle MH_dear = MethodHandles.insertArguments(MH_cat, 1, ", dear?");
617 MethodHandle worker2 = MethodHandles.filterReturnValue(MH_name, MH_dear);
618 assertEquals("Fred, dear?", (String) worker2.invokeExact());
619 name.setTarget(MethodHandles.constant(String.class, "Wilma"));
620 assertEquals("WILMA", (String) worker1.invokeExact());
621 assertEquals("Wilma, dear?", (String) worker2.invokeExact());
622 {}
623 }}
624 }
625
626 // Android-removed: SwitchPoint not supported.
627 /*
628 @Test public void testSwitchPoint() throws Throwable {
629 {{
630 {} /// JAVADOC
631 MethodHandle MH_strcat = MethodHandles.lookup()
632 .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class));
633 SwitchPoint spt = new SwitchPoint();
634 assert(!spt.hasBeenInvalidated());
635 // the following steps may be repeated to re-use the same switch point:
636 MethodHandle worker1 = MH_strcat;
637 MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0);
638 MethodHandle worker = spt.guardWithTest(worker1, worker2);
639 assertEquals("method", (String) worker.invokeExact("met", "hod"));
640 SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
641 assert(spt.hasBeenInvalidated());
642 assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
643 {}
644 }}
645 }
646 */
647
testFoldArguments2()648 @Test public void testFoldArguments2() throws Throwable {
649 {{
650 {} /// JAVADOC
651 // argument-based dispatch for methods of the form boolean x.___(y: String)
652 Lookup lookup = publicLookup();
653 // first, a tracing hack:
654 MethodHandle println = lookup.findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class));
655 MethodHandle arrayToString = lookup.findStatic(Arrays.class, "toString", methodType(String.class, Object[].class));
656 MethodHandle concat = lookup.findVirtual(String.class, "concat", methodType(String.class, String.class));
657 MethodHandle arrayToString_DIS = filterReturnValue(arrayToString, concat.bindTo("DIS:"));
658 MethodHandle arrayToString_INV = filterReturnValue(arrayToString, concat.bindTo("INV:"));
659 MethodHandle printArgs_DIS = filterReturnValue(arrayToString_DIS, println.bindTo(System.out)).asVarargsCollector(Object[].class);
660 MethodHandle printArgs_INV = filterReturnValue(arrayToString_INV, println.bindTo(System.out)).asVarargsCollector(Object[].class);
661 // metaobject protocol:
662 MethodType mtype = methodType(boolean.class, String.class);
663 MethodHandle findVirtual = lookup.findVirtual(Lookup.class,
664 "findVirtual", methodType(MethodHandle.class, Class.class, String.class, MethodType.class));
665 MethodHandle getClass = lookup.findVirtual(Object.class,
666 "getClass", methodType(Class.class));
667 MethodHandle dispatch = findVirtual;
668 dispatch = filterArguments(dispatch, 1, getClass);
669 dispatch = insertArguments(dispatch, 3, mtype);
670 dispatch = dispatch.bindTo(lookup);
671 assertEquals(methodType(MethodHandle.class, Object.class, String.class), dispatch.type());
672 MethodHandle invoker = invoker(mtype.insertParameterTypes(0, Object.class));
673 // wrap tracing around the dispatch and invoke steps:
674 dispatch = foldArguments(dispatch, printArgs_DIS.asType(dispatch.type().changeReturnType(void.class)));
675 invoker = foldArguments(invoker, printArgs_INV.asType(invoker.type().changeReturnType(void.class)));
676 invoker = dropArguments(invoker, 2, String.class); // ignore selector
677 // compose the dispatcher and the invoker:
678 MethodHandle invokeDispatched = foldArguments(invoker, dispatch);
679 Object x = "football", y = new java.util.Scanner("bar");
680 assert( (boolean) invokeDispatched.invokeExact(x, "startsWith", "foo"));
681 assert(!(boolean) invokeDispatched.invokeExact(x, "startsWith", "#"));
682 assert( (boolean) invokeDispatched.invokeExact(x, "endsWith", "all"));
683 assert(!(boolean) invokeDispatched.invokeExact(x, "endsWith", "foo"));
684 assert( (boolean) invokeDispatched.invokeExact(y, "hasNext", "[abc]+[rst]"));
685 assert(!(boolean) invokeDispatched.invokeExact(y, "hasNext", "[123]+[789]"));
686 }}
687 }
688
one(int k)689 static int one(int k) { return 1; }
inc(int i, int acc, int k)690 static int inc(int i, int acc, int k) { return i + 1; }
mult(int i, int acc, int k)691 static int mult(int i, int acc, int k) { return i * acc; }
pred(int i, int acc, int k)692 static boolean pred(int i, int acc, int k) { return i < k; }
fin(int i, int acc, int k)693 static int fin(int i, int acc, int k) { return acc; }
694
testLoop()695 @Test public void testLoop() throws Throwable {
696 MethodHandle MH_inc, MH_one, MH_mult, MH_pred, MH_fin;
697 Class<?> I = int.class;
698 MH_inc = LOOKUP.findStatic(THIS_CLASS, "inc", methodType(I, I, I, I));
699 MH_one = LOOKUP.findStatic(THIS_CLASS, "one", methodType(I, I));
700 MH_mult = LOOKUP.findStatic(THIS_CLASS, "mult", methodType(I, I, I, I));
701 MH_pred = LOOKUP.findStatic(THIS_CLASS, "pred", methodType(boolean.class, I, I, I));
702 MH_fin = LOOKUP.findStatic(THIS_CLASS, "fin", methodType(I, I, I, I));
703 {{
704 {} /// JAVADOC
705 // iterative implementation of the factorial function as a loop handle
706 // null initializer for counter, should initialize to 0
707 MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
708 MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
709 MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
710 assertEquals(120, loop.invoke(5));
711 {}
712 }}
713 }
714
inc(int i)715 static int inc(int i) { return i + 1; } // drop acc, k
mult(int i, int acc)716 static int mult(int i, int acc) { return i * acc; } //drop k
cmp(int i, int k)717 static boolean cmp(int i, int k) { return i < k; }
718
testSimplerLoop()719 @Test public void testSimplerLoop() throws Throwable {
720 MethodHandle MH_inc, MH_mult, MH_cmp;
721 Class<?> I = int.class;
722 MH_inc = LOOKUP.findStatic(THIS_CLASS, "inc", methodType(I, I));
723 MH_mult = LOOKUP.findStatic(THIS_CLASS, "mult", methodType(I, I, I));
724 MH_cmp = LOOKUP.findStatic(THIS_CLASS, "cmp", methodType(boolean.class, I, I));
725 {{
726 {} /// JAVADOC
727 // simplified implementation of the factorial function as a loop handle
728 // null initializer for counter, should initialize to 0
729 MethodHandle MH_one = MethodHandles.constant(int.class, 1);
730 MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
731 MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
732 MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
733 MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
734 MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
735 assertEquals(720, loop.invoke(6));
736 {}
737 }}
738 }
739
740 // for testFacLoop
741 {}
742 static class FacLoop {
743 final int k;
FacLoop(int k)744 FacLoop(int k) { this.k = k; }
inc(int i)745 int inc(int i) { return i + 1; }
mult(int i, int acc)746 int mult(int i, int acc) { return i * acc; }
pred(int i)747 boolean pred(int i) { return i < k; }
fin(int i, int acc)748 int fin(int i, int acc) { return acc; }
749 }
750 {}
751
752 // assume MH_inc, MH_mult, and MH_pred are handles to the above methods
testFacLoop()753 @Test public void testFacLoop() throws Throwable {
754 MethodHandle MH_FacLoop, MH_inc, MH_mult, MH_pred, MH_fin;
755 Class<?> I = int.class;
756 MH_FacLoop = LOOKUP.findConstructor(FacLoop.class, methodType(void.class, I));
757 MH_inc = LOOKUP.findVirtual(FacLoop.class, "inc", methodType(I, I));
758 MH_mult = LOOKUP.findVirtual(FacLoop.class, "mult", methodType(I, I, I));
759 MH_pred = LOOKUP.findVirtual(FacLoop.class, "pred", methodType(boolean.class, I));
760 MH_fin = LOOKUP.findVirtual(FacLoop.class, "fin", methodType(I, I, I));
761 {{
762 {} /// JAVADOC
763 // instance-based implementation of the factorial function as a loop handle
764 // null initializer for counter, should initialize to 0
765 MethodHandle MH_one = MethodHandles.constant(int.class, 1);
766 MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
767 MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
768 MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
769 MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
770 assertEquals(5040, loop.invoke(7));
771 {}
772 }}
773 }
774
initZip(Iterator<String> a, Iterator<String> b)775 static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
zipPred(List<String> zip, Iterator<String> a, Iterator<String> b)776 static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
zipStep(List<String> zip, Iterator<String> a, Iterator<String> b)777 static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
778 zip.add(a.next());
779 zip.add(b.next());
780 return zip;
781 }
782
testWhileLoop()783 @Test public void testWhileLoop() throws Throwable {
784 MethodHandle MH_initZip, MH_zipPred, MH_zipStep;
785 Class<?> IT = Iterator.class;
786 Class<?> L = List.class;
787 MH_initZip = LOOKUP.findStatic(THIS_CLASS, "initZip", methodType(L, IT, IT));
788 MH_zipPred = LOOKUP.findStatic(THIS_CLASS, "zipPred", methodType(boolean.class, L, IT, IT));
789 MH_zipStep = LOOKUP.findStatic(THIS_CLASS, "zipStep", methodType(L, L, IT, IT));
790 {{
791 {} /// JAVADOC
792 // implement the zip function for lists as a loop handle
793 MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
794 List<String> a = Arrays.asList("a", "b", "c", "d");
795 List<String> b = Arrays.asList("e", "f", "g", "h");
796 List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
797 assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
798 {}
799 }}
800 }
801
zero(int limit)802 static int zero(int limit) { return 0; }
step(int i, int limit)803 static int step(int i, int limit) { return i + 1; }
pred(int i, int limit)804 static boolean pred(int i, int limit) { return i < limit; }
805
testDoWhileLoop()806 @Test public void testDoWhileLoop() throws Throwable {
807 MethodHandle MH_zero, MH_step, MH_pred;
808 Class<?> I = int.class;
809 MH_zero = LOOKUP.findStatic(THIS_CLASS, "zero", methodType(I, I));
810 MH_step = LOOKUP.findStatic(THIS_CLASS, "step", methodType(I, I, I));
811 MH_pred = LOOKUP.findStatic(THIS_CLASS, "pred", methodType(boolean.class, I, I));
812 {{
813 {} /// JAVADOC
814 // int i = 0; while (i < limit) { ++i; } return i; => limit
815 MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
816 assertEquals(23, loop.invoke(23));
817 {}
818 }}
819 }
820
step(String v, int counter, String start_)821 static String step(String v, int counter, String start_) { return "na " + v; } //#0
step(String v, int counter )822 static String step(String v, int counter ) { return "na " + v; } //#1
step(String v, int counter, int iterations_, String pre, String start_)823 static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } //#2
step3(String v, int counter, String pre)824 static String step3(String v, int counter, String pre) { return pre + " " + v; } //#3
825
testCountedLoop()826 @Test public void testCountedLoop() throws Throwable {
827 MethodHandle MH_step;
828 Class<?> S = String.class, I = int.class;
829 // Theme:
830 MH_step = LOOKUP.findStatic(THIS_CLASS, "step", methodType(S, S, I, S));
831 {{
832 {} /// JAVADOC
833 // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
834 // => a variation on a well known theme
835 MethodHandle fit13 = MethodHandles.constant(int.class, 13);
836 MethodHandle start = MethodHandles.identity(String.class);
837 MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); // (v, i, _) -> "na " + v
838 assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
839 {}
840 }}
841 // Variation #1:
842 MH_step = LOOKUP.findStatic(THIS_CLASS, "step", methodType(S, S, I));
843 {{
844 {} /// JAVADOC
845 // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
846 // => a variation on a well known theme
847 MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
848 MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
849 MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v
850 assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
851 {}
852 assertEquals("na na Lambdaman!", loop.invoke(2, "Lambdaman!"));
853 assertEquals("Lambdaman!", loop.invoke(0, "Lambdaman!"));
854 assertEquals("Lambdaman!", loop.invoke(-1, "Lambdaman!"));
855 assertEquals("Lambdaman!", loop.invoke(Integer.MIN_VALUE, "Lambdaman!"));
856 }}
857 // Variation #2:
858 MH_step = LOOKUP.findStatic(THIS_CLASS, "step", methodType(S, S, I, I, S, S));
859 {{
860 {} /// JAVADOC
861 // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
862 // => a variation on a well known theme
863 MethodHandle count = MethodHandles.identity(int.class);
864 MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
865 MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v
866 assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
867 {}
868 }}
869 // Variation #3:
870 MH_step = LOOKUP.findStatic(THIS_CLASS, "step3", methodType(S, S, I, S));
871 {{
872 {} /// JAVADOC
873 // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
874 // => a variation on a well known theme
875 MethodType loopType = methodType(String.class, String.class, int.class, String.class);
876 MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1);
877 MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
878 MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0);
879 MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v
880 assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
881 {}
882 }}
883 }
884
reverseStep(List<String> r, String e)885 static List<String> reverseStep(List<String> r, String e) {
886 r.add(0, e);
887 return r;
888 }
newArrayList()889 static List<String> newArrayList() { return new ArrayList<>(); }
890
testIteratedLoop()891 @Test public void testIteratedLoop() throws Throwable {
892 MethodHandle MH_newArrayList, MH_reverseStep;
893 Class<?> L = List.class, S = String.class;
894 MH_newArrayList = LOOKUP.findStatic(THIS_CLASS, "newArrayList", methodType(L));
895 MH_reverseStep = LOOKUP.findStatic(THIS_CLASS, "reverseStep", methodType(L, L, S));
896 {{
897 {} /// JAVADOC
898 // reverse a list
899 MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
900 List<String> list = Arrays.asList("a", "b", "c", "d", "e");
901 List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
902 assertEquals(reversedList, (List<String>) loop.invoke(list));
903 {}
904 }}
905 }
906
testFoldArguments3()907 @Test public void testFoldArguments3() throws Throwable {
908 {{
909 {} /// JAVADOC
910 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
911 "println", methodType(void.class, String.class))
912 .bindTo(System.out);
913 MethodHandle cat = lookup().findVirtual(String.class,
914 "concat", methodType(String.class, String.class));
915 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
916 MethodHandle catTrace = foldArguments(cat, 1, trace);
917 // also prints "jum":
918 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
919 {}
920 }}
921 }
922
testAsCollector2()923 @Test public void testAsCollector2() throws Throwable {
924 {{
925 {} /// JAVADOC
926 StringWriter swr = new StringWriter();
927 MethodHandle swWrite = LOOKUP.findVirtual(StringWriter.class, "write", methodType(void.class, char[].class, int.class, int.class)).bindTo(swr);
928 MethodHandle swWrite4 = swWrite.asCollector(0, char[].class, 4);
929 swWrite4.invoke('A', 'B', 'C', 'D', 1, 2);
930 assertEquals("BC", swr.toString());
931 swWrite4.invoke('P', 'Q', 'R', 'S', 0, 4);
932 assertEquals("BCPQRS", swr.toString());
933 swWrite4.invoke('W', 'X', 'Y', 'Z', 3, 1);
934 assertEquals("BCPQRSZ", swr.toString());
935 {}
936 }}
937 }
938
testAsSpreader2()939 @Test public void testAsSpreader2() throws Throwable {
940 {{
941 {} /// JAVADOC
942 MethodHandle compare = LOOKUP.findStatic(Objects.class, "compare", methodType(int.class, Object.class, Object.class, Comparator.class));
943 MethodHandle compare2FromArray = compare.asSpreader(0, Object[].class, 2);
944 Object[] ints = new Object[]{3, 9, 7, 7};
945 Comparator<Integer> cmp = (a, b) -> a - b;
946 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 0, 2), cmp) < 0);
947 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 1, 3), cmp) > 0);
948 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 2, 4), cmp) == 0);
949 {}
950 }}
951 }
952
953 /* ---- TEMPLATE ----
954 @Test public void testFoo() throws Throwable {
955 {{
956 {} /// JAVADOC
957 {}
958 }}
959 }
960 */
961 }
962