changeset 37:6801a67b2bfd

indy: update code examples
author jrose
date Wed, 24 Mar 2010 21:44:42 -0700
parents 1c7351d7192f
children fa252dd74a58
files netbeans/indy-demo/src/JavaDocExamples.java netbeans/indy-demo/src/PrintArgsDemo.java netbeans/indy-demo/src/VMILDemos.java
diffstat 3 files changed, 397 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/netbeans/indy-demo/src/JavaDocExamples.java	Wed Mar 24 21:44:42 2010 -0700
@@ -0,0 +1,169 @@
+/*
+ Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+   - Redistributions of source code must retain the above copyright
+     notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+     notice, this list of conditions and the following disclaimer in the
+     documentation and/or other materials provided with the distribution.
+
+   - Neither the name of Sun Microsystems nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+import java.dyn.*;
+import static java.dyn.MethodHandles.*;
+import static java.dyn.MethodType.*;
+
+public class JavaDocExamples {
+    public static void main(String... av) throws Throwable {
+        forMethodHandle();
+        forJavaMethodHandle();
+        forInvokeDynamic();
+    }
+
+    static boolean successful(String who) {
+        System.out.println(who + ": all assertions passed");
+        return true;
+    }
+
+    /** Code examples from the javadoc in java.dyn.MethodHandle. */
+    static void forMethodHandle() throws Throwable {
+{;;;}
+Object x, y; String s; int i;
+MethodType mt; MethodHandle mh;
+MethodHandles.Lookup lookup = MethodHandles.lookup();
+// mt is {(char,char) => String}
+mt = MethodType.methodType(String.class, char.class, char.class);
+mh = lookup.findVirtual(String.class, "replace", mt);
+// (Ljava/lang/String;CC)Ljava/lang/String;
+s = mh.<String>invokeExact("daddy",'d','n');
+assert(s.equals("nanny"));
+// weakly typed invocation (using MHs.invoke)
+s = (String) mh.invokeVarargs("sappy", 'p', 'v');
+assert(s.equals("savvy"));
+// mt is {Object[] => List}
+mt = MethodType.methodType(java.util.List.class, Object[].class);
+mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
+// mt is {(Object,Object,Object) => Object}
+mt = MethodType.genericMethodType(3);
+mh = MethodHandles.collectArguments(mh, mt);
+// mt is {(Object,Object,Object) => Object}
+// (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
+x = mh.invokeExact((Object)1, (Object)2, (Object)3);
+assert(x.equals(java.util.Arrays.asList(1,2,3)));
+// mt is { => int}
+mt = MethodType.methodType(int.class);
+mh = lookup.findVirtual(java.util.List.class, "size", mt);
+// (Ljava/util/List;)I
+i = mh.<int>invokeExact(java.util.Arrays.asList(1,2,3));
+assert(i == 3);
+{;;;}
+        assert(successful("forMethodHandle"));
+        oldStuffForMethodHandle();
+    }
+
+    static void oldStuffForMethodHandle() throws Throwable {
+        Object x, y; String s; int i;
+        MethodType mt; MethodHandle mh;
+        // for type imports:
+        mh = lookup().findVirtual(String.class, "hashCode", methodType(int.class));
+        i = mh.<int>invokeExact("foo");
+        assert(i == "foo".hashCode());
+        mh = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
+        s = mh.<String>invokeExact("foo", "tball");
+        assert(s.equals("football"));
+        mh = lookup().findVirtual(String.class, "replace", methodType(String.class, char.class, char.class));
+        s = mh.<String>invokeExact("blubber", 'b', 'f');
+        assert(s.equals("fluffer"));
+        assert(successful("forMethodHandle #2"));
+    }
+
+    /** Code examples from the javadoc in java.dyn.InvokeDynamic. */
+    static void forJavaMethodHandle() throws Throwable {
+        Greeter greeter = new Greeter("world");
+        greeter.run();  // prints "hello, world"
+        // Statically typed method handle invocation (most direct):
+        MethodHandle mh = greeter;
+        mh.<void>invokeExact();  // also prints "hello, world"
+        // Dynamically typed method handle invocation:
+        greeter.invokeVarargs(new Object[0]);  // also prints "hello, world"
+        // We can also do this with symbolic names and/or inner classes:
+        new JavaMethodHandle("yow") {
+            void yow() { System.out.println("yow, world"); }
+        }.invokeVarargs(new Object[0]);
+        assert(successful("forJavaMethodHandle"));
+    }
+
+    static
+    class Greeter extends JavaMethodHandle {
+        public void run() { System.out.println("hello, "+greetee); }
+        private final String greetee;
+        Greeter(String greetee) {
+            super(RUN);
+            this.greetee = greetee;
+        }
+        // the entry point function is computed once:
+        private static final MethodHandle RUN
+            = MethodHandles.lookup().findVirtual(Greeter.class, "run",
+                  methodType(void.class));
+    }
+
+    /** Code examples from the javadoc in java.dyn.InvokeDynamic. */
+    static void forInvokeDynamic() throws Throwable {
+        Object x; String s; int i;
+        x = InvokeDynamic.greet("world"); // greet(Ljava/lang/String;)Ljava/lang/Object;
+        s = InvokeDynamic.<String>hail(x); // hail(Ljava/lang/Object;)Ljava/lang/String;
+        InvokeDynamic.<void>cogito(); // cogito()V
+        i = InvokeDynamic.<int>#"op:+"(2, 3); // op:+(II)I
+        assert(i == 2+3);
+        assert(successful("forInvokeDynamic"));
+    }
+
+    // Set up a class-local bootstrap method.
+    static { Linkage.registerBootstrapMethod("bootstrapDynamic"); }
+    private static CallSite bootstrapDynamic(Class caller, String name, MethodType type) {
+        MethodHandle target = null;
+        if (name.equals("greet") || name.equals("hail")) {
+            target = new JavaMethodHandle("invoke", type) {
+                private String invoke(Object x) {
+                    System.out.println("howdy, "+x);
+                    return "galaxy";
+                }
+            };
+        }
+        if (name.equals("cogito")) {
+            target = new JavaMethodHandle("invoke") {
+                private void invoke() {
+                    System.out.println("if I only had a brain...");
+                }
+            };
+        }
+        if (name.equals("op:+")) {
+            target = new JavaMethodHandle("invoke") {
+                private int invoke(int x, int y) {
+                    return x + y;
+                }
+            };
+        }
+        return new CallSite(target);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/netbeans/indy-demo/src/PrintArgsDemo.java	Wed Mar 24 21:44:42 2010 -0700
@@ -0,0 +1,61 @@
+/*
+ Copyright 2010 Sun Microsystems, Inc.  All Rights Reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+   - Redistributions of source code must retain the above copyright
+     notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+     notice, this list of conditions and the following disclaimer in the
+     documentation and/or other materials provided with the distribution.
+
+   - Neither the name of Sun Microsystems nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+import java.dyn.*;
+
+class PrintArgsDemo {
+    public static void main(String... av) throws Throwable {
+        System.out.println("Printing some argument lists, starting with a empty one:");
+        InvokeDynamic.nothing();
+        InvokeDynamic.foo("foo arg");
+        InvokeDynamic.bar("bar arg", 1);
+        InvokeDynamic.baz("baz arg", 2, 3.14);
+        System.out.println("Done printing argument lists.");
+    }
+
+    //// BEGIN JAVADOC EXAMPLE
+private static void printArgs(Object... args) {
+  System.out.println(java.util.Arrays.deepToString(args));
+}
+private static final MethodHandle printArgs;
+static {
+  MethodHandles.Lookup lookup = MethodHandles.lookup();
+  Class thisClass = lookup.lookupClass();  // (who am I?)
+  printArgs = lookup.findStatic(thisClass,
+      "printArgs", MethodType.methodType(void.class, Object[].class));
+  Linkage.registerBootstrapMethod("bootstrapDynamic");
+}
+private static CallSite bootstrapDynamic(Class caller, String name, MethodType type) {
+  // ignore caller and name, but match the type:
+  return new CallSite(MethodHandles.collectArguments(printArgs, type));
+}
+    //// END JAVADOC EXAMPLE
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/netbeans/indy-demo/src/VMILDemos.java	Wed Mar 24 21:44:42 2010 -0700
@@ -0,0 +1,167 @@
+/*
+ Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+   - Redistributions of source code must retain the above copyright
+     notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+     notice, this list of conditions and the following disclaimer in the
+     documentation and/or other materials provided with the distribution.
+
+   - Neither the name of Sun Microsystems nor the names of its
+     contributors may be used to endorse or promote products derived
+     from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+$JAVA7X_HOME/bin/javac -XDinvokedynamic VMILDemos.java
+$JAVA7X_HOME/bin/java -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic -cp . VMILDemos
+ */
+
+import java.dyn.*;
+import java.io.*;
+
+public class VMILDemos {
+    static MethodHandle println;
+    public static void figure_3() throws Throwable {
+{;;;}
+MethodHandle println = MethodHandles.lookup()
+    .findVirtual(PrintStream.class,
+      "println", MethodType.methodType(
+      void.class, String.class));
+println.<void>invokeExact(
+    System.out, "hello, world");
+//Figure 3. Creating and using a direct method handle.
+{;;;}
+VMILDemos.println = println;
+    }
+    public static void figure_4() throws Throwable {
+{;;;}
+MethodType mt = println.type();
+assert mt.parameterType(0)==PrintStream.class;
+assert mt.parameterType(1)==String.class;
+assert mt.returnType()==void.class;
+//Figure 4. Method handle type, with inserted receiver argument.
+{;;;}
+    }
+    public static void figure_6() throws Throwable {
+{;;;}
+int pos = 0;  // receiver in leading position
+MethodHandle println2out = MethodHandles
+   .insertArguments(println, pos, System.out);
+println2out.<void>invokeExact("hello, world");
+//Figure 6. Creating and using a bound method handle.
+{;;;}
+    }
+
+    public static void figure_7() throws Throwable {
+{;;;}
+CatBox.test();
+//Figure 7. Object-like method handle with a “setter” API.
+{;;;}
+    }
+    public static void figure_8() throws Throwable {
+{;;;} class C {
+MethodHandle greet(final String greeting) {
+  return new JavaMethodHandle("run") {
+      void run(String greetee) {
+        String s = greeting+", "+greetee;
+        System.out.println(s);
+    } };
+}
+{;;;} }; new C().
+greet("hello").<void>invokeExact("world");
+// prints "hello, world"
+//Figure 8. Anonymous class specifying a method handle.
+{;;;}
+    }
+    public static void figure_9() throws Throwable {
+{;;;}
+Number x = 123;
+int y;
+if (!(x instanceof Integer))
+  /*S*/ y = x.intValue(); // invokevirtual
+else
+  /*F*/ y = ((Integer)x).intValue();
+//Figure 9. Pseudocode for inline cache logic, of invokevirtual.{;;;}
+    }
+    public static void figure_10() throws Throwable {
+{;;;}
+//*//Object x, y;  // y = x+1
+//*//static final ICCallSite site = …;
+//*//static final MethodHandle logic = …;
+//*//if (site.target != logic)
+//*//  /*L*/ y = site.target.invokeExact(x,1);
+//*//else if (!(x instanceof Integer))
+//*//  /*S*/ y = site.cacheAndCall(x,1);
+//*//else
+//*//  /*F*/ y = Runtime.add((int)(Integer)x,1);
+//*////Figure 10. Pseudocode for inline cache, at a dynamic call site.
+{;;;}
+    }
+
+    public static void main(String... av) throws Throwable {
+        figure_3();
+        figure_4();
+        figure_6();
+        figure_7();
+        figure_8();
+        figure_9();
+        figure_10();
+    }
+{;;;} static
+abstract class AbstractSettableMethodHandle
+    extends JavaMethodHandle {
+  private final MethodHandle setter;
+  public MethodHandle setter()
+    { return setter; }
+  public AbstractSettableMethodHandle(
+      String get, String set) {
+    super(get);  // self is the getter
+    MethodType getType = this.type();
+    MethodType setType; {{
+            int nargs = getType.parameterCount();
+            Class ret = getType.returnType();
+            setType = getType
+                .insertParameterTypes(nargs, ret)
+                .changeReturnType(void.class);
+        }}
+    this.setter = MethodHandles.publicLookup()
+       .bind(this, set, setType);
+  }
+  {;;;} public MethodHandle getter() { return this; }
+}
+{;;;}
+    static public class CatBox extends AbstractSettableMethodHandle {
+        int thing1;
+        public int getThing1() { return thing1; }
+        public void setThing1(int x) { thing1 = x; }
+        CatBox(int x) {
+            super("getThing1", "setThing1");
+            thing1 = x;
+        }
+        static void test() throws Throwable {
+            CatBox box = new CatBox(123);
+            System.out.println("thing1 = "+box.getter().<int>invoke());
+            box.setter().<void>invoke(456);
+            System.out.println("thing2 = "+box.getter().<int>invoke());
+        }
+    }
+
+}
\ No newline at end of file