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