blob: 9c10f6aa17e4ea60914570f689e0d36d7b62e703 [file] [log] [blame]
jrose900bafd2010-10-30 21:08:23 -07001/*
jrosef108fc02011-02-11 01:26:24 -08002 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
jrose900bafd2010-10-30 21:08:23 -07003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/* @test
jroseada69fa2011-03-23 23:02:31 -070027 * @summary example code used in javadoc for java.lang.invoke API
jrose9633f5f2011-04-07 22:07:06 -070028 * @compile JavaDocExamplesTest.java
29 * @run junit/othervm test.java.lang.invoke.JavaDocExamplesTest
jrose900bafd2010-10-30 21:08:23 -070030 */
31
32/*
33---- To run outside jtreg:
34$ $JAVA7X_HOME/bin/javac -cp $JUNIT4_JAR -d /tmp/Classes \
jroseada69fa2011-03-23 23:02:31 -070035 $DAVINCI/sources/jdk/test/java/lang/invoke/JavaDocExamplesTest.java
jrose900bafd2010-10-30 21:08:23 -070036$ $JAVA7X_HOME/bin/java -cp $JUNIT4_JAR:/tmp/Classes \
jrose9b82ad62011-05-26 17:37:36 -070037 -DJavaDocExamplesTest.verbosity=1 \
jroseada69fa2011-03-23 23:02:31 -070038 test.java.lang.invoke.JavaDocExamplesTest
jrose900bafd2010-10-30 21:08:23 -070039----
40*/
41
jroseada69fa2011-03-23 23:02:31 -070042package test.java.lang.invoke;
jrose900bafd2010-10-30 21:08:23 -070043
jroseada69fa2011-03-23 23:02:31 -070044import java.lang.invoke.*;
45import static java.lang.invoke.MethodHandles.*;
46import static java.lang.invoke.MethodType.*;
jrose900bafd2010-10-30 21:08:23 -070047
jrose900bafd2010-10-30 21:08:23 -070048import java.util.*;
49
50import org.junit.*;
51import static org.junit.Assert.*;
jrose900bafd2010-10-30 21:08:23 -070052
53
54/**
55 * @author jrose
56 */
jrose49494522012-01-18 17:34:29 -080057@SuppressWarnings("LocalVariableHidesMemberVariable")
jrose900bafd2010-10-30 21:08:23 -070058public class JavaDocExamplesTest {
59 /** Wrapper for running the JUnit tests in this module.
60 * Put JUnit on the classpath!
61 */
jrose9b82ad62011-05-26 17:37:36 -070062 public static void main(String... ignore) throws Throwable {
63 System.out.println("can run this as:");
64 System.out.println("$ java org.junit.runner.JUnitCore "+JavaDocExamplesTest.class.getName());
65 new JavaDocExamplesTest().run();
66 }
67 public void run() throws Throwable {
68 testFindVirtual();
69 testPermuteArguments();
70 testDropArguments();
71 testFilterArguments();
72 testFoldArguments();
jroseb4be0262011-07-16 15:44:33 -070073 testFoldArguments2();
jrose9b82ad62011-05-26 17:37:36 -070074 testMethodHandlesSummary();
75 testAsSpreader();
76 testAsCollector();
77 testAsVarargsCollector();
78 testAsFixedArity();
79 testAsTypeCornerCases();
80 testMutableCallSite();
jrose900bafd2010-10-30 21:08:23 -070081 }
82 // How much output?
jrose9b82ad62011-05-26 17:37:36 -070083 static final Class<?> THIS_CLASS = JavaDocExamplesTest.class;
84 static int verbosity = Integer.getInteger(THIS_CLASS.getSimpleName()+".verbosity", 0);
85
jrose900bafd2010-10-30 21:08:23 -070086
87{}
88static final private Lookup LOOKUP = lookup();
89// static final private MethodHandle CONCAT_1 = LOOKUP.findVirtual(String.class,
90// "concat", methodType(String.class, String.class));
91// static final private MethodHandle HASHCODE_1 = LOOKUP.findVirtual(Object.class,
92// "hashCode", methodType(int.class));
93
jrosef15905c2011-02-11 01:26:32 -080094// form required if ReflectiveOperationException is intercepted:
jrose9b82ad62011-05-26 17:37:36 -070095 static final private MethodHandle CONCAT_2, HASHCODE_2, ADD_2, SUB_2;
jrose900bafd2010-10-30 21:08:23 -070096static {
97 try {
jrose9b82ad62011-05-26 17:37:36 -070098 Class<?> THIS_CLASS = LOOKUP.lookupClass();
jrose900bafd2010-10-30 21:08:23 -070099 CONCAT_2 = LOOKUP.findVirtual(String.class,
100 "concat", methodType(String.class, String.class));
101 HASHCODE_2 = LOOKUP.findVirtual(Object.class,
102 "hashCode", methodType(int.class));
jrose9b82ad62011-05-26 17:37:36 -0700103 ADD_2 = LOOKUP.findStatic(THIS_CLASS, "add", methodType(int.class, int.class, int.class));
104 SUB_2 = LOOKUP.findStatic(THIS_CLASS, "sub", methodType(int.class, int.class, int.class));
jrosef15905c2011-02-11 01:26:32 -0800105 } catch (ReflectiveOperationException ex) {
jrose900bafd2010-10-30 21:08:23 -0700106 throw new RuntimeException(ex);
107 }
108}
jrose9b82ad62011-05-26 17:37:36 -0700109 static int add(int x, int y) { return x + y; }
110 static int sub(int x, int y) { return x - y; }
111
jrose900bafd2010-10-30 21:08:23 -0700112{}
113
114 @Test public void testFindVirtual() throws Throwable {
115{}
116MethodHandle CONCAT_3 = LOOKUP.findVirtual(String.class,
117 "concat", methodType(String.class, String.class));
118MethodHandle HASHCODE_3 = LOOKUP.findVirtual(Object.class,
119 "hashCode", methodType(int.class));
120//assertEquals("xy", (String) CONCAT_1.invokeExact("x", "y"));
jrose1c1bfac2010-11-22 22:41:31 -0800121assertEquals("xy", (String) CONCAT_2.invokeExact("x", "y"));
122assertEquals("xy", (String) CONCAT_3.invokeExact("x", "y"));
123//assertEquals("xy".hashCode(), (int) HASHCODE_1.invokeExact((Object)"xy"));
124assertEquals("xy".hashCode(), (int) HASHCODE_2.invokeExact((Object)"xy"));
125assertEquals("xy".hashCode(), (int) HASHCODE_3.invokeExact((Object)"xy"));
jrose900bafd2010-10-30 21:08:23 -0700126{}
127 }
jrose9b82ad62011-05-26 17:37:36 -0700128
129 @Test public void testPermuteArguments() throws Throwable {
130 {{
131{} /// JAVADOC
132MethodType intfn1 = methodType(int.class, int.class);
133MethodType intfn2 = methodType(int.class, int.class, int.class);
134MethodHandle sub = SUB_2;// ... {int x, int y => x-y} ...;
135assert(sub.type().equals(intfn2));
136MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
137MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
138assert((int)rsub.invokeExact(1, 100) == 99);
139MethodHandle add = ADD_2;// ... {int x, int y => x+y} ...;
140assert(add.type().equals(intfn2));
141MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
142assert(twice.type().equals(intfn1));
143assert((int)twice.invokeExact(21) == 42);
144 }}
145 {{
146{} /// JAVADOC
147MethodHandle cat = lookup().findVirtual(String.class,
148 "concat", methodType(String.class, String.class));
149assertEquals("xy", (String) cat.invokeExact("x", "y"));
150MethodHandle d0 = dropArguments(cat, 0, String.class);
151assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
152MethodHandle d1 = dropArguments(cat, 1, String.class);
153assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
154MethodHandle d2 = dropArguments(cat, 2, String.class);
155assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
156MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
157assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
158 }}
159 }
160
jrose900bafd2010-10-30 21:08:23 -0700161 @Test public void testDropArguments() throws Throwable {
162 {{
163{} /// JAVADOC
164MethodHandle cat = lookup().findVirtual(String.class,
165 "concat", methodType(String.class, String.class));
jroseb90d2e72010-12-16 15:59:27 -0800166assertEquals("xy", (String) cat.invokeExact("x", "y"));
jroseada69fa2011-03-23 23:02:31 -0700167MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
168MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
169assertEquals(bigType, d0.type());
170assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
171 }}
172 {{
173{} /// JAVADOC
174MethodHandle cat = lookup().findVirtual(String.class,
175 "concat", methodType(String.class, String.class));
176assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700177MethodHandle d0 = dropArguments(cat, 0, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800178assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700179MethodHandle d1 = dropArguments(cat, 1, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800180assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700181MethodHandle d2 = dropArguments(cat, 2, String.class);
jroseb90d2e72010-12-16 15:59:27 -0800182assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
jrose900bafd2010-10-30 21:08:23 -0700183MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
jroseb90d2e72010-12-16 15:59:27 -0800184assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
jrose900bafd2010-10-30 21:08:23 -0700185 }}
186 }
187
188 @Test public void testFilterArguments() throws Throwable {
189 {{
190{} /// JAVADOC
191MethodHandle cat = lookup().findVirtual(String.class,
192 "concat", methodType(String.class, String.class));
jrose900bafd2010-10-30 21:08:23 -0700193MethodHandle upcase = lookup().findVirtual(String.class,
194 "toUpperCase", methodType(String.class));
jroseb90d2e72010-12-16 15:59:27 -0800195assertEquals("xy", (String) cat.invokeExact("x", "y"));
jrose900bafd2010-10-30 21:08:23 -0700196MethodHandle f0 = filterArguments(cat, 0, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800197assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
jrose900bafd2010-10-30 21:08:23 -0700198MethodHandle f1 = filterArguments(cat, 1, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800199assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
jrose900bafd2010-10-30 21:08:23 -0700200MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
jroseb90d2e72010-12-16 15:59:27 -0800201assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
jrose900bafd2010-10-30 21:08:23 -0700202 }}
203 }
204
jrose9b82ad62011-05-26 17:37:36 -0700205 @Test public void testFoldArguments() throws Throwable {
206 {{
207{} /// JAVADOC
208MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
209 "println", methodType(void.class, String.class))
210 .bindTo(System.out);
211MethodHandle cat = lookup().findVirtual(String.class,
212 "concat", methodType(String.class, String.class));
213assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
214MethodHandle catTrace = foldArguments(cat, trace);
215// also prints "boo":
216assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
217 }}
218 }
219
jrose900bafd2010-10-30 21:08:23 -0700220 static void assertEquals(Object exp, Object act) {
221 if (verbosity > 0)
222 System.out.println("result: "+act);
223 Assert.assertEquals(exp, act);
224 }
225
jrosef108fc02011-02-11 01:26:24 -0800226 @Test public void testMethodHandlesSummary() throws Throwable {
jrose900bafd2010-10-30 21:08:23 -0700227 {{
228{} /// JAVADOC
jrosef108fc02011-02-11 01:26:24 -0800229Object x, y; String s; int i;
230MethodType mt; MethodHandle mh;
231MethodHandles.Lookup lookup = MethodHandles.lookup();
232// mt is (char,char)String
233mt = MethodType.methodType(String.class, char.class, char.class);
234mh = lookup.findVirtual(String.class, "replace", mt);
jrosef108fc02011-02-11 01:26:24 -0800235s = (String) mh.invokeExact("daddy",'d','n');
jroseadc650a2011-02-11 01:26:28 -0800236// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jrose9b82ad62011-05-26 17:37:36 -0700237assertEquals(s, "nanny");
jrosef108fc02011-02-11 01:26:24 -0800238// weakly typed invocation (using MHs.invoke)
239s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jrose9b82ad62011-05-26 17:37:36 -0700240assertEquals(s, "savvy");
jrosef108fc02011-02-11 01:26:24 -0800241// mt is (Object[])List
242mt = MethodType.methodType(java.util.List.class, Object[].class);
243mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
244assert(mh.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700245x = mh.invoke("one", "two");
246// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700247assertEquals(x, java.util.Arrays.asList("one","two"));
jrosef108fc02011-02-11 01:26:24 -0800248// mt is (Object,Object,Object)Object
249mt = MethodType.genericMethodType(3);
jroseadc650a2011-02-11 01:26:28 -0800250mh = mh.asType(mt);
jrosef108fc02011-02-11 01:26:24 -0800251x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jroseadc650a2011-02-11 01:26:28 -0800252// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jrose9b82ad62011-05-26 17:37:36 -0700253assertEquals(x, java.util.Arrays.asList(1,2,3));
254// mt is ()int
jrosef108fc02011-02-11 01:26:24 -0800255mt = MethodType.methodType(int.class);
256mh = lookup.findVirtual(java.util.List.class, "size", mt);
jrosef108fc02011-02-11 01:26:24 -0800257i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jroseadc650a2011-02-11 01:26:28 -0800258// invokeExact(Ljava/util/List;)I
jrosef108fc02011-02-11 01:26:24 -0800259assert(i == 3);
260mt = MethodType.methodType(void.class, String.class);
261mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
262mh.invokeExact(System.out, "Hello, world.");
jroseadc650a2011-02-11 01:26:28 -0800263// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jrosef108fc02011-02-11 01:26:24 -0800264{}
jrose900bafd2010-10-30 21:08:23 -0700265 }}
266 }
267
jrose9b82ad62011-05-26 17:37:36 -0700268 @Test public void testAsSpreader() throws Throwable {
269 {{
270{} /// JAVADOC
271MethodHandle equals = publicLookup()
272 .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
273assert( (boolean) equals.invokeExact("me", (Object)"me"));
274assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
275// spread both arguments from a 2-array:
276MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
277assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
278assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
279// spread both arguments from a String array:
280MethodHandle eq2s = equals.asSpreader(String[].class, 2);
281assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
282assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
283// spread second arguments from a 1-array:
284MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
285assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
286assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
287// spread no arguments from a 0-array or null:
288MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
289assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
290assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
291// asSpreader and asCollector are approximate inverses:
292for (int n = 0; n <= 2; n++) {
293 for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
294 MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
295 assert( (boolean) equals2.invokeWithArguments("me", "me"));
296 assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
297 }
298}
299MethodHandle caToString = publicLookup()
300 .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
301assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
302MethodHandle caString3 = caToString.asCollector(char[].class, 3);
303assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
304MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
305assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
306 }}
307 }
308
309 @Test public void testAsCollector() throws Throwable {
310 {{
311{} /// JAVADOC
312MethodHandle deepToString = publicLookup()
313 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
314assertEquals("[won]", (String) deepToString.invokeExact(new Object[]{"won"}));
315MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
316assertEquals(methodType(String.class, Object.class), ts1.type());
317//assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"})); //FAIL
318assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
319// arrayType can be a subtype of Object[]
320MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
321assertEquals(methodType(String.class, String.class, String.class), ts2.type());
322assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
323MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
324assertEquals("[]", (String) ts0.invokeExact());
325// collectors can be nested, Lisp-style
326MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
327assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
328// arrayType can be any primitive array type
329MethodHandle bytesToString = publicLookup()
330 .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
331 .asCollector(byte[].class, 3);
332assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
333MethodHandle longsToString = publicLookup()
334 .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
335 .asCollector(long[].class, 1);
336assertEquals("[123]", (String) longsToString.invokeExact((long)123));
337 }}
338 }
339
jrose49494522012-01-18 17:34:29 -0800340 @SuppressWarnings("rawtypes")
jrosef108fc02011-02-11 01:26:24 -0800341 @Test public void testAsVarargsCollector() throws Throwable {
342 {{
343{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700344MethodHandle deepToString = publicLookup()
345 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
346MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
347assertEquals("[won]", (String) ts1.invokeExact( new Object[]{"won"}));
348assertEquals("[won]", (String) ts1.invoke( new Object[]{"won"}));
349assertEquals("[won]", (String) ts1.invoke( "won" ));
350assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
351// findStatic of Arrays.asList(...) produces a variable arity method handle:
jrosef108fc02011-02-11 01:26:24 -0800352MethodHandle asList = publicLookup()
jrose9b82ad62011-05-26 17:37:36 -0700353 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
354assertEquals(methodType(List.class, Object[].class), asList.type());
355assert(asList.isVarargsCollector());
jrose79e0a6c2011-05-12 19:27:33 -0700356assertEquals("[]", asList.invoke().toString());
357assertEquals("[1]", asList.invoke(1).toString());
358assertEquals("[two, too]", asList.invoke("two", "too").toString());
jrose9b82ad62011-05-26 17:37:36 -0700359String[] argv = { "three", "thee", "tee" };
jrose79e0a6c2011-05-12 19:27:33 -0700360assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jrose9b82ad62011-05-26 17:37:36 -0700361assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jrose79e0a6c2011-05-12 19:27:33 -0700362List ls = (List) asList.invoke((Object)argv);
jrosef108fc02011-02-11 01:26:24 -0800363assertEquals(1, ls.size());
364assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
365 }}
366 }
jrose900bafd2010-10-30 21:08:23 -0700367
jrose9b82ad62011-05-26 17:37:36 -0700368 @Test public void testAsFixedArity() throws Throwable {
jrosef108fc02011-02-11 01:26:24 -0800369 {{
370{} /// JAVADOC
jrose9b82ad62011-05-26 17:37:36 -0700371MethodHandle asListVar = publicLookup()
jrosef108fc02011-02-11 01:26:24 -0800372 .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
373 .asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -0700374MethodHandle asListFix = asListVar.asFixedArity();
375assertEquals("[1]", asListVar.invoke(1).toString());
376Exception caught = null;
377try { asListFix.invoke((Object)1); }
378catch (Exception ex) { caught = ex; }
379assert(caught instanceof ClassCastException);
380assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
381try { asListFix.invoke("two", "too"); }
382catch (Exception ex) { caught = ex; }
383assert(caught instanceof WrongMethodTypeException);
384Object[] argv = { "three", "thee", "tee" };
385assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
386assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
387assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
388assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
389 }}
390 }
391
392 @Test public void testAsTypeCornerCases() throws Throwable {
393 {{
394{} /// JAVADOC
395MethodHandle i2s = publicLookup()
396 .findVirtual(Integer.class, "toString", methodType(String.class));
397i2s = i2s.asType(i2s.type().unwrap());
398MethodHandle l2s = publicLookup()
399 .findVirtual(Long.class, "toString", methodType(String.class));
400l2s = l2s.asType(l2s.type().unwrap());
401
402Exception caught = null;
403try { i2s.asType(methodType(String.class, String.class)); }
404catch (Exception ex) { caught = ex; }
405assert(caught instanceof WrongMethodTypeException);
406
407i2s.asType(methodType(String.class, byte.class));
408i2s.asType(methodType(String.class, Byte.class));
409i2s.asType(methodType(String.class, Character.class));
410i2s.asType(methodType(String.class, Integer.class));
411l2s.asType(methodType(String.class, byte.class));
412l2s.asType(methodType(String.class, Byte.class));
413l2s.asType(methodType(String.class, Character.class));
414l2s.asType(methodType(String.class, Integer.class));
415l2s.asType(methodType(String.class, Long.class));
416
417caught = null;
418try { i2s.asType(methodType(String.class, Long.class)); }
419catch (Exception ex) { caught = ex; }
420assert(caught instanceof WrongMethodTypeException);
421
422MethodHandle i2sGen = i2s.asType(methodType(String.class, Object.class));
423MethodHandle l2sGen = l2s.asType(methodType(String.class, Object.class));
424
425i2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
426i2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
427l2sGen.invoke(42); // int -> Integer -> Object -> Integer -> int
428l2sGen.invoke((byte)4); // byte -> Byte -> Object -> Byte -> byte -> int
429l2sGen.invoke(0x420000000L);
430
431caught = null;
432try { i2sGen.invoke(0x420000000L); } // long -> Long -> Object -> Integer CCE
433catch (Exception ex) { caught = ex; }
434assert(caught instanceof ClassCastException);
435
436caught = null;
437try { i2sGen.invoke("asdf"); } // String -> Object -> Integer CCE
438catch (Exception ex) { caught = ex; }
439assert(caught instanceof ClassCastException);
jrosef108fc02011-02-11 01:26:24 -0800440{}
441 }}
442 }
jrose9b82ad62011-05-26 17:37:36 -0700443
444 @Test public void testMutableCallSite() throws Throwable {
445 {{
446{} /// JAVADOC
447MutableCallSite name = new MutableCallSite(MethodType.methodType(String.class));
448MethodHandle MH_name = name.dynamicInvoker();
449MethodType MT_str1 = MethodType.methodType(String.class);
450MethodHandle MH_upcase = MethodHandles.lookup()
451 .findVirtual(String.class, "toUpperCase", MT_str1);
452MethodHandle worker1 = MethodHandles.filterReturnValue(MH_name, MH_upcase);
453name.setTarget(MethodHandles.constant(String.class, "Rocky"));
454assertEquals("ROCKY", (String) worker1.invokeExact());
455name.setTarget(MethodHandles.constant(String.class, "Fred"));
456assertEquals("FRED", (String) worker1.invokeExact());
457// (mutation can be continued indefinitely)
458/*
459 * </pre></blockquote>
460 * <p>
461 * The same call site may be used in several places at once.
462 * <blockquote><pre>
463 */
464MethodType MT_str2 = MethodType.methodType(String.class, String.class);
465MethodHandle MH_cat = lookup().findVirtual(String.class,
466 "concat", methodType(String.class, String.class));
467MethodHandle MH_dear = MethodHandles.insertArguments(MH_cat, 1, ", dear?");
468MethodHandle worker2 = MethodHandles.filterReturnValue(MH_name, MH_dear);
469assertEquals("Fred, dear?", (String) worker2.invokeExact());
470name.setTarget(MethodHandles.constant(String.class, "Wilma"));
471assertEquals("WILMA", (String) worker1.invokeExact());
472assertEquals("Wilma, dear?", (String) worker2.invokeExact());
473{}
474 }}
475 }
476
477 @Test public void testSwitchPoint() throws Throwable {
478 {{
479{} /// JAVADOC
480MethodHandle MH_strcat = MethodHandles.lookup()
481 .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class));
482SwitchPoint spt = new SwitchPoint();
jrosecd1d97b2011-06-03 11:20:20 -0700483assert(!spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700484// the following steps may be repeated to re-use the same switch point:
485MethodHandle worker1 = MH_strcat;
486MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0);
487MethodHandle worker = spt.guardWithTest(worker1, worker2);
488assertEquals("method", (String) worker.invokeExact("met", "hod"));
489SwitchPoint.invalidateAll(new SwitchPoint[]{ spt });
jrosecd1d97b2011-06-03 11:20:20 -0700490assert(spt.hasBeenInvalidated());
jrose9b82ad62011-05-26 17:37:36 -0700491assertEquals("hodmet", (String) worker.invokeExact("met", "hod"));
492{}
493 }}
494 }
495
jroseb4be0262011-07-16 15:44:33 -0700496 @Test public void testFoldArguments2() throws Throwable {
497 {{
498{} /// JAVADOC
499// argument-based dispatch for methods of the form boolean x.___(y: String)
500Lookup lookup = publicLookup();
501// first, a tracing hack:
502MethodHandle println = lookup.findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class));
503MethodHandle arrayToString = lookup.findStatic(Arrays.class, "toString", methodType(String.class, Object[].class));
504MethodHandle concat = lookup.findVirtual(String.class, "concat", methodType(String.class, String.class));
505MethodHandle arrayToString_DIS = filterReturnValue(arrayToString, concat.bindTo("DIS:"));
506MethodHandle arrayToString_INV = filterReturnValue(arrayToString, concat.bindTo("INV:"));
507MethodHandle printArgs_DIS = filterReturnValue(arrayToString_DIS, println.bindTo(System.out)).asVarargsCollector(Object[].class);
508MethodHandle printArgs_INV = filterReturnValue(arrayToString_INV, println.bindTo(System.out)).asVarargsCollector(Object[].class);
509// metaobject protocol:
510MethodType mtype = methodType(boolean.class, String.class);
511MethodHandle findVirtual = lookup.findVirtual(Lookup.class,
512 "findVirtual", methodType(MethodHandle.class, Class.class, String.class, MethodType.class));
513MethodHandle getClass = lookup.findVirtual(Object.class,
514 "getClass", methodType(Class.class));
515MethodHandle dispatch = findVirtual;
516dispatch = filterArguments(dispatch, 1, getClass);
517dispatch = insertArguments(dispatch, 3, mtype);
518dispatch = dispatch.bindTo(lookup);
519assertEquals(methodType(MethodHandle.class, Object.class, String.class), dispatch.type());
520MethodHandle invoker = invoker(mtype.insertParameterTypes(0, Object.class));
521// wrap tracing around the dispatch and invoke steps:
522dispatch = foldArguments(dispatch, printArgs_DIS.asType(dispatch.type().changeReturnType(void.class)));
523invoker = foldArguments(invoker, printArgs_INV.asType(invoker.type().changeReturnType(void.class)));
524invoker = dropArguments(invoker, 2, String.class); // ignore selector
525// compose the dispatcher and the invoker:
526MethodHandle invokeDispatched = foldArguments(invoker, dispatch);
527Object x = "football", y = new java.util.Scanner("bar");
528assert( (boolean) invokeDispatched.invokeExact(x, "startsWith", "foo"));
529assert(!(boolean) invokeDispatched.invokeExact(x, "startsWith", "#"));
530assert( (boolean) invokeDispatched.invokeExact(x, "endsWith", "all"));
531assert(!(boolean) invokeDispatched.invokeExact(x, "endsWith", "foo"));
532assert( (boolean) invokeDispatched.invokeExact(y, "hasNext", "[abc]+[rst]"));
533assert(!(boolean) invokeDispatched.invokeExact(y, "hasNext", "[123]+[789]"));
534 }}
535 }
536
jrose9b82ad62011-05-26 17:37:36 -0700537 /* ---- TEMPLATE ----
538 @Test public void testFoo() throws Throwable {
539 {{
540{} /// JAVADOC
541{}
542 }}
543 }
544 */
jrose900bafd2010-10-30 21:08:23 -0700545}